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.
68 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
69 //TODO: pull in some .h and find out whether we have SINGLE_APPLET_MAIN?
70 //#include "applet_tables.h" doesn't work
72 /* #include <dmalloc.h> */
79 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
82 #ifdef WANT_TO_TEST_NOMMU
87 # define USE_FOR_NOMMU(...) __VA_ARGS__
88 # define USE_FOR_MMU(...)
91 #if defined SINGLE_APPLET_MAIN
92 /* STANDALONE does not make sense, and won't compile */
93 #undef CONFIG_FEATURE_SH_STANDALONE
94 #undef ENABLE_FEATURE_SH_STANDALONE
95 #undef USE_FEATURE_SH_STANDALONE
96 #define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
97 #define ENABLE_FEATURE_SH_STANDALONE 0
98 #define USE_FEATURE_SH_STANDALONE(...)
99 #define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
102 #if !ENABLE_HUSH_INTERACTIVE
103 #undef ENABLE_FEATURE_EDITING
104 #define ENABLE_FEATURE_EDITING 0
105 #undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
106 #define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
109 /* Do we support ANY keywords? */
110 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
111 #define HAS_KEYWORDS 1
112 #define IF_HAS_KEYWORDS(...) __VA_ARGS__
113 #define IF_HAS_NO_KEYWORDS(...)
115 #define HAS_KEYWORDS 0
116 #define IF_HAS_KEYWORDS(...)
117 #define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
120 /* Keep unconditionally on for now */
123 #define ENABLE_HUSH_FUNCTIONS 0
126 /* If you comment out one of these below, it will be #defined later
127 * to perform debug printfs to stderr: */
128 #define debug_printf(...) do {} while (0)
129 /* Finer-grained debug switches */
130 #define debug_printf_parse(...) do {} while (0)
131 #define debug_print_tree(a, b) do {} while (0)
132 #define debug_printf_exec(...) do {} while (0)
133 #define debug_printf_env(...) do {} while (0)
134 #define debug_printf_jobs(...) do {} while (0)
135 #define debug_printf_expand(...) do {} while (0)
136 #define debug_printf_glob(...) do {} while (0)
137 #define debug_printf_list(...) do {} while (0)
138 #define debug_printf_subst(...) do {} while (0)
139 #define debug_printf_clean(...) do {} while (0)
142 #define debug_printf(...) fprintf(stderr, __VA_ARGS__)
145 #ifndef debug_printf_parse
146 #define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
149 #ifndef debug_printf_exec
150 #define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
153 #ifndef debug_printf_env
154 #define debug_printf_env(...) fprintf(stderr, __VA_ARGS__)
157 #ifndef debug_printf_jobs
158 #define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
164 #ifndef debug_printf_expand
165 #define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
166 #define DEBUG_EXPAND 1
168 #define DEBUG_EXPAND 0
171 #ifndef debug_printf_glob
172 #define debug_printf_glob(...) fprintf(stderr, __VA_ARGS__)
178 #ifndef debug_printf_list
179 #define debug_printf_list(...) fprintf(stderr, __VA_ARGS__)
182 #ifndef debug_printf_subst
183 #define debug_printf_subst(...) fprintf(stderr, __VA_ARGS__)
186 #ifndef debug_printf_clean
187 /* broken, of course, but OK for testing */
188 static const char *indenter(int i)
190 static const char blanks[] ALIGN1 =
192 return &blanks[sizeof(blanks) - i - 1];
194 #define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
195 #define DEBUG_CLEAN 1
197 #define DEBUG_CLEAN 0
201 static void debug_print_strings(const char *prefix, char **vv)
203 fprintf(stderr, "%s:\n", prefix);
205 fprintf(stderr, " '%s'\n", *vv++);
208 #define debug_print_strings(prefix, vv) ((void)0)
212 * Leak hunting. Use hush_leaktool.sh for post-processing.
214 #ifdef FOR_HUSH_LEAKTOOL
215 static void *xxmalloc(int lineno, size_t size)
217 void *ptr = xmalloc((size + 0xff) & ~0xff);
218 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
221 static void *xxrealloc(int lineno, void *ptr, size_t size)
223 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
224 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
227 static char *xxstrdup(int lineno, const char *str)
229 char *ptr = xstrdup(str);
230 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
233 static void xxfree(void *ptr)
235 fdprintf(2, "free %p\n", ptr);
238 #define xmalloc(s) xxmalloc(__LINE__, s)
239 #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
240 #define xstrdup(s) xxstrdup(__LINE__, s)
241 #define free(p) xxfree(p)
245 #define ERR_PTR ((void*)(long)1)
247 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
249 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
251 #define SPECIAL_VAR_SYMBOL 3
253 /* The descrip member of this structure is only used to make
254 * debugging output pretty */
255 static const struct {
257 signed char default_fd;
261 { O_RDONLY, 0, "<" },
262 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
263 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
264 { O_RDONLY, 0, "<<" },
265 { O_CREAT|O_RDWR, 1, "<>" },
266 /* Should not be needed. Bogus default_fd helps in debugging */
267 /* { O_RDONLY, 77, "<<" }, */
270 typedef enum reserved_style {
279 #if ENABLE_HUSH_LOOPS
286 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
291 /* two pseudo-keywords support contrived "case" syntax: */
292 RES_MATCH , /* "word)" */
293 RES_CASEI , /* "this command is inside CASE" */
300 typedef struct o_string {
302 int length; /* position where data is appended */
304 /* Protect newly added chars against globbing
305 * (by prepending \ to *, ?, [, \) */
308 /* At least some part of the string was inside '' or "",
309 * possibly empty one: word"", wo''rd etc. */
311 smallint has_empty_slot;
312 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
315 MAYBE_ASSIGNMENT = 0,
316 DEFINITELY_ASSIGNMENT = 1,
318 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
320 /* Used for initialization: o_string foo = NULL_O_STRING; */
321 #define NULL_O_STRING { NULL }
323 /* I can almost use ordinary FILE*. Is open_memstream() universally
324 * available? Where is it documented? */
325 typedef struct in_str {
327 /* eof_flag=1: last char in ->p is really an EOF */
328 char eof_flag; /* meaningless if ->p == NULL */
330 #if ENABLE_HUSH_INTERACTIVE
332 smallint promptmode; /* 0: PS1, 1: PS2 */
335 int (*get) (struct in_str *);
336 int (*peek) (struct in_str *);
338 #define i_getch(input) ((input)->get(input))
339 #define i_peek(input) ((input)->peek(input))
341 struct redir_struct {
342 struct redir_struct *next;
343 char *rd_filename; /* filename */
344 int rd_fd; /* fd to redirect */
345 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
347 smallint rd_type; /* (enum redir_type) */
348 /* note: for heredocs, rd_filename contains heredoc delimiter,
349 * and subsequently heredoc itself; and rd_dup is a bitmask:
350 * 1: do we need to trim leading tabs?
351 * 2: is heredoc quoted (<<'dleim' syntax) ?
354 typedef enum redir_type {
355 REDIRECT_INVALID = 0,
357 REDIRECT_OVERWRITE = 2,
359 REDIRECT_HEREDOC = 4,
361 REDIRECT_HEREDOC2 = 6, /* REDIRECT_HEREDOC after heredoc is loaded */
363 HEREDOC_SKIPTABS = 1,
369 pid_t pid; /* 0 if exited */
370 int assignment_cnt; /* how many argv[i] are assignments? */
371 smallint is_stopped; /* is the command currently running? */
372 smallint grp_type; /* GRP_xxx */
373 struct pipe *group; /* if non-NULL, this "command" is { list },
374 * ( list ), or a compound statement */
376 char *group_as_string;
378 char **argv; /* command name and arguments */
379 struct redir_struct *redirects; /* I/O redirections */
381 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
382 * and on execution these are substituted with their values.
383 * Substitution can make _several_ words out of one argv[n]!
384 * Example: argv[0]=='.^C*^C.' here: echo .$*.
385 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
388 #define GRP_SUBSHELL 1
389 #if ENABLE_HUSH_FUNCTIONS
390 #define GRP_FUNCTION 2
395 int num_cmds; /* total number of commands in job */
396 int alive_cmds; /* number of commands running (not exited) */
397 int stopped_cmds; /* number of commands alive, but stopped */
399 int jobid; /* job number */
400 pid_t pgrp; /* process group ID for the job */
401 char *cmdtext; /* name of job */
403 struct command *cmds; /* array of commands in pipe */
404 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
405 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
406 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
408 typedef enum pipe_style {
415 /* This holds pointers to the various results of parsing */
416 struct parse_context {
417 /* linked list of pipes */
418 struct pipe *list_head;
419 /* last pipe (being constructed right now) */
421 /* last command in pipe (being constructed right now) */
422 struct command *command;
423 /* last redirect in command->redirects list */
424 struct redir_struct *pending_redirect;
430 smallint ctx_inverted; /* "! cmd | cmd" */
432 smallint ctx_dsemicolon; /* ";;" seen */
434 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
436 /* group we are enclosed in:
437 * example: "if pipe1; pipe2; then pipe3; fi"
438 * when we see "if" or "then", we malloc and copy current context,
439 * and make ->stack point to it. then we parse pipeN.
440 * when closing "then" / fi" / whatever is found,
441 * we move list_head into ->stack->command->group,
442 * copy ->stack into current context, and delete ->stack.
443 * (parsing of { list } and ( list ) doesn't use this method)
445 struct parse_context *stack;
449 /* On program start, environ points to initial environment.
450 * putenv adds new pointers into it, unsetenv removes them.
451 * Neither of these (de)allocates the strings.
452 * setenv allocates new strings in malloc space and does putenv,
453 * and thus setenv is unusable (leaky) for shell's purposes */
454 #define setenv(...) setenv_is_leaky_dont_use()
456 struct variable *next;
457 char *varstr; /* points to "name=" portion */
458 int max_len; /* if > 0, name is part of initial env; else name is malloced */
459 smallint flg_export; /* putenv should be done on this var */
460 smallint flg_read_only;
469 /* "Globals" within this file */
470 /* Sorted roughly by size (smaller offsets == smaller code) */
472 #if ENABLE_HUSH_INTERACTIVE
473 /* 'interactive_fd' is a fd# open to ctty, if we have one
474 * _AND_ if we decided to act interactively */
478 #define G_interactive_fd (G.interactive_fd)
480 #define G_interactive_fd 0
482 #if ENABLE_FEATURE_EDITING
483 line_input_t *line_input_state;
489 pid_t saved_tty_pgrp;
491 struct pipe *job_list;
492 struct pipe *toplevel_list;
493 //// smallint ctrl_z_flag;
495 smallint flag_SIGINT;
496 #if ENABLE_HUSH_LOOPS
497 smallint flag_break_continue;
500 /* These four support $?, $#, and $1 */
501 smalluint last_exitcode;
502 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
503 smalluint global_args_malloced;
504 /* how many non-NULL argv's we have. NB: $# + 1 */
508 char *argv0_for_re_execing;
509 char **argv_from_re_execing;
511 #if ENABLE_HUSH_LOOPS
512 unsigned depth_break_continue;
513 unsigned depth_of_loop;
517 struct variable *top_var; /* = &G.shell_ver (set in main()) */
518 struct variable shell_ver;
519 /* Signal and trap handling */
520 // unsigned count_SIGCHLD;
521 // unsigned handled_SIGCHLD;
522 /* which signals have non-DFL handler (even with no traps set)? */
523 unsigned non_DFL_mask;
524 char **traps; /* char *traps[NSIG] */
525 sigset_t blocked_set;
526 sigset_t inherited_set;
527 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
528 #if ENABLE_FEATURE_SH_STANDALONE
529 struct nofork_save_area nofork_save;
532 sigjmp_buf toplevel_jb;
535 #define G (*ptr_to_globals)
536 /* Not #defining name to G.name - this quickly gets unwieldy
537 * (too many defines). Also, I actually prefer to see when a variable
538 * is global, thus "G." prefix is a useful hint */
539 #define INIT_G() do { \
540 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
544 /* Function prototypes for builtins */
545 static int builtin_cd(char **argv);
546 static int builtin_echo(char **argv);
547 static int builtin_eval(char **argv);
548 static int builtin_exec(char **argv);
549 static int builtin_exit(char **argv);
550 static int builtin_export(char **argv);
552 static int builtin_fg_bg(char **argv);
553 static int builtin_jobs(char **argv);
556 static int builtin_help(char **argv);
558 static int builtin_pwd(char **argv);
559 static int builtin_read(char **argv);
560 static int builtin_test(char **argv);
561 static int builtin_trap(char **argv);
562 static int builtin_true(char **argv);
563 static int builtin_set(char **argv);
564 static int builtin_shift(char **argv);
565 static int builtin_source(char **argv);
566 static int builtin_umask(char **argv);
567 static int builtin_unset(char **argv);
568 static int builtin_wait(char **argv);
569 #if ENABLE_HUSH_LOOPS
570 static int builtin_break(char **argv);
571 static int builtin_continue(char **argv);
574 /* Table of built-in functions. They can be forked or not, depending on
575 * context: within pipes, they fork. As simple commands, they do not.
576 * When used in non-forking context, they can change global variables
577 * in the parent shell process. If forked, of course they cannot.
578 * For example, 'unset foo | whatever' will parse and run, but foo will
579 * still be set at the end. */
580 struct built_in_command {
582 int (*function)(char **argv);
585 #define BLTIN(cmd, func, help) { cmd, func, help }
587 #define BLTIN(cmd, func, help) { cmd, func }
591 /* For now, echo and test are unconditionally enabled.
592 * Maybe make it configurable? */
593 static const struct built_in_command bltins[] = {
594 BLTIN("." , builtin_source , "Run commands in a file"),
595 BLTIN(":" , builtin_true , "No-op"),
596 BLTIN("[" , builtin_test , "Test condition"),
598 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
600 #if ENABLE_HUSH_LOOPS
601 BLTIN("break" , builtin_break , "Exit from a loop"),
603 BLTIN("cd" , builtin_cd , "Change directory"),
604 #if ENABLE_HUSH_LOOPS
605 BLTIN("continue", builtin_continue, "Start new loop iteration"),
607 BLTIN("echo" , builtin_echo , "Write to stdout"),
608 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
609 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
610 BLTIN("exit" , builtin_exit , "Exit"),
611 BLTIN("export" , builtin_export , "Set environment variable"),
613 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
616 BLTIN("help" , builtin_help , "List shell built-in commands"),
619 BLTIN("jobs" , builtin_jobs , "List active jobs"),
621 BLTIN("pwd" , builtin_pwd , "Print current directory"),
622 BLTIN("read" , builtin_read , "Input environment variable"),
623 // BLTIN("return" , builtin_return , "Return from a function"),
624 BLTIN("set" , builtin_set , "Set/unset shell local variables"),
625 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
626 BLTIN("test" , builtin_test , "Test condition"),
627 BLTIN("trap" , builtin_trap , "Trap signals"),
628 // BLTIN("ulimit" , builtin_return , "Control resource limits"),
629 BLTIN("umask" , builtin_umask , "Set file creation mask"),
630 BLTIN("unset" , builtin_unset , "Unset environment variable"),
631 BLTIN("wait" , builtin_wait , "Wait for process"),
635 static void maybe_die(const char *notice, const char *msg)
637 /* Was using fancy stuff:
638 * (G_interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
639 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
640 void FAST_FUNC (*fp)(const char *s, ...) = bb_error_msg_and_die;
641 #if ENABLE_HUSH_INTERACTIVE
642 if (G_interactive_fd)
645 fp(msg ? "%s: %s" : notice, notice, msg);
648 #define syntax(msg) maybe_die("syntax error", msg);
650 /* Debug -- trick gcc to expand __LINE__ and convert to string */
651 #define __syntax(msg, line) maybe_die("syntax error hush.c:" # line, msg)
652 #define _syntax(msg, line) __syntax(msg, line)
653 #define syntax(msg) _syntax(msg, __LINE__)
657 static int glob_needed(const char *s)
662 if (*s == '*' || *s == '[' || *s == '?')
669 static int is_assignment(const char *s)
671 if (!s || !(isalpha(*s) || *s == '_'))
674 while (isalnum(*s) || *s == '_')
679 /* Replace each \x with x in place, return ptr past NUL. */
680 static char *unbackslash(char *src)
686 if ((*dst++ = *src++) == '\0')
692 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
713 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
714 v[count1 + count2] = NULL;
717 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
721 static char **add_string_to_strings(char **strings, char *add)
726 return add_strings_to_strings(strings, v, /*dup:*/ 0);
729 static void putenv_all(char **strings)
734 debug_printf_env("putenv '%s'\n", *strings);
739 static char **putenv_all_and_save_old(char **strings)
749 eq = strchr(*strings, '=');
752 v = getenv(*strings);
755 /* v points to VAL in VAR=VAL, go back to VAR */
756 v -= (eq - *strings) + 1;
757 old = add_string_to_strings(old, v);
766 static void free_strings_and_unsetenv(char **strings, int unset)
776 debug_printf_env("unsetenv '%s'\n", *v);
784 static void free_strings(char **strings)
786 free_strings_and_unsetenv(strings, 0);
790 /* Basic theory of signal handling in shell
791 * ========================================
792 * This does not describe what hush does, rather, it is current understanding
793 * what it _should_ do. If it doesn't, it's a bug.
794 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
796 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
797 * is finished or backgrounded. It is the same in interactive and
798 * non-interactive shells, and is the same regardless of whether
799 * a user trap handler is installed or a shell special one is in effect.
800 * ^C or ^Z from keyboard seem to execute "at once" because it usually
801 * backgrounds (i.e. stops) or kills all members of currently running
804 * Wait builtin in interruptible by signals for which user trap is set
805 * or by SIGINT in interactive shell.
807 * Trap handlers will execute even within trap handlers. (right?)
809 * User trap handlers are forgotten when subshell ("(cmd)") is entered. [TODO]
811 * If job control is off, backgrounded commands ("cmd &")
812 * have SIGINT, SIGQUIT set to SIG_IGN.
814 * Commands run in command substitution ("`cmd`")
815 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
817 * Ordinary commands have signals set to SIG_IGN/DFL set as inherited
818 * by the shell from its parent.
820 * Siganls which differ from SIG_DFL action
821 * (note: child (i.e., [v]forked) shell is not an interactive shell):
824 * SIGTERM (interactive): ignore
825 * SIGHUP (interactive):
826 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
827 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
828 * (note that ^Z is handled not by trapping SIGTSTP, but by seeing
829 * that all pipe members are stopped) (right?)
830 * SIGINT (interactive): wait for last pipe, ignore the rest
831 * of the command line, show prompt. NB: ^C does not send SIGINT
832 * to interactive shell while shell is waiting for a pipe,
833 * since shell is bg'ed (is not in foreground process group).
834 * (check/expand this)
835 * Example 1: this waits 5 sec, but does not execute ls:
836 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
837 * Example 2: this does not wait and does not execute ls:
838 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
839 * Example 3: this does not wait 5 sec, but executes ls:
840 * "sleep 5; ls -l" + press ^C
842 * (What happens to signals which are IGN on shell start?)
843 * (What happens with signal mask on shell start?)
845 * Implementation in hush
846 * ======================
847 * We use in-kernel pending signal mask to determine which signals were sent.
848 * We block all signals which we don't want to take action immediately,
849 * i.e. we block all signals which need to have special handling as described
850 * above, and all signals which have traps set.
851 * After each pipe execution, we extract any pending signals via sigtimedwait()
854 * unsigned non_DFL_mask: a mask of such "special" signals
855 * sigset_t blocked_set: current blocked signal set
858 * clear bit in blocked_set unless it is also in non_DFL_mask
859 * "trap 'cmd' SIGxxx":
860 * set bit in blocked_set (even if 'cmd' is '')
861 * after [v]fork, if we plan to be a shell:
862 * nothing for {} child shell (say, "true | { true; true; } | true")
863 * unset all traps if () shell. [TODO]
864 * after [v]fork, if we plan to exec:
865 * POSIX says pending signal mask is cleared in child - no need to clear it.
866 * Restore blocked signal set to one inherited by shell just prior to exec.
868 * Note: as a result, we do not use signal handlers much. The only uses
869 * are to count SIGCHLDs [disabled - bug somewhere, + bloat]
870 * and to restore tty pgrp on signal-induced exit.
873 //static void SIGCHLD_handler(int sig UNUSED_PARAM)
875 // G.count_SIGCHLD++;
878 static int check_and_run_traps(int sig)
880 static const struct timespec zero_timespec = { 0, 0 };
881 smalluint save_rcode;
887 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
892 if (G.traps && G.traps[sig]) {
893 if (G.traps[sig][0]) {
894 /* We have user-defined handler */
895 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
896 save_rcode = G.last_exitcode;
899 G.last_exitcode = save_rcode;
900 } /* else: "" trap, ignoring signal */
903 /* not a trap: special action */
906 // G.count_SIGCHLD++;
915 default: /* ignored: */
916 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
925 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
926 #define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
927 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
928 #define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
930 /* Restores tty foreground process group, and exits.
931 * May be called as signal handler for fatal signal
932 * (will faithfully resend signal to itself, producing correct exit state)
933 * or called directly with -EXITCODE.
934 * We also call it if xfunc is exiting. */
935 static void sigexit(int sig) NORETURN;
936 static void sigexit(int sig)
938 /* Disable all signals: job control, SIGPIPE, etc. */
939 sigprocmask_allsigs(SIG_BLOCK);
941 /* Careful: we can end up here after [v]fork. Do not restore
942 * tty pgrp then, only top-level shell process does that */
943 if (G_interactive_fd && getpid() == G.root_pid)
944 tcsetpgrp(G_interactive_fd, G.saved_tty_pgrp);
946 /* Not a signal, just exit */
950 kill_myself_with_sig(sig); /* does not return */
954 #define disable_restore_tty_pgrp_on_exit() ((void)0)
955 #define enable_restore_tty_pgrp_on_exit() ((void)0)
959 /* Restores tty foreground process group, and exits. */
960 static void hush_exit(int exitcode) NORETURN;
961 static void hush_exit(int exitcode)
963 if (G.traps && G.traps[0] && G.traps[0][0]) {
964 char *argv[] = { NULL, xstrdup(G.traps[0]), NULL };
965 //TODO: do we need to prevent recursion?
971 fflush(NULL); /* flush all streams */
972 sigexit(- (exitcode & 0xff));
979 static const char *set_cwd(void)
981 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
982 * we must not try to free(bb_msg_unknown) */
983 if (G.cwd == bb_msg_unknown)
985 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
987 G.cwd = bb_msg_unknown;
992 /* Get/check local shell variables */
993 static struct variable *get_local_var(const char *name)
995 struct variable *cur;
1001 for (cur = G.top_var; cur; cur = cur->next) {
1002 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1008 static const char *get_local_var_value(const char *src)
1010 struct variable *var = get_local_var(src);
1012 return strchr(var->varstr, '=') + 1;
1016 /* str holds "NAME=VAL" and is expected to be malloced.
1017 * We take ownership of it.
1021 * -1: if NAME is set, leave export status alone
1022 * if NAME is not set, do not export
1023 * flg_read_only is set only when we handle -R var=val
1026 #define set_local_var(str, flg_export, flg_read_only) \
1027 set_local_var(str, flg_export)
1029 static int set_local_var(char *str, int flg_export, int flg_read_only)
1031 struct variable *cur;
1035 value = strchr(str, '=');
1036 if (!value) { /* not expected to ever happen? */
1041 name_len = value - str + 1; /* including '=' */
1042 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
1044 if (strncmp(cur->varstr, str, name_len) != 0) {
1046 /* Bail out. Note that now cur points
1047 * to last var in linked list */
1053 /* We found an existing var with this name */
1055 if (cur->flg_read_only) {
1059 bb_error_msg("%s: readonly variable", str);
1063 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1064 unsetenv(str); /* just in case */
1066 if (strcmp(cur->varstr, str) == 0) {
1071 if (cur->max_len >= strlen(str)) {
1072 /* This one is from startup env, reuse space */
1073 strcpy(cur->varstr, str);
1076 /* max_len == 0 signifies "malloced" var, which we can
1077 * (and has to) free */
1081 goto set_str_and_exp;
1084 /* Not found - create next variable struct */
1085 cur->next = xzalloc(sizeof(*cur));
1091 cur->flg_read_only = flg_read_only;
1094 if (flg_export == 1)
1095 cur->flg_export = 1;
1096 if (cur->flg_export) {
1097 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1098 return putenv(cur->varstr);
1103 static int unset_local_var(const char *name)
1105 struct variable *cur;
1106 struct variable *prev = prev; /* for gcc */
1110 return EXIT_SUCCESS;
1111 name_len = strlen(name);
1114 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1115 if (cur->flg_read_only) {
1116 bb_error_msg("%s: readonly variable", name);
1117 return EXIT_FAILURE;
1119 /* prev is ok to use here because 1st variable, HUSH_VERSION,
1120 * is ro, and we cannot reach this code on the 1st pass */
1121 prev->next = cur->next;
1122 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1123 bb_unsetenv(cur->varstr);
1127 return EXIT_SUCCESS;
1132 return EXIT_SUCCESS;
1135 #if ENABLE_SH_MATH_SUPPORT
1136 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1137 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1138 static char *endofname(const char *name)
1146 if (!is_in_name(*p))
1152 static void arith_set_local_var(const char *name, const char *val, int flags)
1154 /* arith code doesnt malloc space, so do it for it */
1155 char *var = xasprintf("%s=%s", name, val);
1156 set_local_var(var, flags, 0);
1164 static int static_get(struct in_str *i)
1173 static int static_peek(struct in_str *i)
1178 #if ENABLE_HUSH_INTERACTIVE
1180 static void cmdedit_set_initial_prompt(void)
1182 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1183 G.PS1 = getenv("PS1");
1190 static const char* setup_prompt_string(int promptmode)
1192 const char *prompt_str;
1193 debug_printf("setup_prompt_string %d ", promptmode);
1194 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1195 /* Set up the prompt */
1196 if (promptmode == 0) { /* PS1 */
1198 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1203 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1204 debug_printf("result '%s'\n", prompt_str);
1208 static void get_user_input(struct in_str *i)
1211 const char *prompt_str;
1213 prompt_str = setup_prompt_string(i->promptmode);
1214 #if ENABLE_FEATURE_EDITING
1215 /* Enable command line editing only while a command line
1216 * is actually being read */
1219 /* buglet: SIGINT will not make new prompt to appear _at once_,
1220 * only after <Enter>. (^C will work) */
1221 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1222 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1223 check_and_run_traps(0);
1224 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1225 i->eof_flag = (r < 0);
1226 if (i->eof_flag) { /* EOF/error detected */
1227 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1228 G.user_input_buf[1] = '\0';
1233 fputs(prompt_str, stdout);
1235 G.user_input_buf[0] = r = fgetc(i->file);
1236 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1237 //do we need check_and_run_traps(0)? (maybe only if stdin)
1238 } while (G.flag_SIGINT);
1239 i->eof_flag = (r == EOF);
1241 i->p = G.user_input_buf;
1244 #endif /* INTERACTIVE */
1246 /* This is the magic location that prints prompts
1247 * and gets data back from the user */
1248 static int file_get(struct in_str *i)
1252 /* If there is data waiting, eat it up */
1253 if (i->p && *i->p) {
1254 #if ENABLE_HUSH_INTERACTIVE
1258 if (i->eof_flag && !*i->p)
1260 /* note: ch is never NUL */
1262 /* need to double check i->file because we might be doing something
1263 * more complicated by now, like sourcing or substituting. */
1264 #if ENABLE_HUSH_INTERACTIVE
1265 if (G_interactive_fd && i->promptme && i->file == stdin) {
1268 } while (!*i->p); /* need non-empty line */
1269 i->promptmode = 1; /* PS2 */
1274 do ch = fgetc(i->file); while (ch == '\0');
1276 debug_printf("file_get: got '%c' %d\n", ch, ch);
1277 #if ENABLE_HUSH_INTERACTIVE
1284 /* All callers guarantee this routine will never
1285 * be used right after a newline, so prompting is not needed.
1287 static int file_peek(struct in_str *i)
1290 if (i->p && *i->p) {
1291 if (i->eof_flag && !i->p[1])
1294 /* note: ch is never NUL */
1296 do ch = fgetc(i->file); while (ch == '\0');
1297 i->eof_flag = (ch == EOF);
1298 i->peek_buf[0] = ch;
1299 i->peek_buf[1] = '\0';
1301 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1305 static void setup_file_in_str(struct in_str *i, FILE *f)
1307 i->peek = file_peek;
1309 #if ENABLE_HUSH_INTERACTIVE
1311 i->promptmode = 0; /* PS1 */
1317 static void setup_string_in_str(struct in_str *i, const char *s)
1319 i->peek = static_peek;
1320 i->get = static_get;
1321 #if ENABLE_HUSH_INTERACTIVE
1323 i->promptmode = 0; /* PS1 */
1333 #define B_CHUNK (32 * sizeof(char*))
1335 static void o_reset(o_string *o)
1343 static void o_free(o_string *o)
1346 memset(o, 0, sizeof(*o));
1349 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1354 static void o_grow_by(o_string *o, int len)
1356 if (o->length + len > o->maxlen) {
1357 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1358 o->data = xrealloc(o->data, 1 + o->maxlen);
1362 static void o_addchr(o_string *o, int ch)
1364 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1366 o->data[o->length] = ch;
1368 o->data[o->length] = '\0';
1371 static void o_addblock(o_string *o, const char *str, int len)
1374 memcpy(&o->data[o->length], str, len);
1376 o->data[o->length] = '\0';
1380 static void o_addstr(o_string *o, const char *str)
1382 o_addblock(o, str, strlen(str));
1384 static void nommu_addchr(o_string *o, int ch)
1390 #define nommu_addchr(o, str) ((void)0)
1393 static void o_addstr_with_NUL(o_string *o, const char *str)
1395 o_addblock(o, str, strlen(str) + 1);
1398 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
1403 && (*str != '*' && *str != '?' && *str != '[')
1411 /* My analysis of quoting semantics tells me that state information
1412 * is associated with a destination, not a source.
1414 static void o_addqchr(o_string *o, int ch)
1417 char *found = strchr("*?[\\", ch);
1422 o->data[o->length] = '\\';
1425 o->data[o->length] = ch;
1427 o->data[o->length] = '\0';
1430 static void o_addQchr(o_string *o, int ch)
1433 if (o->o_escape && strchr("*?[\\", ch)) {
1435 o->data[o->length] = '\\';
1439 o->data[o->length] = ch;
1441 o->data[o->length] = '\0';
1444 static void o_addQstr(o_string *o, const char *str, int len)
1447 o_addblock(o, str, len);
1453 int ordinary_cnt = strcspn(str, "*?[\\");
1454 if (ordinary_cnt > len) /* paranoia */
1456 o_addblock(o, str, ordinary_cnt);
1457 if (ordinary_cnt == len)
1459 str += ordinary_cnt;
1460 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
1464 if (ch) { /* it is necessarily one of "*?[\\" */
1466 o->data[o->length] = '\\';
1470 o->data[o->length] = ch;
1472 o->data[o->length] = '\0';
1476 /* A special kind of o_string for $VAR and `cmd` expansion.
1477 * It contains char* list[] at the beginning, which is grown in 16 element
1478 * increments. Actual string data starts at the next multiple of 16 * (char*).
1479 * list[i] contains an INDEX (int!) into this string data.
1480 * It means that if list[] needs to grow, data needs to be moved higher up
1481 * but list[i]'s need not be modified.
1482 * NB: remembering how many list[i]'s you have there is crucial.
1483 * o_finalize_list() operation post-processes this structure - calculates
1484 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1486 #if DEBUG_EXPAND || DEBUG_GLOB
1487 static void debug_print_list(const char *prefix, o_string *o, int n)
1489 char **list = (char**)o->data;
1490 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1492 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1493 prefix, list, n, string_start, o->length, o->maxlen);
1495 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1496 o->data + (int)list[i] + string_start,
1497 o->data + (int)list[i] + string_start);
1501 const char *p = o->data + (int)list[n - 1] + string_start;
1502 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
1506 #define debug_print_list(prefix, o, n) ((void)0)
1509 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1510 * in list[n] so that it points past last stored byte so far.
1511 * It returns n+1. */
1512 static int o_save_ptr_helper(o_string *o, int n)
1514 char **list = (char**)o->data;
1518 if (!o->has_empty_slot) {
1519 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1520 string_len = o->length - string_start;
1521 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1522 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
1523 /* list[n] points to string_start, make space for 16 more pointers */
1524 o->maxlen += 0x10 * sizeof(list[0]);
1525 o->data = xrealloc(o->data, o->maxlen + 1);
1526 list = (char**)o->data;
1527 memmove(list + n + 0x10, list + n, string_len);
1528 o->length += 0x10 * sizeof(list[0]);
1530 debug_printf_list("list[%d]=%d string_start=%d\n",
1531 n, string_len, string_start);
1534 /* We have empty slot at list[n], reuse without growth */
1535 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1536 string_len = o->length - string_start;
1537 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1538 n, string_len, string_start);
1539 o->has_empty_slot = 0;
1541 list[n] = (char*)(ptrdiff_t)string_len;
1545 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
1546 static int o_get_last_ptr(o_string *o, int n)
1548 char **list = (char**)o->data;
1549 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1551 return ((int)(ptrdiff_t)list[n-1]) + string_start;
1554 /* o_glob performs globbing on last list[], saving each result
1555 * as a new list[]. */
1556 static int o_glob(o_string *o, int n)
1562 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
1564 return o_save_ptr_helper(o, n);
1565 pattern = o->data + o_get_last_ptr(o, n);
1566 debug_printf_glob("glob pattern '%s'\n", pattern);
1567 if (!glob_needed(pattern)) {
1569 o->length = unbackslash(pattern) - o->data;
1570 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
1571 return o_save_ptr_helper(o, n);
1574 memset(&globdata, 0, sizeof(globdata));
1575 gr = glob(pattern, 0, NULL, &globdata);
1576 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1577 if (gr == GLOB_NOSPACE)
1578 bb_error_msg_and_die("out of memory during glob");
1579 if (gr == GLOB_NOMATCH) {
1580 globfree(&globdata);
1583 if (gr != 0) { /* GLOB_ABORTED ? */
1584 //TODO: testcase for bad glob pattern behavior
1585 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1587 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1588 char **argv = globdata.gl_pathv;
1589 o->length = pattern - o->data; /* "forget" pattern */
1591 o_addstr_with_NUL(o, *argv);
1592 n = o_save_ptr_helper(o, n);
1598 globfree(&globdata);
1600 debug_print_list("o_glob returning", o, n);
1604 /* If o->o_glob == 1, glob the string so far remembered.
1605 * Otherwise, just finish current list[] and start new */
1606 static int o_save_ptr(o_string *o, int n)
1608 if (o->o_glob) { /* if globbing is requested */
1609 /* If o->has_empty_slot, list[n] was already globbed
1610 * (if it was requested back then when it was filled)
1611 * so don't do that again! */
1612 if (!o->has_empty_slot)
1613 return o_glob(o, n); /* o_save_ptr_helper is inside */
1615 return o_save_ptr_helper(o, n);
1618 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
1619 static char **o_finalize_list(o_string *o, int n)
1624 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1626 debug_print_list("finalized", o, n);
1627 debug_printf_expand("finalized n:%d\n", n);
1628 list = (char**)o->data;
1629 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1633 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
1639 /* Expansion can recurse */
1640 #if ENABLE_HUSH_TICK
1641 static int process_command_subs(o_string *dest, const char *s);
1643 static char *expand_string_to_string(const char *str);
1645 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
1646 parse_stream_dquoted(dest, input, dquote_end)
1648 static int parse_stream_dquoted(o_string *as_string,
1650 struct in_str *input,
1653 /* expand_strvec_to_strvec() takes a list of strings, expands
1654 * all variable references within and returns a pointer to
1655 * a list of expanded strings, possibly with larger number
1656 * of strings. (Think VAR="a b"; echo $VAR).
1657 * This new list is allocated as a single malloc block.
1658 * NULL-terminated list of char* pointers is at the beginning of it,
1659 * followed by strings themself.
1660 * Caller can deallocate entire list by single free(list). */
1662 /* Store given string, finalizing the word and starting new one whenever
1663 * we encounter IFS char(s). This is used for expanding variable values.
1664 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
1665 static int expand_on_ifs(o_string *output, int n, const char *str)
1668 int word_len = strcspn(str, G.ifs);
1670 if (output->o_escape || !output->o_glob)
1671 o_addQstr(output, str, word_len);
1672 else /* protect backslashes against globbing up :) */
1673 o_addblock_duplicate_backslash(output, str, word_len);
1676 if (!*str) /* EOL - do not finalize word */
1678 o_addchr(output, '\0');
1679 debug_print_list("expand_on_ifs", output, n);
1680 n = o_save_ptr(output, n);
1681 str += strspn(str, G.ifs); /* skip ifs chars */
1683 debug_print_list("expand_on_ifs[1]", output, n);
1687 /* Helper to expand $((...)) and heredoc body. These act as if
1688 * they are in double quotes, with the exception that they are not :).
1689 * Just the rules are similar: "expand only $var and `cmd`"
1691 * Returns malloced string.
1692 * As an optimization, we return NULL if expansion is not needed.
1694 static char *expand_pseudo_dquoted(const char *str)
1697 struct in_str input;
1698 o_string dest = NULL_O_STRING;
1700 if (strchr(str, '$') == NULL
1701 #if ENABLE_HUSH_TICK
1702 && strchr(str, '`') == NULL
1708 /* We need to expand. Example:
1709 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
1711 setup_string_in_str(&input, str);
1712 parse_stream_dquoted(NULL, &dest, &input, EOF);
1713 //bb_error_msg("'%s' -> '%s'", str, dest.data);
1714 exp_str = expand_string_to_string(dest.data);
1715 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
1716 o_free_unsafe(&dest);
1720 /* Expand all variable references in given string, adding words to list[]
1721 * at n, n+1,... positions. Return updated n (so that list[n] is next one
1722 * to be filled). This routine is extremely tricky: has to deal with
1723 * variables/parameters with whitespace, $* and $@, and constructs like
1724 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
1725 static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
1727 /* or_mask is either 0 (normal case) or 0x80
1728 * (expansion of right-hand side of assignment == 1-element expand.
1729 * It will also do no globbing, and thus we must not backslash-quote!) */
1731 char first_ch, ored_ch;
1739 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
1740 debug_print_list("expand_vars_to_list", output, n);
1741 n = o_save_ptr(output, n);
1742 debug_print_list("expand_vars_to_list[0]", output, n);
1744 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
1745 #if ENABLE_HUSH_TICK
1746 o_string subst_result = NULL_O_STRING;
1748 #if ENABLE_SH_MATH_SUPPORT
1749 char arith_buf[sizeof(arith_t)*3 + 2];
1751 o_addblock(output, arg, p - arg);
1752 debug_print_list("expand_vars_to_list[1]", output, n);
1754 p = strchr(p, SPECIAL_VAR_SYMBOL);
1756 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
1757 /* "$@" is special. Even if quoted, it can still
1758 * expand to nothing (not even an empty string) */
1759 if ((first_ch & 0x7f) != '@')
1760 ored_ch |= first_ch;
1763 switch (first_ch & 0x7f) {
1764 /* Highest bit in first_ch indicates that var is double-quoted */
1766 val = utoa(G.root_pid);
1768 case '!': /* bg pid */
1769 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
1771 case '?': /* exitcode */
1772 val = utoa(G.last_exitcode);
1774 case '#': /* argc */
1775 if (arg[1] != SPECIAL_VAR_SYMBOL)
1776 /* actually, it's a ${#var} */
1778 val = utoa(G.global_argc ? G.global_argc-1 : 0);
1783 if (!G.global_argv[i])
1785 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
1786 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
1787 smallint sv = output->o_escape;
1788 /* unquoted var's contents should be globbed, so don't escape */
1789 output->o_escape = 0;
1790 while (G.global_argv[i]) {
1791 n = expand_on_ifs(output, n, G.global_argv[i]);
1792 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
1793 if (G.global_argv[i++][0] && G.global_argv[i]) {
1794 /* this argv[] is not empty and not last:
1795 * put terminating NUL, start new word */
1796 o_addchr(output, '\0');
1797 debug_print_list("expand_vars_to_list[2]", output, n);
1798 n = o_save_ptr(output, n);
1799 debug_print_list("expand_vars_to_list[3]", output, n);
1802 output->o_escape = sv;
1804 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
1805 * and in this case should treat it like '$*' - see 'else...' below */
1806 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
1808 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1809 if (++i >= G.global_argc)
1811 o_addchr(output, '\0');
1812 debug_print_list("expand_vars_to_list[4]", output, n);
1813 n = o_save_ptr(output, n);
1815 } else { /* quoted $*: add as one word */
1817 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1818 if (!G.global_argv[++i])
1821 o_addchr(output, G.ifs[0]);
1825 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
1826 /* "Empty variable", used to make "" etc to not disappear */
1830 #if ENABLE_HUSH_TICK
1831 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
1834 //TODO: can we just stuff it into "output" directly?
1835 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
1836 process_command_subs(&subst_result, arg);
1837 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
1838 val = subst_result.data;
1841 #if ENABLE_SH_MATH_SUPPORT
1842 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
1843 arith_eval_hooks_t hooks;
1848 arg++; /* skip '+' */
1849 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
1850 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
1852 exp_str = expand_pseudo_dquoted(arg);
1853 hooks.lookupvar = get_local_var_value;
1854 hooks.setvar = arith_set_local_var;
1855 hooks.endofname = endofname;
1856 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
1861 case -3: maybe_die("arith", "exponent less than 0"); break;
1862 case -2: maybe_die("arith", "divide by zero"); break;
1863 case -5: maybe_die("arith", "expression recursion loop detected"); break;
1864 default: maybe_die("arith", "syntax error"); break;
1867 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
1868 sprintf(arith_buf, arith_t_fmt, res);
1873 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
1875 bool exp_len = false;
1876 bool exp_null = false;
1878 char exp_save = exp_save; /* for compiler */
1879 char exp_op = exp_op; /* for compiler */
1880 char *exp_word = exp_word; /* for compiler */
1884 arg[0] = first_ch & 0x7f;
1886 /* prepare for expansions */
1887 if (var[0] == '#') {
1888 /* handle length expansion ${#var} */
1892 /* maybe handle parameter expansion */
1893 exp_off = strcspn(var, ":-=+?%#");
1897 exp_save = var[exp_off];
1898 exp_null = exp_save == ':';
1899 exp_word = var + exp_off;
1900 if (exp_null) ++exp_word;
1901 exp_op = *exp_word++;
1902 var[exp_off] = '\0';
1906 /* lookup the variable in question */
1907 if (isdigit(var[0])) {
1908 /* handle_dollar() should have vetted var for us */
1910 if (i < G.global_argc)
1911 val = G.global_argv[i];
1912 /* else val remains NULL: $N with too big N */
1914 val = get_local_var_value(var);
1916 /* handle any expansions */
1918 debug_printf_expand("expand: length of '%s' = ", val);
1919 val = utoa(val ? strlen(val) : 0);
1920 debug_printf_expand("%s\n", val);
1921 } else if (exp_off) {
1922 if (exp_op == '%' || exp_op == '#') {
1923 /* we need to do a pattern match */
1926 scan_t scan = pick_scan(exp_op, *exp_word, &zero);
1927 if (exp_op == *exp_word) /* ## or %% */
1929 val = dyn_val = xstrdup(val);
1930 loc = scan(dyn_val, exp_word, zero);
1936 /* we need to do an expansion */
1937 int exp_test = (!val || (exp_null && !val[0]));
1939 exp_test = !exp_test;
1940 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
1941 exp_null ? "true" : "false", exp_test);
1944 maybe_die(var, *exp_word ? exp_word : "parameter null or not set");
1948 if (exp_op == '=') {
1949 if (isdigit(var[0]) || var[0] == '#') {
1950 maybe_die(var, "special vars cannot assign in this way");
1953 char *new_var = xmalloc(strlen(var) + strlen(val) + 2);
1954 sprintf(new_var, "%s=%s", var, val);
1955 set_local_var(new_var, -1, 0);
1961 var[exp_off] = exp_save;
1965 #if ENABLE_HUSH_TICK
1968 if (!(first_ch & 0x80)) { /* unquoted $VAR */
1969 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
1971 /* unquoted var's contents should be globbed, so don't escape */
1972 smallint sv = output->o_escape;
1973 output->o_escape = 0;
1974 n = expand_on_ifs(output, n, val);
1976 output->o_escape = sv;
1978 } else { /* quoted $VAR, val will be appended below */
1979 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
1982 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
1984 o_addQstr(output, val, strlen(val));
1988 /* Do the check to avoid writing to a const string */
1989 if (*p != SPECIAL_VAR_SYMBOL)
1990 *p = SPECIAL_VAR_SYMBOL;
1992 #if ENABLE_HUSH_TICK
1993 o_free(&subst_result);
1996 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
1999 debug_print_list("expand_vars_to_list[a]", output, n);
2000 /* this part is literal, and it was already pre-quoted
2001 * if needed (much earlier), do not use o_addQstr here! */
2002 o_addstr_with_NUL(output, arg);
2003 debug_print_list("expand_vars_to_list[b]", output, n);
2004 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2005 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2008 /* allow to reuse list[n] later without re-growth */
2009 output->has_empty_slot = 1;
2011 o_addchr(output, '\0');
2016 static char **expand_variables(char **argv, int or_mask)
2021 o_string output = NULL_O_STRING;
2023 if (or_mask & 0x100) {
2024 output.o_escape = 1; /* protect against globbing for "$var" */
2025 /* (unquoted $var will temporarily switch it off) */
2032 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
2035 debug_print_list("expand_variables", &output, n);
2037 /* output.data (malloced in one block) gets returned in "list" */
2038 list = o_finalize_list(&output, n);
2039 debug_print_strings("expand_variables[1]", list);
2043 static char **expand_strvec_to_strvec(char **argv)
2045 return expand_variables(argv, 0x100);
2048 /* Used for expansion of right hand of assignments */
2049 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2051 static char *expand_string_to_string(const char *str)
2053 char *argv[2], **list;
2055 argv[0] = (char*)str;
2057 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2059 if (!list[0] || list[1])
2060 bb_error_msg_and_die("BUG in varexp2");
2061 /* actually, just move string 2*sizeof(char*) bytes back */
2062 overlapping_strcpy((char*)list, list[0]);
2063 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2067 /* Used for "eval" builtin */
2068 static char* expand_strvec_to_string(char **argv)
2072 list = expand_variables(argv, 0x80);
2073 /* Convert all NULs to spaces */
2078 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2079 bb_error_msg_and_die("BUG in varexp3");
2080 list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
2084 overlapping_strcpy((char*)list, list[0]);
2085 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2089 static char **expand_assignments(char **argv, int count)
2093 /* Expand assignments into one string each */
2094 for (i = 0; i < count; i++) {
2095 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2102 void re_execute_shell(const char *s, int is_heredoc); /* never called */
2103 #define clean_up_after_re_execute() ((void)0)
2104 static void reset_traps_to_defaults(void)
2112 for (sig = 0; sig < NSIG; sig++) {
2116 G.traps[sig] = NULL;
2117 /* There is no signal for 0 (EXIT) */
2120 /* there was a trap handler, we are removing it
2121 * (if sig has non-DFL handling,
2122 * we don't need to do anything) */
2123 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
2125 sigdelset(&G.blocked_set, sig);
2129 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
2134 static void re_execute_shell(const char *s, int is_heredoc) NORETURN;
2135 static void re_execute_shell(const char *s, int is_heredoc)
2137 char param_buf[sizeof("-$%x:%x:%x:%x") + sizeof(unsigned) * 4];
2138 struct variable *cur;
2139 char **argv, **pp, **pp2;
2142 sprintf(param_buf, "-$%x:%x:%x" USE_HUSH_LOOPS(":%x")
2143 , (unsigned) G.root_pid
2144 , (unsigned) G.last_bg_pid
2145 , (unsigned) G.last_exitcode
2146 USE_HUSH_LOOPS(, G.depth_of_loop)
2148 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...>
2149 * 3:-c 4:<cmd> <argN...> 5:NULL
2151 cnt = 5 + G.global_argc;
2152 for (cur = G.top_var; cur; cur = cur->next) {
2153 if (!cur->flg_export || cur->flg_read_only)
2156 G.argv_from_re_execing = pp = xzalloc(sizeof(argv[0]) * cnt);
2157 *pp++ = (char *) G.argv0_for_re_execing;
2159 for (cur = G.top_var; cur; cur = cur->next) {
2160 if (cur->varstr == hush_version_str)
2162 if (cur->flg_read_only) {
2163 *pp++ = (char *) "-R";
2164 *pp++ = cur->varstr;
2165 } else if (!cur->flg_export) {
2166 *pp++ = (char *) "-V";
2167 *pp++ = cur->varstr;
2170 //TODO: pass functions
2171 /* We can pass activated traps here. Say, -Tnn:trap_string
2173 * However, POSIX says that subshells reset signals with traps
2175 * I tested bash-3.2 and it not only does that with true subshells
2176 * of the form ( list ), but with any forked children shells.
2177 * I set trap "echo W" WINCH; and then tried:
2179 * { echo 1; sleep 20; echo 2; } &
2180 * while true; do echo 1; sleep 20; echo 2; break; done &
2181 * true | { echo 1; sleep 20; echo 2; } | cat
2183 * In all these cases sending SIGWINCH to the child shell
2184 * did not run the trap. If I add trap "echo V" WINCH;
2185 * _inside_ group (just before echo 1), it works.
2187 * I conclude it means we don't need to pass active traps here.
2188 * exec syscall below resets them to SIG_DFL for us.
2190 *pp++ = (char *) (is_heredoc ? "-<" : "-c");
2192 pp2 = G.global_argv;
2195 /* *pp = NULL; - is already there */
2197 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
2198 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2199 execv(bb_busybox_exec_path, G.argv_from_re_execing);
2200 /* Fallback. Useful for init=/bin/hush usage etc */
2201 if (G.argv0_for_re_execing[0] == '/')
2202 execv(G.argv0_for_re_execing, G.argv_from_re_execing);
2203 xfunc_error_retval = 127;
2204 bb_error_msg_and_die("can't re-execute the shell");
2207 static void clean_up_after_re_execute(void)
2209 char **pp = G.argv_from_re_execing;
2211 /* Must match re_execute_shell's allocations (if any) */
2213 G.argv_from_re_execing = NULL;
2216 #endif /* !BB_MMU */
2219 static void setup_heredoc(struct redir_struct *redir)
2221 struct fd_pair pair;
2224 /* the _body_ of heredoc (misleading field name) */
2225 const char *heredoc = redir->rd_filename;
2229 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
2230 expanded = expand_pseudo_dquoted(heredoc);
2234 len = strlen(heredoc);
2237 xmove_fd(pair.rd, redir->rd_fd);
2239 /* Try writing without forking. Newer kernels have
2240 * dynamically growing pipes. Must use non-blocking write! */
2243 written = write(pair.wr, heredoc, len);
2253 ndelay_off(pair.wr);
2255 /* Okay, pipe buffer was not big enough */
2256 /* Note: we must not create a stray child (bastard? :)
2257 * for the unsuspecting parent process. Child creates a grandchild
2258 * and exits before parent execs the process which consumes heredoc
2259 * (that exec happens after we return from this function) */
2262 bb_perror_msg_and_die("vfork");
2265 pid = BB_MMU ? fork() : vfork();
2267 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
2271 close(redir->rd_fd); /* read side of the pipe */
2273 full_write(pair.wr, heredoc, len); /* may loop or block */
2276 /* Delegate blocking writes to another process */
2277 disable_restore_tty_pgrp_on_exit();
2278 xmove_fd(pair.wr, STDOUT_FILENO);
2279 re_execute_shell(heredoc, 1);
2283 enable_restore_tty_pgrp_on_exit();
2284 clean_up_after_re_execute();
2287 wait(NULL); /* wait till child has died */
2290 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
2291 * and stderr if they are redirected. */
2292 static int setup_redirects(struct command *prog, int squirrel[])
2294 //TODO: no callers ever check return value - ?!
2296 struct redir_struct *redir;
2298 for (redir = prog->redirects; redir; redir = redir->next) {
2299 if (redir->rd_type == REDIRECT_HEREDOC2) {
2300 if (squirrel && redir->rd_fd < 3) {
2301 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2303 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
2305 debug_printf_parse("set heredoc '%s'\n",
2306 redir->rd_filename);
2307 setup_heredoc(redir);
2311 if (redir->rd_dup == -1) {
2313 if (redir->rd_filename == NULL) {
2314 /* Something went wrong in the parse.
2315 * Pretend it didn't happen */
2318 mode = redir_table[redir->rd_type].mode;
2319 //TODO: check redir for names like '\\'
2320 p = expand_string_to_string(redir->rd_filename);
2321 openfd = open_or_warn(p, mode);
2324 /* this could get lost if stderr has been redirected, but
2325 * bash and ash both lose it as well (though zsh doesn't!) */
2326 //what the above comment tries to say?
2330 openfd = redir->rd_dup;
2333 if (openfd != redir->rd_fd) {
2334 if (squirrel && redir->rd_fd < 3) {
2335 squirrel[redir->rd_fd] = dup(redir->rd_fd);
2337 if (openfd == REDIRFD_CLOSE) {
2338 /* "n>-" means "close me" */
2339 close(redir->rd_fd);
2341 xdup2(openfd, redir->rd_fd);
2342 if (redir->rd_dup == -1)
2350 static void restore_redirects(int squirrel[])
2353 for (i = 0; i < 3; i++) {
2356 /* We simply die on error */
2364 #define free_pipe_list(head, indent) free_pipe_list(head)
2365 #define free_pipe(pi, indent) free_pipe(pi)
2367 static void free_pipe_list(struct pipe *head, int indent);
2369 /* Return code is the exit status of the pipe */
2370 static void free_pipe(struct pipe *pi, int indent)
2373 struct command *command;
2374 struct redir_struct *r, *rnext;
2377 if (pi->stopped_cmds > 0) /* why? */
2379 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2380 for (i = 0; i < pi->num_cmds; i++) {
2381 command = &pi->cmds[i];
2382 debug_printf_clean("%s command %d:\n", indenter(indent), i);
2383 if (command->argv) {
2384 for (a = 0, p = command->argv; *p; a++, p++) {
2385 debug_printf_clean("%s argv[%d] = %s\n",
2386 indenter(indent), a, *p);
2388 free_strings(command->argv);
2389 command->argv = NULL;
2391 /* not "else if": on syntax error, we may have both! */
2392 if (command->group) {
2393 debug_printf_clean("%s begin group (grp_type:%d)\n",
2394 indenter(indent), command->grp_type);
2395 free_pipe_list(command->group, indent+3);
2396 debug_printf_clean("%s end group\n", indenter(indent));
2397 command->group = NULL;
2400 free(command->group_as_string);
2401 command->group_as_string = NULL;
2403 for (r = command->redirects; r; r = rnext) {
2404 debug_printf_clean("%s redirect %d%s", indenter(indent),
2405 r->fd, redir_table[r->rd_type].descrip);
2406 /* guard against the case >$FOO, where foo is unset or blank */
2407 if (r->rd_filename) {
2408 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2409 free(r->rd_filename);
2410 r->rd_filename = NULL;
2412 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2416 command->redirects = NULL;
2418 free(pi->cmds); /* children are an array, they get freed all at once */
2426 static void free_pipe_list(struct pipe *head, int indent)
2428 struct pipe *pi, *next;
2430 for (pi = head; pi; pi = next) {
2432 debug_printf_clean("%s pipe reserved word %d\n", indenter(indent), pi->res_word);
2434 free_pipe(pi, indent);
2435 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
2437 /*pi->next = NULL;*/
2444 typedef struct nommu_save_t {
2450 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
2451 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
2452 #define pseudo_exec(nommu_save, command, argv_expanded) \
2453 pseudo_exec(command, argv_expanded)
2456 /* Called after [v]fork() in run_pipe, or from builtin_exec.
2458 * XXX no exit() here. If you don't exec, use _exit instead.
2459 * The at_exit handlers apparently confuse the calling process,
2460 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
2461 static void pseudo_exec_argv(nommu_save_t *nommu_save,
2462 char **argv, int assignment_cnt,
2463 char **argv_expanded) NORETURN;
2464 static void pseudo_exec_argv(nommu_save_t *nommu_save,
2465 char **argv, int assignment_cnt,
2466 char **argv_expanded)
2470 /* Case when we are here: ... | var=val | ... */
2471 if (!argv[assignment_cnt])
2472 _exit(EXIT_SUCCESS);
2474 new_env = expand_assignments(argv, assignment_cnt);
2476 putenv_all(new_env);
2477 free(new_env); /* optional */
2479 nommu_save->new_env = new_env;
2480 nommu_save->old_env = putenv_all_and_save_old(new_env);
2482 if (argv_expanded) {
2483 argv = argv_expanded;
2485 argv = expand_strvec_to_strvec(argv + assignment_cnt);
2487 nommu_save->argv = argv;
2491 /* On NOMMU, we must never block!
2492 * Example: { sleep 99999 | read line } & echo Ok
2493 * read builtin will block on read syscall, leaving parent blocked
2494 * in vfork. Therefore we can't do this:
2497 /* Check if the command matches any of the builtins.
2498 * Depending on context, this might be redundant. But it's
2499 * easier to waste a few CPU cycles than it is to figure out
2500 * if this is one of those cases.
2504 const struct built_in_command *x;
2505 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2506 if (strcmp(argv[0], x->cmd) == 0) {
2507 debug_printf_exec("running builtin '%s'\n",
2509 rcode = x->function(argv);
2517 #if ENABLE_FEATURE_SH_STANDALONE
2518 /* Check if the command matches any busybox applets */
2519 if (strchr(argv[0], '/') == NULL) {
2520 int a = find_applet_by_name(argv[0]);
2522 #if BB_MMU /* see above why on NOMMU it is not allowed */
2523 if (APPLET_IS_NOEXEC(a)) {
2524 debug_printf_exec("running applet '%s'\n", argv[0]);
2525 run_applet_no_and_exit(a, argv);
2528 /* Re-exec ourselves */
2529 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
2530 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2531 execv(bb_busybox_exec_path, argv);
2532 /* If they called chroot or otherwise made the binary no longer
2533 * executable, fall through */
2538 debug_printf_exec("execing '%s'\n", argv[0]);
2539 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2540 execvp(argv[0], argv);
2541 bb_perror_msg("can't exec '%s'", argv[0]);
2542 _exit(EXIT_FAILURE);
2545 static int run_list(struct pipe *pi);
2547 /* Called after [v]fork() in run_pipe
2549 static void pseudo_exec(nommu_save_t *nommu_save,
2550 struct command *command,
2551 char **argv_expanded) NORETURN;
2552 static void pseudo_exec(nommu_save_t *nommu_save,
2553 struct command *command,
2554 char **argv_expanded)
2556 if (command->argv) {
2557 pseudo_exec_argv(nommu_save, command->argv,
2558 command->assignment_cnt, argv_expanded);
2561 if (command->group) {
2562 /* Cases when we are here:
2565 * ... | ( list ) | ...
2566 * ... | { list } | ...
2570 debug_printf_exec("pseudo_exec: run_list\n");
2571 reset_traps_to_defaults();
2572 rcode = run_list(command->group);
2573 /* OK to leak memory by not calling free_pipe_list,
2574 * since this process is about to exit */
2577 re_execute_shell(command->group_as_string, 0);
2581 /* Case when we are here: ... | >file */
2582 debug_printf_exec("pseudo_exec'ed null command\n");
2583 _exit(EXIT_SUCCESS);
2587 static const char *get_cmdtext(struct pipe *pi)
2593 /* This is subtle. ->cmdtext is created only on first backgrounding.
2594 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
2595 * On subsequent bg argv is trashed, but we won't use it */
2598 argv = pi->cmds[0].argv;
2599 if (!argv || !argv[0]) {
2600 pi->cmdtext = xzalloc(1);
2605 do len += strlen(*argv) + 1; while (*++argv);
2606 pi->cmdtext = p = xmalloc(len);
2607 argv = pi->cmds[0].argv;
2609 len = strlen(*argv);
2610 memcpy(p, *argv, len);
2618 static void insert_bg_job(struct pipe *pi)
2620 struct pipe *thejob;
2623 /* Linear search for the ID of the job to use */
2625 for (thejob = G.job_list; thejob; thejob = thejob->next)
2626 if (thejob->jobid >= pi->jobid)
2627 pi->jobid = thejob->jobid + 1;
2629 /* Add thejob to the list of running jobs */
2631 thejob = G.job_list = xmalloc(sizeof(*thejob));
2633 for (thejob = G.job_list; thejob->next; thejob = thejob->next)
2635 thejob->next = xmalloc(sizeof(*thejob));
2636 thejob = thejob->next;
2639 /* Physically copy the struct job */
2640 memcpy(thejob, pi, sizeof(struct pipe));
2641 thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
2642 /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
2643 for (i = 0; i < pi->num_cmds; i++) {
2644 // TODO: do we really need to have so many fields which are just dead weight
2645 // at execution stage?
2646 thejob->cmds[i].pid = pi->cmds[i].pid;
2647 /* all other fields are not used and stay zero */
2649 thejob->next = NULL;
2650 thejob->cmdtext = xstrdup(get_cmdtext(pi));
2652 /* We don't wait for background thejobs to return -- append it
2653 to the list of backgrounded thejobs and leave it alone */
2654 if (G_interactive_fd)
2655 printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
2656 G.last_bg_pid = thejob->cmds[0].pid;
2657 G.last_jobid = thejob->jobid;
2660 static void remove_bg_job(struct pipe *pi)
2662 struct pipe *prev_pipe;
2664 if (pi == G.job_list) {
2665 G.job_list = pi->next;
2667 prev_pipe = G.job_list;
2668 while (prev_pipe->next != pi)
2669 prev_pipe = prev_pipe->next;
2670 prev_pipe->next = pi->next;
2673 G.last_jobid = G.job_list->jobid;
2678 /* Remove a backgrounded job */
2679 static void delete_finished_bg_job(struct pipe *pi)
2682 pi->stopped_cmds = 0;
2688 /* Check to see if any processes have exited -- if they
2689 * have, figure out why and see if a job has completed */
2690 static int checkjobs(struct pipe* fg_pipe)
2700 debug_printf_jobs("checkjobs %p\n", fg_pipe);
2703 // if (G.handled_SIGCHLD == G.count_SIGCHLD)
2704 // /* avoid doing syscall, nothing there anyway */
2707 attributes = WUNTRACED;
2708 if (fg_pipe == NULL)
2709 attributes |= WNOHANG;
2711 /* Do we do this right?
2712 * bash-3.00# sleep 20 | false
2714 * [3]+ Stopped sleep 20 | false
2715 * bash-3.00# echo $?
2716 * 1 <========== bg pipe is not fully done, but exitcode is already known!
2719 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
2720 //are stopped. Testcase: "cat | cat" in a script (not on command line)
2721 // + killall -STOP cat
2728 // i = G.count_SIGCHLD;
2729 childpid = waitpid(-1, &status, attributes);
2730 if (childpid <= 0) {
2731 if (childpid && errno != ECHILD)
2732 bb_perror_msg("waitpid");
2733 // else /* Until next SIGCHLD, waitpid's are useless */
2734 // G.handled_SIGCHLD = i;
2737 dead = WIFEXITED(status) || WIFSIGNALED(status);
2740 if (WIFSTOPPED(status))
2741 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
2742 childpid, WSTOPSIG(status), WEXITSTATUS(status));
2743 if (WIFSIGNALED(status))
2744 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
2745 childpid, WTERMSIG(status), WEXITSTATUS(status));
2746 if (WIFEXITED(status))
2747 debug_printf_jobs("pid %d exited, exitcode %d\n",
2748 childpid, WEXITSTATUS(status));
2750 /* Were we asked to wait for fg pipe? */
2752 for (i = 0; i < fg_pipe->num_cmds; i++) {
2753 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
2754 if (fg_pipe->cmds[i].pid != childpid)
2756 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
2758 fg_pipe->cmds[i].pid = 0;
2759 fg_pipe->alive_cmds--;
2760 if (i == fg_pipe->num_cmds - 1) {
2761 /* last process gives overall exitstatus */
2762 rcode = WEXITSTATUS(status);
2763 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
2766 fg_pipe->cmds[i].is_stopped = 1;
2767 fg_pipe->stopped_cmds++;
2769 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
2770 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
2771 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
2772 /* All processes in fg pipe have exited/stopped */
2774 if (fg_pipe->alive_cmds)
2775 insert_bg_job(fg_pipe);
2779 /* There are still running processes in the fg pipe */
2780 goto wait_more; /* do waitpid again */
2782 /* it wasnt fg_pipe, look for process in bg pipes */
2786 /* We asked to wait for bg or orphaned children */
2787 /* No need to remember exitcode in this case */
2788 for (pi = G.job_list; pi; pi = pi->next) {
2789 for (i = 0; i < pi->num_cmds; i++) {
2790 if (pi->cmds[i].pid == childpid)
2791 goto found_pi_and_prognum;
2794 /* Happens when shell is used as init process (init=/bin/sh) */
2795 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
2796 continue; /* do waitpid again */
2798 found_pi_and_prognum:
2801 pi->cmds[i].pid = 0;
2803 if (!pi->alive_cmds) {
2804 if (G_interactive_fd)
2805 printf(JOB_STATUS_FORMAT, pi->jobid,
2806 "Done", pi->cmdtext);
2807 delete_finished_bg_job(pi);
2811 pi->cmds[i].is_stopped = 1;
2815 } /* while (waitpid succeeds)... */
2821 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
2824 int rcode = checkjobs(fg_pipe);
2825 /* Job finished, move the shell to the foreground */
2826 p = getpgid(0); /* pgid of our process */
2827 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
2828 tcsetpgrp(G_interactive_fd, p);
2833 /* Start all the jobs, but don't wait for anything to finish.
2836 * Return code is normally -1, when the caller has to wait for children
2837 * to finish to determine the exit status of the pipe. If the pipe
2838 * is a simple builtin command, however, the action is done by the
2839 * time run_pipe returns, and the exit code is provided as the
2842 * Returns -1 only if started some children. IOW: we have to
2843 * mask out retvals of builtins etc with 0xff!
2845 * The only case when we do not need to [v]fork is when the pipe
2846 * is single, non-backgrounded, non-subshell command. Examples:
2847 * cmd ; ... { list } ; ...
2848 * cmd && ... { list } && ...
2849 * cmd || ... { list } || ...
2850 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
2851 * or (if SH_STANDALONE) an applet, and we can run the { list }
2852 * with run_list(). If it isn't one of these, we fork and exec cmd.
2854 * Cases when we must fork:
2855 * non-single: cmd | cmd
2856 * backgrounded: cmd & { list } &
2857 * subshell: ( list ) [&]
2859 static int run_pipe(struct pipe *pi)
2861 static const char *const null_ptr = NULL;
2864 int pipefds[2]; /* pipefds[0] is for reading */
2865 struct command *command;
2866 char **argv_expanded;
2869 /* it is not always needed, but we aim to smaller code */
2870 int squirrel[] = { -1, -1, -1 };
2873 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
2875 USE_HUSH_JOB(pi->pgrp = -1;)
2876 pi->stopped_cmds = 0;
2877 command = &(pi->cmds[0]);
2878 argv_expanded = NULL;
2880 if (pi->num_cmds != 1
2881 || pi->followup == PIPE_BG
2882 || command->grp_type == GRP_SUBSHELL
2889 debug_printf_exec(": group:%p argv:'%s'\n",
2890 command->group, command->argv ? command->argv[0] : "NONE");
2892 if (command->group) {
2893 #if ENABLE_HUSH_FUNCTIONS
2894 if (command->grp_type == GRP_FUNCTION) {
2895 /* func () { list } */
2896 bb_error_msg("here we ought to remember function definition, and go on");
2897 return EXIT_SUCCESS;
2901 debug_printf("non-subshell group\n");
2902 setup_redirects(command, squirrel);
2903 debug_printf_exec(": run_list\n");
2904 rcode = run_list(command->group) & 0xff;
2905 restore_redirects(squirrel);
2906 debug_printf_exec("run_pipe return %d\n", rcode);
2907 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2911 argv = command->argv ? command->argv : (char **) &null_ptr;
2913 const struct built_in_command *x;
2914 char **new_env = NULL;
2915 char **old_env = NULL;
2917 if (argv[command->assignment_cnt] == NULL) {
2918 /* Assignments, but no command */
2919 /* Ensure redirects take effect. Try "a=t >file" */
2920 setup_redirects(command, squirrel);
2921 restore_redirects(squirrel);
2922 /* Set shell variables */
2924 p = expand_string_to_string(*argv);
2925 debug_printf_exec("set shell var:'%s'->'%s'\n",
2927 set_local_var(p, 0, 0);
2930 /* Do we need to flag set_local_var() errors?
2931 * "assignment to readonly var" and "putenv error"
2933 return EXIT_SUCCESS;
2936 /* Expand the rest into (possibly) many strings each */
2937 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
2939 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2940 if (strcmp(argv_expanded[0], x->cmd) != 0)
2942 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
2943 debug_printf("exec with redirects only\n");
2944 setup_redirects(command, NULL);
2945 rcode = EXIT_SUCCESS;
2946 goto clean_up_and_ret1;
2948 debug_printf("builtin inline %s\n", argv_expanded[0]);
2949 /* XXX setup_redirects acts on file descriptors, not FILEs.
2950 * This is perfect for work that comes after exec().
2951 * Is it really safe for inline use? Experimentally,
2952 * things seem to work with glibc. */
2953 setup_redirects(command, squirrel);
2954 new_env = expand_assignments(argv, command->assignment_cnt);
2955 old_env = putenv_all_and_save_old(new_env);
2956 debug_printf_exec(": builtin '%s' '%s'...\n",
2957 x->cmd, argv_expanded[1]);
2958 rcode = x->function(argv_expanded) & 0xff;
2959 #if ENABLE_FEATURE_SH_STANDALONE
2962 restore_redirects(squirrel);
2963 free_strings_and_unsetenv(new_env, 1);
2964 putenv_all(old_env);
2965 free(old_env); /* not free_strings()! */
2967 free(argv_expanded);
2968 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2969 debug_printf_exec("run_pipe return %d\n", rcode);
2972 #if ENABLE_FEATURE_SH_STANDALONE
2973 i = find_applet_by_name(argv_expanded[0]);
2974 if (i >= 0 && APPLET_IS_NOFORK(i)) {
2975 setup_redirects(command, squirrel);
2976 save_nofork_data(&G.nofork_save);
2977 new_env = expand_assignments(argv, command->assignment_cnt);
2978 old_env = putenv_all_and_save_old(new_env);
2979 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
2980 argv_expanded[0], argv_expanded[1]);
2981 rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
2982 goto clean_up_and_ret;
2985 /* It is neither builtin nor applet. We must fork. */
2989 /* NB: argv_expanded may already be created, and that
2990 * might include `cmd` runs! Do not rerun it! We *must*
2991 * use argv_expanded if it's non-NULL */
2993 /* Going to fork a child per each pipe member */
2997 for (i = 0; i < pi->num_cmds; i++) {
2999 volatile nommu_save_t nommu_save;
3000 nommu_save.new_env = NULL;
3001 nommu_save.old_env = NULL;
3002 nommu_save.argv = NULL;
3004 command = &(pi->cmds[i]);
3005 if (command->argv) {
3006 debug_printf_exec(": pipe member '%s' '%s'...\n",
3007 command->argv[0], command->argv[1]);
3009 debug_printf_exec(": pipe member with no argv\n");
3012 /* pipes are inserted between pairs of commands */
3015 if ((i + 1) < pi->num_cmds)
3018 command->pid = BB_MMU ? fork() : vfork();
3019 if (!command->pid) { /* child */
3021 disable_restore_tty_pgrp_on_exit();
3023 /* Every child adds itself to new process group
3024 * with pgid == pid_of_first_child_in_pipe */
3025 if (G.run_list_level == 1 && G_interactive_fd) {
3028 if (pgrp < 0) /* true for 1st process only */
3030 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
3031 /* We do it in *every* child, not just first,
3033 tcsetpgrp(G_interactive_fd, pgrp);
3037 xmove_fd(nextin, 0);
3038 xmove_fd(pipefds[1], 1); /* write end */
3040 close(pipefds[0]); /* read end */
3041 /* Like bash, explicit redirects override pipes,
3042 * and the pipe fd is available for dup'ing. */
3043 setup_redirects(command, NULL);
3045 /* Restore default handlers just prior to exec */
3046 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
3048 /* Stores to nommu_save list of env vars putenv'ed
3049 * (NOMMU, on MMU we don't need that) */
3050 /* cast away volatility... */
3051 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
3052 /* pseudo_exec() does not return */
3055 /* parent or error */
3056 enable_restore_tty_pgrp_on_exit();
3058 /* Clean up after vforked child */
3059 clean_up_after_re_execute();
3060 free(nommu_save.argv);
3061 free_strings_and_unsetenv(nommu_save.new_env, 1);
3062 putenv_all(nommu_save.old_env);
3064 free(argv_expanded);
3065 argv_expanded = NULL;
3066 if (command->pid < 0) { /* [v]fork failed */
3067 /* Clearly indicate, was it fork or vfork */
3068 bb_perror_msg(BB_MMU ? "fork" : "vfork");
3072 /* Second and next children need to know pid of first one */
3074 pi->pgrp = command->pid;
3080 if ((i + 1) < pi->num_cmds)
3081 close(pipefds[1]); /* write end */
3082 /* Pass read (output) pipe end to next iteration */
3083 nextin = pipefds[0];
3086 if (!pi->alive_cmds) {
3087 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
3091 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
3095 #ifndef debug_print_tree
3096 static void debug_print_tree(struct pipe *pi, int lvl)
3098 static const char *const PIPE[] = {
3104 static const char *RES[] = {
3105 [RES_NONE ] = "NONE" ,
3108 [RES_THEN ] = "THEN" ,
3109 [RES_ELIF ] = "ELIF" ,
3110 [RES_ELSE ] = "ELSE" ,
3113 #if ENABLE_HUSH_LOOPS
3114 [RES_FOR ] = "FOR" ,
3115 [RES_WHILE] = "WHILE",
3116 [RES_UNTIL] = "UNTIL",
3118 [RES_DONE ] = "DONE" ,
3120 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3123 #if ENABLE_HUSH_CASE
3124 [RES_CASE ] = "CASE" ,
3125 [RES_MATCH] = "MATCH",
3126 [RES_CASEI] = "CASEI",
3127 [RES_ESAC ] = "ESAC" ,
3129 [RES_XXXX ] = "XXXX" ,
3130 [RES_SNTX ] = "SNTX" ,
3132 static const char *const GRPTYPE[] = {
3135 #if ENABLE_HUSH_FUNCTIONS
3144 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3145 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3147 while (prn < pi->num_cmds) {
3148 struct command *command = &pi->cmds[prn];
3149 char **argv = command->argv;
3151 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
3153 command->assignment_cnt);
3154 if (command->group) {
3155 fprintf(stderr, " group %s: (argv=%p)\n",
3156 GRPTYPE[command->grp_type],
3158 debug_print_tree(command->group, lvl+1);
3162 if (argv) while (*argv) {
3163 fprintf(stderr, " '%s'", *argv);
3166 fprintf(stderr, "\n");
3175 /* NB: called by pseudo_exec, and therefore must not modify any
3176 * global data until exec/_exit (we can be a child after vfork!) */
3177 static int run_list(struct pipe *pi)
3179 #if ENABLE_HUSH_CASE
3180 char *case_word = NULL;
3182 #if ENABLE_HUSH_LOOPS
3183 struct pipe *loop_top = NULL;
3184 char *for_varname = NULL;
3185 char **for_lcur = NULL;
3186 char **for_list = NULL;
3188 smallint last_followup;
3190 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
3191 smalluint cond_code = 0;
3193 enum { cond_code = 0 };
3196 smallint rword; /* enum reserved_style */
3197 smallint last_rword; /* ditto */
3200 debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
3202 #if ENABLE_HUSH_LOOPS
3203 /* Check syntax for "for" */
3204 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
3205 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
3207 /* current word is FOR or IN (BOLD in comments below) */
3208 if (cpipe->next == NULL) {
3209 syntax("malformed for");
3210 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
3213 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
3214 if (cpipe->next->res_word == RES_DO)
3216 /* next word is not "do". It must be "in" then ("FOR v in ...") */
3217 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
3218 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
3220 syntax("malformed for");
3221 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
3227 /* Past this point, all code paths should jump to ret: label
3228 * in order to return, no direct "return" statements please.
3229 * This helps to ensure that no memory is leaked. */
3231 ////TODO: ctrl-Z handling needs re-thinking and re-testing
3234 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
3235 * We are saving state before entering outermost list ("while...done")
3236 * so that ctrl-Z will correctly background _entire_ outermost list,
3237 * not just a part of it (like "sleep 1 | exit 2") */
3238 if (++G.run_list_level == 1 && G_interactive_fd) {
3239 if (sigsetjmp(G.toplevel_jb, 1)) {
3240 /* ctrl-Z forked and we are parent; or ctrl-C.
3241 * Sighandler has longjmped us here */
3242 signal(SIGINT, SIG_IGN);
3243 signal(SIGTSTP, SIG_IGN);
3244 /* Restore level (we can be coming from deep inside
3246 G.run_list_level = 1;
3247 #if ENABLE_FEATURE_SH_STANDALONE
3248 if (G.nofork_save.saved) { /* if save area is valid */
3249 debug_printf_jobs("exiting nofork early\n");
3250 restore_nofork_data(&G.nofork_save);
3253 //// if (G.ctrl_z_flag) {
3254 //// /* ctrl-Z has forked and stored pid of the child in pi->pid.
3255 //// * Remember this child as background job */
3256 //// insert_bg_job(pi);
3258 /* ctrl-C. We just stop doing whatever we were doing */
3261 USE_HUSH_LOOPS(loop_top = NULL;)
3262 USE_HUSH_LOOPS(G.depth_of_loop = 0;)
3266 //// /* ctrl-Z handler will store pid etc in pi */
3267 //// G.toplevel_list = pi;
3268 //// G.ctrl_z_flag = 0;
3269 ////#if ENABLE_FEATURE_SH_STANDALONE
3270 //// G.nofork_save.saved = 0; /* in case we will run a nofork later */
3272 //// signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
3273 //// signal(SIGINT, handler_ctrl_c);
3279 last_rword = RES_XXXX;
3281 last_followup = PIPE_SEQ;
3282 rcode = G.last_exitcode;
3284 /* Go through list of pipes, (maybe) executing them. */
3285 for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
3289 IF_HAS_KEYWORDS(rword = pi->res_word;)
3290 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
3291 rword, cond_code, last_rword);
3292 #if ENABLE_HUSH_LOOPS
3293 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
3294 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
3296 /* start of a loop: remember where loop starts */
3301 /* Still in the same "if...", "then..." or "do..." branch? */
3302 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
3303 if ((rcode == 0 && last_followup == PIPE_OR)
3304 || (rcode != 0 && last_followup == PIPE_AND)
3306 /* It is "<true> || CMD" or "<false> && CMD"
3307 * and we should not execute CMD */
3308 debug_printf_exec("skipped cmd because of || or &&\n");
3309 last_followup = pi->followup;
3313 last_followup = pi->followup;
3314 IF_HAS_KEYWORDS(last_rword = rword;)
3317 if (rword == RES_THEN) {
3318 /* if false; then ... fi has exitcode 0! */
3319 G.last_exitcode = rcode = EXIT_SUCCESS;
3320 /* "if <false> THEN cmd": skip cmd */
3324 if (rword == RES_ELSE || rword == RES_ELIF) {
3325 /* "if <true> then ... ELSE/ELIF cmd":
3326 * skip cmd and all following ones */
3331 #if ENABLE_HUSH_LOOPS
3332 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
3334 /* first loop through for */
3336 static const char encoded_dollar_at[] ALIGN1 = {
3337 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
3338 }; /* encoded representation of "$@" */
3339 static const char *const encoded_dollar_at_argv[] = {
3340 encoded_dollar_at, NULL
3341 }; /* argv list with one element: "$@" */
3344 vals = (char**)encoded_dollar_at_argv;
3345 if (pi->next->res_word == RES_IN) {
3346 /* if no variable values after "in" we skip "for" */
3347 if (!pi->next->cmds[0].argv) {
3348 G.last_exitcode = rcode = EXIT_SUCCESS;
3349 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
3352 vals = pi->next->cmds[0].argv;
3353 } /* else: "for var; do..." -> assume "$@" list */
3354 /* create list of variable values */
3355 debug_print_strings("for_list made from", vals);
3356 for_list = expand_strvec_to_strvec(vals);
3357 for_lcur = for_list;
3358 debug_print_strings("for_list", for_list);
3359 for_varname = pi->cmds[0].argv[0];
3360 pi->cmds[0].argv[0] = NULL;
3362 free(pi->cmds[0].argv[0]);
3364 /* "for" loop is over, clean up */
3368 pi->cmds[0].argv[0] = for_varname;
3371 /* Insert next value from for_lcur */
3372 //TODO: does it need escaping?
3373 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
3374 pi->cmds[0].assignment_cnt = 1;
3376 if (rword == RES_IN) {
3377 continue; /* "for v IN list;..." - "in" has no cmds anyway */
3379 if (rword == RES_DONE) {
3380 continue; /* "done" has no cmds too */
3383 #if ENABLE_HUSH_CASE
3384 if (rword == RES_CASE) {
3385 case_word = expand_strvec_to_string(pi->cmds->argv);
3388 if (rword == RES_MATCH) {
3391 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
3393 /* all prev words didn't match, does this one match? */
3394 argv = pi->cmds->argv;
3396 char *pattern = expand_string_to_string(*argv);
3397 /* TODO: which FNM_xxx flags to use? */
3398 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
3400 if (cond_code == 0) { /* match! we will execute this branch */
3401 free(case_word); /* make future "word)" stop */
3409 if (rword == RES_CASEI) { /* inside of a case branch */
3411 continue; /* not matched yet, skip this pipe */
3414 /* Just pressing <enter> in shell should check for jobs.
3415 * OTOH, in non-interactive shell this is useless
3416 * and only leads to extra job checks */
3417 if (pi->num_cmds == 0) {
3418 if (G_interactive_fd)
3419 goto check_jobs_and_continue;
3423 /* After analyzing all keywords and conditions, we decided
3424 * to execute this pipe. NB: have to do checkjobs(NULL)
3425 * after run_pipe to collect any background children,
3426 * even if list execution is to be stopped. */
3427 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
3430 #if ENABLE_HUSH_LOOPS
3431 G.flag_break_continue = 0;
3433 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
3435 /* We only ran a builtin: rcode is already known
3436 * and we don't need to wait for anything. */
3437 G.last_exitcode = rcode;
3438 debug_printf_exec(": builtin exitcode %d\n", rcode);
3439 check_and_run_traps(0);
3440 #if ENABLE_HUSH_LOOPS
3441 /* Was it "break" or "continue"? */
3442 if (G.flag_break_continue) {
3443 smallint fbc = G.flag_break_continue;
3444 /* We might fall into outer *loop*,
3445 * don't want to break it too */
3447 G.depth_break_continue--;
3448 if (G.depth_break_continue == 0)
3449 G.flag_break_continue = 0;
3450 /* else: e.g. "continue 2" should *break* once, *then* continue */
3451 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
3452 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
3453 goto check_jobs_and_break;
3454 /* "continue": simulate end of loop */
3459 } else if (pi->followup == PIPE_BG) {
3460 /* What does bash do with attempts to background builtins? */
3461 /* even bash 3.2 doesn't do that well with nested bg:
3462 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
3463 * I'm NOT treating inner &'s as jobs */
3464 check_and_run_traps(0);
3466 if (G.run_list_level == 1)
3469 G.last_exitcode = rcode = EXIT_SUCCESS;
3470 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
3473 if (G.run_list_level == 1 && G_interactive_fd) {
3474 /* Waits for completion, then fg's main shell */
3475 rcode = checkjobs_and_fg_shell(pi);
3476 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
3477 check_and_run_traps(0);
3480 { /* This one just waits for completion */
3481 rcode = checkjobs(pi);
3482 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
3483 check_and_run_traps(0);
3485 G.last_exitcode = rcode;
3489 /* Analyze how result affects subsequent commands */
3491 if (rword == RES_IF || rword == RES_ELIF)
3494 #if ENABLE_HUSH_LOOPS
3495 /* Beware of "while false; true; do ..."! */
3496 if (pi->next && pi->next->res_word == RES_DO) {
3497 if (rword == RES_WHILE) {
3499 /* "while false; do...done" - exitcode 0 */
3500 G.last_exitcode = rcode = EXIT_SUCCESS;
3501 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
3502 goto check_jobs_and_break;
3505 if (rword == RES_UNTIL) {
3507 debug_printf_exec(": until expr is true: breaking\n");
3508 check_jobs_and_break:
3516 check_jobs_and_continue:
3521 //// if (G.ctrl_z_flag) {
3522 //// /* ctrl-Z forked somewhere in the past, we are the child,
3523 //// * and now we completed running the list. Exit. */
3529 //// if (!G.run_list_level && G_interactive_fd) {
3530 //// signal(SIGTSTP, SIG_IGN);
3531 //// signal(SIGINT, SIG_IGN);
3534 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
3535 #if ENABLE_HUSH_LOOPS
3540 #if ENABLE_HUSH_CASE
3546 /* Select which version we will use */
3547 static int run_and_free_list(struct pipe *pi)
3550 debug_printf_exec("run_and_free_list entered\n");
3552 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
3553 rcode = run_list(pi);
3555 /* free_pipe_list has the side effect of clearing memory.
3556 * In the long run that function can be merged with run_list,
3557 * but doing that now would hobble the debugging effort. */
3558 free_pipe_list(pi, /* indent: */ 0);
3559 debug_printf_exec("run_and_free_list return %d\n", rcode);
3564 static struct pipe *new_pipe(void)
3567 pi = xzalloc(sizeof(struct pipe));
3568 /*pi->followup = 0; - deliberately invalid value */
3569 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3573 /* Command (member of a pipe) is complete. The only possible error here
3574 * is out of memory, in which case xmalloc exits. */
3575 static int done_command(struct parse_context *ctx)
3577 /* The command is really already in the pipe structure, so
3578 * advance the pipe counter and make a new, null command. */
3579 struct pipe *pi = ctx->pipe;
3580 struct command *command = ctx->command;
3583 if (command->group == NULL
3584 && command->argv == NULL
3585 && command->redirects == NULL
3587 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3588 memset(command, 0, sizeof(*command)); /* paranoia */
3589 return pi->num_cmds;
3592 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3593 //debug_print_tree(ctx->list_head, 20);
3595 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3598 /* Only real trickiness here is that the uncommitted
3599 * command structure is not counted in pi->num_cmds. */
3600 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3601 command = &pi->cmds[pi->num_cmds];
3602 memset(command, 0, sizeof(*command));
3604 ctx->command = command;
3605 /* but ctx->pipe and ctx->list_head remain unchanged */
3607 return pi->num_cmds; /* used only for 0/nonzero check */
3610 static void done_pipe(struct parse_context *ctx, pipe_style type)
3614 debug_printf_parse("done_pipe entered, followup %d\n", type);
3615 /* Close previous command */
3616 not_null = done_command(ctx);
3617 ctx->pipe->followup = type;
3619 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3620 ctx->ctx_inverted = 0;
3621 ctx->pipe->res_word = ctx->ctx_res_w;
3624 /* Without this check, even just <enter> on command line generates
3625 * tree of three NOPs (!). Which is harmless but annoying.
3626 * IOW: it is safe to do it unconditionally.
3627 * RES_NONE case is for "for a in; do ..." (empty IN set)
3628 * and other cases to work. */
3631 || ctx->ctx_res_w == RES_FI
3632 || ctx->ctx_res_w == RES_DONE
3633 || ctx->ctx_res_w == RES_FOR
3634 || ctx->ctx_res_w == RES_IN
3635 || ctx->ctx_res_w == RES_ESAC
3639 debug_printf_parse("done_pipe: adding new pipe: "
3640 "not_null:%d ctx->ctx_res_w:%d\n",
3641 not_null, ctx->ctx_res_w);
3643 ctx->pipe->next = new_p;
3645 /* RES_THEN, RES_DO etc are "sticky" -
3646 * they remain set for commands inside if/while.
3647 * This is used to control execution.
3648 * RES_FOR and RES_IN are NOT sticky (needed to support
3649 * cases where variable or value happens to match a keyword):
3651 #if ENABLE_HUSH_LOOPS
3652 if (ctx->ctx_res_w == RES_FOR
3653 || ctx->ctx_res_w == RES_IN)
3654 ctx->ctx_res_w = RES_NONE;
3656 #if ENABLE_HUSH_CASE
3657 if (ctx->ctx_res_w == RES_MATCH)
3658 ctx->ctx_res_w = RES_CASEI;
3660 ctx->command = NULL; /* trick done_command below */
3661 /* Create the memory for command, roughly:
3662 * ctx->pipe->cmds = new struct command;
3663 * ctx->command = &ctx->pipe->cmds[0];
3666 //debug_print_tree(ctx->list_head, 10);
3668 debug_printf_parse("done_pipe return\n");
3671 static void initialize_context(struct parse_context *ctx)
3673 memset(ctx, 0, sizeof(*ctx));
3674 ctx->pipe = ctx->list_head = new_pipe();
3675 /* Create the memory for command, roughly:
3676 * ctx->pipe->cmds = new struct command;
3677 * ctx->command = &ctx->pipe->cmds[0];
3682 /* If a reserved word is found and processed, parse context is modified
3683 * and 1 is returned.
3686 struct reserved_combo {
3689 unsigned char assignment_flag;
3693 FLAG_END = (1 << RES_NONE ),
3695 FLAG_IF = (1 << RES_IF ),
3696 FLAG_THEN = (1 << RES_THEN ),
3697 FLAG_ELIF = (1 << RES_ELIF ),
3698 FLAG_ELSE = (1 << RES_ELSE ),
3699 FLAG_FI = (1 << RES_FI ),
3701 #if ENABLE_HUSH_LOOPS
3702 FLAG_FOR = (1 << RES_FOR ),
3703 FLAG_WHILE = (1 << RES_WHILE),
3704 FLAG_UNTIL = (1 << RES_UNTIL),
3705 FLAG_DO = (1 << RES_DO ),
3706 FLAG_DONE = (1 << RES_DONE ),
3707 FLAG_IN = (1 << RES_IN ),
3709 #if ENABLE_HUSH_CASE
3710 FLAG_MATCH = (1 << RES_MATCH),
3711 FLAG_ESAC = (1 << RES_ESAC ),
3713 FLAG_START = (1 << RES_XXXX ),
3716 static const struct reserved_combo* match_reserved_word(o_string *word)
3718 /* Mostly a list of accepted follow-up reserved words.
3719 * FLAG_END means we are done with the sequence, and are ready
3720 * to turn the compound list into a command.
3721 * FLAG_START means the word must start a new compound list.
3723 static const struct reserved_combo reserved_list[] = {
3725 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3726 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
3727 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3728 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
3729 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
3730 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3732 #if ENABLE_HUSH_LOOPS
3733 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3734 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3735 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3736 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3737 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
3738 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3740 #if ENABLE_HUSH_CASE
3741 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3742 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3745 const struct reserved_combo *r;
3747 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3748 if (strcmp(word->data, r->literal) == 0)
3753 static int reserved_word(o_string *word, struct parse_context *ctx)
3755 #if ENABLE_HUSH_CASE
3756 static const struct reserved_combo reserved_match = {
3757 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3760 const struct reserved_combo *r;
3762 r = match_reserved_word(word);
3766 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3767 #if ENABLE_HUSH_CASE
3768 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
3769 /* "case word IN ..." - IN part starts first match part */
3770 r = &reserved_match;
3773 if (r->flag == 0) { /* '!' */
3774 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3775 syntax("! ! command");
3776 IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
3778 ctx->ctx_inverted = 1;
3781 if (r->flag & FLAG_START) {
3782 struct parse_context *old;
3783 old = xmalloc(sizeof(*old));
3784 debug_printf_parse("push stack %p\n", old);
3785 *old = *ctx; /* physical copy */
3786 initialize_context(ctx);
3788 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3790 ctx->ctx_res_w = RES_SNTX;
3793 ctx->ctx_res_w = r->res;
3794 ctx->old_flag = r->flag;
3795 if (ctx->old_flag & FLAG_END) {
3796 struct parse_context *old;
3797 done_pipe(ctx, PIPE_SEQ);
3798 debug_printf_parse("pop stack %p\n", ctx->stack);
3800 old->command->group = ctx->list_head;
3801 old->command->grp_type = GRP_NORMAL;
3803 o_addstr(&old->as_string, ctx->as_string.data);
3804 o_free_unsafe(&ctx->as_string);
3805 old->command->group_as_string = xstrdup(old->as_string.data);
3806 debug_printf_parse("pop, remembering as:'%s'\n",
3807 old->command->group_as_string);
3809 *ctx = *old; /* physical copy */
3812 word->o_assignment = r->assignment_flag;
3817 /* Word is complete, look at it and update parsing context.
3818 * Normal return is 0. Syntax errors return 1.
3819 * Note: on return, word is reset, but not o_free'd!
3821 static int done_word(o_string *word, struct parse_context *ctx)
3823 struct command *command = ctx->command;
3825 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3826 if (word->length == 0 && word->o_quoted == 0) {
3827 debug_printf_parse("done_word return 0: true null, ignored\n");
3830 /* If this word wasn't an assignment, next ones definitely
3831 * can't be assignments. Even if they look like ones. */
3832 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3833 && word->o_assignment != WORD_IS_KEYWORD
3835 word->o_assignment = NOT_ASSIGNMENT;
3837 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3838 command->assignment_cnt++;
3839 word->o_assignment = MAYBE_ASSIGNMENT;
3842 if (ctx->pending_redirect) {
3843 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3844 * only if run as "bash", not "sh" */
3845 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3847 * ...the word that follows the redirection operator
3848 * shall be subjected to tilde expansion, parameter expansion,
3849 * command substitution, arithmetic expansion, and quote
3850 * removal. Pathname expansion shall not be performed
3851 * on the word by a non-interactive shell; an interactive
3852 * shell may perform it, but shall do so only when
3853 * the expansion would result in one word."
3855 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3856 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC
3859 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3861 word->o_assignment = NOT_ASSIGNMENT;
3862 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3864 /* "{ echo foo; } echo bar" - bad */
3865 /* NB: bash allows e.g.:
3866 * if true; then { echo foo; } fi
3867 * while if false; then false; fi do break; done
3869 * while if false; then false; fi; do; break; done
3871 if (command->group) {
3873 debug_printf_parse("done_word return 1: syntax error, "
3874 "groups and arglists don't mix\n");
3878 #if ENABLE_HUSH_CASE
3879 if (ctx->ctx_dsemicolon
3880 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3882 /* already done when ctx_dsemicolon was set to 1: */
3883 /* ctx->ctx_res_w = RES_MATCH; */
3884 ctx->ctx_dsemicolon = 0;
3887 if (!command->argv /* if it's the first word... */
3888 #if ENABLE_HUSH_LOOPS
3889 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3890 && ctx->ctx_res_w != RES_IN
3893 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
3894 if (reserved_word(word, ctx)) {
3896 debug_printf_parse("done_word return %d\n",
3897 (ctx->ctx_res_w == RES_SNTX));
3898 return (ctx->ctx_res_w == RES_SNTX);
3902 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
3903 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3904 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3905 /* (otherwise it's known to be not empty and is already safe) */
3907 /* exclude "$@" - it can expand to no word despite "" */
3908 char *p = word->data;
3909 while (p[0] == SPECIAL_VAR_SYMBOL
3910 && (p[1] & 0x7f) == '@'
3911 && p[2] == SPECIAL_VAR_SYMBOL
3915 if (p == word->data || p[0] != '\0') {
3916 /* saw no "$@", or not only "$@" but some
3917 * real text is there too */
3918 /* insert "empty variable" reference, this makes
3919 * e.g. "", $empty"" etc to not disappear */
3920 o_addchr(word, SPECIAL_VAR_SYMBOL);
3921 o_addchr(word, SPECIAL_VAR_SYMBOL);
3924 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3925 debug_print_strings("word appended to argv", command->argv);
3929 ctx->pending_redirect = NULL;
3931 #if ENABLE_HUSH_LOOPS
3932 /* Force FOR to have just one word (variable name) */
3933 /* NB: basically, this makes hush see "for v in ..." syntax as if
3934 * as it is "for v; in ...". FOR and IN become two pipe structs
3936 if (ctx->ctx_res_w == RES_FOR) {
3937 //TODO: check that command->argv[0] is a valid variable name!
3938 done_pipe(ctx, PIPE_SEQ);
3941 #if ENABLE_HUSH_CASE
3942 /* Force CASE to have just one word */
3943 if (ctx->ctx_res_w == RES_CASE) {
3944 done_pipe(ctx, PIPE_SEQ);
3947 debug_printf_parse("done_word return 0\n");
3952 /* Peek ahead in the input to find out if we have a "&n" construct,
3953 * as in "2>&1", that represents duplicating a file descriptor.
3954 * Return: REDIRFD_CLOSE (-3) if >&- "close fd" construct is seen,
3955 * -2 (syntax error), -1 if no & was seen, or the number found.
3958 #define redirect_dup_num(as_string, input) \
3959 redirect_dup_num(input)
3961 static int redirect_dup_num(o_string *as_string, struct in_str *input)
3969 ch = i_getch(input); /* get the & */
3970 nommu_addchr(as_string, ch);
3973 ch = i_getch(input);
3974 nommu_addchr(as_string, ch);
3975 return REDIRFD_CLOSE;
3979 while (ch != EOF && isdigit(ch)) {
3980 d = d*10 + (ch-'0');
3982 ch = i_getch(input);
3983 nommu_addchr(as_string, ch);
3988 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3990 bb_error_msg("ambiguous redirect");
3994 /* Return code is 0 normally, 1 if a syntax error is detected
3996 static int parse_redirect(struct parse_context *ctx,
3999 struct in_str *input)
4001 struct command *command = ctx->command;
4002 struct redir_struct *redir;
4003 struct redir_struct **redirp;
4007 if (style != REDIRECT_HEREDOC) {
4008 /* Check for a '2>&1' type redirect */
4009 dup_num = redirect_dup_num(&ctx->as_string, input);
4011 return 1; /* syntax error */
4013 int ch = i_peek(input);
4014 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
4015 if (dup_num) { /* <<-... */
4016 ch = i_getch(input);
4017 nommu_addchr(&ctx->as_string, ch);
4020 /* <<[-] word is the same as <<[-]word */
4021 while (ch == ' ' || ch == '\t') {
4022 ch = i_getch(input);
4023 nommu_addchr(&ctx->as_string, ch);
4028 if (style == REDIRECT_OVERWRITE && dup_num == -1) {
4029 int ch = i_peek(input);
4031 /* >|FILE redirect ("clobbering" >).
4032 * Since we do not support "set -o noclobber" yet,
4033 * >| and > are the same for now. Just eat |.
4035 ch = i_getch(input);
4036 nommu_addchr(&ctx->as_string, ch);
4040 /* Create a new redir_struct and append it to the linked list */
4041 redirp = &command->redirects;
4042 while ((redir = *redirp) != NULL) {
4043 redirp = &(redir->next);
4045 *redirp = redir = xzalloc(sizeof(*redir));
4046 /* redir->next = NULL; */
4047 /* redir->rd_filename = NULL; */
4048 redir->rd_type = style;
4049 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
4051 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4052 redir_table[style].descrip);
4054 redir->rd_dup = dup_num;
4055 if (style != REDIRECT_HEREDOC && dup_num != -1) {
4056 /* Erik had a check here that the file descriptor in question
4057 * is legit; I postpone that to "run time"
4058 * A "-" representation of "close me" shows up as a -3 here */
4059 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4060 redir->rd_fd, redir->rd_dup);
4062 /* Set ctx->pending_redirect, so we know what to do at the
4063 * end of the next parsed word. */
4064 ctx->pending_redirect = redir;
4069 /* If a redirect is immediately preceded by a number, that number is
4070 * supposed to tell which file descriptor to redirect. This routine
4071 * looks for such preceding numbers. In an ideal world this routine
4072 * needs to handle all the following classes of redirects...
4073 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4074 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4075 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4076 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
4078 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4080 * ... If n is quoted, the number shall not be recognized as part of
4081 * the redirection expression. For example:
4083 * writes the character 2 into file a"
4084 * We are getting it right by setting ->o_quoted on any \<char>
4086 * A -1 return means no valid number was found,
4087 * the caller should use the appropriate default for this redirection.
4089 static int redirect_opt_num(o_string *o)
4093 if (o->data == NULL)
4095 num = bb_strtou(o->data, NULL, 10);
4096 if (errno || num < 0)
4103 #define fetch_till_str(as_string, input, word, skip_tabs) \
4104 fetch_till_str(input, word, skip_tabs)
4106 static char *fetch_till_str(o_string *as_string,
4107 struct in_str *input,
4111 o_string heredoc = NULL_O_STRING;
4117 ch = i_getch(input);
4118 nommu_addchr(as_string, ch);
4120 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4121 heredoc.data[past_EOL] = '\0';
4122 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4123 return heredoc.data;
4126 o_addchr(&heredoc, ch);
4127 past_EOL = heredoc.length;
4130 ch = i_getch(input);
4131 nommu_addchr(as_string, ch);
4132 } while (skip_tabs && ch == '\t');
4133 } while (ch == '\n');
4136 o_free_unsafe(&heredoc);
4139 o_addchr(&heredoc, ch);
4140 nommu_addchr(as_string, ch);
4144 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4145 * and load them all. There should be exactly heredoc_cnt of them.
4147 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4149 struct pipe *pi = ctx->list_head;
4153 struct command *cmd = pi->cmds;
4155 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4157 cmd->argv ? cmd->argv[0] : "NONE");
4158 for (i = 0; i < pi->num_cmds; i++) {
4159 struct redir_struct *redir = cmd->redirects;
4161 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4162 i, cmd->argv ? cmd->argv[0] : "NONE");
4164 if (redir->rd_type == REDIRECT_HEREDOC) {
4167 if (heredoc_cnt <= 0) {
4168 syntax("heredoc BUG 1");
4169 return 1; /* error */
4171 redir->rd_type = REDIRECT_HEREDOC2;
4172 /* redir->dup is (ab)used to indicate <<- */
4173 p = fetch_till_str(&ctx->as_string, input,
4174 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
4176 syntax("unexpected EOF in here document");
4179 free(redir->rd_filename);
4180 redir->rd_filename = p;
4183 redir = redir->next;
4189 /* Should be 0. If it isn't, it's a parse error */
4191 syntax("heredoc BUG 2");
4197 #define parse_stream(pstring, input, end_trigger) \
4198 parse_stream(input, end_trigger)
4200 static struct pipe *parse_stream(char **pstring,
4201 struct in_str *input,
4203 static void parse_and_run_string(const char *s);
4205 #if ENABLE_HUSH_TICK
4206 static FILE *generate_stream_from_string(const char *s)
4209 int pid, channel[2];
4212 pid = BB_MMU ? fork() : vfork();
4214 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
4216 if (pid == 0) { /* child */
4217 disable_restore_tty_pgrp_on_exit();
4218 /* Process substitution is not considered to be usual
4219 * 'command execution'.
4220 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
4227 close(channel[0]); /* NB: close _first_, then move fd! */
4228 xmove_fd(channel[1], 1);
4229 /* Prevent it from trying to handle ctrl-z etc */
4230 USE_HUSH_JOB(G.run_list_level = 1;)
4232 reset_traps_to_defaults();
4233 parse_and_run_string(s);
4234 _exit(G.last_exitcode);
4236 /* We re-execute after vfork on NOMMU. This makes this script safe:
4237 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
4238 * huge=`cat BIG` # was blocking here forever
4241 re_execute_shell(s, 0);
4246 enable_restore_tty_pgrp_on_exit();
4247 clean_up_after_re_execute();
4249 pf = fdopen(channel[0], "r");
4253 /* Return code is exit status of the process that is run. */
4254 static int process_command_subs(o_string *dest, const char *s)
4257 struct in_str pipe_str;
4260 pf = generate_stream_from_string(s);
4263 close_on_exec_on(fileno(pf));
4265 /* Now send results of command back into original context */
4266 setup_file_in_str(&pipe_str, pf);
4268 while ((ch = i_getch(&pipe_str)) != EOF) {
4274 o_addchr(dest, '\n');
4277 o_addQchr(dest, ch);
4280 debug_printf("done reading from pipe, pclose()ing\n");
4281 /* Note: we got EOF, and we just close the read end of the pipe.
4282 * We do not wait for the `cmd` child to terminate. bash and ash do.
4284 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
4285 * `false`; echo $? - bash outputs "1"
4288 debug_printf("closed FILE from child. return 0\n");
4293 static int parse_group(o_string *dest, struct parse_context *ctx,
4294 struct in_str *input, int ch)
4296 /* dest contains characters seen prior to ( or {.
4297 * Typically it's empty, but for function defs,
4298 * it contains function name (without '()'). */
4299 struct pipe *pipe_list;
4301 struct command *command = ctx->command;
4303 debug_printf_parse("parse_group entered\n");
4304 #if ENABLE_HUSH_FUNCTIONS
4305 if (ch == 'F') { /* function definition? */
4306 bb_error_msg("aha '%s' is a function, parsing it...", dest->data);
4307 //command->fname = dest->data;
4308 command->grp_type = GRP_FUNCTION;
4309 //TODO: review every o_reset() location... do they handle all o_string fields correctly?
4310 memset(dest, 0, sizeof(*dest));
4313 if (command->argv /* word [word](... */
4314 || dest->length /* word(... */
4315 || dest->o_quoted /* ""(... */
4318 debug_printf_parse("parse_group return 1: "
4319 "syntax error, groups and arglists don't mix\n");
4325 command->grp_type = GRP_SUBSHELL;
4329 char *as_string = NULL;
4331 pipe_list = parse_stream(&as_string, input, endch);
4334 o_addstr(&ctx->as_string, as_string);
4336 /* empty ()/{} or parse error? */
4337 if (!pipe_list || pipe_list == ERR_PTR) {
4342 debug_printf_parse("parse_group return 1: "
4343 "parse_stream returned %p\n", pipe_list);
4346 command->group = pipe_list;
4348 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4349 command->group_as_string = as_string;
4350 debug_printf_parse("end of group, remembering as:'%s'\n",
4351 command->group_as_string);
4354 debug_printf_parse("parse_group return 0\n");
4356 /* command remains "open", available for possible redirects */
4359 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
4360 /* Subroutines for copying $(...) and `...` things */
4361 static void add_till_backquote(o_string *dest, struct in_str *input);
4363 static void add_till_single_quote(o_string *dest, struct in_str *input)
4366 int ch = i_getch(input);
4374 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
4375 static void add_till_double_quote(o_string *dest, struct in_str *input)
4378 int ch = i_getch(input);
4381 if (ch == '\\') { /* \x. Copy both chars. */
4383 ch = i_getch(input);
4389 add_till_backquote(dest, input);
4393 //if (ch == '$') ...
4396 /* Process `cmd` - copy contents until "`" is seen. Complicated by
4398 * "Within the backquoted style of command substitution, backslash
4399 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4400 * The search for the matching backquote shall be satisfied by the first
4401 * backquote found without a preceding backslash; during this search,
4402 * if a non-escaped backquote is encountered within a shell comment,
4403 * a here-document, an embedded command substitution of the $(command)
4404 * form, or a quoted string, undefined results occur. A single-quoted
4405 * or double-quoted string that begins, but does not end, within the
4406 * "`...`" sequence produces undefined results."
4408 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4410 static void add_till_backquote(o_string *dest, struct in_str *input)
4413 int ch = i_getch(input);
4416 if (ch == '\\') { /* \x. Copy both chars unless it is \` */
4417 int ch2 = i_getch(input);
4418 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
4427 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
4428 * quoting and nested ()s.
4429 * "With the $(command) style of command substitution, all characters
4430 * following the open parenthesis to the matching closing parenthesis
4431 * constitute the command. Any valid shell script can be used for command,
4432 * except a script consisting solely of redirections which produces
4433 * unspecified results."
4435 * echo $(echo '(TEST)' BEST) (TEST) BEST
4436 * echo $(echo 'TEST)' BEST) TEST) BEST
4437 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
4439 static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
4443 int ch = i_getch(input);
4452 if (i_peek(input) == ')') {
4460 add_till_single_quote(dest, input);
4465 add_till_double_quote(dest, input);
4469 if (ch == '\\') { /* \x. Copy verbatim. Important for \(, \) */
4470 ch = i_getch(input);
4478 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
4480 /* Return code: 0 for OK, 1 for syntax error */
4482 #define handle_dollar(as_string, dest, input) \
4483 handle_dollar(dest, input)
4485 static int handle_dollar(o_string *as_string,
4487 struct in_str *input)
4490 int ch = i_peek(input); /* first character after the $ */
4491 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
4493 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
4495 ch = i_getch(input);
4496 nommu_addchr(as_string, ch);
4498 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4500 debug_printf_parse(": '%c'\n", ch);
4501 o_addchr(dest, ch | quote_mask);
4504 if (!isalnum(ch) && ch != '_')
4506 ch = i_getch(input);
4507 nommu_addchr(as_string, ch);
4509 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4510 } else if (isdigit(ch)) {
4512 ch = i_getch(input);
4513 nommu_addchr(as_string, ch);
4514 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4515 debug_printf_parse(": '%c'\n", ch);
4516 o_addchr(dest, ch | quote_mask);
4517 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4518 } else switch (ch) {
4520 case '!': /* last bg pid */
4521 case '?': /* last exit code */
4522 case '#': /* number of args */
4523 case '*': /* args */
4524 case '@': /* args */
4525 goto make_one_char_var;
4527 bool first_char, all_digits;
4529 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4530 ch = i_getch(input);
4531 nommu_addchr(as_string, ch);
4532 /* XXX maybe someone will try to escape the '}' */
4537 ch = i_getch(input);
4538 nommu_addchr(as_string, ch);
4544 /* ${#var}: length of var contents */
4546 else if (isdigit(ch)) {
4553 && ( (all_digits && !isdigit(ch))
4554 || (!all_digits && !isalnum(ch) && ch != '_')
4557 /* handle parameter expansions
4558 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4563 case ':': /* null modifier */
4564 if (expansion == 0) {
4565 debug_printf_parse(": null modifier\n");
4570 case '#': /* remove prefix */
4571 case '%': /* remove suffix */
4572 if (expansion == 0) {
4573 debug_printf_parse(": remove suffix/prefix\n");
4578 case '-': /* default value */
4579 case '=': /* assign default */
4580 case '+': /* alternative */
4581 case '?': /* error indicate */
4582 debug_printf_parse(": parameter expansion\n");
4587 syntax("unterminated ${name}");
4588 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
4593 debug_printf_parse(": '%c'\n", ch);
4594 o_addchr(dest, ch | quote_mask);
4598 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4601 #if (ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK)
4606 ch = i_getch(input);
4607 nommu_addchr(as_string, ch);
4608 # if ENABLE_SH_MATH_SUPPORT
4609 if (i_peek(input) == '(') {
4610 ch = i_getch(input);
4611 nommu_addchr(as_string, ch);
4612 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4613 o_addchr(dest, /*quote_mask |*/ '+');
4617 add_till_closing_paren(dest, input, true);
4620 o_addstr(as_string, dest->data + pos);
4621 o_addchr(as_string, ')');
4622 o_addchr(as_string, ')');
4625 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4629 # if ENABLE_HUSH_TICK
4630 //int pos = dest->length;
4631 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4632 o_addchr(dest, quote_mask | '`');
4636 add_till_closing_paren(dest, input, false);
4639 o_addstr(as_string, dest->data + pos);
4640 o_addchr(as_string, '`');
4643 //debug_printf_subst("SUBST RES2 '%s'\n", dest->data + pos);
4644 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4650 ch = i_getch(input);
4651 nommu_addchr(as_string, ch);
4653 if (isalnum(ch)) { /* it's $_name or $_123 */
4659 /* $_ Shell or shell script name; or last cmd name */
4660 /* $- Option flags set by set builtin or shell options (-i etc) */
4662 o_addQchr(dest, '$');
4664 debug_printf_parse("handle_dollar return 0\n");
4669 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
4670 parse_stream_dquoted(dest, input, dquote_end)
4672 static int parse_stream_dquoted(o_string *as_string,
4674 struct in_str *input,
4681 ch = i_getch(input);
4683 nommu_addchr(as_string, ch);
4684 if (ch == dquote_end) { /* may be only '"' or EOF */
4685 if (dest->o_assignment == NOT_ASSIGNMENT)
4686 dest->o_escape ^= 1;
4687 debug_printf_parse("parse_stream_dquoted return 0\n");
4690 /* note: can't move it above ch == dquote_end check! */
4692 syntax("unterminated \"");
4693 debug_printf_parse("parse_stream_dquoted return 1: unterminated \"\n");
4698 next = i_peek(input);
4700 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4701 ch, ch, dest->o_escape);
4705 debug_printf_parse("parse_stream_dquoted return 1: \\<eof>\n");
4709 * "The backslash retains its special meaning [in "..."]
4710 * only when followed by one of the following characters:
4711 * $, `, ", \, or <newline>. A double quote may be quoted
4712 * within double quotes by preceding it with a backslash.
4713 * If enabled, history expansion will be performed unless
4714 * an ! appearing in double quotes is escaped using
4715 * a backslash. The backslash preceding the ! is not removed."
4717 if (strchr("$`\"\\", next) != NULL) {
4718 o_addqchr(dest, i_getch(input));
4720 o_addqchr(dest, '\\');
4725 if (handle_dollar(as_string, dest, input) != 0) {
4726 debug_printf_parse("parse_stream_dquoted return 1: "
4727 "handle_dollar returned non-0\n");
4732 #if ENABLE_HUSH_TICK
4734 //int pos = dest->length;
4735 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4736 o_addchr(dest, 0x80 | '`');
4737 add_till_backquote(dest, input);
4738 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4739 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4743 o_addQchr(dest, ch);
4745 && (dest->o_assignment == MAYBE_ASSIGNMENT
4746 || dest->o_assignment == WORD_IS_KEYWORD)
4747 && is_assignment(dest->data)
4749 dest->o_assignment = DEFINITELY_ASSIGNMENT;
4755 * Scan input until EOF or end_trigger char.
4756 * Return a list of pipes to execute, or NULL on EOF
4757 * or if end_trigger character is met.
4758 * On syntax error, exit is shell is not interactive,
4759 * reset parsing machinery and start parsing anew,
4760 * or return ERR_PTR.
4762 static struct pipe *parse_stream(char **pstring,
4763 struct in_str *input,
4766 struct parse_context ctx;
4767 o_string dest = NULL_O_STRING;
4771 /* Double-quote state is handled in the state variable is_in_dquote.
4772 * A single-quote triggers a bypass of the main loop until its mate is
4773 * found. When recursing, quote state is passed in via dest->o_escape.
4775 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4776 end_trigger ? : 'X');
4778 G.ifs = get_local_var_value("IFS");
4783 #if ENABLE_HUSH_INTERACTIVE
4784 input->promptmode = 0; /* PS1 */
4786 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
4787 initialize_context(&ctx);
4792 const char *is_special;
4796 redir_type redir_style;
4799 /* dest.o_quoted = 1; - already is (see below) */
4800 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
4803 /* We reached closing '"' */
4806 ch = i_getch(input);
4807 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4808 ch, ch, dest.o_escape);
4813 syntax("unterminated here document");
4816 if (done_word(&dest, &ctx)) {
4820 done_pipe(&ctx, PIPE_SEQ);
4822 /* If we got nothing... */
4823 // TODO: test script consisting of just "&"
4824 if (pi->num_cmds == 0
4825 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4827 free_pipe_list(pi, 0);
4830 debug_printf_parse("parse_stream return %p\n", pi);
4832 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4834 *pstring = ctx.as_string.data;
4836 o_free_unsafe(&ctx.as_string);
4840 nommu_addchr(&ctx.as_string, ch);
4841 is_ifs = strchr(G.ifs, ch);
4842 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
4843 "\\$\"" USE_HUSH_TICK("`") /* always special */
4846 if (!is_special && !is_ifs) { /* ordinary char */
4847 o_addQchr(&dest, ch);
4848 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4849 || dest.o_assignment == WORD_IS_KEYWORD)
4851 && is_assignment(dest.data)
4853 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4859 if (done_word(&dest, &ctx)) {
4863 #if ENABLE_HUSH_CASE
4864 /* "case ... in <newline> word) ..." -
4865 * newlines are ignored (but ';' wouldn't be) */
4866 if (ctx.command->argv == NULL
4867 && ctx.ctx_res_w == RES_MATCH
4872 /* Treat newline as a command separator. */
4873 done_pipe(&ctx, PIPE_SEQ);
4874 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4876 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
4881 dest.o_assignment = MAYBE_ASSIGNMENT;
4883 /* note: if (is_ifs) continue;
4884 * will still trigger for us */
4887 if (end_trigger && end_trigger == ch
4888 && (heredoc_cnt == 0 || end_trigger != ';')
4890 //TODO: disallow "{ cmd }" without semicolon
4892 /* This is technically valid:
4893 * { cat <<HERE; }; echo Ok
4898 * but we don't support this.
4899 * We require heredoc to be in enclosing {}/(),
4902 syntax("unterminated here document");
4905 if (done_word(&dest, &ctx)) {
4908 done_pipe(&ctx, PIPE_SEQ);
4909 dest.o_assignment = MAYBE_ASSIGNMENT;
4910 /* Do we sit outside of any if's, loops or case's? */
4912 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4914 debug_printf_parse("parse_stream return %p: "
4915 "end_trigger char found\n",
4919 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4921 *pstring = ctx.as_string.data;
4923 o_free_unsafe(&ctx.as_string);
4925 return ctx.list_head;
4931 if (dest.o_assignment == MAYBE_ASSIGNMENT) {
4932 /* ch is a special char and thus this word
4933 * cannot be an assignment */
4934 dest.o_assignment = NOT_ASSIGNMENT;
4939 next = i_peek(input);
4944 if (dest.length == 0) {
4947 if (ch == EOF || ch == '\n')
4950 /* note: we do not add it to &ctx.as_string */
4952 nommu_addchr(&ctx.as_string, '\n');
4954 o_addQchr(&dest, ch);
4962 o_addchr(&dest, '\\');
4963 ch = i_getch(input);
4964 nommu_addchr(&ctx.as_string, ch);
4965 o_addchr(&dest, ch);
4966 /* Example: echo Hello \2>file
4967 * we need to know that word 2 is quoted */
4971 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
4972 debug_printf_parse("parse_stream parse error: "
4973 "handle_dollar returned non-0\n");
4980 ch = i_getch(input);
4982 syntax("unterminated '");
4985 nommu_addchr(&ctx.as_string, ch);
4988 if (dest.o_assignment == NOT_ASSIGNMENT)
4989 o_addqchr(&dest, ch);
4991 o_addchr(&dest, ch);
4996 is_in_dquote ^= 1; /* invert */
4997 if (dest.o_assignment == NOT_ASSIGNMENT)
5000 #if ENABLE_HUSH_TICK
5002 //int pos = dest.length;
5003 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5004 o_addchr(&dest, '`');
5005 add_till_backquote(&dest, input);
5006 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5007 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
5012 redir_fd = redirect_opt_num(&dest);
5013 if (done_word(&dest, &ctx)) {
5016 redir_style = REDIRECT_OVERWRITE;
5018 redir_style = REDIRECT_APPEND;
5019 ch = i_getch(input);
5020 nommu_addchr(&ctx.as_string, ch);
5023 else if (next == '(') {
5024 syntax(">(process) not supported");
5028 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5032 redir_fd = redirect_opt_num(&dest);
5033 if (done_word(&dest, &ctx)) {
5036 redir_style = REDIRECT_INPUT;
5038 redir_style = REDIRECT_HEREDOC;
5040 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5041 ch = i_getch(input);
5042 nommu_addchr(&ctx.as_string, ch);
5043 } else if (next == '>') {
5044 redir_style = REDIRECT_IO;
5045 ch = i_getch(input);
5046 nommu_addchr(&ctx.as_string, ch);
5049 else if (next == '(') {
5050 syntax("<(process) not supported");
5054 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5058 #if ENABLE_HUSH_CASE
5061 if (done_word(&dest, &ctx)) {
5064 done_pipe(&ctx, PIPE_SEQ);
5065 #if ENABLE_HUSH_CASE
5066 /* Eat multiple semicolons, detect
5067 * whether it means something special */
5072 ch = i_getch(input);
5073 nommu_addchr(&ctx.as_string, ch);
5074 if (ctx.ctx_res_w == RES_CASEI) {
5075 ctx.ctx_dsemicolon = 1;
5076 ctx.ctx_res_w = RES_MATCH;
5082 /* We just finished a cmd. New one may start
5083 * with an assignment */
5084 dest.o_assignment = MAYBE_ASSIGNMENT;
5087 if (done_word(&dest, &ctx)) {
5091 ch = i_getch(input);
5092 nommu_addchr(&ctx.as_string, ch);
5093 done_pipe(&ctx, PIPE_AND);
5095 done_pipe(&ctx, PIPE_BG);
5099 if (done_word(&dest, &ctx)) {
5102 #if ENABLE_HUSH_CASE
5103 if (ctx.ctx_res_w == RES_MATCH)
5104 break; /* we are in case's "word | word)" */
5106 if (next == '|') { /* || */
5107 ch = i_getch(input);
5108 nommu_addchr(&ctx.as_string, ch);
5109 done_pipe(&ctx, PIPE_OR);
5111 /* we could pick up a file descriptor choice here
5112 * with redirect_opt_num(), but bash doesn't do it.
5113 * "echo foo 2| cat" yields "foo 2". */
5118 #if ENABLE_HUSH_CASE
5119 /* "case... in [(]word)..." - skip '(' */
5120 if (ctx.ctx_res_w == RES_MATCH
5121 && ctx.command->argv == NULL /* not (word|(... */
5122 && dest.length == 0 /* not word(... */
5123 && dest.o_quoted == 0 /* not ""(... */
5128 #if ENABLE_HUSH_FUNCTIONS
5129 if (dest.length != 0 /* not just () but word() */
5130 && dest.o_quoted == 0 /* not a"b"c() */
5131 && ctx.command->argv == NULL /* it's the first word */
5132 //TODO: "func ( ) {...}" - note spaces - is valid format too in bash
5133 && i_peek(input) == ')'
5134 && !match_reserved_word(&dest)
5136 bb_error_msg("seems like a function definition");
5138 //if !BB_MMU o_addchr(&ctx.as_string...
5140 //TODO: do it properly.
5141 ch = i_getch(input);
5142 } while (ch == ' ' || ch == '\n');
5144 syntax("was expecting {");
5147 ch = 'F'; /* magic value */
5151 if (parse_group(&dest, &ctx, input, ch) != 0) {
5156 #if ENABLE_HUSH_CASE
5157 if (ctx.ctx_res_w == RES_MATCH)
5161 /* proper use of this character is caught by end_trigger:
5162 * if we see {, we call parse_group(..., end_trigger='}')
5163 * and it will match } earlier (not here). */
5164 syntax("unexpected } or )");
5168 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
5174 struct parse_context *pctx;
5175 IF_HAS_KEYWORDS(struct parse_context *p2;)
5177 /* Clean up allocated tree.
5178 * Samples for finding leaks on syntax error recovery path.
5179 * Run them from interactive shell, watch pmap `pidof hush`.
5180 * while if false; then false; fi do break; done
5182 * while if false; then false; fi; do break; fi
5183 * Samples to catch leaks at execution:
5184 * while if (true | {true;}); then echo ok; fi; do break; done
5185 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
5189 /* Update pipe/command counts,
5190 * otherwise freeing may miss some */
5191 done_pipe(pctx, PIPE_SEQ);
5192 debug_printf_clean("freeing list %p from ctx %p\n",
5193 pctx->list_head, pctx);
5194 debug_print_tree(pctx->list_head, 0);
5195 free_pipe_list(pctx->list_head, 0);
5196 debug_printf_clean("freed list %p\n", pctx->list_head);
5198 o_free_unsafe(&pctx->as_string);
5200 IF_HAS_KEYWORDS(p2 = pctx->stack;)
5204 IF_HAS_KEYWORDS(pctx = p2;)
5205 } while (HAS_KEYWORDS && pctx);
5206 /* Free text, clear all dest fields */
5208 /* If we are not in top-level parse, we return,
5209 * our caller will propagate error.
5211 if (end_trigger != ';') {
5218 /* Discard cached input, force prompt */
5220 USE_HUSH_INTERACTIVE(input->promptme = 1;)
5225 /* Executing from string: eval, sh -c '...'
5226 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5227 * end_trigger controls how often we stop parsing
5228 * NUL: parse all, execute, return
5229 * ';': parse till ';' or newline, execute, repeat till EOF
5231 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5234 struct pipe *pipe_list;
5236 pipe_list = parse_stream(NULL, inp, end_trigger);
5237 if (!pipe_list) /* EOF */
5239 debug_print_tree(pipe_list, 0);
5240 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5241 run_and_free_list(pipe_list);
5245 static void parse_and_run_string(const char *s)
5247 struct in_str input;
5248 setup_string_in_str(&input, s);
5249 parse_and_run_stream(&input, '\0');
5252 static void parse_and_run_file(FILE *f)
5254 struct in_str input;
5255 setup_file_in_str(&input, f);
5256 parse_and_run_stream(&input, ';');
5259 /* Called a few times only (or even once if "sh -c") */
5260 static void block_signals(int second_time)
5265 mask = (1 << SIGQUIT);
5266 if (G_interactive_fd) {
5270 //TODO | (1 << SIGHUP)
5272 | (1 << SIGTTIN) | (1 << SIGTTOU) | (1 << SIGTSTP)
5277 G.non_DFL_mask = mask;
5280 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
5284 sigaddset(&G.blocked_set, sig);
5288 sigdelset(&G.blocked_set, SIGCHLD);
5290 sigprocmask(SIG_SETMASK, &G.blocked_set,
5291 second_time ? NULL : &G.inherited_set);
5292 /* POSIX allows shell to re-enable SIGCHLD
5293 * even if it was SIG_IGN on entry */
5294 // G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
5296 signal(SIGCHLD, SIG_DFL); // SIGCHLD_handler);
5301 static void maybe_set_to_sigexit(int sig)
5303 void (*handler)(int);
5304 /* non_DFL_mask'ed signals are, well, masked,
5305 * no need to set handler for them.
5307 if (!((G.non_DFL_mask >> sig) & 1)) {
5308 handler = signal(sig, sigexit);
5309 if (handler == SIG_IGN) /* oops... restore back to IGN! */
5310 signal(sig, handler);
5313 /* Set handlers to restore tty pgrp and exit */
5314 static void set_fatal_handlers(void)
5316 /* We _must_ restore tty pgrp on fatal signals */
5318 maybe_set_to_sigexit(SIGILL );
5319 maybe_set_to_sigexit(SIGFPE );
5320 maybe_set_to_sigexit(SIGBUS );
5321 maybe_set_to_sigexit(SIGSEGV);
5322 maybe_set_to_sigexit(SIGTRAP);
5323 } /* else: hush is perfect. what SEGV? */
5324 maybe_set_to_sigexit(SIGABRT);
5325 /* bash 3.2 seems to handle these just like 'fatal' ones */
5326 maybe_set_to_sigexit(SIGPIPE);
5327 maybe_set_to_sigexit(SIGALRM);
5328 //TODO: disable and move down when proper SIGHUP handling is added
5329 maybe_set_to_sigexit(SIGHUP );
5330 /* if we are interactive, [SIGHUP,] SIGTERM and SIGINT are masked.
5331 * if we aren't interactive... but in this case
5332 * we never want to restore pgrp on exit, and this fn is not called */
5333 /*maybe_set_to_sigexit(SIGTERM);*/
5334 /*maybe_set_to_sigexit(SIGINT );*/
5338 static int set_mode(const char cstate, const char mode)
5340 int state = (cstate == '-' ? 1 : 0);
5342 case 'n': G.fake_mode = state; break;
5343 case 'x': /*G.debug_mode = state;*/ break;
5344 default: return EXIT_FAILURE;
5346 return EXIT_SUCCESS;
5349 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
5350 int hush_main(int argc, char **argv)
5352 static const struct variable const_shell_ver = {
5354 .varstr = (char*)hush_version_str,
5355 .max_len = 1, /* 0 can provoke free(name) */
5359 int signal_mask_is_inited = 0;
5362 struct variable *cur_var;
5365 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
5366 G.last_exitcode = EXIT_SUCCESS;
5368 G.argv0_for_re_execing = argv[0];
5370 /* Deal with HUSH_VERSION */
5371 G.shell_ver = const_shell_ver; /* copying struct here */
5372 G.top_var = &G.shell_ver;
5373 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
5374 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
5375 /* Initialize our shell local variables with the values
5376 * currently living in the environment */
5377 cur_var = G.top_var;
5380 char *value = strchr(*e, '=');
5381 if (value) { /* paranoia */
5382 cur_var->next = xzalloc(sizeof(*cur_var));
5383 cur_var = cur_var->next;
5384 cur_var->varstr = *e;
5385 cur_var->max_len = strlen(*e);
5386 cur_var->flg_export = 1;
5390 debug_printf_env("putenv '%s'\n", hush_version_str);
5391 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
5392 #if ENABLE_FEATURE_EDITING
5393 G.line_input_state = new_line_input_t(FOR_SHELL);
5395 G.global_argc = argc;
5396 G.global_argv = argv;
5397 /* Initialize some more globals to non-zero values */
5399 #if ENABLE_HUSH_INTERACTIVE
5400 if (ENABLE_FEATURE_EDITING)
5401 cmdedit_set_initial_prompt();
5405 /* Shell is non-interactive at first. We need to call
5406 * block_signals(0) if we are going to execute "sh <script>",
5407 * "sh -c <cmds>" or login shell's /etc/profile and friends.
5408 * If we later decide that we are interactive, we run block_signals(0)
5409 * (or re-run block_signals(1) if we ran block_signals(0) before)
5410 * in order to intercept (more) signals.
5414 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
5416 opt = getopt(argc, argv, "c:xins"
5426 G.root_pid = getpid();
5427 G.global_argv = argv + optind;
5428 if (!argv[optind]) {
5429 /* -c 'script' (no params): prevent empty $0 */
5430 *--G.global_argv = argv[0];
5432 } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
5433 G.global_argc = argc - optind;
5434 block_signals(0); /* 0: called 1st time */
5435 parse_and_run_string(optarg);
5438 /* Well, we cannot just declare interactiveness,
5439 * we have to have some stuff (ctty, etc) */
5440 /* G_interactive_fd++; */
5443 /* "-s" means "read from stdin", but this is how we always
5444 * operate, so simply do nothing here. */
5447 case '<': /* "big heredoc" support */
5448 full_write(STDOUT_FILENO, optarg, strlen(optarg));
5451 G.root_pid = bb_strtou(optarg, &optarg, 16);
5453 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
5455 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
5456 # if ENABLE_HUSH_LOOPS
5458 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
5463 set_local_var(xstrdup(optarg), 0, opt == 'R');
5468 if (!set_mode('-', opt))
5472 fprintf(stderr, "Usage: sh [FILE]...\n"
5473 " or: sh -c command [args]...\n\n");
5479 } /* option parsing loop */
5482 G.root_pid = getpid();
5484 /* If we are login shell... */
5485 if (argv[0] && argv[0][0] == '-') {
5487 /* XXX what should argv be while sourcing /etc/profile? */
5488 debug_printf("sourcing /etc/profile\n");
5489 input = fopen_for_read("/etc/profile");
5490 if (input != NULL) {
5491 close_on_exec_on(fileno(input));
5492 block_signals(0); /* 0: called 1st time */
5493 signal_mask_is_inited = 1;
5494 parse_and_run_file(input);
5497 /* bash: after sourcing /etc/profile,
5498 * tries to source (in the given order):
5499 * ~/.bash_profile, ~/.bash_login, ~/.profile,
5500 * stopping of first found. --noprofile turns this off.
5501 * bash also sources ~/.bash_logout on exit.
5502 * If called as sh, skips .bash_XXX files.
5509 * "bash <script>" (which is never interactive (unless -i?))
5510 * sources $BASH_ENV here (without scanning $PATH).
5511 * If called as sh, does the same but with $ENV.
5513 debug_printf("running script '%s'\n", argv[optind]);
5514 G.global_argv = argv + optind;
5515 G.global_argc = argc - optind;
5516 input = xfopen_for_read(argv[optind]);
5517 close_on_exec_on(fileno(input));
5518 if (!signal_mask_is_inited)
5519 block_signals(0); /* 0: called 1st time */
5520 parse_and_run_file(input);
5521 #if ENABLE_FEATURE_CLEAN_UP
5527 /* Up to here, shell was non-interactive. Now it may become one.
5528 * NB: don't forget to (re)run block_signals(0/1) as needed.
5531 /* A shell is interactive if the '-i' flag was given, or if all of
5532 * the following conditions are met:
5534 * no arguments remaining or the -s flag given
5535 * standard input is a terminal
5536 * standard output is a terminal
5537 * Refer to Posix.2, the description of the 'sh' utility.
5540 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
5541 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
5542 debug_printf("saved_tty_pgrp:%d\n", G.saved_tty_pgrp);
5543 //TODO: "interactive" and "have job control" are two different things.
5544 //If tcgetpgrp fails here, "have job control" is false, but "interactive"
5545 //should stay on! Currently, we mix these into one.
5546 if (G.saved_tty_pgrp >= 0) {
5547 /* try to dup stdin to high fd#, >= 255 */
5548 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
5549 if (G_interactive_fd < 0) {
5550 /* try to dup to any fd */
5551 G_interactive_fd = dup(STDIN_FILENO);
5552 if (G_interactive_fd < 0)
5554 G_interactive_fd = 0;
5556 // TODO: track & disallow any attempts of user
5557 // to (inadvertently) close/redirect it
5560 debug_printf("interactive_fd:%d\n", G_interactive_fd);
5561 if (G_interactive_fd) {
5564 /* We are indeed interactive shell, and we will perform
5565 * job control. Setting up for that. */
5567 close_on_exec_on(G_interactive_fd);
5568 /* If we were run as 'hush &', sleep until we are
5569 * in the foreground (tty pgrp == our pgrp).
5570 * If we get started under a job aware app (like bash),
5571 * make sure we are now in charge so we don't fight over
5572 * who gets the foreground */
5574 shell_pgrp = getpgrp();
5575 G.saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
5576 if (G.saved_tty_pgrp == shell_pgrp)
5578 /* send TTIN to ourself (should stop us) */
5579 kill(- shell_pgrp, SIGTTIN);
5581 /* Block some signals */
5582 block_signals(signal_mask_is_inited);
5583 /* Set other signals to restore saved_tty_pgrp */
5584 set_fatal_handlers();
5585 /* Put ourselves in our own process group */
5586 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
5587 /* Grab control of the terminal */
5588 tcsetpgrp(G_interactive_fd, getpid());
5589 /* -1 is special - makes xfuncs longjmp, not exit
5590 * (we reset die_sleep = 0 whereever we [v]fork) */
5591 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
5592 if (setjmp(die_jmp)) {
5593 /* xfunc has failed! die die die */
5594 hush_exit(xfunc_error_retval);
5596 } else if (!signal_mask_is_inited) {
5597 block_signals(0); /* 0: called 1st time */
5598 } /* else: block_signals(0) was done before */
5599 #elif ENABLE_HUSH_INTERACTIVE
5600 /* No job control compiled in, only prompt/line editing */
5601 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
5602 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
5603 if (G_interactive_fd < 0) {
5604 /* try to dup to any fd */
5605 G_interactive_fd = dup(STDIN_FILENO);
5606 if (G_interactive_fd < 0)
5608 G_interactive_fd = 0;
5611 if (G_interactive_fd) {
5612 close_on_exec_on(G_interactive_fd);
5613 block_signals(signal_mask_is_inited);
5614 } else if (!signal_mask_is_inited) {
5618 /* We have interactiveness code disabled */
5619 if (!signal_mask_is_inited) {
5624 * if interactive but not a login shell, sources ~/.bashrc
5625 * (--norc turns this off, --rcfile <file> overrides)
5628 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
5629 printf("\n\n%s hush - the humble shell\n", bb_banner);
5630 printf("Enter 'help' for a list of built-in commands.\n\n");
5633 parse_and_run_file(stdin);
5636 #if ENABLE_FEATURE_CLEAN_UP
5637 if (G.cwd != bb_msg_unknown)
5639 cur_var = G.top_var->next;
5641 struct variable *tmp = cur_var;
5642 if (!cur_var->max_len)
5643 free(cur_var->varstr);
5644 cur_var = cur_var->next;
5648 hush_exit(G.last_exitcode);
5653 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
5654 int lash_main(int argc, char **argv)
5656 //bb_error_msg("lash is deprecated, please use hush instead");
5657 return hush_main(argc, argv);
5665 static int builtin_trap(char **argv)
5672 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
5676 /* No args: print all trapped. This isn't 100% correct as we
5677 * should be escaping the cmd so that it can be pasted back in
5679 for (i = 0; i < NSIG; ++i)
5681 printf("trap -- '%s' %s\n", G.traps[i], get_signame(i));
5682 return EXIT_SUCCESS;
5687 /* If first arg is decimal: reset all specified signals */
5688 sig = bb_strtou(*argv, NULL, 10);
5694 sig = get_signum(*argv++);
5695 if (sig < 0 || sig >= NSIG) {
5697 /* Mimic bash message exactly */
5698 bb_perror_msg("trap: %s: invalid signal specification", argv[i]);
5703 G.traps[sig] = xstrdup(new_cmd);
5705 debug_printf("trap: setting SIG%s (%i) to '%s'",
5706 get_signame(sig), sig, G.traps[sig]);
5708 /* There is no signal for 0 (EXIT) */
5713 sigaddset(&G.blocked_set, sig);
5715 /* There was a trap handler, we are removing it
5716 * (if sig has non-DFL handling,
5717 * we don't need to do anything) */
5718 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
5720 sigdelset(&G.blocked_set, sig);
5722 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5727 /* First arg is "-": reset all specified to default */
5728 /* First arg is "": ignore all specified */
5729 /* Everything else: execute first arg upon signal */
5731 bb_error_msg("trap: invalid arguments");
5732 return EXIT_FAILURE;
5734 if (NOT_LONE_DASH(*argv))
5740 static int builtin_true(char **argv UNUSED_PARAM)
5745 static int builtin_test(char **argv)
5752 return test_main(argc, argv - argc);
5755 static int builtin_echo(char **argv)
5762 return echo_main(argc, argv - argc);
5765 static int builtin_eval(char **argv)
5767 int rcode = EXIT_SUCCESS;
5770 char *str = expand_strvec_to_string(argv);
5772 * eval "echo Hi; done" ("done" is syntax error):
5773 * "echo Hi" will not execute too.
5775 parse_and_run_string(str);
5777 rcode = G.last_exitcode;
5782 static int builtin_cd(char **argv)
5784 const char *newdir = argv[1];
5785 if (newdir == NULL) {
5786 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
5787 * bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
5789 newdir = getenv("HOME") ? : "/";
5791 if (chdir(newdir)) {
5792 /* Mimic bash message exactly */
5793 bb_perror_msg("cd: %s", newdir);
5794 return EXIT_FAILURE;
5797 return EXIT_SUCCESS;
5800 static int builtin_exec(char **argv)
5802 if (*++argv == NULL)
5803 return EXIT_SUCCESS; /* bash does this */
5808 // FIXME: if exec fails, bash does NOT exit! We do...
5809 pseudo_exec_argv(&dummy, argv, 0, NULL);
5814 static int builtin_exit(char **argv)
5816 debug_printf_exec("%s()\n", __func__);
5817 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
5818 //puts("exit"); /* bash does it */
5819 // TODO: warn if we have background jobs: "There are stopped jobs"
5820 // On second consecutive 'exit', exit anyway.
5821 if (*++argv == NULL)
5822 hush_exit(G.last_exitcode);
5823 /* mimic bash: exit 123abc == exit 255 + error msg */
5824 xfunc_error_retval = 255;
5825 /* bash: exit -2 == exit 254, no error msg */
5826 hush_exit(xatoi(*argv) & 0xff);
5829 static int builtin_export(char **argv)
5831 if (*++argv == NULL) {
5833 // ash emits: export VAR='VAL'
5834 // bash: declare -x VAR="VAL"
5835 // (both also escape as needed (quotes, $, etc))
5840 return EXIT_SUCCESS;
5847 value = strchr(name, '=');
5849 /* They are exporting something without a =VALUE */
5850 struct variable *var;
5852 var = get_local_var(name);
5854 var->flg_export = 1;
5855 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
5856 putenv(var->varstr);
5858 /* bash does not return an error when trying to export
5859 * an undefined variable. Do likewise. */
5862 set_local_var(xstrdup(name), 1, 0);
5865 return EXIT_SUCCESS;
5869 /* built-in 'fg' and 'bg' handler */
5870 static int builtin_fg_bg(char **argv)
5875 if (!G_interactive_fd)
5876 return EXIT_FAILURE;
5877 /* If they gave us no args, assume they want the last backgrounded task */
5879 for (pi = G.job_list; pi; pi = pi->next) {
5880 if (pi->jobid == G.last_jobid) {
5884 bb_error_msg("%s: no current job", argv[0]);
5885 return EXIT_FAILURE;
5887 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
5888 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
5889 return EXIT_FAILURE;
5891 for (pi = G.job_list; pi; pi = pi->next) {
5892 if (pi->jobid == jobnum) {
5896 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
5897 return EXIT_FAILURE;
5899 // TODO: bash prints a string representation
5900 // of job being foregrounded (like "sleep 1 | cat")
5901 if (argv[0][0] == 'f') {
5902 /* Put the job into the foreground. */
5903 tcsetpgrp(G_interactive_fd, pi->pgrp);
5906 /* Restart the processes in the job */
5907 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
5908 for (i = 0; i < pi->num_cmds; i++) {
5909 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
5910 pi->cmds[i].is_stopped = 0;
5912 pi->stopped_cmds = 0;
5914 i = kill(- pi->pgrp, SIGCONT);
5916 if (errno == ESRCH) {
5917 delete_finished_bg_job(pi);
5918 return EXIT_SUCCESS;
5920 bb_perror_msg("kill (SIGCONT)");
5923 if (argv[0][0] == 'f') {
5925 return checkjobs_and_fg_shell(pi);
5927 return EXIT_SUCCESS;
5931 #if ENABLE_HUSH_HELP
5932 static int builtin_help(char **argv UNUSED_PARAM)
5934 const struct built_in_command *x;
5937 "Built-in commands:\n"
5938 "------------------\n");
5939 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
5940 printf("%s\t%s\n", x->cmd, x->descr);
5943 return EXIT_SUCCESS;
5948 static int builtin_jobs(char **argv UNUSED_PARAM)
5951 const char *status_string;
5953 for (job = G.job_list; job; job = job->next) {
5954 if (job->alive_cmds == job->stopped_cmds)
5955 status_string = "Stopped";
5957 status_string = "Running";
5959 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
5961 return EXIT_SUCCESS;
5965 static int builtin_pwd(char **argv UNUSED_PARAM)
5968 return EXIT_SUCCESS;
5971 static int builtin_read(char **argv)
5974 const char *name = argv[1] ? argv[1] : "REPLY";
5975 //TODO: check that argv[1] is a valid variable name
5977 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
5978 return set_local_var(string, 0, 0);
5981 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
5982 * built-in 'set' handler
5984 * set [-abCefhmnuvx] [-o option] [argument...]
5985 * set [+abCefhmnuvx] [+o option] [argument...]
5986 * set -- [argument...]
5989 * Implementations shall support the options in both their hyphen and
5990 * plus-sign forms. These options can also be specified as options to sh.
5992 * Write out all variables and their values: set
5993 * Set $1, $2, and $3 and set "$#" to 3: set c a b
5994 * Turn on the -x and -v options: set -xv
5995 * Unset all positional parameters: set --
5996 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
5997 * Set the positional parameters to the expansion of x, even if x expands
5998 * with a leading '-' or '+': set -- $x
6000 * So far, we only support "set -- [argument...]" and some of the short names.
6002 static int builtin_set(char **argv)
6005 char **pp, **g_argv;
6006 char *arg = *++argv;
6010 for (e = G.top_var; e; e = e->next)
6012 return EXIT_SUCCESS;
6016 if (!strcmp(arg, "--")) {
6021 if (arg[0] == '+' || arg[0] == '-') {
6022 for (n = 1; arg[n]; ++n)
6023 if (set_mode(arg[0], arg[n]))
6029 } while ((arg = *++argv) != NULL);
6030 /* Now argv[0] is 1st argument */
6032 /* Only reset global_argv if we didn't process anything */
6034 return EXIT_SUCCESS;
6037 /* NB: G.global_argv[0] ($0) is never freed/changed */
6038 g_argv = G.global_argv;
6039 if (G.global_args_malloced) {
6045 G.global_args_malloced = 1;
6046 pp = xzalloc(sizeof(pp[0]) * 2);
6047 pp[0] = g_argv[0]; /* retain $0 */
6050 /* This realloc's G.global_argv */
6051 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
6058 return EXIT_SUCCESS;
6060 /* Nothing known, so abort */
6062 bb_error_msg("set: %s: invalid option", arg);
6063 return EXIT_FAILURE;
6066 static int builtin_shift(char **argv)
6072 if (n >= 0 && n < G.global_argc) {
6073 if (G.global_args_malloced) {
6076 free(G.global_argv[m++]);
6079 memmove(&G.global_argv[1], &G.global_argv[n+1],
6080 G.global_argc * sizeof(G.global_argv[0]));
6081 return EXIT_SUCCESS;
6083 return EXIT_FAILURE;
6086 static int builtin_source(char **argv)
6090 if (*++argv == NULL)
6091 return EXIT_FAILURE;
6093 /* XXX search through $PATH is missing */
6094 input = fopen_or_warn(*argv, "r");
6096 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
6097 return EXIT_FAILURE;
6099 close_on_exec_on(fileno(input));
6101 /* Now run the file */
6103 /* XXX argv and argc are broken; need to save old G.global_argv
6104 * (pointer only is OK!) on this stack frame,
6105 * set G.global_argv=argv+1, recurse, and restore. */
6106 parse_and_run_file(input);
6108 return G.last_exitcode;
6111 static int builtin_umask(char **argv)
6114 const char *arg = argv[1];
6116 //TODO: umask may take chmod-like symbolic masks
6117 new_umask = bb_strtou(arg, NULL, 8);
6119 //Message? bash examples:
6120 //bash: umask: 'q': invalid symbolic mode operator
6121 //bash: umask: 999: octal number out of range
6122 return EXIT_FAILURE;
6125 new_umask = umask(0);
6126 printf("%.3o\n", (unsigned) new_umask);
6127 /* fall through and restore new_umask which we set to 0 */
6130 return EXIT_SUCCESS;
6133 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
6134 static int builtin_unset(char **argv)
6140 return EXIT_SUCCESS;
6143 if (argv[0][0] == '-') {
6144 switch (argv[0][1]) {
6150 bb_error_msg("unset: %s: invalid option", *argv);
6151 return EXIT_FAILURE;
6153 //TODO: disallow "unset -vf ..." too
6160 if (unset_local_var(*argv)) {
6161 /* unset <nonexistent_var> doesn't fail.
6162 * Error is when one tries to unset RO var.
6163 * Message was printed by unset_local_var. */
6167 #if ENABLE_HUSH_FUNCTIONS
6169 unset_local_func(*argv);
6177 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
6178 static int builtin_wait(char **argv)
6180 int ret = EXIT_SUCCESS;
6183 if (*++argv == NULL) {
6184 /* Don't care about wait results */
6185 /* Note 1: must wait until there are no more children */
6186 /* Note 2: must be interruptible */
6188 * $ sleep 3 & sleep 6 & wait
6193 * $ sleep 3 & sleep 6 & wait
6197 * ^C <-- after ~4 sec from keyboard
6200 sigaddset(&G.blocked_set, SIGCHLD);
6201 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6204 if (errno == ECHILD)
6206 /* Wait for SIGCHLD or any other signal of interest */
6207 /* sigtimedwait with infinite timeout: */
6208 sig = sigwaitinfo(&G.blocked_set, NULL);
6210 sig = check_and_run_traps(sig);
6211 if (sig && sig != SIGCHLD) { /* see note 2 */
6217 sigdelset(&G.blocked_set, SIGCHLD);
6218 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6222 /* This is probably buggy wrt interruptible-ness */
6224 pid_t pid = bb_strtou(*argv, NULL, 10);
6226 /* mimic bash message */
6227 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
6228 return EXIT_FAILURE;
6230 if (waitpid(pid, &status, 0) == pid) {
6231 if (WIFSIGNALED(status))
6232 ret = 128 + WTERMSIG(status);
6233 else if (WIFEXITED(status))
6234 ret = WEXITSTATUS(status);
6238 bb_perror_msg("wait %s", *argv);
6247 #if ENABLE_HUSH_LOOPS
6248 static int builtin_break(char **argv)
6250 if (G.depth_of_loop == 0) {
6251 bb_error_msg("%s: only meaningful in a loop", argv[0]);
6252 return EXIT_SUCCESS; /* bash compat */
6254 G.flag_break_continue++; /* BC_BREAK = 1 */
6255 G.depth_break_continue = 1;
6257 G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
6258 if (errno || !G.depth_break_continue || argv[2]) {
6259 bb_error_msg("%s: bad arguments", argv[0]);
6260 G.flag_break_continue = BC_BREAK;
6261 G.depth_break_continue = UINT_MAX;
6264 if (G.depth_of_loop < G.depth_break_continue)
6265 G.depth_break_continue = G.depth_of_loop;
6266 return EXIT_SUCCESS;
6269 static int builtin_continue(char **argv)
6271 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
6272 return builtin_break(argv);