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 1
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 */
346 REDIRFD_SYNTAX_ERR = -2,
347 REDIRFD_TO_FILE = -1,
348 /* otherwise, rd_fd is redirected to rd_dup */
350 HEREDOC_SKIPTABS = 1,
356 pid_t pid; /* 0 if exited */
357 int assignment_cnt; /* how many argv[i] are assignments? */
358 smallint is_stopped; /* is the command currently running? */
359 smallint grp_type; /* GRP_xxx */
360 struct pipe *group; /* if non-NULL, this "command" is { list },
361 * ( list ), or a compound statement */
363 char *group_as_string;
365 char **argv; /* command name and arguments */
366 struct redir_struct *redirects; /* I/O redirections */
368 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
369 * and on execution these are substituted with their values.
370 * Substitution can make _several_ words out of one argv[n]!
371 * Example: argv[0]=='.^C*^C.' here: echo .$*.
372 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
375 #define GRP_SUBSHELL 1
376 #if ENABLE_HUSH_FUNCTIONS
377 # define GRP_FUNCTION 2
382 int num_cmds; /* total number of commands in pipe */
383 int alive_cmds; /* number of commands running (not exited) */
384 int stopped_cmds; /* number of commands alive, but stopped */
386 int jobid; /* job number */
387 pid_t pgrp; /* process group ID for the job */
388 char *cmdtext; /* name of job */
390 struct command *cmds; /* array of commands in pipe */
391 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
392 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
393 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
395 typedef enum pipe_style {
402 /* This holds pointers to the various results of parsing */
403 struct parse_context {
404 /* linked list of pipes */
405 struct pipe *list_head;
406 /* last pipe (being constructed right now) */
408 /* last command in pipe (being constructed right now) */
409 struct command *command;
410 /* last redirect in command->redirects list */
411 struct redir_struct *pending_redirect;
417 smallint ctx_inverted; /* "! cmd | cmd" */
419 smallint ctx_dsemicolon; /* ";;" seen */
421 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
423 /* group we are enclosed in:
424 * example: "if pipe1; pipe2; then pipe3; fi"
425 * when we see "if" or "then", we malloc and copy current context,
426 * and make ->stack point to it. then we parse pipeN.
427 * when closing "then" / fi" / whatever is found,
428 * we move list_head into ->stack->command->group,
429 * copy ->stack into current context, and delete ->stack.
430 * (parsing of { list } and ( list ) doesn't use this method)
432 struct parse_context *stack;
436 /* On program start, environ points to initial environment.
437 * putenv adds new pointers into it, unsetenv removes them.
438 * Neither of these (de)allocates the strings.
439 * setenv allocates new strings in malloc space and does putenv,
440 * and thus setenv is unusable (leaky) for shell's purposes */
441 #define setenv(...) setenv_is_leaky_dont_use()
443 struct variable *next;
444 char *varstr; /* points to "name=" portion */
445 int max_len; /* if > 0, name is part of initial env; else name is malloced */
446 smallint flg_export; /* putenv should be done on this var */
447 smallint flg_read_only;
455 #if ENABLE_HUSH_FUNCTIONS
457 struct function *next;
461 char *body_as_string;
467 /* "Globals" within this file */
468 /* Sorted roughly by size (smaller offsets == smaller code) */
470 #if ENABLE_HUSH_INTERACTIVE
471 /* 'interactive_fd' is a fd# open to ctty, if we have one
472 * _AND_ if we decided to act interactively */
476 #define G_interactive_fd (G.interactive_fd)
478 #define G_interactive_fd 0
480 #if ENABLE_FEATURE_EDITING
481 line_input_t *line_input_state;
487 pid_t saved_tty_pgrp;
489 struct pipe *job_list;
490 struct pipe *toplevel_list;
491 //// smallint ctrl_z_flag;
493 smallint flag_SIGINT;
494 #if ENABLE_HUSH_LOOPS
495 smallint flag_break_continue;
498 smallint exiting; /* used to prevent EXIT trap recursion */
499 /* These four support $?, $#, and $1 */
500 smalluint last_exitcode;
501 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
502 smalluint global_args_malloced;
503 /* how many non-NULL argv's we have. NB: $# + 1 */
507 char *argv0_for_re_execing;
508 char **argv_from_re_execing;
510 #if ENABLE_HUSH_LOOPS
511 unsigned depth_break_continue;
512 unsigned depth_of_loop;
516 struct variable *top_var; /* = &G.shell_ver (set in main()) */
517 struct variable shell_ver;
518 #if ENABLE_HUSH_FUNCTIONS
519 struct function *top_func;
521 /* Signal and trap handling */
522 // unsigned count_SIGCHLD;
523 // unsigned handled_SIGCHLD;
524 /* which signals have non-DFL handler (even with no traps set)? */
525 unsigned non_DFL_mask;
526 char **traps; /* char *traps[NSIG] */
527 sigset_t blocked_set;
528 sigset_t inherited_set;
530 unsigned long memleak_value;
532 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
533 #if ENABLE_FEATURE_SH_STANDALONE
534 struct nofork_save_area nofork_save;
537 sigjmp_buf toplevel_jb;
540 #define G (*ptr_to_globals)
541 /* Not #defining name to G.name - this quickly gets unwieldy
542 * (too many defines). Also, I actually prefer to see when a variable
543 * is global, thus "G." prefix is a useful hint */
544 #define INIT_G() do { \
545 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
549 /* Function prototypes for builtins */
550 static int builtin_cd(char **argv);
551 static int builtin_echo(char **argv);
552 static int builtin_eval(char **argv);
553 static int builtin_exec(char **argv);
554 static int builtin_exit(char **argv);
555 static int builtin_export(char **argv);
557 static int builtin_fg_bg(char **argv);
558 static int builtin_jobs(char **argv);
561 static int builtin_help(char **argv);
564 static int builtin_memleak(char **argv);
566 static int builtin_pwd(char **argv);
567 static int builtin_read(char **argv);
568 static int builtin_set(char **argv);
569 static int builtin_shift(char **argv);
570 static int builtin_source(char **argv);
571 static int builtin_test(char **argv);
572 static int builtin_trap(char **argv);
573 static int builtin_true(char **argv);
574 static int builtin_umask(char **argv);
575 static int builtin_unset(char **argv);
576 static int builtin_wait(char **argv);
577 #if ENABLE_HUSH_LOOPS
578 static int builtin_break(char **argv);
579 static int builtin_continue(char **argv);
582 /* Table of built-in functions. They can be forked or not, depending on
583 * context: within pipes, they fork. As simple commands, they do not.
584 * When used in non-forking context, they can change global variables
585 * in the parent shell process. If forked, of course they cannot.
586 * For example, 'unset foo | whatever' will parse and run, but foo will
587 * still be set at the end. */
588 struct built_in_command {
590 int (*function)(char **argv);
593 #define BLTIN(cmd, func, help) { cmd, func, help }
595 #define BLTIN(cmd, func, help) { cmd, func }
599 /* For now, echo and test are unconditionally enabled.
600 * Maybe make it configurable? */
601 static const struct built_in_command bltins[] = {
602 BLTIN("." , builtin_source , "Run commands in a file"),
603 BLTIN(":" , builtin_true , "No-op"),
604 BLTIN("[" , builtin_test , "Test condition"),
606 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
608 #if ENABLE_HUSH_LOOPS
609 BLTIN("break" , builtin_break , "Exit from a loop"),
611 BLTIN("cd" , builtin_cd , "Change directory"),
612 #if ENABLE_HUSH_LOOPS
613 BLTIN("continue", builtin_continue, "Start new loop iteration"),
615 BLTIN("echo" , builtin_echo , "Write to stdout"),
616 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
617 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
618 BLTIN("exit" , builtin_exit , "Exit"),
619 BLTIN("export" , builtin_export , "Set environment variable"),
621 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
624 BLTIN("help" , builtin_help , "List shell built-in commands"),
627 BLTIN("jobs" , builtin_jobs , "List active jobs"),
630 BLTIN("memleak" , builtin_memleak , "Debug tool"),
632 BLTIN("pwd" , builtin_pwd , "Print current directory"),
633 BLTIN("read" , builtin_read , "Input environment variable"),
634 // BLTIN("return" , builtin_return , "Return from a function"),
635 BLTIN("set" , builtin_set , "Set/unset shell local variables"),
636 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
637 BLTIN("test" , builtin_test , "Test condition"),
638 BLTIN("trap" , builtin_trap , "Trap signals"),
639 // BLTIN("ulimit" , builtin_return , "Control resource limits"),
640 BLTIN("umask" , builtin_umask , "Set file creation mask"),
641 BLTIN("unset" , builtin_unset , "Unset environment variable"),
642 BLTIN("wait" , builtin_wait , "Wait for process"),
646 /* Leak hunting. Use hush_leaktool.sh for post-processing.
649 static void *xxmalloc(int lineno, size_t size)
651 void *ptr = xmalloc((size + 0xff) & ~0xff);
652 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
655 static void *xxrealloc(int lineno, void *ptr, size_t size)
657 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
658 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
661 static char *xxstrdup(int lineno, const char *str)
663 char *ptr = xstrdup(str);
664 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
667 static void xxfree(void *ptr)
669 fdprintf(2, "free %p\n", ptr);
672 #define xmalloc(s) xxmalloc(__LINE__, s)
673 #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
674 #define xstrdup(s) xxstrdup(__LINE__, s)
675 #define free(p) xxfree(p)
679 /* Syntax and runtime errors. They always abort scripts.
680 * In interactive use they usually discard unparsed and/or unexecuted commands
681 * and return to the prompt.
682 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
685 # define die_if_script(lineno, fmt...) die_if_script(fmt)
686 # define syntax_error(lineno, msg) syntax_error(msg)
687 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
688 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
689 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
690 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
693 static void die_if_script(unsigned lineno, const char *fmt, ...)
698 bb_error_msg("hush.c:%u", lineno);
701 bb_verror_msg(fmt, p, NULL);
703 if (!G_interactive_fd)
707 static void syntax_error(unsigned lineno, const char *msg)
710 die_if_script(lineno, "syntax error: %s", msg);
712 die_if_script(lineno, "syntax error", NULL);
715 static void syntax_error_at(unsigned lineno, const char *msg)
717 die_if_script(lineno, "syntax error at '%s'", msg);
720 /* It so happens that all such cases are totally fatal
721 * even if shell is interactive: EOF while looking for closing
722 * delimiter. There is nowhere to read stuff from after that,
723 * it's EOF! The only choice is to terminate.
725 static void syntax_error_unterm_ch(unsigned lineno, char ch) NORETURN;
726 static void syntax_error_unterm_ch(unsigned lineno, char ch)
731 die_if_script(lineno, "syntax error: unterminated %s", msg);
735 static void syntax_error_unterm_str(unsigned lineno, const char *s)
737 die_if_script(lineno, "syntax error: unterminated %s", s);
740 static void syntax_error_unexpected_ch(unsigned lineno, char ch)
745 die_if_script(lineno, "syntax error: unexpected %s", msg);
750 # undef die_if_script
752 # undef syntax_error_at
753 # undef syntax_error_unterm_ch
754 # undef syntax_error_unterm_str
755 # undef syntax_error_unexpected_ch
757 # define die_if_script(fmt...) die_if_script(__LINE__, fmt)
758 # define syntax_error(msg) syntax_error(__LINE__, msg)
759 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
760 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
761 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
762 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
768 static int glob_needed(const char *s)
773 if (*s == '*' || *s == '[' || *s == '?')
780 static int is_well_formed_var_name(const char *s, char terminator)
782 if (!s || !(isalpha(*s) || *s == '_'))
785 while (isalnum(*s) || *s == '_')
787 return *s == terminator;
790 /* Replace each \x with x in place, return ptr past NUL. */
791 static char *unbackslash(char *src)
797 if ((*dst++ = *src++) == '\0')
803 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
824 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
825 v[count1 + count2] = NULL;
828 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
832 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
834 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
835 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
838 #define add_strings_to_strings(strings, add, need_to_dup) \
839 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
842 static char **add_string_to_strings(char **strings, char *add)
847 return add_strings_to_strings(strings, v, /*dup:*/ 0);
850 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
852 char **ptr = add_string_to_strings(strings, add);
853 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
856 #define add_string_to_strings(strings, add) \
857 xx_add_string_to_strings(__LINE__, strings, add)
860 static void putenv_all(char **strings)
865 debug_printf_env("putenv '%s'\n", *strings);
870 static char **putenv_all_and_save_old(char **strings)
880 eq = strchr(*strings, '=');
883 v = getenv(*strings);
886 /* v points to VAL in VAR=VAL, go back to VAR */
887 v -= (eq - *strings) + 1;
888 old = add_string_to_strings(old, v);
897 static void free_strings_and_unsetenv(char **strings, int unset)
907 debug_printf_env("unsetenv '%s'\n", *v);
915 static void free_strings(char **strings)
917 free_strings_and_unsetenv(strings, 0);
921 /* Basic theory of signal handling in shell
922 * ========================================
923 * This does not describe what hush does, rather, it is current understanding
924 * what it _should_ do. If it doesn't, it's a bug.
925 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
927 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
928 * is finished or backgrounded. It is the same in interactive and
929 * non-interactive shells, and is the same regardless of whether
930 * a user trap handler is installed or a shell special one is in effect.
931 * ^C or ^Z from keyboard seem to execute "at once" because it usually
932 * backgrounds (i.e. stops) or kills all members of currently running
935 * Wait builtin in interruptible by signals for which user trap is set
936 * or by SIGINT in interactive shell.
938 * Trap handlers will execute even within trap handlers. (right?)
940 * User trap handlers are forgotten when subshell ("(cmd)") is entered.
942 * If job control is off, backgrounded commands ("cmd &")
943 * have SIGINT, SIGQUIT set to SIG_IGN.
945 * Commands run in command substitution ("`cmd`")
946 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
948 * Ordinary commands have signals set to SIG_IGN/DFL set as inherited
949 * by the shell from its parent.
951 * Siganls which differ from SIG_DFL action
952 * (note: child (i.e., [v]forked) shell is not an interactive shell):
955 * SIGTERM (interactive): ignore
956 * SIGHUP (interactive):
957 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
958 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
959 * (note that ^Z is handled not by trapping SIGTSTP, but by seeing
960 * that all pipe members are stopped) (right?)
961 * SIGINT (interactive): wait for last pipe, ignore the rest
962 * of the command line, show prompt. NB: ^C does not send SIGINT
963 * to interactive shell while shell is waiting for a pipe,
964 * since shell is bg'ed (is not in foreground process group).
965 * (check/expand this)
966 * Example 1: this waits 5 sec, but does not execute ls:
967 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
968 * Example 2: this does not wait and does not execute ls:
969 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
970 * Example 3: this does not wait 5 sec, but executes ls:
971 * "sleep 5; ls -l" + press ^C
973 * (What happens to signals which are IGN on shell start?)
974 * (What happens with signal mask on shell start?)
976 * Implementation in hush
977 * ======================
978 * We use in-kernel pending signal mask to determine which signals were sent.
979 * We block all signals which we don't want to take action immediately,
980 * i.e. we block all signals which need to have special handling as described
981 * above, and all signals which have traps set.
982 * After each pipe execution, we extract any pending signals via sigtimedwait()
985 * unsigned non_DFL_mask: a mask of such "special" signals
986 * sigset_t blocked_set: current blocked signal set
989 * clear bit in blocked_set unless it is also in non_DFL_mask
990 * "trap 'cmd' SIGxxx":
991 * set bit in blocked_set (even if 'cmd' is '')
992 * after [v]fork, if we plan to be a shell:
993 * nothing for {} child shell (say, "true | { true; true; } | true")
994 * unset all traps if () shell.
995 * after [v]fork, if we plan to exec:
996 * POSIX says pending signal mask is cleared in child - no need to clear it.
997 * Restore blocked signal set to one inherited by shell just prior to exec.
999 * Note: as a result, we do not use signal handlers much. The only uses
1000 * are to count SIGCHLDs [disabled - bug somewhere, + bloat]
1001 * and to restore tty pgrp on signal-induced exit.
1004 //static void SIGCHLD_handler(int sig UNUSED_PARAM)
1006 // G.count_SIGCHLD++;
1009 static int check_and_run_traps(int sig)
1011 static const struct timespec zero_timespec = { 0, 0 };
1012 smalluint save_rcode;
1018 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
1023 if (G.traps && G.traps[sig]) {
1024 if (G.traps[sig][0]) {
1025 /* We have user-defined handler */
1026 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
1027 save_rcode = G.last_exitcode;
1030 G.last_exitcode = save_rcode;
1031 } /* else: "" trap, ignoring signal */
1034 /* not a trap: special action */
1037 // G.count_SIGCHLD++;
1046 default: /* ignored: */
1047 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1056 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1057 #define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1058 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1059 #define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1061 /* Restores tty foreground process group, and exits.
1062 * May be called as signal handler for fatal signal
1063 * (will faithfully resend signal to itself, producing correct exit state)
1064 * or called directly with -EXITCODE.
1065 * We also call it if xfunc is exiting. */
1066 static void sigexit(int sig) NORETURN;
1067 static void sigexit(int sig)
1069 /* Disable all signals: job control, SIGPIPE, etc. */
1070 sigprocmask_allsigs(SIG_BLOCK);
1072 /* Careful: we can end up here after [v]fork. Do not restore
1073 * tty pgrp then, only top-level shell process does that */
1074 if (G_interactive_fd && getpid() == G.root_pid)
1075 tcsetpgrp(G_interactive_fd, G.saved_tty_pgrp);
1077 /* Not a signal, just exit */
1081 kill_myself_with_sig(sig); /* does not return */
1085 #define disable_restore_tty_pgrp_on_exit() ((void)0)
1086 #define enable_restore_tty_pgrp_on_exit() ((void)0)
1090 /* Restores tty foreground process group, and exits. */
1091 static void hush_exit(int exitcode) NORETURN;
1092 static void hush_exit(int exitcode)
1094 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1095 /* Prevent recursion:
1096 * trap "echo Hi; exit" EXIT; exit
1098 char *argv[] = { NULL, G.traps[0], NULL };
1106 fflush(NULL); /* flush all streams */
1107 sigexit(- (exitcode & 0xff));
1114 static const char *set_cwd(void)
1116 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1117 * we must not try to free(bb_msg_unknown) */
1118 if (G.cwd == bb_msg_unknown)
1120 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1122 G.cwd = bb_msg_unknown;
1127 /* Get/check local shell variables */
1128 static struct variable *get_local_var(const char *name)
1130 struct variable *cur;
1136 for (cur = G.top_var; cur; cur = cur->next) {
1137 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1143 static const char *get_local_var_value(const char *src)
1145 struct variable *var = get_local_var(src);
1147 return strchr(var->varstr, '=') + 1;
1151 /* str holds "NAME=VAL" and is expected to be malloced.
1152 * We take ownership of it.
1156 * -1: if NAME is set, leave export status alone
1157 * if NAME is not set, do not export
1158 * flg_read_only is set only when we handle -R var=val
1161 #define set_local_var(str, flg_export, flg_read_only) \
1162 set_local_var(str, flg_export)
1164 static int set_local_var(char *str, int flg_export, int flg_read_only)
1166 struct variable *cur;
1170 value = strchr(str, '=');
1171 if (!value) { /* not expected to ever happen? */
1176 name_len = value - str + 1; /* including '=' */
1177 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
1179 if (strncmp(cur->varstr, str, name_len) != 0) {
1181 /* Bail out. Note that now cur points
1182 * to last var in linked list */
1188 /* We found an existing var with this name */
1190 if (cur->flg_read_only) {
1194 bb_error_msg("%s: readonly variable", str);
1198 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1199 unsetenv(str); /* just in case */
1201 if (strcmp(cur->varstr, str) == 0) {
1206 if (cur->max_len >= strlen(str)) {
1207 /* This one is from startup env, reuse space */
1208 strcpy(cur->varstr, str);
1211 /* max_len == 0 signifies "malloced" var, which we can
1212 * (and has to) free */
1216 goto set_str_and_exp;
1219 /* Not found - create next variable struct */
1220 cur->next = xzalloc(sizeof(*cur));
1226 cur->flg_read_only = flg_read_only;
1229 if (flg_export == 1)
1230 cur->flg_export = 1;
1231 if (cur->flg_export) {
1232 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1233 return putenv(cur->varstr);
1238 static int unset_local_var(const char *name)
1240 struct variable *cur;
1241 struct variable *prev = prev; /* for gcc */
1245 return EXIT_SUCCESS;
1246 name_len = strlen(name);
1249 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1250 if (cur->flg_read_only) {
1251 bb_error_msg("%s: readonly variable", name);
1252 return EXIT_FAILURE;
1254 /* prev is ok to use here because 1st variable, HUSH_VERSION,
1255 * is ro, and we cannot reach this code on the 1st pass */
1256 prev->next = cur->next;
1257 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1258 bb_unsetenv(cur->varstr);
1262 return EXIT_SUCCESS;
1267 return EXIT_SUCCESS;
1270 #if ENABLE_SH_MATH_SUPPORT
1271 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1272 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1273 static char *endofname(const char *name)
1281 if (!is_in_name(*p))
1287 static void arith_set_local_var(const char *name, const char *val, int flags)
1289 /* arith code doesnt malloc space, so do it for it */
1290 char *var = xasprintf("%s=%s", name, val);
1291 set_local_var(var, flags, 0);
1299 static int static_get(struct in_str *i)
1308 static int static_peek(struct in_str *i)
1313 #if ENABLE_HUSH_INTERACTIVE
1315 static void cmdedit_set_initial_prompt(void)
1317 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1318 G.PS1 = getenv("PS1");
1325 static const char* setup_prompt_string(int promptmode)
1327 const char *prompt_str;
1328 debug_printf("setup_prompt_string %d ", promptmode);
1329 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1330 /* Set up the prompt */
1331 if (promptmode == 0) { /* PS1 */
1333 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1338 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1339 debug_printf("result '%s'\n", prompt_str);
1343 static void get_user_input(struct in_str *i)
1346 const char *prompt_str;
1348 prompt_str = setup_prompt_string(i->promptmode);
1349 #if ENABLE_FEATURE_EDITING
1350 /* Enable command line editing only while a command line
1351 * is actually being read */
1354 /* buglet: SIGINT will not make new prompt to appear _at once_,
1355 * only after <Enter>. (^C will work) */
1356 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1357 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1358 check_and_run_traps(0);
1359 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1360 i->eof_flag = (r < 0);
1361 if (i->eof_flag) { /* EOF/error detected */
1362 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1363 G.user_input_buf[1] = '\0';
1368 fputs(prompt_str, stdout);
1370 G.user_input_buf[0] = r = fgetc(i->file);
1371 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1372 //do we need check_and_run_traps(0)? (maybe only if stdin)
1373 } while (G.flag_SIGINT);
1374 i->eof_flag = (r == EOF);
1376 i->p = G.user_input_buf;
1379 #endif /* INTERACTIVE */
1381 /* This is the magic location that prints prompts
1382 * and gets data back from the user */
1383 static int file_get(struct in_str *i)
1387 /* If there is data waiting, eat it up */
1388 if (i->p && *i->p) {
1389 #if ENABLE_HUSH_INTERACTIVE
1393 if (i->eof_flag && !*i->p)
1395 /* note: ch is never NUL */
1397 /* need to double check i->file because we might be doing something
1398 * more complicated by now, like sourcing or substituting. */
1399 #if ENABLE_HUSH_INTERACTIVE
1400 if (G_interactive_fd && i->promptme && i->file == stdin) {
1403 } while (!*i->p); /* need non-empty line */
1404 i->promptmode = 1; /* PS2 */
1409 do ch = fgetc(i->file); while (ch == '\0');
1411 debug_printf("file_get: got '%c' %d\n", ch, ch);
1412 #if ENABLE_HUSH_INTERACTIVE
1419 /* All callers guarantee this routine will never
1420 * be used right after a newline, so prompting is not needed.
1422 static int file_peek(struct in_str *i)
1425 if (i->p && *i->p) {
1426 if (i->eof_flag && !i->p[1])
1429 /* note: ch is never NUL */
1431 do ch = fgetc(i->file); while (ch == '\0');
1432 i->eof_flag = (ch == EOF);
1433 i->peek_buf[0] = ch;
1434 i->peek_buf[1] = '\0';
1436 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1440 static void setup_file_in_str(struct in_str *i, FILE *f)
1442 i->peek = file_peek;
1444 #if ENABLE_HUSH_INTERACTIVE
1446 i->promptmode = 0; /* PS1 */
1452 static void setup_string_in_str(struct in_str *i, const char *s)
1454 i->peek = static_peek;
1455 i->get = static_get;
1456 #if ENABLE_HUSH_INTERACTIVE
1458 i->promptmode = 0; /* PS1 */
1468 #define B_CHUNK (32 * sizeof(char*))
1470 static void o_reset_to_empty_unquoted(o_string *o)
1478 static void o_free(o_string *o)
1481 memset(o, 0, sizeof(*o));
1484 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1489 static void o_grow_by(o_string *o, int len)
1491 if (o->length + len > o->maxlen) {
1492 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1493 o->data = xrealloc(o->data, 1 + o->maxlen);
1497 static void o_addchr(o_string *o, int ch)
1499 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1501 o->data[o->length] = ch;
1503 o->data[o->length] = '\0';
1506 static void o_addblock(o_string *o, const char *str, int len)
1509 memcpy(&o->data[o->length], str, len);
1511 o->data[o->length] = '\0';
1515 static void o_addstr(o_string *o, const char *str)
1517 o_addblock(o, str, strlen(str));
1519 static void nommu_addchr(o_string *o, int ch)
1525 #define nommu_addchr(o, str) ((void)0)
1528 static void o_addstr_with_NUL(o_string *o, const char *str)
1530 o_addblock(o, str, strlen(str) + 1);
1533 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
1538 && (*str != '*' && *str != '?' && *str != '[')
1546 /* My analysis of quoting semantics tells me that state information
1547 * is associated with a destination, not a source.
1549 static void o_addqchr(o_string *o, int ch)
1552 char *found = strchr("*?[\\", ch);
1557 o->data[o->length] = '\\';
1560 o->data[o->length] = ch;
1562 o->data[o->length] = '\0';
1565 static void o_addQchr(o_string *o, int ch)
1568 if (o->o_escape && strchr("*?[\\", ch)) {
1570 o->data[o->length] = '\\';
1574 o->data[o->length] = ch;
1576 o->data[o->length] = '\0';
1579 static void o_addQstr(o_string *o, const char *str, int len)
1582 o_addblock(o, str, len);
1588 int ordinary_cnt = strcspn(str, "*?[\\");
1589 if (ordinary_cnt > len) /* paranoia */
1591 o_addblock(o, str, ordinary_cnt);
1592 if (ordinary_cnt == len)
1594 str += ordinary_cnt;
1595 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
1599 if (ch) { /* it is necessarily one of "*?[\\" */
1601 o->data[o->length] = '\\';
1605 o->data[o->length] = ch;
1607 o->data[o->length] = '\0';
1611 /* A special kind of o_string for $VAR and `cmd` expansion.
1612 * It contains char* list[] at the beginning, which is grown in 16 element
1613 * increments. Actual string data starts at the next multiple of 16 * (char*).
1614 * list[i] contains an INDEX (int!) into this string data.
1615 * It means that if list[] needs to grow, data needs to be moved higher up
1616 * but list[i]'s need not be modified.
1617 * NB: remembering how many list[i]'s you have there is crucial.
1618 * o_finalize_list() operation post-processes this structure - calculates
1619 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1621 #if DEBUG_EXPAND || DEBUG_GLOB
1622 static void debug_print_list(const char *prefix, o_string *o, int n)
1624 char **list = (char**)o->data;
1625 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1627 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1628 prefix, list, n, string_start, o->length, o->maxlen);
1630 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1631 o->data + (int)list[i] + string_start,
1632 o->data + (int)list[i] + string_start);
1636 const char *p = o->data + (int)list[n - 1] + string_start;
1637 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
1641 #define debug_print_list(prefix, o, n) ((void)0)
1644 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1645 * in list[n] so that it points past last stored byte so far.
1646 * It returns n+1. */
1647 static int o_save_ptr_helper(o_string *o, int n)
1649 char **list = (char**)o->data;
1653 if (!o->has_empty_slot) {
1654 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1655 string_len = o->length - string_start;
1656 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1657 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
1658 /* list[n] points to string_start, make space for 16 more pointers */
1659 o->maxlen += 0x10 * sizeof(list[0]);
1660 o->data = xrealloc(o->data, o->maxlen + 1);
1661 list = (char**)o->data;
1662 memmove(list + n + 0x10, list + n, string_len);
1663 o->length += 0x10 * sizeof(list[0]);
1665 debug_printf_list("list[%d]=%d string_start=%d\n",
1666 n, string_len, string_start);
1669 /* We have empty slot at list[n], reuse without growth */
1670 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1671 string_len = o->length - string_start;
1672 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1673 n, string_len, string_start);
1674 o->has_empty_slot = 0;
1676 list[n] = (char*)(ptrdiff_t)string_len;
1680 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
1681 static int o_get_last_ptr(o_string *o, int n)
1683 char **list = (char**)o->data;
1684 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1686 return ((int)(ptrdiff_t)list[n-1]) + string_start;
1689 /* o_glob performs globbing on last list[], saving each result
1690 * as a new list[]. */
1691 static int o_glob(o_string *o, int n)
1697 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
1699 return o_save_ptr_helper(o, n);
1700 pattern = o->data + o_get_last_ptr(o, n);
1701 debug_printf_glob("glob pattern '%s'\n", pattern);
1702 if (!glob_needed(pattern)) {
1704 o->length = unbackslash(pattern) - o->data;
1705 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
1706 return o_save_ptr_helper(o, n);
1709 memset(&globdata, 0, sizeof(globdata));
1710 gr = glob(pattern, 0, NULL, &globdata);
1711 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1712 if (gr == GLOB_NOSPACE)
1713 bb_error_msg_and_die("out of memory during glob");
1714 if (gr == GLOB_NOMATCH) {
1715 globfree(&globdata);
1718 if (gr != 0) { /* GLOB_ABORTED ? */
1719 //TODO: testcase for bad glob pattern behavior
1720 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1722 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1723 char **argv = globdata.gl_pathv;
1724 o->length = pattern - o->data; /* "forget" pattern */
1726 o_addstr_with_NUL(o, *argv);
1727 n = o_save_ptr_helper(o, n);
1733 globfree(&globdata);
1735 debug_print_list("o_glob returning", o, n);
1739 /* If o->o_glob == 1, glob the string so far remembered.
1740 * Otherwise, just finish current list[] and start new */
1741 static int o_save_ptr(o_string *o, int n)
1743 if (o->o_glob) { /* if globbing is requested */
1744 /* If o->has_empty_slot, list[n] was already globbed
1745 * (if it was requested back then when it was filled)
1746 * so don't do that again! */
1747 if (!o->has_empty_slot)
1748 return o_glob(o, n); /* o_save_ptr_helper is inside */
1750 return o_save_ptr_helper(o, n);
1753 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
1754 static char **o_finalize_list(o_string *o, int n)
1759 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1761 debug_print_list("finalized", o, n);
1762 debug_printf_expand("finalized n:%d\n", n);
1763 list = (char**)o->data;
1764 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1768 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
1774 /* Expansion can recurse */
1775 #if ENABLE_HUSH_TICK
1776 static int process_command_subs(o_string *dest, const char *s);
1778 static char *expand_string_to_string(const char *str);
1780 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
1781 parse_stream_dquoted(dest, input, dquote_end)
1783 static int parse_stream_dquoted(o_string *as_string,
1785 struct in_str *input,
1788 /* expand_strvec_to_strvec() takes a list of strings, expands
1789 * all variable references within and returns a pointer to
1790 * a list of expanded strings, possibly with larger number
1791 * of strings. (Think VAR="a b"; echo $VAR).
1792 * This new list is allocated as a single malloc block.
1793 * NULL-terminated list of char* pointers is at the beginning of it,
1794 * followed by strings themself.
1795 * Caller can deallocate entire list by single free(list). */
1797 /* Store given string, finalizing the word and starting new one whenever
1798 * we encounter IFS char(s). This is used for expanding variable values.
1799 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
1800 static int expand_on_ifs(o_string *output, int n, const char *str)
1803 int word_len = strcspn(str, G.ifs);
1805 if (output->o_escape || !output->o_glob)
1806 o_addQstr(output, str, word_len);
1807 else /* protect backslashes against globbing up :) */
1808 o_addblock_duplicate_backslash(output, str, word_len);
1811 if (!*str) /* EOL - do not finalize word */
1813 o_addchr(output, '\0');
1814 debug_print_list("expand_on_ifs", output, n);
1815 n = o_save_ptr(output, n);
1816 str += strspn(str, G.ifs); /* skip ifs chars */
1818 debug_print_list("expand_on_ifs[1]", output, n);
1822 /* Helper to expand $((...)) and heredoc body. These act as if
1823 * they are in double quotes, with the exception that they are not :).
1824 * Just the rules are similar: "expand only $var and `cmd`"
1826 * Returns malloced string.
1827 * As an optimization, we return NULL if expansion is not needed.
1829 static char *expand_pseudo_dquoted(const char *str)
1832 struct in_str input;
1833 o_string dest = NULL_O_STRING;
1835 if (strchr(str, '$') == NULL
1836 #if ENABLE_HUSH_TICK
1837 && strchr(str, '`') == NULL
1843 /* We need to expand. Example:
1844 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
1846 setup_string_in_str(&input, str);
1847 parse_stream_dquoted(NULL, &dest, &input, EOF);
1848 //bb_error_msg("'%s' -> '%s'", str, dest.data);
1849 exp_str = expand_string_to_string(dest.data);
1850 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
1851 o_free_unsafe(&dest);
1855 /* Expand all variable references in given string, adding words to list[]
1856 * at n, n+1,... positions. Return updated n (so that list[n] is next one
1857 * to be filled). This routine is extremely tricky: has to deal with
1858 * variables/parameters with whitespace, $* and $@, and constructs like
1859 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
1860 static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
1862 /* or_mask is either 0 (normal case) or 0x80
1863 * (expansion of right-hand side of assignment == 1-element expand.
1864 * It will also do no globbing, and thus we must not backslash-quote!) */
1866 char first_ch, ored_ch;
1874 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
1875 debug_print_list("expand_vars_to_list", output, n);
1876 n = o_save_ptr(output, n);
1877 debug_print_list("expand_vars_to_list[0]", output, n);
1879 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
1880 #if ENABLE_HUSH_TICK
1881 o_string subst_result = NULL_O_STRING;
1883 #if ENABLE_SH_MATH_SUPPORT
1884 char arith_buf[sizeof(arith_t)*3 + 2];
1886 o_addblock(output, arg, p - arg);
1887 debug_print_list("expand_vars_to_list[1]", output, n);
1889 p = strchr(p, SPECIAL_VAR_SYMBOL);
1891 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
1892 /* "$@" is special. Even if quoted, it can still
1893 * expand to nothing (not even an empty string) */
1894 if ((first_ch & 0x7f) != '@')
1895 ored_ch |= first_ch;
1898 switch (first_ch & 0x7f) {
1899 /* Highest bit in first_ch indicates that var is double-quoted */
1901 val = utoa(G.root_pid);
1903 case '!': /* bg pid */
1904 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
1906 case '?': /* exitcode */
1907 val = utoa(G.last_exitcode);
1909 case '#': /* argc */
1910 if (arg[1] != SPECIAL_VAR_SYMBOL)
1911 /* actually, it's a ${#var} */
1913 val = utoa(G.global_argc ? G.global_argc-1 : 0);
1918 if (!G.global_argv[i])
1920 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
1921 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
1922 smallint sv = output->o_escape;
1923 /* unquoted var's contents should be globbed, so don't escape */
1924 output->o_escape = 0;
1925 while (G.global_argv[i]) {
1926 n = expand_on_ifs(output, n, G.global_argv[i]);
1927 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
1928 if (G.global_argv[i++][0] && G.global_argv[i]) {
1929 /* this argv[] is not empty and not last:
1930 * put terminating NUL, start new word */
1931 o_addchr(output, '\0');
1932 debug_print_list("expand_vars_to_list[2]", output, n);
1933 n = o_save_ptr(output, n);
1934 debug_print_list("expand_vars_to_list[3]", output, n);
1937 output->o_escape = sv;
1939 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
1940 * and in this case should treat it like '$*' - see 'else...' below */
1941 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
1943 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1944 if (++i >= G.global_argc)
1946 o_addchr(output, '\0');
1947 debug_print_list("expand_vars_to_list[4]", output, n);
1948 n = o_save_ptr(output, n);
1950 } else { /* quoted $*: add as one word */
1952 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1953 if (!G.global_argv[++i])
1956 o_addchr(output, G.ifs[0]);
1960 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
1961 /* "Empty variable", used to make "" etc to not disappear */
1965 #if ENABLE_HUSH_TICK
1966 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
1969 //TODO: can we just stuff it into "output" directly?
1970 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
1971 process_command_subs(&subst_result, arg);
1972 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
1973 val = subst_result.data;
1976 #if ENABLE_SH_MATH_SUPPORT
1977 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
1978 arith_eval_hooks_t hooks;
1983 arg++; /* skip '+' */
1984 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
1985 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
1987 exp_str = expand_pseudo_dquoted(arg);
1988 hooks.lookupvar = get_local_var_value;
1989 hooks.setvar = arith_set_local_var;
1990 hooks.endofname = endofname;
1991 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
1995 const char *msg = "error in arithmetic";
1998 msg = "exponent less than 0";
2001 msg = "divide by 0";
2004 msg = "expression recursion loop detected";
2009 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
2010 sprintf(arith_buf, arith_t_fmt, res);
2015 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
2017 bool exp_len = false;
2018 bool exp_null = false;
2020 char exp_save = exp_save; /* for compiler */
2021 char exp_op = exp_op; /* for compiler */
2022 char *exp_word = exp_word; /* for compiler */
2026 arg[0] = first_ch & 0x7f;
2028 /* prepare for expansions */
2029 if (var[0] == '#') {
2030 /* handle length expansion ${#var} */
2034 /* maybe handle parameter expansion */
2035 exp_off = strcspn(var, ":-=+?%#");
2039 exp_save = var[exp_off];
2040 exp_null = exp_save == ':';
2041 exp_word = var + exp_off;
2044 exp_op = *exp_word++;
2045 var[exp_off] = '\0';
2049 /* lookup the variable in question */
2050 if (isdigit(var[0])) {
2051 /* handle_dollar() should have vetted var for us */
2053 if (i < G.global_argc)
2054 val = G.global_argv[i];
2055 /* else val remains NULL: $N with too big N */
2057 val = get_local_var_value(var);
2059 /* handle any expansions */
2061 debug_printf_expand("expand: length of '%s' = ", val);
2062 val = utoa(val ? strlen(val) : 0);
2063 debug_printf_expand("%s\n", val);
2064 } else if (exp_off) {
2065 if (exp_op == '%' || exp_op == '#') {
2067 /* we need to do a pattern match */
2070 scan_t scan = pick_scan(exp_op, *exp_word, &zero);
2071 if (exp_op == *exp_word) /* ## or %% */
2073 val = dyn_val = xstrdup(val);
2074 loc = scan(dyn_val, exp_word, zero);
2081 /* we need to do an expansion */
2082 int exp_test = (!val || (exp_null && !val[0]));
2084 exp_test = !exp_test;
2085 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2086 exp_null ? "true" : "false", exp_test);
2088 if (exp_op == '?') {
2089 //TODO: how interactive bash aborts expansion mid-command?
2090 /* ${var?[error_msg_if_unset]} */
2091 /* ${var:?[error_msg_if_unset_or_null]} */
2092 /* mimic bash message */
2093 die_if_script("%s: %s",
2095 exp_word[0] ? exp_word : "parameter null or not set"
2101 if (exp_op == '=') {
2102 /* ${var=[word]} or ${var:=[word]} */
2103 if (isdigit(var[0]) || var[0] == '#') {
2104 /* mimic bash message */
2105 die_if_script("$%s: cannot assign in this way", var);
2108 char *new_var = xasprintf("%s=%s", var, val);
2109 set_local_var(new_var, -1, 0);
2115 var[exp_off] = exp_save;
2119 #if ENABLE_HUSH_TICK
2122 if (!(first_ch & 0x80)) { /* unquoted $VAR */
2123 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
2125 /* unquoted var's contents should be globbed, so don't escape */
2126 smallint sv = output->o_escape;
2127 output->o_escape = 0;
2128 n = expand_on_ifs(output, n, val);
2130 output->o_escape = sv;
2132 } else { /* quoted $VAR, val will be appended below */
2133 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
2136 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
2138 o_addQstr(output, val, strlen(val));
2142 /* Do the check to avoid writing to a const string */
2143 if (*p != SPECIAL_VAR_SYMBOL)
2144 *p = SPECIAL_VAR_SYMBOL;
2146 #if ENABLE_HUSH_TICK
2147 o_free(&subst_result);
2150 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2153 debug_print_list("expand_vars_to_list[a]", output, n);
2154 /* this part is literal, and it was already pre-quoted
2155 * if needed (much earlier), do not use o_addQstr here! */
2156 o_addstr_with_NUL(output, arg);
2157 debug_print_list("expand_vars_to_list[b]", output, n);
2158 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2159 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2162 /* allow to reuse list[n] later without re-growth */
2163 output->has_empty_slot = 1;
2165 o_addchr(output, '\0');
2170 static char **expand_variables(char **argv, int or_mask)
2175 o_string output = NULL_O_STRING;
2177 if (or_mask & 0x100) {
2178 output.o_escape = 1; /* protect against globbing for "$var" */
2179 /* (unquoted $var will temporarily switch it off) */
2186 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
2189 debug_print_list("expand_variables", &output, n);
2191 /* output.data (malloced in one block) gets returned in "list" */
2192 list = o_finalize_list(&output, n);
2193 debug_print_strings("expand_variables[1]", list);
2197 static char **expand_strvec_to_strvec(char **argv)
2199 return expand_variables(argv, 0x100);
2202 /* Used for expansion of right hand of assignments */
2203 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2205 static char *expand_string_to_string(const char *str)
2207 char *argv[2], **list;
2209 argv[0] = (char*)str;
2211 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2213 if (!list[0] || list[1])
2214 bb_error_msg_and_die("BUG in varexp2");
2215 /* actually, just move string 2*sizeof(char*) bytes back */
2216 overlapping_strcpy((char*)list, list[0]);
2217 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2221 /* Used for "eval" builtin */
2222 static char* expand_strvec_to_string(char **argv)
2226 list = expand_variables(argv, 0x80);
2227 /* Convert all NULs to spaces */
2232 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2233 bb_error_msg_and_die("BUG in varexp3");
2234 list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
2238 overlapping_strcpy((char*)list, list[0]);
2239 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2243 static char **expand_assignments(char **argv, int count)
2247 /* Expand assignments into one string each */
2248 for (i = 0; i < count; i++) {
2249 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2257 void re_execute_shell(const char *s, char *argv0, char **argv);
2259 #define clean_up_after_re_execute() ((void)0)
2261 static void reset_traps_to_defaults(void)
2269 for (sig = 0; sig < NSIG; sig++) {
2273 G.traps[sig] = NULL;
2274 /* There is no signal for 0 (EXIT) */
2277 /* there was a trap handler, we are removing it
2278 * (if sig has non-DFL handling,
2279 * we don't need to do anything) */
2280 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
2282 sigdelset(&G.blocked_set, sig);
2286 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
2291 static void re_execute_shell(const char *s, char *g_argv0, char **g_argv) NORETURN;
2292 static void re_execute_shell(const char *s, char *g_argv0, char **g_argv)
2294 char param_buf[sizeof("-$%x:%x:%x:%x") + sizeof(unsigned) * 4];
2295 char *heredoc_argv[4];
2296 struct variable *cur;
2300 if (!g_argv0) { /* heredoc */
2301 argv = heredoc_argv;
2302 argv[0] = (char *) G.argv0_for_re_execing;
2303 argv[1] = (char *) "-<";
2304 argv[2] = (char *) s;
2306 pp = &argv[3]; /* used as pointer to empty environment */
2310 sprintf(param_buf, "-$%x:%x:%x" USE_HUSH_LOOPS(":%x")
2311 , (unsigned) G.root_pid
2312 , (unsigned) G.last_bg_pid
2313 , (unsigned) G.last_exitcode
2314 USE_HUSH_LOOPS(, G.depth_of_loop)
2316 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...>
2317 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
2320 for (cur = G.top_var; cur; cur = cur->next) {
2321 if (!cur->flg_export || cur->flg_read_only)
2327 G.argv_from_re_execing = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
2328 *pp++ = (char *) G.argv0_for_re_execing;
2330 for (cur = G.top_var; cur; cur = cur->next) {
2331 if (cur->varstr == hush_version_str)
2333 if (cur->flg_read_only) {
2334 *pp++ = (char *) "-R";
2335 *pp++ = cur->varstr;
2336 } else if (!cur->flg_export) {
2337 *pp++ = (char *) "-V";
2338 *pp++ = cur->varstr;
2341 //TODO: pass functions
2342 /* We can pass activated traps here. Say, -Tnn:trap_string
2344 * However, POSIX says that subshells reset signals with traps
2346 * I tested bash-3.2 and it not only does that with true subshells
2347 * of the form ( list ), but with any forked children shells.
2348 * I set trap "echo W" WINCH; and then tried:
2350 * { echo 1; sleep 20; echo 2; } &
2351 * while true; do echo 1; sleep 20; echo 2; break; done &
2352 * true | { echo 1; sleep 20; echo 2; } | cat
2354 * In all these cases sending SIGWINCH to the child shell
2355 * did not run the trap. If I add trap "echo V" WINCH;
2356 * _inside_ group (just before echo 1), it works.
2358 * I conclude it means we don't need to pass active traps here.
2359 * exec syscall below resets them to SIG_DFL for us.
2361 *pp++ = (char *) "-c";
2366 /* *pp = NULL; - is already there */
2370 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
2371 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2372 execve(bb_busybox_exec_path, argv, pp);
2373 /* Fallback. Useful for init=/bin/hush usage etc */
2374 if (argv[0][0] == '/')
2375 execve(argv[0], argv, pp);
2376 xfunc_error_retval = 127;
2377 bb_error_msg_and_die("can't re-execute the shell");
2380 static void clean_up_after_re_execute(void)
2382 char **pp = G.argv_from_re_execing;
2384 /* Must match re_execute_shell's allocations (if any) */
2386 G.argv_from_re_execing = NULL;
2389 #endif /* !BB_MMU */
2392 static void setup_heredoc(struct redir_struct *redir)
2394 struct fd_pair pair;
2397 /* the _body_ of heredoc (misleading field name) */
2398 const char *heredoc = redir->rd_filename;
2402 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
2403 expanded = expand_pseudo_dquoted(heredoc);
2407 len = strlen(heredoc);
2409 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
2411 xmove_fd(pair.rd, redir->rd_fd);
2413 /* Try writing without forking. Newer kernels have
2414 * dynamically growing pipes. Must use non-blocking write! */
2417 written = write(pair.wr, heredoc, len);
2428 ndelay_off(pair.wr);
2430 /* Okay, pipe buffer was not big enough */
2431 /* Note: we must not create a stray child (bastard? :)
2432 * for the unsuspecting parent process. Child creates a grandchild
2433 * and exits before parent execs the process which consumes heredoc
2434 * (that exec happens after we return from this function) */
2437 bb_perror_msg_and_die("vfork");
2440 pid = BB_MMU ? fork() : vfork();
2442 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
2446 close(redir->rd_fd); /* read side of the pipe */
2448 full_write(pair.wr, heredoc, len); /* may loop or block */
2451 /* Delegate blocking writes to another process */
2452 disable_restore_tty_pgrp_on_exit();
2453 xmove_fd(pair.wr, STDOUT_FILENO);
2454 re_execute_shell(heredoc, NULL, NULL);
2458 enable_restore_tty_pgrp_on_exit();
2459 clean_up_after_re_execute();
2462 wait(NULL); /* wait till child has died */
2465 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
2466 * and stderr if they are redirected. */
2467 static int setup_redirects(struct command *prog, int squirrel[])
2470 struct redir_struct *redir;
2472 for (redir = prog->redirects; redir; redir = redir->next) {
2473 if (redir->rd_type == REDIRECT_HEREDOC2) {
2474 /* rd_fd<<HERE case */
2475 if (squirrel && redir->rd_fd < 3) {
2476 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2478 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
2480 debug_printf_parse("set heredoc '%s'\n",
2481 redir->rd_filename);
2482 setup_heredoc(redir);
2486 if (redir->rd_dup == REDIRFD_TO_FILE) {
2487 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
2489 if (redir->rd_filename == NULL) {
2490 /* Something went wrong in the parse.
2491 * Pretend it didn't happen */
2492 bb_error_msg("bug in redirect parse");
2495 mode = redir_table[redir->rd_type].mode;
2496 p = expand_string_to_string(redir->rd_filename);
2497 openfd = open_or_warn(p, mode);
2500 /* this could get lost if stderr has been redirected, but
2501 * bash and ash both lose it as well (though zsh doesn't!) */
2502 //what the above comment tries to say?
2506 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
2507 openfd = redir->rd_dup;
2510 if (openfd != redir->rd_fd) {
2511 if (squirrel && redir->rd_fd < 3) {
2512 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2514 if (openfd == REDIRFD_CLOSE) {
2515 /* "n>-" means "close me" */
2516 close(redir->rd_fd);
2518 xdup2(openfd, redir->rd_fd);
2519 if (redir->rd_dup == REDIRFD_TO_FILE)
2527 static void restore_redirects(int squirrel[])
2530 for (i = 0; i < 3; i++) {
2533 /* We simply die on error */
2541 #define free_pipe_list(head, indent) free_pipe_list(head)
2542 #define free_pipe(pi, indent) free_pipe(pi)
2544 static void free_pipe_list(struct pipe *head, int indent);
2546 /* Return code is the exit status of the pipe */
2547 static void free_pipe(struct pipe *pi, int indent)
2550 struct command *command;
2551 struct redir_struct *r, *rnext;
2554 if (pi->stopped_cmds > 0) /* why? */
2556 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2557 for (i = 0; i < pi->num_cmds; i++) {
2558 command = &pi->cmds[i];
2559 debug_printf_clean("%s command %d:\n", indenter(indent), i);
2560 if (command->argv) {
2561 for (a = 0, p = command->argv; *p; a++, p++) {
2562 debug_printf_clean("%s argv[%d] = %s\n",
2563 indenter(indent), a, *p);
2565 free_strings(command->argv);
2566 command->argv = NULL;
2568 /* not "else if": on syntax error, we may have both! */
2569 if (command->group) {
2570 debug_printf_clean("%s begin group (grp_type:%d)\n",
2571 indenter(indent), command->grp_type);
2572 free_pipe_list(command->group, indent+3);
2573 debug_printf_clean("%s end group\n", indenter(indent));
2574 command->group = NULL;
2577 free(command->group_as_string);
2578 command->group_as_string = NULL;
2580 for (r = command->redirects; r; r = rnext) {
2581 debug_printf_clean("%s redirect %d%s", indenter(indent),
2582 r->fd, redir_table[r->rd_type].descrip);
2583 /* guard against the case >$FOO, where foo is unset or blank */
2584 if (r->rd_filename) {
2585 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2586 free(r->rd_filename);
2587 r->rd_filename = NULL;
2589 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2593 command->redirects = NULL;
2595 free(pi->cmds); /* children are an array, they get freed all at once */
2603 static void free_pipe_list(struct pipe *head, int indent)
2605 struct pipe *pi, *next;
2607 for (pi = head; pi; pi = next) {
2609 debug_printf_clean("%s pipe reserved word %d\n", indenter(indent), pi->res_word);
2611 free_pipe(pi, indent);
2612 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
2614 /*pi->next = NULL;*/
2620 static int run_list(struct pipe *pi);
2622 static const struct built_in_command* find_builtin(const char *name)
2624 const struct built_in_command *x;
2625 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2626 if (strcmp(name, x->cmd) != 0)
2628 debug_printf_exec("found builtin '%s'\n", name);
2634 #if ENABLE_HUSH_FUNCTIONS
2635 static const struct function *find_function(const char *name)
2637 const struct function *funcp = G.top_func;
2639 if (strcmp(name, funcp->name) == 0) {
2642 funcp = funcp->next;
2644 debug_printf_exec("found function '%s'\n", name);
2648 static void exec_function(const struct function *funcp, char **argv) NORETURN;
2649 static void exec_function(const struct function *funcp, char **argv)
2654 argv[0] = G.global_argv[0];
2655 G.global_argv = argv;
2659 n = run_list(funcp->body);
2663 re_execute_shell(funcp->body_as_string, G.global_argv[0], argv + 1);
2667 static int run_function(const struct function *funcp, char **argv)
2672 smallint sv_g_malloced;
2677 sv_g_malloced = G.global_args_malloced;
2678 sv_g_argc = G.global_argc;
2679 sv_g_argv = G.global_argv;
2686 argv[0] = G.global_argv[0]; /* retain $0 */
2687 G.global_args_malloced = 0;
2689 G.global_argv = argv;
2691 n = run_list(funcp->body);
2693 if (G.global_args_malloced) {
2694 /* function ran "set -- arg1 arg2 ..." */
2698 free(G.global_argv);
2702 G.global_args_malloced = sv_g_malloced;
2703 G.global_argc = sv_g_argc;
2704 G.global_argv = sv_g_argv;
2712 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
2713 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
2714 #define pseudo_exec(nommu_save, command, argv_expanded) \
2715 pseudo_exec(command, argv_expanded)
2718 /* Called after [v]fork() in run_pipe, or from builtin_exec.
2720 * XXX no exit() here. If you don't exec, use _exit instead.
2721 * The at_exit handlers apparently confuse the calling process,
2722 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
2723 static void pseudo_exec_argv(nommu_save_t *nommu_save,
2724 char **argv, int assignment_cnt,
2725 char **argv_expanded) NORETURN;
2726 static void pseudo_exec_argv(nommu_save_t *nommu_save,
2727 char **argv, int assignment_cnt,
2728 char **argv_expanded)
2732 /* Case when we are here: ... | var=val | ... */
2733 if (!argv[assignment_cnt])
2734 _exit(EXIT_SUCCESS);
2736 new_env = expand_assignments(argv, assignment_cnt);
2738 putenv_all(new_env);
2739 free(new_env); /* optional */
2741 nommu_save->new_env = new_env;
2742 nommu_save->old_env = putenv_all_and_save_old(new_env);
2744 if (argv_expanded) {
2745 argv = argv_expanded;
2747 argv = expand_strvec_to_strvec(argv + assignment_cnt);
2749 nommu_save->argv = argv;
2753 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
2754 if (strchr(argv[0], '/') != NULL)
2758 /* On NOMMU, we must never block!
2759 * Example: { sleep 99999 | read line } & echo Ok
2760 * read builtin will block on read syscall, leaving parent blocked
2761 * in vfork. Therefore we can't do this:
2764 /* Check if the command matches any of the builtins.
2765 * Depending on context, this might be redundant. But it's
2766 * easier to waste a few CPU cycles than it is to figure out
2767 * if this is one of those cases.
2771 const struct built_in_command *x = find_builtin(argv[0]);
2773 rcode = x->function(argv);
2779 #if ENABLE_HUSH_FUNCTIONS
2780 /* Check if the command matches any functions */
2782 const struct function *funcp = find_function(argv[0]);
2784 exec_function(funcp, argv);
2789 #if ENABLE_FEATURE_SH_STANDALONE
2790 /* Check if the command matches any busybox applets */
2792 int a = find_applet_by_name(argv[0]);
2794 # if BB_MMU /* see above why on NOMMU it is not allowed */
2795 if (APPLET_IS_NOEXEC(a)) {
2796 debug_printf_exec("running applet '%s'\n", argv[0]);
2797 run_applet_no_and_exit(a, argv);
2800 /* Re-exec ourselves */
2801 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
2802 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2803 execv(bb_busybox_exec_path, argv);
2804 /* If they called chroot or otherwise made the binary no longer
2805 * executable, fall through */
2810 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
2813 debug_printf_exec("execing '%s'\n", argv[0]);
2814 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2815 execvp(argv[0], argv);
2816 bb_perror_msg("can't exec '%s'", argv[0]);
2817 _exit(EXIT_FAILURE);
2820 /* Called after [v]fork() in run_pipe
2822 static void pseudo_exec(nommu_save_t *nommu_save,
2823 struct command *command,
2824 char **argv_expanded) NORETURN;
2825 static void pseudo_exec(nommu_save_t *nommu_save,
2826 struct command *command,
2827 char **argv_expanded)
2829 if (command->argv) {
2830 pseudo_exec_argv(nommu_save, command->argv,
2831 command->assignment_cnt, argv_expanded);
2834 if (command->group) {
2835 /* Cases when we are here:
2838 * ... | ( list ) | ...
2839 * ... | { list } | ...
2843 debug_printf_exec("pseudo_exec: run_list\n");
2844 reset_traps_to_defaults();
2845 rcode = run_list(command->group);
2846 /* OK to leak memory by not calling free_pipe_list,
2847 * since this process is about to exit */
2850 re_execute_shell(command->group_as_string,
2856 /* Case when we are here: ... | >file */
2857 debug_printf_exec("pseudo_exec'ed null command\n");
2858 _exit(EXIT_SUCCESS);
2862 static const char *get_cmdtext(struct pipe *pi)
2868 /* This is subtle. ->cmdtext is created only on first backgrounding.
2869 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
2870 * On subsequent bg argv is trashed, but we won't use it */
2873 argv = pi->cmds[0].argv;
2874 if (!argv || !argv[0]) {
2875 pi->cmdtext = xzalloc(1);
2880 do len += strlen(*argv) + 1; while (*++argv);
2881 pi->cmdtext = p = xmalloc(len);
2882 argv = pi->cmds[0].argv;
2884 len = strlen(*argv);
2885 memcpy(p, *argv, len);
2893 static void insert_bg_job(struct pipe *pi)
2895 struct pipe *thejob;
2898 /* Linear search for the ID of the job to use */
2900 for (thejob = G.job_list; thejob; thejob = thejob->next)
2901 if (thejob->jobid >= pi->jobid)
2902 pi->jobid = thejob->jobid + 1;
2904 /* Add thejob to the list of running jobs */
2906 thejob = G.job_list = xmalloc(sizeof(*thejob));
2908 for (thejob = G.job_list; thejob->next; thejob = thejob->next)
2910 thejob->next = xmalloc(sizeof(*thejob));
2911 thejob = thejob->next;
2914 /* Physically copy the struct job */
2915 memcpy(thejob, pi, sizeof(struct pipe));
2916 thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
2917 /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
2918 for (i = 0; i < pi->num_cmds; i++) {
2919 // TODO: do we really need to have so many fields which are just dead weight
2920 // at execution stage?
2921 thejob->cmds[i].pid = pi->cmds[i].pid;
2922 /* all other fields are not used and stay zero */
2924 thejob->next = NULL;
2925 thejob->cmdtext = xstrdup(get_cmdtext(pi));
2927 /* We don't wait for background thejobs to return -- append it
2928 to the list of backgrounded thejobs and leave it alone */
2929 if (G_interactive_fd)
2930 printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
2931 G.last_bg_pid = thejob->cmds[0].pid;
2932 G.last_jobid = thejob->jobid;
2935 static void remove_bg_job(struct pipe *pi)
2937 struct pipe *prev_pipe;
2939 if (pi == G.job_list) {
2940 G.job_list = pi->next;
2942 prev_pipe = G.job_list;
2943 while (prev_pipe->next != pi)
2944 prev_pipe = prev_pipe->next;
2945 prev_pipe->next = pi->next;
2948 G.last_jobid = G.job_list->jobid;
2953 /* Remove a backgrounded job */
2954 static void delete_finished_bg_job(struct pipe *pi)
2957 pi->stopped_cmds = 0;
2963 /* Check to see if any processes have exited -- if they
2964 * have, figure out why and see if a job has completed */
2965 static int checkjobs(struct pipe* fg_pipe)
2975 debug_printf_jobs("checkjobs %p\n", fg_pipe);
2978 // if (G.handled_SIGCHLD == G.count_SIGCHLD)
2979 // /* avoid doing syscall, nothing there anyway */
2982 attributes = WUNTRACED;
2983 if (fg_pipe == NULL)
2984 attributes |= WNOHANG;
2986 /* Do we do this right?
2987 * bash-3.00# sleep 20 | false
2989 * [3]+ Stopped sleep 20 | false
2990 * bash-3.00# echo $?
2991 * 1 <========== bg pipe is not fully done, but exitcode is already known!
2994 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
2995 //are stopped. Testcase: "cat | cat" in a script (not on command line)
2996 // + killall -STOP cat
3003 // i = G.count_SIGCHLD;
3004 childpid = waitpid(-1, &status, attributes);
3005 if (childpid <= 0) {
3006 if (childpid && errno != ECHILD)
3007 bb_perror_msg("waitpid");
3008 // else /* Until next SIGCHLD, waitpid's are useless */
3009 // G.handled_SIGCHLD = i;
3012 dead = WIFEXITED(status) || WIFSIGNALED(status);
3015 if (WIFSTOPPED(status))
3016 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
3017 childpid, WSTOPSIG(status), WEXITSTATUS(status));
3018 if (WIFSIGNALED(status))
3019 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
3020 childpid, WTERMSIG(status), WEXITSTATUS(status));
3021 if (WIFEXITED(status))
3022 debug_printf_jobs("pid %d exited, exitcode %d\n",
3023 childpid, WEXITSTATUS(status));
3025 /* Were we asked to wait for fg pipe? */
3027 for (i = 0; i < fg_pipe->num_cmds; i++) {
3028 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
3029 if (fg_pipe->cmds[i].pid != childpid)
3031 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
3033 fg_pipe->cmds[i].pid = 0;
3034 fg_pipe->alive_cmds--;
3035 if (i == fg_pipe->num_cmds - 1) {
3036 /* last process gives overall exitstatus */
3037 rcode = WEXITSTATUS(status);
3038 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
3041 fg_pipe->cmds[i].is_stopped = 1;
3042 fg_pipe->stopped_cmds++;
3044 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
3045 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
3046 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
3047 /* All processes in fg pipe have exited/stopped */
3049 if (fg_pipe->alive_cmds)
3050 insert_bg_job(fg_pipe);
3054 /* There are still running processes in the fg pipe */
3055 goto wait_more; /* do waitpid again */
3057 /* it wasnt fg_pipe, look for process in bg pipes */
3061 /* We asked to wait for bg or orphaned children */
3062 /* No need to remember exitcode in this case */
3063 for (pi = G.job_list; pi; pi = pi->next) {
3064 for (i = 0; i < pi->num_cmds; i++) {
3065 if (pi->cmds[i].pid == childpid)
3066 goto found_pi_and_prognum;
3069 /* Happens when shell is used as init process (init=/bin/sh) */
3070 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
3071 continue; /* do waitpid again */
3073 found_pi_and_prognum:
3076 pi->cmds[i].pid = 0;
3078 if (!pi->alive_cmds) {
3079 if (G_interactive_fd)
3080 printf(JOB_STATUS_FORMAT, pi->jobid,
3081 "Done", pi->cmdtext);
3082 delete_finished_bg_job(pi);
3086 pi->cmds[i].is_stopped = 1;
3090 } /* while (waitpid succeeds)... */
3096 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
3099 int rcode = checkjobs(fg_pipe);
3100 /* Job finished, move the shell to the foreground */
3101 p = getpgid(0); /* pgid of our process */
3102 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
3103 tcsetpgrp(G_interactive_fd, p);
3108 /* Start all the jobs, but don't wait for anything to finish.
3111 * Return code is normally -1, when the caller has to wait for children
3112 * to finish to determine the exit status of the pipe. If the pipe
3113 * is a simple builtin command, however, the action is done by the
3114 * time run_pipe returns, and the exit code is provided as the
3117 * Returns -1 only if started some children. IOW: we have to
3118 * mask out retvals of builtins etc with 0xff!
3120 * The only case when we do not need to [v]fork is when the pipe
3121 * is single, non-backgrounded, non-subshell command. Examples:
3122 * cmd ; ... { list } ; ...
3123 * cmd && ... { list } && ...
3124 * cmd || ... { list } || ...
3125 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
3126 * or (if SH_STANDALONE) an applet, and we can run the { list }
3127 * with run_list(). If it isn't one of these, we fork and exec cmd.
3129 * Cases when we must fork:
3130 * non-single: cmd | cmd
3131 * backgrounded: cmd & { list } &
3132 * subshell: ( list ) [&]
3134 static int run_pipe(struct pipe *pi)
3136 static const char *const null_ptr = NULL;
3139 int pipefds[2]; /* pipefds[0] is for reading */
3140 struct command *command;
3141 char **argv_expanded;
3144 /* it is not always needed, but we aim to smaller code */
3145 int squirrel[] = { -1, -1, -1 };
3148 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
3150 USE_HUSH_JOB(pi->pgrp = -1;)
3151 pi->stopped_cmds = 0;
3152 command = &(pi->cmds[0]);
3153 argv_expanded = NULL;
3155 if (pi->num_cmds != 1
3156 || pi->followup == PIPE_BG
3157 || command->grp_type == GRP_SUBSHELL
3164 debug_printf_exec(": group:%p argv:'%s'\n",
3165 command->group, command->argv ? command->argv[0] : "NONE");
3167 if (command->group) {
3168 #if ENABLE_HUSH_FUNCTIONS
3169 if (command->grp_type == GRP_FUNCTION) {
3170 /* "executing" func () { list } */
3171 struct function *funcp;
3172 struct function **funcpp = &G.top_func;
3174 while ((funcp = *funcpp) != NULL) {
3175 if (strcmp(funcp->name, command->argv[0]) == 0) {
3176 debug_printf_exec("replacing function '%s'\n", funcp->name);
3178 free_pipe_list(funcp->body, /* indent: */ 0);
3181 funcpp = &funcp->next;
3183 debug_printf_exec("remembering new function '%s'\n", command->argv[0]);
3184 funcp = *funcpp = xzalloc(sizeof(*funcp));
3185 /*funcp->next = NULL;*/
3187 funcp->name = command->argv[0];
3188 funcp->body = command->group;
3190 funcp->body_as_string = command->group_as_string;
3191 command->group_as_string = NULL;
3193 command->group = NULL;
3194 command->argv[0] = NULL;
3195 free_strings(command->argv);
3196 command->argv = NULL;
3197 /* note: if we are in a loop, future "executions"
3198 * of func def will see it as null command since
3199 * command->group == NULL and command->argv == NULL */
3200 //this isn't exactly right: while...do f1() {a;}; f1; f1 {b;}; done
3201 //second loop will execute b!
3203 return EXIT_SUCCESS;
3207 debug_printf("non-subshell group\n");
3208 rcode = 1; /* exitcode if redir failed */
3209 if (setup_redirects(command, squirrel) == 0) {
3210 debug_printf_exec(": run_list\n");
3211 rcode = run_list(command->group) & 0xff;
3212 debug_printf_exec("run_pipe return %d\n", rcode);
3214 restore_redirects(squirrel);
3215 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3219 argv = command->argv ? command->argv : (char **) &null_ptr;
3221 const struct built_in_command *x;
3222 #if ENABLE_HUSH_FUNCTIONS
3223 const struct function *funcp;
3227 char **new_env = NULL;
3228 char **old_env = NULL;
3230 if (argv[command->assignment_cnt] == NULL) {
3231 /* Assignments, but no command */
3232 /* Ensure redirects take effect. Try "a=t >file" */
3233 rcode = setup_redirects(command, squirrel);
3234 restore_redirects(squirrel);
3235 /* Set shell variables */
3237 p = expand_string_to_string(*argv);
3238 debug_printf_exec("set shell var:'%s'->'%s'\n",
3240 set_local_var(p, 0, 0);
3243 /* Do we need to flag set_local_var() errors?
3244 * "assignment to readonly var" and "putenv error"
3246 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3250 /* Expand the rest into (possibly) many strings each */
3251 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
3253 x = find_builtin(argv_expanded[0]);
3254 #if ENABLE_HUSH_FUNCTIONS
3257 funcp = find_function(argv_expanded[0]);
3261 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
3262 debug_printf("exec with redirects only\n");
3263 rcode = setup_redirects(command, NULL);
3264 goto clean_up_and_ret1;
3267 /* XXX setup_redirects acts on file descriptors, not FILEs.
3268 * This is perfect for work that comes after exec().
3269 * Is it really safe for inline use? Experimentally,
3270 * things seem to work with glibc. */
3271 rcode = setup_redirects(command, squirrel);
3273 new_env = expand_assignments(argv, command->assignment_cnt);
3274 old_env = putenv_all_and_save_old(new_env);
3276 debug_printf_exec(": builtin '%s' '%s'...\n",
3277 x->cmd, argv_expanded[1]);
3278 rcode = x->function(argv_expanded) & 0xff;
3280 #if ENABLE_HUSH_FUNCTIONS
3282 debug_printf_exec(": function '%s' '%s'...\n",
3283 funcp->name, argv_expanded[1]);
3284 rcode = run_function(funcp, argv_expanded) & 0xff;
3288 #if ENABLE_FEATURE_SH_STANDALONE
3291 restore_redirects(squirrel);
3292 free_strings_and_unsetenv(new_env, 1);
3293 putenv_all(old_env);
3294 /* Free the pointers, but the strings themselves
3295 * are in environ now, don't use free_strings! */
3298 free(argv_expanded);
3299 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3300 debug_printf_exec("run_pipe return %d\n", rcode);
3304 #if ENABLE_FEATURE_SH_STANDALONE
3305 i = find_applet_by_name(argv_expanded[0]);
3306 if (i >= 0 && APPLET_IS_NOFORK(i)) {
3307 rcode = setup_redirects(command, squirrel);
3309 save_nofork_data(&G.nofork_save);
3310 new_env = expand_assignments(argv, command->assignment_cnt);
3311 old_env = putenv_all_and_save_old(new_env);
3312 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
3313 argv_expanded[0], argv_expanded[1]);
3314 rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
3316 goto clean_up_and_ret;
3319 /* It is neither builtin nor applet. We must fork. */
3323 /* NB: argv_expanded may already be created, and that
3324 * might include `cmd` runs! Do not rerun it! We *must*
3325 * use argv_expanded if it's non-NULL */
3327 /* Going to fork a child per each pipe member */
3331 for (i = 0; i < pi->num_cmds; i++) {
3333 volatile nommu_save_t nommu_save;
3334 nommu_save.new_env = NULL;
3335 nommu_save.old_env = NULL;
3336 nommu_save.argv = NULL;
3338 command = &(pi->cmds[i]);
3339 if (command->argv) {
3340 debug_printf_exec(": pipe member '%s' '%s'...\n",
3341 command->argv[0], command->argv[1]);
3343 debug_printf_exec(": pipe member with no argv\n");
3346 /* pipes are inserted between pairs of commands */
3349 if ((i + 1) < pi->num_cmds)
3352 command->pid = BB_MMU ? fork() : vfork();
3353 if (!command->pid) { /* child */
3355 disable_restore_tty_pgrp_on_exit();
3357 /* Every child adds itself to new process group
3358 * with pgid == pid_of_first_child_in_pipe */
3359 if (G.run_list_level == 1 && G_interactive_fd) {
3362 if (pgrp < 0) /* true for 1st process only */
3364 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
3365 /* We do it in *every* child, not just first,
3367 tcsetpgrp(G_interactive_fd, pgrp);
3371 xmove_fd(nextin, 0);
3372 xmove_fd(pipefds[1], 1); /* write end */
3374 close(pipefds[0]); /* read end */
3375 /* Like bash, explicit redirects override pipes,
3376 * and the pipe fd is available for dup'ing. */
3377 if (setup_redirects(command, NULL))
3380 /* Restore default handlers just prior to exec */
3381 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
3383 /* Stores to nommu_save list of env vars putenv'ed
3384 * (NOMMU, on MMU we don't need that) */
3385 /* cast away volatility... */
3386 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
3387 /* pseudo_exec() does not return */
3390 /* parent or error */
3391 enable_restore_tty_pgrp_on_exit();
3393 /* Clean up after vforked child */
3394 clean_up_after_re_execute();
3395 free(nommu_save.argv);
3396 free_strings_and_unsetenv(nommu_save.new_env, 1);
3397 putenv_all(nommu_save.old_env);
3398 /* Free the pointers, but the strings themselves
3399 * are in environ now, don't use free_strings! */
3400 free(nommu_save.old_env);
3402 free(argv_expanded);
3403 argv_expanded = NULL;
3404 if (command->pid < 0) { /* [v]fork failed */
3405 /* Clearly indicate, was it fork or vfork */
3406 bb_perror_msg(BB_MMU ? "fork" : "vfork");
3410 /* Second and next children need to know pid of first one */
3412 pi->pgrp = command->pid;
3418 if ((i + 1) < pi->num_cmds)
3419 close(pipefds[1]); /* write end */
3420 /* Pass read (output) pipe end to next iteration */
3421 nextin = pipefds[0];
3424 if (!pi->alive_cmds) {
3425 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
3429 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
3433 #ifndef debug_print_tree
3434 static void debug_print_tree(struct pipe *pi, int lvl)
3436 static const char *const PIPE[] = {
3442 static const char *RES[] = {
3443 [RES_NONE ] = "NONE" ,
3446 [RES_THEN ] = "THEN" ,
3447 [RES_ELIF ] = "ELIF" ,
3448 [RES_ELSE ] = "ELSE" ,
3451 #if ENABLE_HUSH_LOOPS
3452 [RES_FOR ] = "FOR" ,
3453 [RES_WHILE] = "WHILE",
3454 [RES_UNTIL] = "UNTIL",
3456 [RES_DONE ] = "DONE" ,
3458 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3461 #if ENABLE_HUSH_CASE
3462 [RES_CASE ] = "CASE" ,
3463 [RES_MATCH] = "MATCH",
3464 [RES_CASEI] = "CASEI",
3465 [RES_ESAC ] = "ESAC" ,
3467 [RES_XXXX ] = "XXXX" ,
3468 [RES_SNTX ] = "SNTX" ,
3470 static const char *const GRPTYPE[] = {
3473 #if ENABLE_HUSH_FUNCTIONS
3482 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3483 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3485 while (prn < pi->num_cmds) {
3486 struct command *command = &pi->cmds[prn];
3487 char **argv = command->argv;
3489 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
3491 command->assignment_cnt);
3492 if (command->group) {
3493 fprintf(stderr, " group %s: (argv=%p)\n",
3494 GRPTYPE[command->grp_type],
3496 debug_print_tree(command->group, lvl+1);
3500 if (argv) while (*argv) {
3501 fprintf(stderr, " '%s'", *argv);
3504 fprintf(stderr, "\n");
3513 /* NB: called by pseudo_exec, and therefore must not modify any
3514 * global data until exec/_exit (we can be a child after vfork!) */
3515 static int run_list(struct pipe *pi)
3517 #if ENABLE_HUSH_CASE
3518 char *case_word = NULL;
3520 #if ENABLE_HUSH_LOOPS
3521 struct pipe *loop_top = NULL;
3522 char *for_varname = NULL;
3523 char **for_lcur = NULL;
3524 char **for_list = NULL;
3526 smallint last_followup;
3528 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
3529 smalluint cond_code = 0;
3531 enum { cond_code = 0 };
3534 smallint rword; /* enum reserved_style */
3535 smallint last_rword; /* ditto */
3538 debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
3540 #if ENABLE_HUSH_LOOPS
3541 /* Check syntax for "for" */
3542 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
3543 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
3545 /* current word is FOR or IN (BOLD in comments below) */
3546 if (cpipe->next == NULL) {
3547 syntax_error("malformed for");
3548 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
3551 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
3552 if (cpipe->next->res_word == RES_DO)
3554 /* next word is not "do". It must be "in" then ("FOR v in ...") */
3555 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
3556 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
3558 syntax_error("malformed for");
3559 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
3565 /* Past this point, all code paths should jump to ret: label
3566 * in order to return, no direct "return" statements please.
3567 * This helps to ensure that no memory is leaked. */
3569 ////TODO: ctrl-Z handling needs re-thinking and re-testing
3572 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
3573 * We are saving state before entering outermost list ("while...done")
3574 * so that ctrl-Z will correctly background _entire_ outermost list,
3575 * not just a part of it (like "sleep 1 | exit 2") */
3576 if (++G.run_list_level == 1 && G_interactive_fd) {
3577 if (sigsetjmp(G.toplevel_jb, 1)) {
3578 /* ctrl-Z forked and we are parent; or ctrl-C.
3579 * Sighandler has longjmped us here */
3580 signal(SIGINT, SIG_IGN);
3581 signal(SIGTSTP, SIG_IGN);
3582 /* Restore level (we can be coming from deep inside
3584 G.run_list_level = 1;
3585 #if ENABLE_FEATURE_SH_STANDALONE
3586 if (G.nofork_save.saved) { /* if save area is valid */
3587 debug_printf_jobs("exiting nofork early\n");
3588 restore_nofork_data(&G.nofork_save);
3591 //// if (G.ctrl_z_flag) {
3592 //// /* ctrl-Z has forked and stored pid of the child in pi->pid.
3593 //// * Remember this child as background job */
3594 //// insert_bg_job(pi);
3596 /* ctrl-C. We just stop doing whatever we were doing */
3599 USE_HUSH_LOOPS(loop_top = NULL;)
3600 USE_HUSH_LOOPS(G.depth_of_loop = 0;)
3604 //// /* ctrl-Z handler will store pid etc in pi */
3605 //// G.toplevel_list = pi;
3606 //// G.ctrl_z_flag = 0;
3607 #if ENABLE_FEATURE_SH_STANDALONE
3608 G.nofork_save.saved = 0; /* in case we will run a nofork later */
3610 //// signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
3611 //// signal(SIGINT, handler_ctrl_c);
3617 last_rword = RES_XXXX;
3619 last_followup = PIPE_SEQ;
3620 rcode = G.last_exitcode;
3622 /* Go through list of pipes, (maybe) executing them. */
3623 for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
3627 IF_HAS_KEYWORDS(rword = pi->res_word;)
3628 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
3629 rword, cond_code, last_rword);
3630 #if ENABLE_HUSH_LOOPS
3631 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
3632 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
3634 /* start of a loop: remember where loop starts */
3639 /* Still in the same "if...", "then..." or "do..." branch? */
3640 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
3641 if ((rcode == 0 && last_followup == PIPE_OR)
3642 || (rcode != 0 && last_followup == PIPE_AND)
3644 /* It is "<true> || CMD" or "<false> && CMD"
3645 * and we should not execute CMD */
3646 debug_printf_exec("skipped cmd because of || or &&\n");
3647 last_followup = pi->followup;
3651 last_followup = pi->followup;
3652 IF_HAS_KEYWORDS(last_rword = rword;)
3655 if (rword == RES_THEN) {
3656 /* if false; then ... fi has exitcode 0! */
3657 G.last_exitcode = rcode = EXIT_SUCCESS;
3658 /* "if <false> THEN cmd": skip cmd */
3662 if (rword == RES_ELSE || rword == RES_ELIF) {
3663 /* "if <true> then ... ELSE/ELIF cmd":
3664 * skip cmd and all following ones */
3669 #if ENABLE_HUSH_LOOPS
3670 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
3672 /* first loop through for */
3674 static const char encoded_dollar_at[] ALIGN1 = {
3675 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
3676 }; /* encoded representation of "$@" */
3677 static const char *const encoded_dollar_at_argv[] = {
3678 encoded_dollar_at, NULL
3679 }; /* argv list with one element: "$@" */
3682 vals = (char**)encoded_dollar_at_argv;
3683 if (pi->next->res_word == RES_IN) {
3684 /* if no variable values after "in" we skip "for" */
3685 if (!pi->next->cmds[0].argv) {
3686 G.last_exitcode = rcode = EXIT_SUCCESS;
3687 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
3690 vals = pi->next->cmds[0].argv;
3691 } /* else: "for var; do..." -> assume "$@" list */
3692 /* create list of variable values */
3693 debug_print_strings("for_list made from", vals);
3694 for_list = expand_strvec_to_strvec(vals);
3695 for_lcur = for_list;
3696 debug_print_strings("for_list", for_list);
3697 for_varname = pi->cmds[0].argv[0];
3698 pi->cmds[0].argv[0] = NULL;
3700 free(pi->cmds[0].argv[0]);
3702 /* "for" loop is over, clean up */
3706 pi->cmds[0].argv[0] = for_varname;
3709 /* Insert next value from for_lcur */
3710 /* note: *for_lcur already has quotes removed, $var expanded, etc */
3711 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
3712 pi->cmds[0].assignment_cnt = 1;
3714 if (rword == RES_IN) {
3715 continue; /* "for v IN list;..." - "in" has no cmds anyway */
3717 if (rword == RES_DONE) {
3718 continue; /* "done" has no cmds too */
3721 #if ENABLE_HUSH_CASE
3722 if (rword == RES_CASE) {
3723 case_word = expand_strvec_to_string(pi->cmds->argv);
3726 if (rword == RES_MATCH) {
3729 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
3731 /* all prev words didn't match, does this one match? */
3732 argv = pi->cmds->argv;
3734 char *pattern = expand_string_to_string(*argv);
3735 /* TODO: which FNM_xxx flags to use? */
3736 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
3738 if (cond_code == 0) { /* match! we will execute this branch */
3739 free(case_word); /* make future "word)" stop */
3747 if (rword == RES_CASEI) { /* inside of a case branch */
3749 continue; /* not matched yet, skip this pipe */
3752 /* Just pressing <enter> in shell should check for jobs.
3753 * OTOH, in non-interactive shell this is useless
3754 * and only leads to extra job checks */
3755 if (pi->num_cmds == 0) {
3756 if (G_interactive_fd)
3757 goto check_jobs_and_continue;
3761 /* After analyzing all keywords and conditions, we decided
3762 * to execute this pipe. NB: have to do checkjobs(NULL)
3763 * after run_pipe to collect any background children,
3764 * even if list execution is to be stopped. */
3765 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
3768 #if ENABLE_HUSH_LOOPS
3769 G.flag_break_continue = 0;
3771 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
3773 /* We only ran a builtin: rcode is already known
3774 * and we don't need to wait for anything. */
3775 G.last_exitcode = rcode;
3776 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
3777 check_and_run_traps(0);
3778 #if ENABLE_HUSH_LOOPS
3779 /* Was it "break" or "continue"? */
3780 if (G.flag_break_continue) {
3781 smallint fbc = G.flag_break_continue;
3782 /* We might fall into outer *loop*,
3783 * don't want to break it too */
3785 G.depth_break_continue--;
3786 if (G.depth_break_continue == 0)
3787 G.flag_break_continue = 0;
3788 /* else: e.g. "continue 2" should *break* once, *then* continue */
3789 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
3790 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
3791 goto check_jobs_and_break;
3792 /* "continue": simulate end of loop */
3797 } else if (pi->followup == PIPE_BG) {
3798 /* What does bash do with attempts to background builtins? */
3799 /* even bash 3.2 doesn't do that well with nested bg:
3800 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
3801 * I'm NOT treating inner &'s as jobs */
3802 check_and_run_traps(0);
3804 if (G.run_list_level == 1)
3807 G.last_exitcode = rcode = EXIT_SUCCESS;
3808 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
3811 if (G.run_list_level == 1 && G_interactive_fd) {
3812 /* Waits for completion, then fg's main shell */
3813 rcode = checkjobs_and_fg_shell(pi);
3814 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
3815 check_and_run_traps(0);
3818 { /* This one just waits for completion */
3819 rcode = checkjobs(pi);
3820 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
3821 check_and_run_traps(0);
3823 G.last_exitcode = rcode;
3827 /* Analyze how result affects subsequent commands */
3829 if (rword == RES_IF || rword == RES_ELIF)
3832 #if ENABLE_HUSH_LOOPS
3833 /* Beware of "while false; true; do ..."! */
3834 if (pi->next && pi->next->res_word == RES_DO) {
3835 if (rword == RES_WHILE) {
3837 /* "while false; do...done" - exitcode 0 */
3838 G.last_exitcode = rcode = EXIT_SUCCESS;
3839 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
3840 goto check_jobs_and_break;
3843 if (rword == RES_UNTIL) {
3845 debug_printf_exec(": until expr is true: breaking\n");
3846 check_jobs_and_break:
3854 check_jobs_and_continue:
3859 //// if (G.ctrl_z_flag) {
3860 //// /* ctrl-Z forked somewhere in the past, we are the child,
3861 //// * and now we completed running the list. Exit. */
3867 //// if (!G.run_list_level && G_interactive_fd) {
3868 //// signal(SIGTSTP, SIG_IGN);
3869 //// signal(SIGINT, SIG_IGN);
3872 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
3873 #if ENABLE_HUSH_LOOPS
3878 #if ENABLE_HUSH_CASE
3884 /* Select which version we will use */
3885 static int run_and_free_list(struct pipe *pi)
3888 debug_printf_exec("run_and_free_list entered\n");
3890 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
3891 rcode = run_list(pi);
3893 /* free_pipe_list has the side effect of clearing memory.
3894 * In the long run that function can be merged with run_list,
3895 * but doing that now would hobble the debugging effort. */
3896 free_pipe_list(pi, /* indent: */ 0);
3897 debug_printf_exec("run_and_free_list return %d\n", rcode);
3902 static struct pipe *new_pipe(void)
3905 pi = xzalloc(sizeof(struct pipe));
3906 /*pi->followup = 0; - deliberately invalid value */
3907 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3911 /* Command (member of a pipe) is complete. The only possible error here
3912 * is out of memory, in which case xmalloc exits. */
3913 static int done_command(struct parse_context *ctx)
3915 /* The command is really already in the pipe structure, so
3916 * advance the pipe counter and make a new, null command. */
3917 struct pipe *pi = ctx->pipe;
3918 struct command *command = ctx->command;
3921 if (command->group == NULL
3922 && command->argv == NULL
3923 && command->redirects == NULL
3925 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3926 memset(command, 0, sizeof(*command)); /* paranoia */
3927 return pi->num_cmds;
3930 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3931 //debug_print_tree(ctx->list_head, 20);
3933 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3936 /* Only real trickiness here is that the uncommitted
3937 * command structure is not counted in pi->num_cmds. */
3938 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3939 command = &pi->cmds[pi->num_cmds];
3940 memset(command, 0, sizeof(*command));
3942 ctx->command = command;
3943 /* but ctx->pipe and ctx->list_head remain unchanged */
3945 return pi->num_cmds; /* used only for 0/nonzero check */
3948 static void done_pipe(struct parse_context *ctx, pipe_style type)
3952 debug_printf_parse("done_pipe entered, followup %d\n", type);
3953 /* Close previous command */
3954 not_null = done_command(ctx);
3955 ctx->pipe->followup = type;
3957 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3958 ctx->ctx_inverted = 0;
3959 ctx->pipe->res_word = ctx->ctx_res_w;
3962 /* Without this check, even just <enter> on command line generates
3963 * tree of three NOPs (!). Which is harmless but annoying.
3964 * IOW: it is safe to do it unconditionally.
3965 * RES_NONE case is for "for a in; do ..." (empty IN set)
3966 * and other cases to work. */
3969 || ctx->ctx_res_w == RES_FI
3970 || ctx->ctx_res_w == RES_DONE
3971 || ctx->ctx_res_w == RES_FOR
3972 || ctx->ctx_res_w == RES_IN
3973 || ctx->ctx_res_w == RES_ESAC
3977 debug_printf_parse("done_pipe: adding new pipe: "
3978 "not_null:%d ctx->ctx_res_w:%d\n",
3979 not_null, ctx->ctx_res_w);
3981 ctx->pipe->next = new_p;
3983 /* RES_THEN, RES_DO etc are "sticky" -
3984 * they remain set for commands inside if/while.
3985 * This is used to control execution.
3986 * RES_FOR and RES_IN are NOT sticky (needed to support
3987 * cases where variable or value happens to match a keyword):
3989 #if ENABLE_HUSH_LOOPS
3990 if (ctx->ctx_res_w == RES_FOR
3991 || ctx->ctx_res_w == RES_IN)
3992 ctx->ctx_res_w = RES_NONE;
3994 #if ENABLE_HUSH_CASE
3995 if (ctx->ctx_res_w == RES_MATCH)
3996 ctx->ctx_res_w = RES_CASEI;
3998 ctx->command = NULL; /* trick done_command below */
3999 /* Create the memory for command, roughly:
4000 * ctx->pipe->cmds = new struct command;
4001 * ctx->command = &ctx->pipe->cmds[0];
4004 //debug_print_tree(ctx->list_head, 10);
4006 debug_printf_parse("done_pipe return\n");
4009 static void initialize_context(struct parse_context *ctx)
4011 memset(ctx, 0, sizeof(*ctx));
4012 ctx->pipe = ctx->list_head = new_pipe();
4013 /* Create the memory for command, roughly:
4014 * ctx->pipe->cmds = new struct command;
4015 * ctx->command = &ctx->pipe->cmds[0];
4020 /* If a reserved word is found and processed, parse context is modified
4021 * and 1 is returned.
4024 struct reserved_combo {
4027 unsigned char assignment_flag;
4031 FLAG_END = (1 << RES_NONE ),
4033 FLAG_IF = (1 << RES_IF ),
4034 FLAG_THEN = (1 << RES_THEN ),
4035 FLAG_ELIF = (1 << RES_ELIF ),
4036 FLAG_ELSE = (1 << RES_ELSE ),
4037 FLAG_FI = (1 << RES_FI ),
4039 #if ENABLE_HUSH_LOOPS
4040 FLAG_FOR = (1 << RES_FOR ),
4041 FLAG_WHILE = (1 << RES_WHILE),
4042 FLAG_UNTIL = (1 << RES_UNTIL),
4043 FLAG_DO = (1 << RES_DO ),
4044 FLAG_DONE = (1 << RES_DONE ),
4045 FLAG_IN = (1 << RES_IN ),
4047 #if ENABLE_HUSH_CASE
4048 FLAG_MATCH = (1 << RES_MATCH),
4049 FLAG_ESAC = (1 << RES_ESAC ),
4051 FLAG_START = (1 << RES_XXXX ),
4054 static const struct reserved_combo* match_reserved_word(o_string *word)
4056 /* Mostly a list of accepted follow-up reserved words.
4057 * FLAG_END means we are done with the sequence, and are ready
4058 * to turn the compound list into a command.
4059 * FLAG_START means the word must start a new compound list.
4061 static const struct reserved_combo reserved_list[] = {
4063 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
4064 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
4065 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
4066 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
4067 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
4068 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
4070 #if ENABLE_HUSH_LOOPS
4071 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
4072 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4073 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
4074 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
4075 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
4076 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
4078 #if ENABLE_HUSH_CASE
4079 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
4080 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
4083 const struct reserved_combo *r;
4085 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
4086 if (strcmp(word->data, r->literal) == 0)
4091 static int reserved_word(o_string *word, struct parse_context *ctx)
4093 #if ENABLE_HUSH_CASE
4094 static const struct reserved_combo reserved_match = {
4095 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
4098 const struct reserved_combo *r;
4100 r = match_reserved_word(word);
4104 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
4105 #if ENABLE_HUSH_CASE
4106 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
4107 /* "case word IN ..." - IN part starts first match part */
4108 r = &reserved_match;
4111 if (r->flag == 0) { /* '!' */
4112 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
4113 syntax_error("! ! command");
4114 IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
4116 ctx->ctx_inverted = 1;
4119 if (r->flag & FLAG_START) {
4120 struct parse_context *old;
4121 old = xmalloc(sizeof(*old));
4122 debug_printf_parse("push stack %p\n", old);
4123 *old = *ctx; /* physical copy */
4124 initialize_context(ctx);
4126 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
4127 syntax_error_at(word->data);
4128 ctx->ctx_res_w = RES_SNTX;
4131 ctx->ctx_res_w = r->res;
4132 ctx->old_flag = r->flag;
4133 if (ctx->old_flag & FLAG_END) {
4134 struct parse_context *old;
4135 done_pipe(ctx, PIPE_SEQ);
4136 debug_printf_parse("pop stack %p\n", ctx->stack);
4138 old->command->group = ctx->list_head;
4139 old->command->grp_type = GRP_NORMAL;
4141 o_addstr(&old->as_string, ctx->as_string.data);
4142 o_free_unsafe(&ctx->as_string);
4143 old->command->group_as_string = xstrdup(old->as_string.data);
4144 debug_printf_parse("pop, remembering as:'%s'\n",
4145 old->command->group_as_string);
4147 *ctx = *old; /* physical copy */
4150 word->o_assignment = r->assignment_flag;
4155 /* Word is complete, look at it and update parsing context.
4156 * Normal return is 0. Syntax errors return 1.
4157 * Note: on return, word is reset, but not o_free'd!
4159 static int done_word(o_string *word, struct parse_context *ctx)
4161 struct command *command = ctx->command;
4163 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
4164 if (word->length == 0 && word->o_quoted == 0) {
4165 debug_printf_parse("done_word return 0: true null, ignored\n");
4169 if (ctx->pending_redirect) {
4170 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
4171 * only if run as "bash", not "sh" */
4172 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4174 * ...the word that follows the redirection operator
4175 * shall be subjected to tilde expansion, parameter expansion,
4176 * command substitution, arithmetic expansion, and quote
4177 * removal. Pathname expansion shall not be performed
4178 * on the word by a non-interactive shell; an interactive
4179 * shell may perform it, but shall do so only when
4180 * the expansion would result in one word."
4182 ctx->pending_redirect->rd_filename = xstrdup(word->data);
4183 /* Cater for >\file case:
4184 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
4185 * Same with heredocs:
4186 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
4188 unbackslash(ctx->pending_redirect->rd_filename);
4189 /* Is it <<"HEREDOC"? */
4190 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC
4193 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
4195 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
4196 ctx->pending_redirect = NULL;
4198 /* If this word wasn't an assignment, next ones definitely
4199 * can't be assignments. Even if they look like ones. */
4200 if (word->o_assignment != DEFINITELY_ASSIGNMENT
4201 && word->o_assignment != WORD_IS_KEYWORD
4203 word->o_assignment = NOT_ASSIGNMENT;
4205 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
4206 command->assignment_cnt++;
4207 word->o_assignment = MAYBE_ASSIGNMENT;
4210 if (command->group) {
4211 /* "{ echo foo; } echo bar" - bad */
4212 /* NB: bash allows e.g.:
4213 * if true; then { echo foo; } fi
4214 * while if false; then false; fi do break; done
4216 * while if false; then false; fi; do; break; done
4218 syntax_error_at(word->data);
4219 debug_printf_parse("done_word return 1: syntax error, "
4220 "groups and arglists don't mix\n");
4224 # if ENABLE_HUSH_CASE
4225 if (ctx->ctx_dsemicolon
4226 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
4228 /* already done when ctx_dsemicolon was set to 1: */
4229 /* ctx->ctx_res_w = RES_MATCH; */
4230 ctx->ctx_dsemicolon = 0;
4233 if (!command->argv /* if it's the first word... */
4234 # if ENABLE_HUSH_LOOPS
4235 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4236 && ctx->ctx_res_w != RES_IN
4239 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
4240 if (reserved_word(word, ctx)) {
4241 o_reset_to_empty_unquoted(word);
4242 debug_printf_parse("done_word return %d\n",
4243 (ctx->ctx_res_w == RES_SNTX));
4244 return (ctx->ctx_res_w == RES_SNTX);
4248 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
4249 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
4250 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
4251 /* (otherwise it's known to be not empty and is already safe) */
4253 /* exclude "$@" - it can expand to no word despite "" */
4254 char *p = word->data;
4255 while (p[0] == SPECIAL_VAR_SYMBOL
4256 && (p[1] & 0x7f) == '@'
4257 && p[2] == SPECIAL_VAR_SYMBOL
4261 if (p == word->data || p[0] != '\0') {
4262 /* saw no "$@", or not only "$@" but some
4263 * real text is there too */
4264 /* insert "empty variable" reference, this makes
4265 * e.g. "", $empty"" etc to not disappear */
4266 o_addchr(word, SPECIAL_VAR_SYMBOL);
4267 o_addchr(word, SPECIAL_VAR_SYMBOL);
4270 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
4271 //SEGV, but good idea.
4272 // command->argv = add_string_to_strings(command->argv, word->data);
4273 // word->data = NULL;
4274 // word->length = 0;
4275 debug_print_strings("word appended to argv", command->argv);
4278 #if ENABLE_HUSH_LOOPS
4279 if (ctx->ctx_res_w == RES_FOR) {
4281 || !is_well_formed_var_name(command->argv[0], '\0')
4283 /* bash says just "not a valid identifier" */
4284 syntax_error("not a valid identifier in for");
4287 /* Force FOR to have just one word (variable name) */
4288 /* NB: basically, this makes hush see "for v in ..."
4289 * syntax as if it is "for v; in ...". FOR and IN become
4290 * two pipe structs in parse tree. */
4291 done_pipe(ctx, PIPE_SEQ);
4294 #if ENABLE_HUSH_CASE
4295 /* Force CASE to have just one word */
4296 if (ctx->ctx_res_w == RES_CASE) {
4297 done_pipe(ctx, PIPE_SEQ);
4301 o_reset_to_empty_unquoted(word);
4303 debug_printf_parse("done_word return 0\n");
4308 /* Peek ahead in the input to find out if we have a "&n" construct,
4309 * as in "2>&1", that represents duplicating a file descriptor.
4311 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4312 * REDIRFD_SYNTAX_ERR if syntax error,
4313 * REDIRFD_TO_FILE if no & was seen,
4314 * or the number found.
4317 #define parse_redir_right_fd(as_string, input) \
4318 parse_redir_right_fd(input)
4320 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
4326 return REDIRFD_TO_FILE;
4328 ch = i_getch(input); /* get the & */
4329 nommu_addchr(as_string, ch);
4332 ch = i_getch(input);
4333 nommu_addchr(as_string, ch);
4334 return REDIRFD_CLOSE;
4338 while (ch != EOF && isdigit(ch)) {
4339 d = d*10 + (ch-'0');
4341 ch = i_getch(input);
4342 nommu_addchr(as_string, ch);
4347 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4349 bb_error_msg("ambiguous redirect");
4350 return REDIRFD_SYNTAX_ERR;
4353 /* Return code is 0 normal, 1 if a syntax error is detected
4355 static int parse_redirect(struct parse_context *ctx,
4358 struct in_str *input)
4360 struct command *command = ctx->command;
4361 struct redir_struct *redir;
4362 struct redir_struct **redirp;
4365 dup_num = REDIRFD_TO_FILE;
4366 if (style != REDIRECT_HEREDOC) {
4367 /* Check for a '>&1' type redirect */
4368 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4369 if (dup_num == REDIRFD_SYNTAX_ERR)
4372 int ch = i_peek(input);
4373 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
4374 if (dup_num) { /* <<-... */
4375 ch = i_getch(input);
4376 nommu_addchr(&ctx->as_string, ch);
4381 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
4382 int ch = i_peek(input);
4384 /* >|FILE redirect ("clobbering" >).
4385 * Since we do not support "set -o noclobber" yet,
4386 * >| and > are the same for now. Just eat |.
4388 ch = i_getch(input);
4389 nommu_addchr(&ctx->as_string, ch);
4393 /* Create a new redir_struct and append it to the linked list */
4394 redirp = &command->redirects;
4395 while ((redir = *redirp) != NULL) {
4396 redirp = &(redir->next);
4398 *redirp = redir = xzalloc(sizeof(*redir));
4399 /* redir->next = NULL; */
4400 /* redir->rd_filename = NULL; */
4401 redir->rd_type = style;
4402 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
4404 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4405 redir_table[style].descrip);
4407 redir->rd_dup = dup_num;
4408 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
4409 /* Erik had a check here that the file descriptor in question
4410 * is legit; I postpone that to "run time"
4411 * A "-" representation of "close me" shows up as a -3 here */
4412 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4413 redir->rd_fd, redir->rd_dup);
4415 /* Set ctx->pending_redirect, so we know what to do at the
4416 * end of the next parsed word. */
4417 ctx->pending_redirect = redir;
4422 /* If a redirect is immediately preceded by a number, that number is
4423 * supposed to tell which file descriptor to redirect. This routine
4424 * looks for such preceding numbers. In an ideal world this routine
4425 * needs to handle all the following classes of redirects...
4426 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4427 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4428 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4429 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
4431 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4433 * ... If n is quoted, the number shall not be recognized as part of
4434 * the redirection expression. For example:
4436 * writes the character 2 into file a"
4437 * We are getting it right by setting ->o_quoted on any \<char>
4439 * A -1 return means no valid number was found,
4440 * the caller should use the appropriate default for this redirection.
4442 static int redirect_opt_num(o_string *o)
4446 if (o->data == NULL)
4448 num = bb_strtou(o->data, NULL, 10);
4449 if (errno || num < 0)
4451 o_reset_to_empty_unquoted(o);
4456 #define fetch_till_str(as_string, input, word, skip_tabs) \
4457 fetch_till_str(input, word, skip_tabs)
4459 static char *fetch_till_str(o_string *as_string,
4460 struct in_str *input,
4464 o_string heredoc = NULL_O_STRING;
4470 ch = i_getch(input);
4471 nommu_addchr(as_string, ch);
4473 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4474 heredoc.data[past_EOL] = '\0';
4475 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4476 return heredoc.data;
4479 o_addchr(&heredoc, ch);
4480 past_EOL = heredoc.length;
4483 ch = i_getch(input);
4484 nommu_addchr(as_string, ch);
4485 } while (skip_tabs && ch == '\t');
4486 } while (ch == '\n');
4489 o_free_unsafe(&heredoc);
4492 o_addchr(&heredoc, ch);
4493 nommu_addchr(as_string, ch);
4497 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4498 * and load them all. There should be exactly heredoc_cnt of them.
4500 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4502 struct pipe *pi = ctx->list_head;
4504 while (pi && heredoc_cnt) {
4506 struct command *cmd = pi->cmds;
4508 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4510 cmd->argv ? cmd->argv[0] : "NONE");
4511 for (i = 0; i < pi->num_cmds; i++) {
4512 struct redir_struct *redir = cmd->redirects;
4514 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4515 i, cmd->argv ? cmd->argv[0] : "NONE");
4517 if (redir->rd_type == REDIRECT_HEREDOC) {
4520 redir->rd_type = REDIRECT_HEREDOC2;
4521 /* redir->dup is (ab)used to indicate <<- */
4522 p = fetch_till_str(&ctx->as_string, input,
4523 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
4525 syntax_error("unexpected EOF in here document");
4528 free(redir->rd_filename);
4529 redir->rd_filename = p;
4532 redir = redir->next;
4539 /* Should be 0. If it isn't, it's a parse error */
4541 bb_error_msg_and_die("heredoc BUG 2");
4548 #define parse_stream(pstring, input, end_trigger) \
4549 parse_stream(input, end_trigger)
4551 static struct pipe *parse_stream(char **pstring,
4552 struct in_str *input,
4554 static void parse_and_run_string(const char *s);
4556 #if ENABLE_HUSH_TICK
4557 static FILE *generate_stream_from_string(const char *s)
4560 int pid, channel[2];
4563 pid = BB_MMU ? fork() : vfork();
4565 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
4567 if (pid == 0) { /* child */
4568 disable_restore_tty_pgrp_on_exit();
4569 /* Process substitution is not considered to be usual
4570 * 'command execution'.
4571 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
4578 close(channel[0]); /* NB: close _first_, then move fd! */
4579 xmove_fd(channel[1], 1);
4580 /* Prevent it from trying to handle ctrl-z etc */
4581 USE_HUSH_JOB(G.run_list_level = 1;)
4583 reset_traps_to_defaults();
4584 parse_and_run_string(s);
4585 _exit(G.last_exitcode);
4587 /* We re-execute after vfork on NOMMU. This makes this script safe:
4588 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
4589 * huge=`cat BIG` # was blocking here forever
4599 enable_restore_tty_pgrp_on_exit();
4600 clean_up_after_re_execute();
4602 pf = fdopen(channel[0], "r");
4606 /* Return code is exit status of the process that is run. */
4607 static int process_command_subs(o_string *dest, const char *s)
4610 struct in_str pipe_str;
4613 pf = generate_stream_from_string(s);
4616 close_on_exec_on(fileno(pf));
4618 /* Now send results of command back into original context */
4619 setup_file_in_str(&pipe_str, pf);
4621 while ((ch = i_getch(&pipe_str)) != EOF) {
4627 o_addchr(dest, '\n');
4630 o_addQchr(dest, ch);
4633 debug_printf("done reading from pipe, pclose()ing\n");
4634 /* Note: we got EOF, and we just close the read end of the pipe.
4635 * We do not wait for the `cmd` child to terminate. bash and ash do.
4637 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
4638 * `false`; echo $? - bash outputs "1"
4641 debug_printf("closed FILE from child. return 0\n");
4646 static int parse_group(o_string *dest, struct parse_context *ctx,
4647 struct in_str *input, int ch)
4649 /* dest contains characters seen prior to ( or {.
4650 * Typically it's empty, but for function defs,
4651 * it contains function name (without '()'). */
4652 struct pipe *pipe_list;
4654 struct command *command = ctx->command;
4656 debug_printf_parse("parse_group entered\n");
4657 #if ENABLE_HUSH_FUNCTIONS
4658 if (ch == '(' && !dest->o_quoted) {
4660 done_word(dest, ctx);
4662 goto skip; /* (... */
4663 if (command->argv[1]) { /* word word ... (... */
4664 syntax_error_unexpected_ch('(');
4667 /* it is "word(..." or "word (..." */
4669 ch = i_getch(input);
4670 while (ch == ' ' || ch == '\t');
4672 syntax_error_unexpected_ch(ch);
4675 nommu_addchr(&ctx->as_string, ch);
4677 ch = i_getch(input);
4678 while (ch == ' ' || ch == '\t' || ch == '\n');
4680 syntax_error_unexpected_ch(ch);
4683 nommu_addchr(&ctx->as_string, ch);
4684 command->grp_type = GRP_FUNCTION;
4688 if (command->argv /* word [word]{... */
4689 || dest->length /* word{... */
4690 || dest->o_quoted /* ""{... */
4693 debug_printf_parse("parse_group return 1: "
4694 "syntax error, groups and arglists don't mix\n");
4698 #if ENABLE_HUSH_FUNCTIONS
4704 command->grp_type = GRP_SUBSHELL;
4709 char *as_string = NULL;
4711 pipe_list = parse_stream(&as_string, input, endch);
4714 o_addstr(&ctx->as_string, as_string);
4716 /* empty ()/{} or parse error? */
4717 if (!pipe_list || pipe_list == ERR_PTR) {
4722 debug_printf_parse("parse_group return 1: "
4723 "parse_stream returned %p\n", pipe_list);
4726 command->group = pipe_list;
4728 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4729 command->group_as_string = as_string;
4730 debug_printf_parse("end of group, remembering as:'%s'\n",
4731 command->group_as_string);
4734 debug_printf_parse("parse_group return 0\n");
4736 /* command remains "open", available for possible redirects */
4739 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
4740 /* Subroutines for copying $(...) and `...` things */
4741 static void add_till_backquote(o_string *dest, struct in_str *input);
4743 static void add_till_single_quote(o_string *dest, struct in_str *input)
4746 int ch = i_getch(input);
4748 syntax_error_unterm_ch('\'');
4749 /*xfunc_die(); - redundant */
4756 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
4757 static void add_till_double_quote(o_string *dest, struct in_str *input)
4760 int ch = i_getch(input);
4762 syntax_error_unterm_ch('"');
4763 /*xfunc_die(); - redundant */
4767 if (ch == '\\') { /* \x. Copy both chars. */
4769 ch = i_getch(input);
4773 add_till_backquote(dest, input);
4777 //if (ch == '$') ...
4780 /* Process `cmd` - copy contents until "`" is seen. Complicated by
4782 * "Within the backquoted style of command substitution, backslash
4783 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4784 * The search for the matching backquote shall be satisfied by the first
4785 * backquote found without a preceding backslash; during this search,
4786 * if a non-escaped backquote is encountered within a shell comment,
4787 * a here-document, an embedded command substitution of the $(command)
4788 * form, or a quoted string, undefined results occur. A single-quoted
4789 * or double-quoted string that begins, but does not end, within the
4790 * "`...`" sequence produces undefined results."
4792 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4794 static void add_till_backquote(o_string *dest, struct in_str *input)
4797 int ch = i_getch(input);
4799 syntax_error_unterm_ch('`');
4800 /*xfunc_die(); - redundant */
4805 /* \x. Copy both chars unless it is \` */
4806 int ch2 = i_getch(input);
4808 syntax_error_unterm_ch('`');
4809 /*xfunc_die(); - redundant */
4811 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
4818 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
4819 * quoting and nested ()s.
4820 * "With the $(command) style of command substitution, all characters
4821 * following the open parenthesis to the matching closing parenthesis
4822 * constitute the command. Any valid shell script can be used for command,
4823 * except a script consisting solely of redirections which produces
4824 * unspecified results."
4826 * echo $(echo '(TEST)' BEST) (TEST) BEST
4827 * echo $(echo 'TEST)' BEST) TEST) BEST
4828 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
4830 static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
4834 int ch = i_getch(input);
4836 syntax_error_unterm_ch(')');
4837 /*xfunc_die(); - redundant */
4845 if (i_peek(input) == ')') {
4853 add_till_single_quote(dest, input);
4858 add_till_double_quote(dest, input);
4863 /* \x. Copy verbatim. Important for \(, \) */
4864 ch = i_getch(input);
4866 syntax_error_unterm_ch(')');
4867 /*xfunc_die(); - redundant */
4874 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
4876 /* Return code: 0 for OK, 1 for syntax error */
4878 #define handle_dollar(as_string, dest, input) \
4879 handle_dollar(dest, input)
4881 static int handle_dollar(o_string *as_string,
4883 struct in_str *input)
4886 int ch = i_peek(input); /* first character after the $ */
4887 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
4889 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
4891 ch = i_getch(input);
4892 nommu_addchr(as_string, ch);
4894 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4896 debug_printf_parse(": '%c'\n", ch);
4897 o_addchr(dest, ch | quote_mask);
4900 if (!isalnum(ch) && ch != '_')
4902 ch = i_getch(input);
4903 nommu_addchr(as_string, ch);
4905 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4906 } else if (isdigit(ch)) {
4908 ch = i_getch(input);
4909 nommu_addchr(as_string, ch);
4910 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4911 debug_printf_parse(": '%c'\n", ch);
4912 o_addchr(dest, ch | quote_mask);
4913 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4914 } else switch (ch) {
4916 case '!': /* last bg pid */
4917 case '?': /* last exit code */
4918 case '#': /* number of args */
4919 case '*': /* args */
4920 case '@': /* args */
4921 goto make_one_char_var;
4923 bool first_char, all_digits;
4925 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4926 ch = i_getch(input);
4927 nommu_addchr(as_string, ch);
4928 /* XXX maybe someone will try to escape the '}' */
4933 ch = i_getch(input);
4934 nommu_addchr(as_string, ch);
4940 /* ${#var}: length of var contents */
4942 else if (isdigit(ch)) {
4949 && ( (all_digits && !isdigit(ch))
4950 || (!all_digits && !isalnum(ch) && ch != '_')
4953 /* handle parameter expansions
4954 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4959 case ':': /* null modifier */
4960 if (expansion == 0) {
4961 debug_printf_parse(": null modifier\n");
4966 case '#': /* remove prefix */
4967 case '%': /* remove suffix */
4968 if (expansion == 0) {
4969 debug_printf_parse(": remove suffix/prefix\n");
4974 case '-': /* default value */
4975 case '=': /* assign default */
4976 case '+': /* alternative */
4977 case '?': /* error indicate */
4978 debug_printf_parse(": parameter expansion\n");
4983 syntax_error_unterm_str("${name}");
4984 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
4989 debug_printf_parse(": '%c'\n", ch);
4990 o_addchr(dest, ch | quote_mask);
4994 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4997 #if (ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK)
5002 ch = i_getch(input);
5003 nommu_addchr(as_string, ch);
5004 # if ENABLE_SH_MATH_SUPPORT
5005 if (i_peek(input) == '(') {
5006 ch = i_getch(input);
5007 nommu_addchr(as_string, ch);
5008 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5009 o_addchr(dest, /*quote_mask |*/ '+');
5013 add_till_closing_paren(dest, input, true);
5016 o_addstr(as_string, dest->data + pos);
5017 o_addchr(as_string, ')');
5018 o_addchr(as_string, ')');
5021 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5025 # if ENABLE_HUSH_TICK
5026 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5027 o_addchr(dest, quote_mask | '`');
5031 add_till_closing_paren(dest, input, false);
5034 o_addstr(as_string, dest->data + pos);
5035 o_addchr(as_string, '`');
5038 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5044 ch = i_getch(input);
5045 nommu_addchr(as_string, ch);
5047 if (isalnum(ch)) { /* it's $_name or $_123 */
5053 /* $_ Shell or shell script name; or last cmd name */
5054 /* $- Option flags set by set builtin or shell options (-i etc) */
5056 o_addQchr(dest, '$');
5058 debug_printf_parse("handle_dollar return 0\n");
5063 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
5064 parse_stream_dquoted(dest, input, dquote_end)
5066 static int parse_stream_dquoted(o_string *as_string,
5068 struct in_str *input,
5075 ch = i_getch(input);
5077 nommu_addchr(as_string, ch);
5078 if (ch == dquote_end) { /* may be only '"' or EOF */
5079 if (dest->o_assignment == NOT_ASSIGNMENT)
5080 dest->o_escape ^= 1;
5081 debug_printf_parse("parse_stream_dquoted return 0\n");
5084 /* note: can't move it above ch == dquote_end check! */
5086 syntax_error_unterm_ch('"');
5087 /*xfunc_die(); - redundant */
5091 next = i_peek(input);
5093 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5094 ch, ch, dest->o_escape);
5097 syntax_error("\\<eof>");
5101 * "The backslash retains its special meaning [in "..."]
5102 * only when followed by one of the following characters:
5103 * $, `, ", \, or <newline>. A double quote may be quoted
5104 * within double quotes by preceding it with a backslash.
5106 if (strchr("$`\"\\", next) != NULL) {
5107 o_addqchr(dest, i_getch(input));
5109 o_addqchr(dest, '\\');
5114 if (handle_dollar(as_string, dest, input) != 0) {
5115 debug_printf_parse("parse_stream_dquoted return 1: "
5116 "handle_dollar returned non-0\n");
5121 #if ENABLE_HUSH_TICK
5123 //int pos = dest->length;
5124 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5125 o_addchr(dest, 0x80 | '`');
5126 add_till_backquote(dest, input);
5127 o_addchr(dest, SPECIAL_VAR_SYMBOL);
5128 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
5132 o_addQchr(dest, ch);
5134 && (dest->o_assignment == MAYBE_ASSIGNMENT
5135 || dest->o_assignment == WORD_IS_KEYWORD)
5136 && is_well_formed_var_name(dest->data, '=')
5138 dest->o_assignment = DEFINITELY_ASSIGNMENT;
5144 * Scan input until EOF or end_trigger char.
5145 * Return a list of pipes to execute, or NULL on EOF
5146 * or if end_trigger character is met.
5147 * On syntax error, exit is shell is not interactive,
5148 * reset parsing machinery and start parsing anew,
5149 * or return ERR_PTR.
5151 static struct pipe *parse_stream(char **pstring,
5152 struct in_str *input,
5155 struct parse_context ctx;
5156 o_string dest = NULL_O_STRING;
5160 /* Double-quote state is handled in the state variable is_in_dquote.
5161 * A single-quote triggers a bypass of the main loop until its mate is
5162 * found. When recursing, quote state is passed in via dest->o_escape.
5164 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
5165 end_trigger ? : 'X');
5167 G.ifs = get_local_var_value("IFS");
5172 #if ENABLE_HUSH_INTERACTIVE
5173 input->promptmode = 0; /* PS1 */
5175 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
5176 initialize_context(&ctx);
5181 const char *is_special;
5185 redir_type redir_style;
5188 /* dest.o_quoted = 1; - already is (see below) */
5189 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
5192 /* We reached closing '"' */
5195 ch = i_getch(input);
5196 debug_printf_parse(": ch=%c (%d) escape=%d\n",
5197 ch, ch, dest.o_escape);
5202 syntax_error_unterm_str("here document");
5205 if (done_word(&dest, &ctx)) {
5209 done_pipe(&ctx, PIPE_SEQ);
5211 /* If we got nothing... */
5212 /* (this makes bare "&" cmd a no-op.
5213 * bash says: "syntax error near unexpected token '&'") */
5214 if (pi->num_cmds == 0
5215 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
5217 free_pipe_list(pi, 0);
5220 debug_printf_parse("parse_stream return %p\n", pi);
5222 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5224 *pstring = ctx.as_string.data;
5226 o_free_unsafe(&ctx.as_string);
5230 nommu_addchr(&ctx.as_string, ch);
5231 is_ifs = strchr(G.ifs, ch);
5232 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
5233 "\\$\"" USE_HUSH_TICK("`") /* always special */
5236 if (!is_special && !is_ifs) { /* ordinary char */
5237 o_addQchr(&dest, ch);
5238 if ((dest.o_assignment == MAYBE_ASSIGNMENT
5239 || dest.o_assignment == WORD_IS_KEYWORD)
5241 && is_well_formed_var_name(dest.data, '=')
5243 dest.o_assignment = DEFINITELY_ASSIGNMENT;
5249 if (done_word(&dest, &ctx)) {
5253 #if ENABLE_HUSH_CASE
5254 /* "case ... in <newline> word) ..." -
5255 * newlines are ignored (but ';' wouldn't be) */
5256 if (ctx.command->argv == NULL
5257 && ctx.ctx_res_w == RES_MATCH
5262 /* Treat newline as a command separator. */
5263 done_pipe(&ctx, PIPE_SEQ);
5264 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5266 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
5271 dest.o_assignment = MAYBE_ASSIGNMENT;
5273 /* note: if (is_ifs) continue;
5274 * will still trigger for us */
5277 if (end_trigger && end_trigger == ch
5278 && (heredoc_cnt == 0 || end_trigger != ';')
5280 //TODO: disallow "{ cmd }" without semicolon
5282 /* This is technically valid:
5283 * { cat <<HERE; }; echo Ok
5288 * but we don't support this.
5289 * We require heredoc to be in enclosing {}/(),
5292 syntax_error_unterm_str("here document");
5295 if (done_word(&dest, &ctx)) {
5298 done_pipe(&ctx, PIPE_SEQ);
5299 dest.o_assignment = MAYBE_ASSIGNMENT;
5300 /* Do we sit outside of any if's, loops or case's? */
5302 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
5304 debug_printf_parse("parse_stream return %p: "
5305 "end_trigger char found\n",
5309 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5311 *pstring = ctx.as_string.data;
5313 o_free_unsafe(&ctx.as_string);
5315 return ctx.list_head;
5323 next = i_peek(input);
5326 /* Catch <, > before deciding whether this word is
5327 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5330 redir_fd = redirect_opt_num(&dest);
5331 if (done_word(&dest, &ctx)) {
5334 redir_style = REDIRECT_OVERWRITE;
5336 redir_style = REDIRECT_APPEND;
5337 ch = i_getch(input);
5338 nommu_addchr(&ctx.as_string, ch);
5341 else if (next == '(') {
5342 syntax_error(">(process) not supported");
5346 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5348 continue; /* back to top of while (1) */
5350 redir_fd = redirect_opt_num(&dest);
5351 if (done_word(&dest, &ctx)) {
5354 redir_style = REDIRECT_INPUT;
5356 redir_style = REDIRECT_HEREDOC;
5358 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5359 ch = i_getch(input);
5360 nommu_addchr(&ctx.as_string, ch);
5361 } else if (next == '>') {
5362 redir_style = REDIRECT_IO;
5363 ch = i_getch(input);
5364 nommu_addchr(&ctx.as_string, ch);
5367 else if (next == '(') {
5368 syntax_error("<(process) not supported");
5372 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5374 continue; /* back to top of while (1) */
5377 if (dest.o_assignment == MAYBE_ASSIGNMENT
5378 /* check that we are not in word in "a=1 2>word b=1": */
5379 && !ctx.pending_redirect
5381 /* ch is a special char and thus this word
5382 * cannot be an assignment */
5383 dest.o_assignment = NOT_ASSIGNMENT;
5388 if (dest.length == 0) {
5391 if (ch == EOF || ch == '\n')
5394 /* note: we do not add it to &ctx.as_string */
5396 nommu_addchr(&ctx.as_string, '\n');
5398 o_addQchr(&dest, ch);
5403 syntax_error("\\<eof>");
5406 o_addchr(&dest, '\\');
5407 ch = i_getch(input);
5408 nommu_addchr(&ctx.as_string, ch);
5409 o_addchr(&dest, ch);
5410 /* Example: echo Hello \2>file
5411 * we need to know that word 2 is quoted */
5415 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
5416 debug_printf_parse("parse_stream parse error: "
5417 "handle_dollar returned non-0\n");
5424 ch = i_getch(input);
5426 syntax_error_unterm_ch('\'');
5427 /*xfunc_die(); - redundant */
5429 nommu_addchr(&ctx.as_string, ch);
5432 if (dest.o_assignment == NOT_ASSIGNMENT)
5433 o_addqchr(&dest, ch);
5435 o_addchr(&dest, ch);
5440 is_in_dquote ^= 1; /* invert */
5441 if (dest.o_assignment == NOT_ASSIGNMENT)
5444 #if ENABLE_HUSH_TICK
5449 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5450 o_addchr(&dest, '`');
5454 add_till_backquote(&dest, input);
5456 o_addstr(&ctx.as_string, dest.data + pos);
5457 o_addchr(&ctx.as_string, '`');
5459 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5460 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
5465 #if ENABLE_HUSH_CASE
5468 if (done_word(&dest, &ctx)) {
5471 done_pipe(&ctx, PIPE_SEQ);
5472 #if ENABLE_HUSH_CASE
5473 /* Eat multiple semicolons, detect
5474 * whether it means something special */
5479 ch = i_getch(input);
5480 nommu_addchr(&ctx.as_string, ch);
5481 if (ctx.ctx_res_w == RES_CASEI) {
5482 ctx.ctx_dsemicolon = 1;
5483 ctx.ctx_res_w = RES_MATCH;
5489 /* We just finished a cmd. New one may start
5490 * with an assignment */
5491 dest.o_assignment = MAYBE_ASSIGNMENT;
5494 if (done_word(&dest, &ctx)) {
5498 ch = i_getch(input);
5499 nommu_addchr(&ctx.as_string, ch);
5500 done_pipe(&ctx, PIPE_AND);
5502 done_pipe(&ctx, PIPE_BG);
5506 if (done_word(&dest, &ctx)) {
5509 #if ENABLE_HUSH_CASE
5510 if (ctx.ctx_res_w == RES_MATCH)
5511 break; /* we are in case's "word | word)" */
5513 if (next == '|') { /* || */
5514 ch = i_getch(input);
5515 nommu_addchr(&ctx.as_string, ch);
5516 done_pipe(&ctx, PIPE_OR);
5518 /* we could pick up a file descriptor choice here
5519 * with redirect_opt_num(), but bash doesn't do it.
5520 * "echo foo 2| cat" yields "foo 2". */
5525 #if ENABLE_HUSH_CASE
5526 /* "case... in [(]word)..." - skip '(' */
5527 if (ctx.ctx_res_w == RES_MATCH
5528 && ctx.command->argv == NULL /* not (word|(... */
5529 && dest.length == 0 /* not word(... */
5530 && dest.o_quoted == 0 /* not ""(... */
5536 if (parse_group(&dest, &ctx, input, ch) != 0) {
5541 #if ENABLE_HUSH_CASE
5542 if (ctx.ctx_res_w == RES_MATCH)
5546 /* proper use of this character is caught by end_trigger:
5547 * if we see {, we call parse_group(..., end_trigger='}')
5548 * and it will match } earlier (not here). */
5549 syntax_error_unexpected_ch(ch);
5553 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
5559 struct parse_context *pctx;
5560 IF_HAS_KEYWORDS(struct parse_context *p2;)
5562 /* Clean up allocated tree.
5563 * Samples for finding leaks on syntax error recovery path.
5564 * Run them from interactive shell, watch pmap `pidof hush`.
5565 * while if false; then false; fi do break; done
5567 * while if false; then false; fi; do break; fi
5568 * Samples to catch leaks at execution:
5569 * while if (true | {true;}); then echo ok; fi; do break; done
5570 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
5574 /* Update pipe/command counts,
5575 * otherwise freeing may miss some */
5576 done_pipe(pctx, PIPE_SEQ);
5577 debug_printf_clean("freeing list %p from ctx %p\n",
5578 pctx->list_head, pctx);
5579 debug_print_tree(pctx->list_head, 0);
5580 free_pipe_list(pctx->list_head, 0);
5581 debug_printf_clean("freed list %p\n", pctx->list_head);
5583 o_free_unsafe(&pctx->as_string);
5585 IF_HAS_KEYWORDS(p2 = pctx->stack;)
5589 IF_HAS_KEYWORDS(pctx = p2;)
5590 } while (HAS_KEYWORDS && pctx);
5591 /* Free text, clear all dest fields */
5593 /* If we are not in top-level parse, we return,
5594 * our caller will propagate error.
5596 if (end_trigger != ';') {
5603 /* Discard cached input, force prompt */
5605 USE_HUSH_INTERACTIVE(input->promptme = 1;)
5610 /* Executing from string: eval, sh -c '...'
5611 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5612 * end_trigger controls how often we stop parsing
5613 * NUL: parse all, execute, return
5614 * ';': parse till ';' or newline, execute, repeat till EOF
5616 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5619 struct pipe *pipe_list;
5621 pipe_list = parse_stream(NULL, inp, end_trigger);
5622 if (!pipe_list) /* EOF */
5624 debug_print_tree(pipe_list, 0);
5625 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5626 run_and_free_list(pipe_list);
5630 static void parse_and_run_string(const char *s)
5632 struct in_str input;
5633 setup_string_in_str(&input, s);
5634 parse_and_run_stream(&input, '\0');
5637 static void parse_and_run_file(FILE *f)
5639 struct in_str input;
5640 setup_file_in_str(&input, f);
5641 parse_and_run_stream(&input, ';');
5644 /* Called a few times only (or even once if "sh -c") */
5645 static void block_signals(int second_time)
5650 mask = (1 << SIGQUIT);
5651 if (G_interactive_fd) {
5655 //TODO | (1 << SIGHUP)
5657 | (1 << SIGTTIN) | (1 << SIGTTOU) | (1 << SIGTSTP)
5662 G.non_DFL_mask = mask;
5665 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
5669 sigaddset(&G.blocked_set, sig);
5673 sigdelset(&G.blocked_set, SIGCHLD);
5675 sigprocmask(SIG_SETMASK, &G.blocked_set,
5676 second_time ? NULL : &G.inherited_set);
5677 /* POSIX allows shell to re-enable SIGCHLD
5678 * even if it was SIG_IGN on entry */
5679 // G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
5681 signal(SIGCHLD, SIG_DFL); // SIGCHLD_handler);
5686 static void maybe_set_to_sigexit(int sig)
5688 void (*handler)(int);
5689 /* non_DFL_mask'ed signals are, well, masked,
5690 * no need to set handler for them.
5692 if (!((G.non_DFL_mask >> sig) & 1)) {
5693 handler = signal(sig, sigexit);
5694 if (handler == SIG_IGN) /* oops... restore back to IGN! */
5695 signal(sig, handler);
5698 /* Set handlers to restore tty pgrp and exit */
5699 static void set_fatal_handlers(void)
5701 /* We _must_ restore tty pgrp on fatal signals */
5703 maybe_set_to_sigexit(SIGILL );
5704 maybe_set_to_sigexit(SIGFPE );
5705 maybe_set_to_sigexit(SIGBUS );
5706 maybe_set_to_sigexit(SIGSEGV);
5707 maybe_set_to_sigexit(SIGTRAP);
5708 } /* else: hush is perfect. what SEGV? */
5709 maybe_set_to_sigexit(SIGABRT);
5710 /* bash 3.2 seems to handle these just like 'fatal' ones */
5711 maybe_set_to_sigexit(SIGPIPE);
5712 maybe_set_to_sigexit(SIGALRM);
5713 //TODO: disable and move down when proper SIGHUP handling is added
5714 maybe_set_to_sigexit(SIGHUP );
5715 /* if we are interactive, [SIGHUP,] SIGTERM and SIGINT are masked.
5716 * if we aren't interactive... but in this case
5717 * we never want to restore pgrp on exit, and this fn is not called */
5718 /*maybe_set_to_sigexit(SIGTERM);*/
5719 /*maybe_set_to_sigexit(SIGINT );*/
5723 static int set_mode(const char cstate, const char mode)
5725 int state = (cstate == '-' ? 1 : 0);
5727 case 'n': G.fake_mode = state; break;
5728 case 'x': /*G.debug_mode = state;*/ break;
5729 default: return EXIT_FAILURE;
5731 return EXIT_SUCCESS;
5734 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
5735 int hush_main(int argc, char **argv)
5737 static const struct variable const_shell_ver = {
5739 .varstr = (char*)hush_version_str,
5740 .max_len = 1, /* 0 can provoke free(name) */
5744 int signal_mask_is_inited = 0;
5747 struct variable *cur_var;
5750 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
5751 G.last_exitcode = EXIT_SUCCESS;
5753 G.argv0_for_re_execing = argv[0];
5755 /* Deal with HUSH_VERSION */
5756 G.shell_ver = const_shell_ver; /* copying struct here */
5757 G.top_var = &G.shell_ver;
5758 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
5759 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
5760 /* Initialize our shell local variables with the values
5761 * currently living in the environment */
5762 cur_var = G.top_var;
5765 char *value = strchr(*e, '=');
5766 if (value) { /* paranoia */
5767 cur_var->next = xzalloc(sizeof(*cur_var));
5768 cur_var = cur_var->next;
5769 cur_var->varstr = *e;
5770 cur_var->max_len = strlen(*e);
5771 cur_var->flg_export = 1;
5775 debug_printf_env("putenv '%s'\n", hush_version_str);
5776 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
5777 #if ENABLE_FEATURE_EDITING
5778 G.line_input_state = new_line_input_t(FOR_SHELL);
5780 G.global_argc = argc;
5781 G.global_argv = argv;
5782 /* Initialize some more globals to non-zero values */
5784 #if ENABLE_HUSH_INTERACTIVE
5785 if (ENABLE_FEATURE_EDITING)
5786 cmdedit_set_initial_prompt();
5790 if (setjmp(die_jmp)) {
5791 /* xfunc has failed! die die die */
5792 /* no EXIT traps, this is an escape hatch! */
5794 hush_exit(xfunc_error_retval);
5797 /* Shell is non-interactive at first. We need to call
5798 * block_signals(0) if we are going to execute "sh <script>",
5799 * "sh -c <cmds>" or login shell's /etc/profile and friends.
5800 * If we later decide that we are interactive, we run block_signals(0)
5801 * (or re-run block_signals(1) if we ran block_signals(0) before)
5802 * in order to intercept (more) signals.
5806 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
5808 opt = getopt(argc, argv, "c:xins"
5818 G.root_pid = getpid();
5819 G.global_argv = argv + optind;
5820 if (!argv[optind]) {
5821 /* -c 'script' (no params): prevent empty $0 */
5822 *--G.global_argv = argv[0];
5824 } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
5825 G.global_argc = argc - optind;
5826 block_signals(0); /* 0: called 1st time */
5827 parse_and_run_string(optarg);
5830 /* Well, we cannot just declare interactiveness,
5831 * we have to have some stuff (ctty, etc) */
5832 /* G_interactive_fd++; */
5835 /* "-s" means "read from stdin", but this is how we always
5836 * operate, so simply do nothing here. */
5839 case '<': /* "big heredoc" support */
5840 full_write(STDOUT_FILENO, optarg, strlen(optarg));
5843 G.root_pid = bb_strtou(optarg, &optarg, 16);
5845 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
5847 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
5848 # if ENABLE_HUSH_LOOPS
5850 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
5855 set_local_var(xstrdup(optarg), 0, opt == 'R');
5860 if (!set_mode('-', opt))
5864 fprintf(stderr, "Usage: sh [FILE]...\n"
5865 " or: sh -c command [args]...\n\n");
5871 } /* option parsing loop */
5874 G.root_pid = getpid();
5876 /* If we are login shell... */
5877 if (argv[0] && argv[0][0] == '-') {
5879 /* XXX what should argv be while sourcing /etc/profile? */
5880 debug_printf("sourcing /etc/profile\n");
5881 input = fopen_for_read("/etc/profile");
5882 if (input != NULL) {
5883 close_on_exec_on(fileno(input));
5884 block_signals(0); /* 0: called 1st time */
5885 signal_mask_is_inited = 1;
5886 parse_and_run_file(input);
5889 /* bash: after sourcing /etc/profile,
5890 * tries to source (in the given order):
5891 * ~/.bash_profile, ~/.bash_login, ~/.profile,
5892 * stopping of first found. --noprofile turns this off.
5893 * bash also sources ~/.bash_logout on exit.
5894 * If called as sh, skips .bash_XXX files.
5901 * "bash <script>" (which is never interactive (unless -i?))
5902 * sources $BASH_ENV here (without scanning $PATH).
5903 * If called as sh, does the same but with $ENV.
5905 debug_printf("running script '%s'\n", argv[optind]);
5906 G.global_argv = argv + optind;
5907 G.global_argc = argc - optind;
5908 input = xfopen_for_read(argv[optind]);
5909 close_on_exec_on(fileno(input));
5910 if (!signal_mask_is_inited)
5911 block_signals(0); /* 0: called 1st time */
5912 parse_and_run_file(input);
5913 #if ENABLE_FEATURE_CLEAN_UP
5919 /* Up to here, shell was non-interactive. Now it may become one.
5920 * NB: don't forget to (re)run block_signals(0/1) as needed.
5923 /* A shell is interactive if the '-i' flag was given, or if all of
5924 * the following conditions are met:
5926 * no arguments remaining or the -s flag given
5927 * standard input is a terminal
5928 * standard output is a terminal
5929 * Refer to Posix.2, the description of the 'sh' utility.
5932 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
5933 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
5934 debug_printf("saved_tty_pgrp:%d\n", G.saved_tty_pgrp);
5935 //TODO: "interactive" and "have job control" are two different things.
5936 //If tcgetpgrp fails here, "have job control" is false, but "interactive"
5937 //should stay on! Currently, we mix these into one.
5938 if (G.saved_tty_pgrp >= 0) {
5939 /* try to dup stdin to high fd#, >= 255 */
5940 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
5941 if (G_interactive_fd < 0) {
5942 /* try to dup to any fd */
5943 G_interactive_fd = dup(STDIN_FILENO);
5944 if (G_interactive_fd < 0)
5946 G_interactive_fd = 0;
5948 // TODO: track & disallow any attempts of user
5949 // to (inadvertently) close/redirect it
5952 debug_printf("interactive_fd:%d\n", G_interactive_fd);
5953 if (G_interactive_fd) {
5956 /* We are indeed interactive shell, and we will perform
5957 * job control. Setting up for that. */
5959 close_on_exec_on(G_interactive_fd);
5960 /* If we were run as 'hush &', sleep until we are
5961 * in the foreground (tty pgrp == our pgrp).
5962 * If we get started under a job aware app (like bash),
5963 * make sure we are now in charge so we don't fight over
5964 * who gets the foreground */
5966 shell_pgrp = getpgrp();
5967 G.saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
5968 if (G.saved_tty_pgrp == shell_pgrp)
5970 /* send TTIN to ourself (should stop us) */
5971 kill(- shell_pgrp, SIGTTIN);
5973 /* Block some signals */
5974 block_signals(signal_mask_is_inited);
5975 /* Set other signals to restore saved_tty_pgrp */
5976 set_fatal_handlers();
5977 /* Put ourselves in our own process group */
5978 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
5979 /* Grab control of the terminal */
5980 tcsetpgrp(G_interactive_fd, getpid());
5981 /* -1 is special - makes xfuncs longjmp, not exit
5982 * (we reset die_sleep = 0 whereever we [v]fork) */
5983 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
5984 } else if (!signal_mask_is_inited) {
5985 block_signals(0); /* 0: called 1st time */
5986 } /* else: block_signals(0) was done before */
5987 #elif ENABLE_HUSH_INTERACTIVE
5988 /* No job control compiled in, only prompt/line editing */
5989 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
5990 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
5991 if (G_interactive_fd < 0) {
5992 /* try to dup to any fd */
5993 G_interactive_fd = dup(STDIN_FILENO);
5994 if (G_interactive_fd < 0)
5996 G_interactive_fd = 0;
5999 if (G_interactive_fd) {
6000 close_on_exec_on(G_interactive_fd);
6001 block_signals(signal_mask_is_inited);
6002 } else if (!signal_mask_is_inited) {
6006 /* We have interactiveness code disabled */
6007 if (!signal_mask_is_inited) {
6012 * if interactive but not a login shell, sources ~/.bashrc
6013 * (--norc turns this off, --rcfile <file> overrides)
6016 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
6017 printf("\n\n%s hush - the humble shell\n", bb_banner);
6018 printf("Enter 'help' for a list of built-in commands.\n\n");
6021 parse_and_run_file(stdin);
6024 #if ENABLE_FEATURE_CLEAN_UP
6025 if (G.cwd != bb_msg_unknown)
6027 cur_var = G.top_var->next;
6029 struct variable *tmp = cur_var;
6030 if (!cur_var->max_len)
6031 free(cur_var->varstr);
6032 cur_var = cur_var->next;
6036 hush_exit(G.last_exitcode);
6041 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
6042 int lash_main(int argc, char **argv)
6044 //bb_error_msg("lash is deprecated, please use hush instead");
6045 return hush_main(argc, argv);
6053 static int builtin_trap(char **argv)
6060 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
6064 /* No args: print all trapped. This isn't 100% correct as we
6065 * should be escaping the cmd so that it can be pasted back in
6067 for (i = 0; i < NSIG; ++i)
6069 printf("trap -- '%s' %s\n", G.traps[i], get_signame(i));
6070 return EXIT_SUCCESS;
6075 /* If first arg is decimal: reset all specified signals */
6076 sig = bb_strtou(*argv, NULL, 10);
6082 sig = get_signum(*argv++);
6083 if (sig < 0 || sig >= NSIG) {
6085 /* Mimic bash message exactly */
6086 bb_perror_msg("trap: %s: invalid signal specification", argv[i]);
6091 G.traps[sig] = xstrdup(new_cmd);
6093 debug_printf("trap: setting SIG%s (%i) to '%s'",
6094 get_signame(sig), sig, G.traps[sig]);
6096 /* There is no signal for 0 (EXIT) */
6101 sigaddset(&G.blocked_set, sig);
6103 /* There was a trap handler, we are removing it
6104 * (if sig has non-DFL handling,
6105 * we don't need to do anything) */
6106 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
6108 sigdelset(&G.blocked_set, sig);
6110 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6115 /* First arg is "-": reset all specified to default */
6116 /* First arg is "": ignore all specified */
6117 /* Everything else: execute first arg upon signal */
6119 bb_error_msg("trap: invalid arguments");
6120 return EXIT_FAILURE;
6122 if (NOT_LONE_DASH(*argv))
6128 static int builtin_true(char **argv UNUSED_PARAM)
6133 static int builtin_test(char **argv)
6140 return test_main(argc, argv - argc);
6143 static int builtin_echo(char **argv)
6150 return echo_main(argc, argv - argc);
6153 static int builtin_eval(char **argv)
6155 int rcode = EXIT_SUCCESS;
6158 char *str = expand_strvec_to_string(argv);
6160 * eval "echo Hi; done" ("done" is syntax error):
6161 * "echo Hi" will not execute too.
6163 parse_and_run_string(str);
6165 rcode = G.last_exitcode;
6170 static int builtin_cd(char **argv)
6172 const char *newdir = argv[1];
6173 if (newdir == NULL) {
6174 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
6175 * bash says "bash: cd: HOME not set" and does nothing
6178 newdir = getenv("HOME") ? : "/";
6180 if (chdir(newdir)) {
6181 /* Mimic bash message exactly */
6182 bb_perror_msg("cd: %s", newdir);
6183 return EXIT_FAILURE;
6186 return EXIT_SUCCESS;
6189 static int builtin_exec(char **argv)
6191 if (*++argv == NULL)
6192 return EXIT_SUCCESS; /* bash does this */
6197 // FIXME: if exec fails, bash does NOT exit! We do...
6198 pseudo_exec_argv(&dummy, argv, 0, NULL);
6203 static int builtin_exit(char **argv)
6205 debug_printf_exec("%s()\n", __func__);
6206 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
6207 //puts("exit"); /* bash does it */
6208 // TODO: warn if we have background jobs: "There are stopped jobs"
6209 // On second consecutive 'exit', exit anyway.
6210 // perhaps use G.exiting = -1 as indicator "last cmd was exit"
6212 /* note: EXIT trap is run by hush_exit */
6213 if (*++argv == NULL)
6214 hush_exit(G.last_exitcode);
6215 /* mimic bash: exit 123abc == exit 255 + error msg */
6216 xfunc_error_retval = 255;
6217 /* bash: exit -2 == exit 254, no error msg */
6218 hush_exit(xatoi(*argv) & 0xff);
6221 static int builtin_export(char **argv)
6223 if (*++argv == NULL) {
6230 /* ash emits: export VAR='VAL'
6231 * bash: declare -x VAR="VAL"
6232 * we follow ash example */
6233 const char *s = *e++;
6234 const char *p = strchr(s, '=');
6236 if (!p) /* wtf? take next variable */
6239 printf("export %.*s", (int)(p - s) + 1, s);
6243 p = strchrnul(s, '\'');
6245 printf("'%.*s'", (int)(p - s), s);
6250 /* s points to '; print ''...'''" */
6252 do putchar('\''); while (*++s == '\'');
6260 return EXIT_SUCCESS;
6267 value = strchr(name, '=');
6269 /* They are exporting something without a =VALUE */
6270 struct variable *var;
6272 var = get_local_var(name);
6274 var->flg_export = 1;
6275 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
6276 putenv(var->varstr);
6278 /* bash does not return an error when trying to export
6279 * an undefined variable. Do likewise. */
6282 set_local_var(xstrdup(name), 1, 0);
6285 return EXIT_SUCCESS;
6289 /* built-in 'fg' and 'bg' handler */
6290 static int builtin_fg_bg(char **argv)
6295 if (!G_interactive_fd)
6296 return EXIT_FAILURE;
6297 /* If they gave us no args, assume they want the last backgrounded task */
6299 for (pi = G.job_list; pi; pi = pi->next) {
6300 if (pi->jobid == G.last_jobid) {
6304 bb_error_msg("%s: no current job", argv[0]);
6305 return EXIT_FAILURE;
6307 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
6308 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
6309 return EXIT_FAILURE;
6311 for (pi = G.job_list; pi; pi = pi->next) {
6312 if (pi->jobid == jobnum) {
6316 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
6317 return EXIT_FAILURE;
6319 // TODO: bash prints a string representation
6320 // of job being foregrounded (like "sleep 1 | cat")
6321 if (argv[0][0] == 'f') {
6322 /* Put the job into the foreground. */
6323 tcsetpgrp(G_interactive_fd, pi->pgrp);
6326 /* Restart the processes in the job */
6327 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
6328 for (i = 0; i < pi->num_cmds; i++) {
6329 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
6330 pi->cmds[i].is_stopped = 0;
6332 pi->stopped_cmds = 0;
6334 i = kill(- pi->pgrp, SIGCONT);
6336 if (errno == ESRCH) {
6337 delete_finished_bg_job(pi);
6338 return EXIT_SUCCESS;
6340 bb_perror_msg("kill (SIGCONT)");
6343 if (argv[0][0] == 'f') {
6345 return checkjobs_and_fg_shell(pi);
6347 return EXIT_SUCCESS;
6351 #if ENABLE_HUSH_HELP
6352 static int builtin_help(char **argv UNUSED_PARAM)
6354 const struct built_in_command *x;
6357 "Built-in commands:\n"
6358 "------------------\n");
6359 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
6360 printf("%s\t%s\n", x->cmd, x->descr);
6363 return EXIT_SUCCESS;
6368 static int builtin_jobs(char **argv UNUSED_PARAM)
6371 const char *status_string;
6373 for (job = G.job_list; job; job = job->next) {
6374 if (job->alive_cmds == job->stopped_cmds)
6375 status_string = "Stopped";
6377 status_string = "Running";
6379 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
6381 return EXIT_SUCCESS;
6386 static int builtin_memleak(char **argv UNUSED_PARAM)
6391 /* Crude attempt to find where "free memory" starts,
6392 * sans fragmentation. */
6394 l = (unsigned long)p;
6397 if (l < (unsigned long)p) l = (unsigned long)p;
6400 if (!G.memleak_value)
6401 G.memleak_value = l;
6403 l -= G.memleak_value;
6410 /* Exitcode is "how many kilobytes we leaked since 1st call" */
6415 static int builtin_pwd(char **argv UNUSED_PARAM)
6418 return EXIT_SUCCESS;
6421 static int builtin_read(char **argv)
6424 const char *name = "REPLY";
6428 /* bash (3.2.33(1)) bug: "read 0abcd" will execute,
6429 * and _after_ that_ it will complain */
6430 if (!is_well_formed_var_name(name, '\0')) {
6431 /* Mimic bash message */
6432 bb_error_msg("read: '%s': not a valid identifier", name);
6437 //TODO: bash unbackslashes input, splits words and puts them in argv[i]
6439 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
6440 return set_local_var(string, 0, 0);
6443 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
6444 * built-in 'set' handler
6446 * set [-abCefhmnuvx] [-o option] [argument...]
6447 * set [+abCefhmnuvx] [+o option] [argument...]
6448 * set -- [argument...]
6451 * Implementations shall support the options in both their hyphen and
6452 * plus-sign forms. These options can also be specified as options to sh.
6454 * Write out all variables and their values: set
6455 * Set $1, $2, and $3 and set "$#" to 3: set c a b
6456 * Turn on the -x and -v options: set -xv
6457 * Unset all positional parameters: set --
6458 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
6459 * Set the positional parameters to the expansion of x, even if x expands
6460 * with a leading '-' or '+': set -- $x
6462 * So far, we only support "set -- [argument...]" and some of the short names.
6464 static int builtin_set(char **argv)
6467 char **pp, **g_argv;
6468 char *arg = *++argv;
6472 for (e = G.top_var; e; e = e->next)
6474 return EXIT_SUCCESS;
6478 if (!strcmp(arg, "--")) {
6482 if (arg[0] != '+' && arg[0] != '-')
6484 for (n = 1; arg[n]; ++n)
6485 if (set_mode(arg[0], arg[n]))
6487 } while ((arg = *++argv) != NULL);
6488 /* Now argv[0] is 1st argument */
6491 return EXIT_SUCCESS;
6494 /* NB: G.global_argv[0] ($0) is never freed/changed */
6495 g_argv = G.global_argv;
6496 if (G.global_args_malloced) {
6502 G.global_args_malloced = 1;
6503 pp = xzalloc(sizeof(pp[0]) * 2);
6504 pp[0] = g_argv[0]; /* retain $0 */
6507 /* This realloc's G.global_argv */
6508 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
6515 return EXIT_SUCCESS;
6517 /* Nothing known, so abort */
6519 bb_error_msg("set: %s: invalid option", arg);
6520 return EXIT_FAILURE;
6523 static int builtin_shift(char **argv)
6529 if (n >= 0 && n < G.global_argc) {
6530 if (G.global_args_malloced) {
6533 free(G.global_argv[m++]);
6536 memmove(&G.global_argv[1], &G.global_argv[n+1],
6537 G.global_argc * sizeof(G.global_argv[0]));
6538 return EXIT_SUCCESS;
6540 return EXIT_FAILURE;
6543 static int builtin_source(char **argv)
6547 if (*++argv == NULL)
6548 return EXIT_FAILURE;
6550 /* XXX search through $PATH is missing */
6551 input = fopen_or_warn(*argv, "r");
6553 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
6554 return EXIT_FAILURE;
6556 close_on_exec_on(fileno(input));
6558 /* Now run the file */
6560 /* XXX argv and argc are broken; need to save old G.global_argv
6561 * (pointer only is OK!) on this stack frame,
6562 * set G.global_argv=argv+1, recurse, and restore. */
6563 parse_and_run_file(input);
6565 return G.last_exitcode;
6568 static int builtin_umask(char **argv)
6571 const char *arg = argv[1];
6573 //TODO: umask may take chmod-like symbolic masks
6574 new_umask = bb_strtou(arg, NULL, 8);
6576 //Message? bash examples:
6577 //bash: umask: 'q': invalid symbolic mode operator
6578 //bash: umask: 999: octal number out of range
6579 return EXIT_FAILURE;
6582 new_umask = umask(0);
6583 printf("%.3o\n", (unsigned) new_umask);
6584 /* fall through and restore new_umask which we set to 0 */
6587 return EXIT_SUCCESS;
6590 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
6591 static int builtin_unset(char **argv)
6597 return EXIT_SUCCESS;
6600 if (argv[0][0] == '-') {
6601 switch (argv[0][1]) {
6607 bb_error_msg("unset: %s: invalid option", *argv);
6608 return EXIT_FAILURE;
6610 //TODO: disallow "unset -vf ..." too
6617 if (unset_local_var(*argv)) {
6618 /* unset <nonexistent_var> doesn't fail.
6619 * Error is when one tries to unset RO var.
6620 * Message was printed by unset_local_var. */
6624 //#if ENABLE_HUSH_FUNCTIONS
6626 // unset_local_func(*argv);
6634 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
6635 static int builtin_wait(char **argv)
6637 int ret = EXIT_SUCCESS;
6640 if (*++argv == NULL) {
6641 /* Don't care about wait results */
6642 /* Note 1: must wait until there are no more children */
6643 /* Note 2: must be interruptible */
6645 * $ sleep 3 & sleep 6 & wait
6650 * $ sleep 3 & sleep 6 & wait
6654 * ^C <-- after ~4 sec from keyboard
6657 sigaddset(&G.blocked_set, SIGCHLD);
6658 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6661 if (errno == ECHILD)
6663 /* Wait for SIGCHLD or any other signal of interest */
6664 /* sigtimedwait with infinite timeout: */
6665 sig = sigwaitinfo(&G.blocked_set, NULL);
6667 sig = check_and_run_traps(sig);
6668 if (sig && sig != SIGCHLD) { /* see note 2 */
6674 sigdelset(&G.blocked_set, SIGCHLD);
6675 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6679 /* This is probably buggy wrt interruptible-ness */
6681 pid_t pid = bb_strtou(*argv, NULL, 10);
6683 /* mimic bash message */
6684 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
6685 return EXIT_FAILURE;
6687 if (waitpid(pid, &status, 0) == pid) {
6688 if (WIFSIGNALED(status))
6689 ret = 128 + WTERMSIG(status);
6690 else if (WIFEXITED(status))
6691 ret = WEXITSTATUS(status);
6695 bb_perror_msg("wait %s", *argv);
6704 #if ENABLE_HUSH_LOOPS
6705 static int builtin_break(char **argv)
6707 if (G.depth_of_loop == 0) {
6708 bb_error_msg("%s: only meaningful in a loop", argv[0]);
6709 return EXIT_SUCCESS; /* bash compat */
6711 G.flag_break_continue++; /* BC_BREAK = 1 */
6712 G.depth_break_continue = 1;
6714 G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
6715 if (errno || !G.depth_break_continue || argv[2]) {
6716 bb_error_msg("%s: bad arguments", argv[0]);
6717 G.flag_break_continue = BC_BREAK;
6718 G.depth_break_continue = UINT_MAX;
6721 if (G.depth_of_loop < G.depth_break_continue)
6722 G.depth_break_continue = G.depth_of_loop;
6723 return EXIT_SUCCESS;
6726 static int builtin_continue(char **argv)
6728 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
6729 return builtin_break(argv);