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>
11 * The parser routines proper are all original material, first
12 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
13 * execution engine, the builtins, and much of the underlying
14 * support has been adapted from busybox-0.49pre's lash, which is
15 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
16 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
17 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
18 * Troan, which they placed in the public domain. I don't know
19 * how much of the Johnson/Troan code has survived the repeated
23 * o_addchr() derived from similar w_addchar function in glibc-2.2.
24 * setup_redirect(), redirect_opt_num(), and big chunks of main()
25 * and many builtins derived from contributions by Erik Andersen.
26 * Miscellaneous bugfixes from Matt Kraai.
28 * There are two big (and related) architecture differences between
29 * this parser and the lash parser. One is that this version is
30 * actually designed from the ground up to understand nearly all
31 * of the Bourne grammar. The second, consequential change is that
32 * the parser and input reader have been turned inside out. Now,
33 * the parser is in control, and asks for input as needed. The old
34 * way had the input reader in control, and it asked for parsing to
35 * take place as needed. The new way makes it much easier to properly
36 * handle the recursion implicit in the various substitutions, especially
37 * across continuation lines.
39 * POSIX syntax not implemented:
41 * <(list) and >(list) Process Substitution
42 * Here Documents ( << word )
45 * Parameter Expansion for substring processing ${var#word} ${var%word}
47 * Bash stuff maybe optional enable:
48 * &> and >& redirection of stdout+stderr
50 * reserved words: [[ ]] function select
51 * substrings ${var:1:5}
54 * job handling woefully incomplete and buggy (improved --vda)
56 * port selected bugfixes from post-0.49 busybox lash - done?
57 * change { and } from special chars to reserved words
58 * builtins: return, trap, ulimit
59 * test magic exec with redirection only
60 * follow IFS rules more precisely, including update semantics
61 * figure out what to do with backslash-newline
62 * propagate syntax errors, die on resource errors?
63 * continuation lines, both explicit and implicit - done?
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 HUSH_VER_STR "0.92"
81 #if defined SINGLE_APPLET_MAIN
82 /* STANDALONE does not make sense, and won't compile */
83 #undef CONFIG_FEATURE_SH_STANDALONE
84 #undef ENABLE_FEATURE_SH_STANDALONE
85 #undef USE_FEATURE_SH_STANDALONE
86 #define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
87 #define ENABLE_FEATURE_SH_STANDALONE 0
88 #define USE_FEATURE_SH_STANDALONE(...)
89 #define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
92 #if !ENABLE_HUSH_INTERACTIVE
93 #undef ENABLE_FEATURE_EDITING
94 #define ENABLE_FEATURE_EDITING 0
95 #undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
96 #define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
99 /* Do we support ANY keywords? */
100 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
101 #define HAS_KEYWORDS 1
102 #define IF_HAS_KEYWORDS(...) __VA_ARGS__
103 #define IF_HAS_NO_KEYWORDS(...)
105 #define HAS_KEYWORDS 0
106 #define IF_HAS_KEYWORDS(...)
107 #define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
110 /* Keep unconditionally on for now */
113 #define ENABLE_HUSH_FUNCTIONS 0
116 /* If you comment out one of these below, it will be #defined later
117 * to perform debug printfs to stderr: */
118 #define debug_printf(...) do {} while (0)
119 /* Finer-grained debug switches */
120 #define debug_printf_parse(...) do {} while (0)
121 #define debug_print_tree(a, b) do {} while (0)
122 #define debug_printf_exec(...) do {} while (0)
123 #define debug_printf_env(...) do {} while (0)
124 #define debug_printf_jobs(...) do {} while (0)
125 #define debug_printf_expand(...) do {} while (0)
126 #define debug_printf_glob(...) do {} while (0)
127 #define debug_printf_list(...) do {} while (0)
128 #define debug_printf_subst(...) do {} while (0)
129 #define debug_printf_clean(...) do {} while (0)
132 #define debug_printf(...) fprintf(stderr, __VA_ARGS__)
135 #ifndef debug_printf_parse
136 #define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
139 #ifndef debug_printf_exec
140 #define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
143 #ifndef debug_printf_env
144 #define debug_printf_env(...) fprintf(stderr, __VA_ARGS__)
147 #ifndef debug_printf_jobs
148 #define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
154 #ifndef debug_printf_expand
155 #define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
156 #define DEBUG_EXPAND 1
158 #define DEBUG_EXPAND 0
161 #ifndef debug_printf_glob
162 #define debug_printf_glob(...) fprintf(stderr, __VA_ARGS__)
168 #ifndef debug_printf_list
169 #define debug_printf_list(...) fprintf(stderr, __VA_ARGS__)
172 #ifndef debug_printf_subst
173 #define debug_printf_subst(...) fprintf(stderr, __VA_ARGS__)
176 #ifndef debug_printf_clean
177 /* broken, of course, but OK for testing */
178 static const char *indenter(int i)
180 static const char blanks[] ALIGN1 =
182 return &blanks[sizeof(blanks) - i - 1];
184 #define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
185 #define DEBUG_CLEAN 1
189 static void debug_print_strings(const char *prefix, char **vv)
191 fprintf(stderr, "%s:\n", prefix);
193 fprintf(stderr, " '%s'\n", *vv++);
196 #define debug_print_strings(prefix, vv) ((void)0)
200 * Leak hunting. Use hush_leaktool.sh for post-processing.
202 #ifdef FOR_HUSH_LEAKTOOL
203 static void *xxmalloc(int lineno, size_t size)
205 void *ptr = xmalloc((size + 0xff) & ~0xff);
206 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
209 static void *xxrealloc(int lineno, void *ptr, size_t size)
211 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
212 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
215 static char *xxstrdup(int lineno, const char *str)
217 char *ptr = xstrdup(str);
218 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
221 static void xxfree(void *ptr)
223 fdprintf(2, "free %p\n", ptr);
226 #define xmalloc(s) xxmalloc(__LINE__, s)
227 #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
228 #define xstrdup(s) xxstrdup(__LINE__, s)
229 #define free(p) xxfree(p)
233 #define ERR_PTR ((void*)(long)1)
235 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="HUSH_VER_STR;
237 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
239 #define SPECIAL_VAR_SYMBOL 3
241 typedef enum redir_type {
243 REDIRECT_OVERWRITE = 2,
249 /* The descrip member of this structure is only used to make
250 * debugging output pretty */
251 static const struct {
253 signed char default_fd;
257 { O_RDONLY, 0, "<" },
258 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
259 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
260 { O_RDONLY, -1, "<<" },
264 typedef enum pipe_style {
271 typedef enum reserved_style {
280 #if ENABLE_HUSH_LOOPS
287 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
292 /* two pseudo-keywords support contrived "case" syntax: */
293 RES_MATCH , /* "word)" */
294 RES_CASEI , /* "this command is inside CASE" */
301 struct redir_struct {
302 struct redir_struct *next;
303 char *rd_filename; /* filename */
304 int fd; /* file descriptor being redirected */
305 int dup; /* -1, or file descriptor being duplicated */
306 smallint /*enum redir_type*/ rd_type;
310 pid_t pid; /* 0 if exited */
311 int assignment_cnt; /* how many argv[i] are assignments? */
312 smallint is_stopped; /* is the command currently running? */
313 smallint grp_type; /* GRP_xxx */
314 struct pipe *group; /* if non-NULL, this "prog" is {} group,
315 * subshell, or a compound statement */
316 char **argv; /* command name and arguments */
317 struct redir_struct *redirects; /* I/O redirections */
319 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
320 * and on execution these are substituted with their values.
321 * Substitution can make _several_ words out of one argv[n]!
322 * Example: argv[0]=='.^C*^C.' here: echo .$*.
323 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
326 #define GRP_SUBSHELL 1
327 #if ENABLE_HUSH_FUNCTIONS
328 #define GRP_FUNCTION 2
333 int num_cmds; /* total number of commands in job */
334 int alive_cmds; /* number of commands running (not exited) */
335 int stopped_cmds; /* number of commands alive, but stopped */
337 int jobid; /* job number */
338 pid_t pgrp; /* process group ID for the job */
339 char *cmdtext; /* name of job */
341 struct command *cmds; /* array of commands in pipe */
342 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
343 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
344 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
347 /* This holds pointers to the various results of parsing */
348 struct parse_context {
349 /* linked list of pipes */
350 struct pipe *list_head;
351 /* last pipe (being constructed right now) */
353 /* last command in pipe (being constructed right now) */
354 struct command *command;
355 /* last redirect in command->redirects list */
356 struct redir_struct *pending_redirect;
359 smallint ctx_inverted; /* "! cmd | cmd" */
361 smallint ctx_dsemicolon; /* ";;" seen */
363 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
365 /* group we are enclosed in:
366 * example 1: "{ { false; ..."
367 * example 2: "if true; then { false; ..."
368 * example 3: "if true; then if false; ..."
369 * when we find closing "}" / "fi" / whatever, we move list_head
370 * into stack->command->group and delete ourself.
372 struct parse_context *stack;
376 /* On program start, environ points to initial environment.
377 * putenv adds new pointers into it, unsetenv removes them.
378 * Neither of these (de)allocates the strings.
379 * setenv allocates new strings in malloc space and does putenv,
380 * and thus setenv is unusable (leaky) for shell's purposes */
381 #define setenv(...) setenv_is_leaky_dont_use()
383 struct variable *next;
384 char *varstr; /* points to "name=" portion */
385 int max_len; /* if > 0, name is part of initial env; else name is malloced */
386 smallint flg_export; /* putenv should be done on this var */
387 smallint flg_read_only;
390 typedef struct o_string {
392 int length; /* position where data is appended */
394 /* Protect newly added chars against globbing
395 * (by prepending \ to *, ?, [, \) */
399 smallint has_empty_slot;
400 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
403 MAYBE_ASSIGNMENT = 0,
404 DEFINITELY_ASSIGNMENT = 1,
406 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
408 /* Used for initialization: o_string foo = NULL_O_STRING; */
409 #define NULL_O_STRING { NULL }
411 /* I can almost use ordinary FILE*. Is open_memstream() universally
412 * available? Where is it documented? */
413 typedef struct in_str {
415 /* eof_flag=1: last char in ->p is really an EOF */
416 char eof_flag; /* meaningless if ->p == NULL */
418 #if ENABLE_HUSH_INTERACTIVE
420 smallint promptmode; /* 0: PS1, 1: PS2 */
423 int (*get) (struct in_str *);
424 int (*peek) (struct in_str *);
426 #define i_getch(input) ((input)->get(input))
427 #define i_peek(input) ((input)->peek(input))
435 /* "Globals" within this file */
436 /* Sorted roughly by size (smaller offsets == smaller code) */
438 #if ENABLE_HUSH_INTERACTIVE
439 /* 'interactive_fd' is a fd# open to ctty, if we have one
440 * _AND_ if we decided to act interactively */
444 #define G_interactive_fd (G.interactive_fd)
446 #define G_interactive_fd 0
448 #if ENABLE_FEATURE_EDITING
449 line_input_t *line_input_state;
455 pid_t saved_tty_pgrp;
457 struct pipe *job_list;
458 struct pipe *toplevel_list;
459 //// smallint ctrl_z_flag;
461 smallint flag_SIGINT;
462 #if ENABLE_HUSH_LOOPS
463 smallint flag_break_continue;
466 /* These four support $?, $#, and $1 */
467 smalluint last_return_code;
468 /* is global_argv and global_argv[1..n] malloced? (note: not [0]) */
469 smalluint global_args_malloced;
470 /* how many non-NULL argv's we have. NB: $# + 1 */
473 #if ENABLE_HUSH_LOOPS
474 unsigned depth_break_continue;
475 unsigned depth_of_loop;
479 struct variable *top_var; /* = &G.shell_ver (set in main()) */
480 struct variable shell_ver;
481 /* Signal and trap handling */
482 // unsigned count_SIGCHLD;
483 // unsigned handled_SIGCHLD;
484 /* which signals have non-DFL handler (even with no traps set)? */
485 unsigned non_DFL_mask;
486 char **traps; /* char *traps[NSIG] */
487 sigset_t blocked_set;
488 sigset_t inherited_set;
489 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
490 #if ENABLE_FEATURE_SH_STANDALONE
491 struct nofork_save_area nofork_save;
494 sigjmp_buf toplevel_jb;
497 #define G (*ptr_to_globals)
498 /* Not #defining name to G.name - this quickly gets unwieldy
499 * (too many defines). Also, I actually prefer to see when a variable
500 * is global, thus "G." prefix is a useful hint */
501 #define INIT_G() do { \
502 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
506 /* Function prototypes for builtins */
507 static int builtin_cd(char **argv);
508 static int builtin_echo(char **argv);
509 static int builtin_eval(char **argv);
510 static int builtin_exec(char **argv);
511 static int builtin_exit(char **argv);
512 static int builtin_export(char **argv);
514 static int builtin_fg_bg(char **argv);
515 static int builtin_jobs(char **argv);
518 static int builtin_help(char **argv);
520 static int builtin_pwd(char **argv);
521 static int builtin_read(char **argv);
522 static int builtin_test(char **argv);
523 static int builtin_trap(char **argv);
524 static int builtin_true(char **argv);
525 static int builtin_set(char **argv);
526 static int builtin_shift(char **argv);
527 static int builtin_source(char **argv);
528 static int builtin_umask(char **argv);
529 static int builtin_unset(char **argv);
530 static int builtin_wait(char **argv);
531 #if ENABLE_HUSH_LOOPS
532 static int builtin_break(char **argv);
533 static int builtin_continue(char **argv);
535 //static int builtin_not_written(char **argv);
537 /* Table of built-in functions. They can be forked or not, depending on
538 * context: within pipes, they fork. As simple commands, they do not.
539 * When used in non-forking context, they can change global variables
540 * in the parent shell process. If forked, of course they cannot.
541 * For example, 'unset foo | whatever' will parse and run, but foo will
542 * still be set at the end. */
543 struct built_in_command {
545 int (*function)(char **argv);
548 #define BLTIN(cmd, func, help) { cmd, func, help }
550 #define BLTIN(cmd, func, help) { cmd, func }
554 /* For now, echo and test are unconditionally enabled.
555 * Maybe make it configurable? */
556 static const struct built_in_command bltins[] = {
557 BLTIN("." , builtin_source, "Run commands in a file"),
558 BLTIN(":" , builtin_true, "No-op"),
559 BLTIN("[" , builtin_test, "Test condition"),
561 BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"),
563 #if ENABLE_HUSH_LOOPS
564 BLTIN("break" , builtin_break, "Exit from a loop"),
566 BLTIN("cd" , builtin_cd, "Change directory"),
567 #if ENABLE_HUSH_LOOPS
568 BLTIN("continue", builtin_continue, "Start new loop iteration"),
570 BLTIN("echo" , builtin_echo, "Write to stdout"),
571 BLTIN("eval" , builtin_eval, "Construct and run shell command"),
572 BLTIN("exec" , builtin_exec, "Execute command, don't return to shell"),
573 BLTIN("exit" , builtin_exit, "Exit"),
574 BLTIN("export", builtin_export, "Set environment variable"),
576 BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"),
577 BLTIN("jobs" , builtin_jobs, "List active jobs"),
579 BLTIN("pwd" , builtin_pwd, "Print current directory"),
580 BLTIN("read" , builtin_read, "Input environment variable"),
581 // BLTIN("return", builtin_not_written, "Return from a function"),
582 BLTIN("set" , builtin_set, "Set/unset shell local variables"),
583 BLTIN("shift" , builtin_shift, "Shift positional parameters"),
584 BLTIN("test" , builtin_test, "Test condition"),
585 BLTIN("trap" , builtin_trap, "Trap signals"),
586 // BLTIN("ulimit", builtin_not_written, "Control resource limits"),
587 BLTIN("umask" , builtin_umask, "Set file creation mask"),
588 BLTIN("unset" , builtin_unset, "Unset environment variable"),
589 BLTIN("wait" , builtin_wait, "Wait for process"),
591 BLTIN("help" , builtin_help, "List shell built-in commands"),
596 static void maybe_die(const char *notice, const char *msg)
598 /* Was using fancy stuff:
599 * (G_interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
600 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
601 void FAST_FUNC (*fp)(const char *s, ...) = bb_error_msg_and_die;
602 #if ENABLE_HUSH_INTERACTIVE
603 if (G_interactive_fd)
606 fp(msg ? "%s: %s" : notice, notice, msg);
609 #define syntax(msg) maybe_die("syntax error", msg);
611 /* Debug -- trick gcc to expand __LINE__ and convert to string */
612 #define __syntax(msg, line) maybe_die("syntax error hush.c:" # line, msg)
613 #define _syntax(msg, line) __syntax(msg, line)
614 #define syntax(msg) _syntax(msg, __LINE__)
618 static int glob_needed(const char *s)
623 if (*s == '*' || *s == '[' || *s == '?')
630 static int is_assignment(const char *s)
632 if (!s || !(isalpha(*s) || *s == '_'))
635 while (isalnum(*s) || *s == '_')
640 /* Replace each \x with x in place, return ptr past NUL. */
641 static char *unbackslash(char *src)
647 if ((*dst++ = *src++) == '\0')
653 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
674 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
675 v[count1 + count2] = NULL;
678 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
682 static char **add_string_to_strings(char **strings, char *add)
687 return add_strings_to_strings(strings, v, /*dup:*/ 0);
690 static void putenv_all(char **strings)
695 debug_printf_env("putenv '%s'\n", *strings);
700 static char **putenv_all_and_save_old(char **strings)
710 eq = strchr(*strings, '=');
713 v = getenv(*strings);
716 /* v points to VAL in VAR=VAL, go back to VAR */
717 v -= (eq - *strings) + 1;
718 old = add_string_to_strings(old, v);
727 static void free_strings_and_unsetenv(char **strings, int unset)
737 debug_printf_env("unsetenv '%s'\n", *v);
745 static void free_strings(char **strings)
747 free_strings_and_unsetenv(strings, 0);
751 /* Basic theory of signal handling in shell
752 * ========================================
753 * This does not describe what hush does, rather, it is current understanding
754 * what it _should_ do. If it doesn't, it's a bug.
755 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
757 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
758 * is finished or backgrounded. It is the same in interactive and
759 * non-interactive shells, and is the same regardless of whether
760 * a user trap handler is installed or a shell special one is in effect.
761 * ^C or ^Z from keyboard seem to execute "at once" because it usually
762 * backgrounds (i.e. stops) or kills all members of currently running
765 * Wait builtin in interruptible by signals for which user trap is set
766 * or by SIGINT in interactive shell.
768 * Trap handlers will execute even within trap handlers. (right?)
770 * User trap handlers are forgotten when subshell ("(cmd)") is entered. [TODO]
772 * If job control is off, backgrounded commands ("cmd &")
773 * have SIGINT, SIGQUIT set to SIG_IGN.
775 * Commands run in command substitution ("`cmd`")
776 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
778 * Ordinary commands have signals set to SIG_IGN/DFL set as inherited
779 * by the shell from its parent.
781 * Siganls which differ from SIG_DFL action
782 * (note: child (i.e., [v]forked) shell is not an interactive shell):
785 * SIGTERM (interactive): ignore
786 * SIGHUP (interactive):
787 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
788 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
789 * (note that ^Z is handled not by trapping SIGTSTP, but by seeing
790 * that all pipe members are stopped) (right?)
791 * SIGINT (interactive): wait for last pipe, ignore the rest
792 * of the command line, show prompt. NB: ^C does not send SIGINT
793 * to interactive shell while shell is waiting for a pipe,
794 * since shell is bg'ed (is not in foreground process group).
795 * (check/expand this)
796 * Example 1: this waits 5 sec, but does not execute ls:
797 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
798 * Example 2: this does not wait and does not execute ls:
799 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
800 * Example 3: this does not wait 5 sec, but executes ls:
801 * "sleep 5; ls -l" + press ^C
803 * (What happens to signals which are IGN on shell start?)
804 * (What happens with signal mask on shell start?)
806 * Implementation in hush
807 * ======================
808 * We use in-kernel pending signal mask to determine which signals were sent.
809 * We block all signals which we don't want to take action immediately,
810 * i.e. we block all signals which need to have special handling as described
811 * above, and all signals which have traps set.
812 * After each pipe execution, we extract any pending signals via sigtimedwait()
815 * unsigned non_DFL_mask: a mask of such "special" signals
816 * sigset_t blocked_set: current blocked signal set
819 * clear bit in blocked_set unless it is also in non_DFL_mask
820 * "trap 'cmd' SIGxxx":
821 * set bit in blocked_set (even if 'cmd' is '')
822 * after [v]fork, if we plan to be a shell:
823 * nothing for {} child shell (say, "true | { true; true; } | true")
824 * unset all traps if () shell. [TODO]
825 * after [v]fork, if we plan to exec:
826 * POSIX says pending signal mask is cleared in child - no need to clear it.
827 * Restore blocked signal set to one inherited by shell just prior to exec.
829 * Note: as a result, we do not use signal handlers much. The only uses
830 * are to count SIGCHLDs [disabled - bug somewhere, + bloat]
831 * and to restore tty pgrp on signal-induced exit.
833 * TODO: check/fix wait builtin to be interruptible.
836 //static void SIGCHLD_handler(int sig UNUSED_PARAM)
838 // G.count_SIGCHLD++;
841 /* called once at shell init */
842 static void init_signal_mask(void)
845 unsigned mask = (1 << SIGQUIT);
846 if (G_interactive_fd) {
852 | (1 << SIGTTIN) | (1 << SIGTTOU) | (1 << SIGTSTP)
857 G.non_DFL_mask = mask;
859 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
863 sigaddset(&G.blocked_set, sig);
867 sigdelset(&G.blocked_set, SIGCHLD);
868 sigprocmask(SIG_SETMASK, &G.blocked_set, &G.inherited_set);
871 static int check_and_run_traps(int sig)
873 static const struct timespec zero_timespec = { 0, 0 };
874 smalluint save_rcode;
880 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
885 if (G.traps && G.traps[sig]) {
886 if (G.traps[sig][0]) {
887 /* We have user-defined handler */
888 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
889 save_rcode = G.last_return_code;
892 G.last_return_code = save_rcode;
893 } /* else: "" trap, ignoring signal */
896 /* not a trap: special action */
899 // G.count_SIGCHLD++;
908 default: /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
917 /* Restores tty foreground process group, and exits.
918 * May be called as signal handler for fatal signal
919 * (will faithfully resend signal to itself, producing correct exit state)
920 * or called directly with -EXITCODE.
921 * We also call it if xfunc is exiting. */
922 static void sigexit(int sig) NORETURN;
923 static void sigexit(int sig)
925 /* Disable all signals: job control, SIGPIPE, etc. */
926 sigprocmask_allsigs(SIG_BLOCK);
928 /* Careful: we can end up here after [v]fork. Do not restore
929 * tty pgrp then, only top-level shell process does that */
930 if (G_interactive_fd && getpid() == G.root_pid)
931 tcsetpgrp(G_interactive_fd, G.saved_tty_pgrp);
933 /* Not a signal, just exit */
937 kill_myself_with_sig(sig); /* does not return */
941 static void maybe_set_sighandler(int sig)
943 void (*handler)(int);
944 /* non_DFL_mask'ed signals are, well, masked,
945 * no need to set handler for them.
947 if (!((G.non_DFL_mask >> sig) & 1)) {
948 handler = signal(sig, sigexit);
949 if (handler == SIG_IGN) /* oops... restore back to IGN! */
950 signal(sig, handler);
953 /* Used only to set handler to restore pgrp on exit */
954 static void set_fatal_signals_to_sigexit(void)
957 maybe_set_sighandler(SIGILL );
958 maybe_set_sighandler(SIGFPE );
959 maybe_set_sighandler(SIGBUS );
960 maybe_set_sighandler(SIGSEGV);
961 maybe_set_sighandler(SIGTRAP);
962 } /* else: hush is perfect. what SEGV? */
964 maybe_set_sighandler(SIGABRT);
966 /* bash 3.2 seems to handle these just like 'fatal' ones */
967 maybe_set_sighandler(SIGPIPE);
968 maybe_set_sighandler(SIGALRM);
969 maybe_set_sighandler(SIGHUP );
971 /* if we aren't interactive... but in this case
972 * we never want to restore pgrp on exit, and this fn is not called */
973 /*maybe_set_sighandler(SIGTERM);*/
974 /*maybe_set_sighandler(SIGINT );*/
979 #define set_fatal_signals_to_sigexit(handler) ((void)0)
983 /* Restores tty foreground process group, and exits. */
984 static void hush_exit(int exitcode) NORETURN;
985 static void hush_exit(int exitcode)
987 if (G.traps && G.traps[0] && G.traps[0][0]) {
988 char *argv[] = { NULL, xstrdup(G.traps[0]), NULL };
994 fflush(NULL); /* flush all streams */
995 sigexit(- (exitcode & 0xff));
1002 static const char *set_cwd(void)
1004 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1005 * we must not try to free(bb_msg_unknown) */
1006 if (G.cwd == bb_msg_unknown)
1008 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1010 G.cwd = bb_msg_unknown;
1015 /* Get/check local shell variables */
1016 static struct variable *get_local_var(const char *name)
1018 struct variable *cur;
1024 for (cur = G.top_var; cur; cur = cur->next) {
1025 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1031 static const char *get_local_var_value(const char *src)
1033 struct variable *var = get_local_var(src);
1035 return strchr(var->varstr, '=') + 1;
1039 /* str holds "NAME=VAL" and is expected to be malloced.
1040 * We take ownership of it.
1041 * flg_export is used by:
1044 * -1: if NAME is set, leave export status alone
1045 * if NAME is not set, do not export
1047 static int set_local_var(char *str, int flg_export)
1049 struct variable *cur;
1053 value = strchr(str, '=');
1054 if (!value) { /* not expected to ever happen? */
1059 name_len = value - str + 1; /* including '=' */
1060 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
1062 if (strncmp(cur->varstr, str, name_len) != 0) {
1064 /* Bail out. Note that now cur points
1065 * to last var in linked list */
1071 /* We found an existing var with this name */
1073 if (cur->flg_read_only) {
1074 bb_error_msg("%s: readonly variable", str);
1078 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1079 unsetenv(str); /* just in case */
1081 if (strcmp(cur->varstr, str) == 0) {
1086 if (cur->max_len >= strlen(str)) {
1087 /* This one is from startup env, reuse space */
1088 strcpy(cur->varstr, str);
1091 /* max_len == 0 signifies "malloced" var, which we can
1092 * (and has to) free */
1096 goto set_str_and_exp;
1099 /* Not found - create next variable struct */
1100 cur->next = xzalloc(sizeof(*cur));
1106 if (flg_export == 1)
1107 cur->flg_export = 1;
1108 if (cur->flg_export) {
1109 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1110 return putenv(cur->varstr);
1115 static int unset_local_var(const char *name)
1117 struct variable *cur;
1118 struct variable *prev = prev; /* for gcc */
1122 return EXIT_SUCCESS;
1123 name_len = strlen(name);
1126 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1127 if (cur->flg_read_only) {
1128 bb_error_msg("%s: readonly variable", name);
1129 return EXIT_FAILURE;
1131 /* prev is ok to use here because 1st variable, HUSH_VERSION,
1132 * is ro, and we cannot reach this code on the 1st pass */
1133 prev->next = cur->next;
1134 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1135 bb_unsetenv(cur->varstr);
1139 return EXIT_SUCCESS;
1144 return EXIT_SUCCESS;
1147 #if ENABLE_SH_MATH_SUPPORT
1148 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1149 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1150 static char *endofname(const char *name)
1158 if (!is_in_name(*p))
1164 static void arith_set_local_var(const char *name, const char *val, int flags)
1166 /* arith code doesnt malloc space, so do it for it */
1167 char *var = xasprintf("%s=%s", name, val);
1168 set_local_var(var, flags);
1176 static int static_get(struct in_str *i)
1185 static int static_peek(struct in_str *i)
1190 #if ENABLE_HUSH_INTERACTIVE
1192 static void cmdedit_set_initial_prompt(void)
1194 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1195 G.PS1 = getenv("PS1");
1202 static const char* setup_prompt_string(int promptmode)
1204 const char *prompt_str;
1205 debug_printf("setup_prompt_string %d ", promptmode);
1206 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1207 /* Set up the prompt */
1208 if (promptmode == 0) { /* PS1 */
1210 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1215 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1216 debug_printf("result '%s'\n", prompt_str);
1220 static void get_user_input(struct in_str *i)
1223 const char *prompt_str;
1225 prompt_str = setup_prompt_string(i->promptmode);
1226 #if ENABLE_FEATURE_EDITING
1227 /* Enable command line editing only while a command line
1228 * is actually being read */
1231 /* buglet: SIGINT will not make new prompt to appear _at once_,
1232 * only after <Enter>. (^C will work) */
1233 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1234 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1235 check_and_run_traps(0);
1236 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1237 i->eof_flag = (r < 0);
1238 if (i->eof_flag) { /* EOF/error detected */
1239 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1240 G.user_input_buf[1] = '\0';
1245 fputs(prompt_str, stdout);
1247 G.user_input_buf[0] = r = fgetc(i->file);
1248 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1249 //do we need check_and_run_traps(0)? (maybe only if stdin)
1250 } while (G.flag_SIGINT);
1251 i->eof_flag = (r == EOF);
1253 i->p = G.user_input_buf;
1256 #endif /* INTERACTIVE */
1258 /* This is the magic location that prints prompts
1259 * and gets data back from the user */
1260 static int file_get(struct in_str *i)
1264 /* If there is data waiting, eat it up */
1265 if (i->p && *i->p) {
1266 #if ENABLE_HUSH_INTERACTIVE
1270 if (i->eof_flag && !*i->p)
1273 /* need to double check i->file because we might be doing something
1274 * more complicated by now, like sourcing or substituting. */
1275 #if ENABLE_HUSH_INTERACTIVE
1276 if (G_interactive_fd && i->promptme && i->file == stdin) {
1279 } while (!*i->p); /* need non-empty line */
1280 i->promptmode = 1; /* PS2 */
1285 ch = fgetc(i->file);
1287 debug_printf("file_get: got a '%c' %d\n", ch, ch);
1288 #if ENABLE_HUSH_INTERACTIVE
1295 /* All the callers guarantee this routine will never be
1296 * used right after a newline, so prompting is not needed.
1298 static int file_peek(struct in_str *i)
1301 if (i->p && *i->p) {
1302 if (i->eof_flag && !i->p[1])
1306 ch = fgetc(i->file);
1307 i->eof_flag = (ch == EOF);
1308 i->peek_buf[0] = ch;
1309 i->peek_buf[1] = '\0';
1311 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
1315 static void setup_file_in_str(struct in_str *i, FILE *f)
1317 i->peek = file_peek;
1319 #if ENABLE_HUSH_INTERACTIVE
1321 i->promptmode = 0; /* PS1 */
1327 static void setup_string_in_str(struct in_str *i, const char *s)
1329 i->peek = static_peek;
1330 i->get = static_get;
1331 #if ENABLE_HUSH_INTERACTIVE
1333 i->promptmode = 0; /* PS1 */
1343 #define B_CHUNK (32 * sizeof(char*))
1345 static void o_reset(o_string *o)
1353 static void o_free(o_string *o)
1356 memset(o, 0, sizeof(*o));
1359 static void o_grow_by(o_string *o, int len)
1361 if (o->length + len > o->maxlen) {
1362 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1363 o->data = xrealloc(o->data, 1 + o->maxlen);
1367 static void o_addchr(o_string *o, int ch)
1369 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1371 o->data[o->length] = ch;
1373 o->data[o->length] = '\0';
1376 static void o_addstr(o_string *o, const char *str, int len)
1379 memcpy(&o->data[o->length], str, len);
1381 o->data[o->length] = '\0';
1384 static void o_addstrauto(o_string *o, const char *str)
1386 o_addstr(o, str, strlen(str) + 1);
1389 static void o_addstr_duplicate_backslash(o_string *o, const char *str, int len)
1394 && (*str != '*' && *str != '?' && *str != '[')
1402 /* My analysis of quoting semantics tells me that state information
1403 * is associated with a destination, not a source.
1405 static void o_addqchr(o_string *o, int ch)
1408 char *found = strchr("*?[\\", ch);
1413 o->data[o->length] = '\\';
1416 o->data[o->length] = ch;
1418 o->data[o->length] = '\0';
1421 static void o_addQchr(o_string *o, int ch)
1424 if (o->o_escape && strchr("*?[\\", ch)) {
1426 o->data[o->length] = '\\';
1430 o->data[o->length] = ch;
1432 o->data[o->length] = '\0';
1435 static void o_addQstr(o_string *o, const char *str, int len)
1438 o_addstr(o, str, len);
1444 int ordinary_cnt = strcspn(str, "*?[\\");
1445 if (ordinary_cnt > len) /* paranoia */
1447 o_addstr(o, str, ordinary_cnt);
1448 if (ordinary_cnt == len)
1450 str += ordinary_cnt;
1451 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
1455 if (ch) { /* it is necessarily one of "*?[\\" */
1457 o->data[o->length] = '\\';
1461 o->data[o->length] = ch;
1463 o->data[o->length] = '\0';
1467 /* A special kind of o_string for $VAR and `cmd` expansion.
1468 * It contains char* list[] at the beginning, which is grown in 16 element
1469 * increments. Actual string data starts at the next multiple of 16 * (char*).
1470 * list[i] contains an INDEX (int!) into this string data.
1471 * It means that if list[] needs to grow, data needs to be moved higher up
1472 * but list[i]'s need not be modified.
1473 * NB: remembering how many list[i]'s you have there is crucial.
1474 * o_finalize_list() operation post-processes this structure - calculates
1475 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1477 #if DEBUG_EXPAND || DEBUG_GLOB
1478 static void debug_print_list(const char *prefix, o_string *o, int n)
1480 char **list = (char**)o->data;
1481 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1483 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1484 prefix, list, n, string_start, o->length, o->maxlen);
1486 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1487 o->data + (int)list[i] + string_start,
1488 o->data + (int)list[i] + string_start);
1492 const char *p = o->data + (int)list[n - 1] + string_start;
1493 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
1497 #define debug_print_list(prefix, o, n) ((void)0)
1500 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1501 * in list[n] so that it points past last stored byte so far.
1502 * It returns n+1. */
1503 static int o_save_ptr_helper(o_string *o, int n)
1505 char **list = (char**)o->data;
1509 if (!o->has_empty_slot) {
1510 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1511 string_len = o->length - string_start;
1512 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1513 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
1514 /* list[n] points to string_start, make space for 16 more pointers */
1515 o->maxlen += 0x10 * sizeof(list[0]);
1516 o->data = xrealloc(o->data, o->maxlen + 1);
1517 list = (char**)o->data;
1518 memmove(list + n + 0x10, list + n, string_len);
1519 o->length += 0x10 * sizeof(list[0]);
1521 debug_printf_list("list[%d]=%d string_start=%d\n",
1522 n, string_len, string_start);
1525 /* We have empty slot at list[n], reuse without growth */
1526 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1527 string_len = o->length - string_start;
1528 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1529 n, string_len, string_start);
1530 o->has_empty_slot = 0;
1532 list[n] = (char*)(ptrdiff_t)string_len;
1536 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
1537 static int o_get_last_ptr(o_string *o, int n)
1539 char **list = (char**)o->data;
1540 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1542 return ((int)(ptrdiff_t)list[n-1]) + string_start;
1545 /* o_glob performs globbing on last list[], saving each result
1546 * as a new list[]. */
1547 static int o_glob(o_string *o, int n)
1553 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
1555 return o_save_ptr_helper(o, n);
1556 pattern = o->data + o_get_last_ptr(o, n);
1557 debug_printf_glob("glob pattern '%s'\n", pattern);
1558 if (!glob_needed(pattern)) {
1560 o->length = unbackslash(pattern) - o->data;
1561 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
1562 return o_save_ptr_helper(o, n);
1565 memset(&globdata, 0, sizeof(globdata));
1566 gr = glob(pattern, 0, NULL, &globdata);
1567 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1568 if (gr == GLOB_NOSPACE)
1569 bb_error_msg_and_die("out of memory during glob");
1570 if (gr == GLOB_NOMATCH) {
1571 globfree(&globdata);
1574 if (gr != 0) { /* GLOB_ABORTED ? */
1575 //TODO: testcase for bad glob pattern behavior
1576 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1578 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1579 char **argv = globdata.gl_pathv;
1580 o->length = pattern - o->data; /* "forget" pattern */
1582 o_addstrauto(o, *argv);
1583 n = o_save_ptr_helper(o, n);
1589 globfree(&globdata);
1591 debug_print_list("o_glob returning", o, n);
1595 /* If o->o_glob == 1, glob the string so far remembered.
1596 * Otherwise, just finish current list[] and start new */
1597 static int o_save_ptr(o_string *o, int n)
1599 if (o->o_glob) { /* if globbing is requested */
1600 /* If o->has_empty_slot, list[n] was already globbed
1601 * (if it was requested back then when it was filled)
1602 * so don't do that again! */
1603 if (!o->has_empty_slot)
1604 return o_glob(o, n); /* o_save_ptr_helper is inside */
1606 return o_save_ptr_helper(o, n);
1609 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
1610 static char **o_finalize_list(o_string *o, int n)
1615 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1617 debug_print_list("finalized", o, n);
1618 debug_printf_expand("finalized n:%d\n", n);
1619 list = (char**)o->data;
1620 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1624 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
1630 /* Expansion can recurse */
1631 #if ENABLE_HUSH_TICK
1632 static int process_command_subs(o_string *dest, const char *s);
1634 static char *expand_string_to_string(const char *str);
1635 static int parse_stream_dquoted(o_string *dest, struct in_str *input, int dquote_end);
1637 /* expand_strvec_to_strvec() takes a list of strings, expands
1638 * all variable references within and returns a pointer to
1639 * a list of expanded strings, possibly with larger number
1640 * of strings. (Think VAR="a b"; echo $VAR).
1641 * This new list is allocated as a single malloc block.
1642 * NULL-terminated list of char* pointers is at the beginning of it,
1643 * followed by strings themself.
1644 * Caller can deallocate entire list by single free(list). */
1646 /* Store given string, finalizing the word and starting new one whenever
1647 * we encounter IFS char(s). This is used for expanding variable values.
1648 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
1649 static int expand_on_ifs(o_string *output, int n, const char *str)
1652 int word_len = strcspn(str, G.ifs);
1654 if (output->o_escape || !output->o_glob)
1655 o_addQstr(output, str, word_len);
1656 else /* protect backslashes against globbing up :) */
1657 o_addstr_duplicate_backslash(output, str, word_len);
1660 if (!*str) /* EOL - do not finalize word */
1662 o_addchr(output, '\0');
1663 debug_print_list("expand_on_ifs", output, n);
1664 n = o_save_ptr(output, n);
1665 str += strspn(str, G.ifs); /* skip ifs chars */
1667 debug_print_list("expand_on_ifs[1]", output, n);
1671 /* Expand all variable references in given string, adding words to list[]
1672 * at n, n+1,... positions. Return updated n (so that list[n] is next one
1673 * to be filled). This routine is extremely tricky: has to deal with
1674 * variables/parameters with whitespace, $* and $@, and constructs like
1675 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
1676 static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
1678 /* or_mask is either 0 (normal case) or 0x80
1679 * (expansion of right-hand side of assignment == 1-element expand.
1680 * It will also do no globbing, and thus we must not backslash-quote!) */
1682 char first_ch, ored_ch;
1689 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
1690 debug_print_list("expand_vars_to_list", output, n);
1691 n = o_save_ptr(output, n);
1692 debug_print_list("expand_vars_to_list[0]", output, n);
1694 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
1695 #if ENABLE_HUSH_TICK
1696 o_string subst_result = NULL_O_STRING;
1698 #if ENABLE_SH_MATH_SUPPORT
1699 char arith_buf[sizeof(arith_t)*3 + 2];
1701 o_addstr(output, arg, p - arg);
1702 debug_print_list("expand_vars_to_list[1]", output, n);
1704 p = strchr(p, SPECIAL_VAR_SYMBOL);
1706 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
1707 /* "$@" is special. Even if quoted, it can still
1708 * expand to nothing (not even an empty string) */
1709 if ((first_ch & 0x7f) != '@')
1710 ored_ch |= first_ch;
1713 switch (first_ch & 0x7f) {
1714 /* Highest bit in first_ch indicates that var is double-quoted */
1716 val = utoa(G.root_pid);
1718 case '!': /* bg pid */
1719 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
1721 case '?': /* exitcode */
1722 val = utoa(G.last_return_code);
1724 case '#': /* argc */
1725 if (arg[1] != SPECIAL_VAR_SYMBOL)
1726 /* actually, it's a ${#var} */
1728 val = utoa(G.global_argc ? G.global_argc-1 : 0);
1733 if (!G.global_argv[i])
1735 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
1736 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
1737 smallint sv = output->o_escape;
1738 /* unquoted var's contents should be globbed, so don't escape */
1739 output->o_escape = 0;
1740 while (G.global_argv[i]) {
1741 n = expand_on_ifs(output, n, G.global_argv[i]);
1742 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
1743 if (G.global_argv[i++][0] && G.global_argv[i]) {
1744 /* this argv[] is not empty and not last:
1745 * put terminating NUL, start new word */
1746 o_addchr(output, '\0');
1747 debug_print_list("expand_vars_to_list[2]", output, n);
1748 n = o_save_ptr(output, n);
1749 debug_print_list("expand_vars_to_list[3]", output, n);
1752 output->o_escape = sv;
1754 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
1755 * and in this case should treat it like '$*' - see 'else...' below */
1756 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
1758 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1759 if (++i >= G.global_argc)
1761 o_addchr(output, '\0');
1762 debug_print_list("expand_vars_to_list[4]", output, n);
1763 n = o_save_ptr(output, n);
1765 } else { /* quoted $*: add as one word */
1767 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1768 if (!G.global_argv[++i])
1771 o_addchr(output, G.ifs[0]);
1775 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
1776 /* "Empty variable", used to make "" etc to not disappear */
1780 #if ENABLE_HUSH_TICK
1781 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
1784 //TODO: can we just stuff it into "output" directly?
1785 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
1786 process_command_subs(&subst_result, arg);
1787 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
1788 val = subst_result.data;
1791 #if ENABLE_SH_MATH_SUPPORT
1792 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
1793 arith_eval_hooks_t hooks;
1798 arg++; /* skip '+' */
1799 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
1800 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
1802 /* Optional: skip expansion if expr is simple ("a + 3", "i++" etc) */
1805 unsigned char c = *exp_str++;
1812 if (strchr(" \t+-*/%_", c) != NULL)
1814 c |= 0x20; /* tolower */
1815 if (c >= 'a' && c <= 'z')
1819 /* We need to expand. Example: "echo $(($a + 1)) $((1 + $((2)) ))" */
1821 struct in_str input;
1822 o_string dest = NULL_O_STRING;
1824 setup_string_in_str(&input, arg);
1825 parse_stream_dquoted(&dest, &input, EOF);
1826 //bb_error_msg("'%s' -> '%s'", arg, dest.data);
1827 exp_str = expand_string_to_string(dest.data);
1828 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
1832 hooks.lookupvar = get_local_var_value;
1833 hooks.setvar = arith_set_local_var;
1834 hooks.endofname = endofname;
1835 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
1840 case -3: maybe_die("arith", "exponent less than 0"); break;
1841 case -2: maybe_die("arith", "divide by zero"); break;
1842 case -5: maybe_die("arith", "expression recursion loop detected"); break;
1843 default: maybe_die("arith", "syntax error"); break;
1846 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
1847 sprintf(arith_buf, arith_t_fmt, res);
1852 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
1854 bool exp_len = false, exp_null = false;
1855 char *var = arg, exp_save, exp_op, *exp_word;
1858 arg[0] = first_ch & 0x7f;
1860 /* prepare for expansions */
1861 if (var[0] == '#') {
1862 /* handle length expansion ${#var} */
1866 /* maybe handle parameter expansion */
1867 exp_off = strcspn(var, ":-=+?");
1871 exp_save = var[exp_off];
1872 exp_null = exp_save == ':';
1873 exp_word = var + exp_off;
1874 if (exp_null) ++exp_word;
1875 exp_op = *exp_word++;
1876 var[exp_off] = '\0';
1880 /* lookup the variable in question */
1881 if (isdigit(var[0])) {
1882 /* handle_dollar() should have vetted var for us */
1884 if (i < G.global_argc)
1885 val = G.global_argv[i];
1886 /* else val remains NULL: $N with too big N */
1888 val = get_local_var_value(var);
1890 /* handle any expansions */
1892 debug_printf_expand("expand: length of '%s' = ", val);
1893 val = utoa(val ? strlen(val) : 0);
1894 debug_printf_expand("%s\n", val);
1895 } else if (exp_off) {
1896 /* we need to do an expansion */
1897 int exp_test = (!val || (exp_null && !val[0]));
1899 exp_test = !exp_test;
1900 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
1901 exp_null ? "true" : "false", exp_test);
1904 maybe_die(var, *exp_word ? exp_word : "parameter null or not set");
1908 if (exp_op == '=') {
1909 if (isdigit(var[0]) || var[0] == '#') {
1910 maybe_die(var, "special vars cannot assign in this way");
1913 char *new_var = xmalloc(strlen(var) + strlen(val) + 2);
1914 sprintf(new_var, "%s=%s", var, val);
1915 set_local_var(new_var, -1);
1919 var[exp_off] = exp_save;
1923 #if ENABLE_HUSH_TICK
1926 if (!(first_ch & 0x80)) { /* unquoted $VAR */
1927 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
1929 /* unquoted var's contents should be globbed, so don't escape */
1930 smallint sv = output->o_escape;
1931 output->o_escape = 0;
1932 n = expand_on_ifs(output, n, val);
1934 output->o_escape = sv;
1936 } else { /* quoted $VAR, val will be appended below */
1937 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
1940 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
1942 o_addQstr(output, val, strlen(val));
1944 /* Do the check to avoid writing to a const string */
1945 if (*p != SPECIAL_VAR_SYMBOL)
1946 *p = SPECIAL_VAR_SYMBOL;
1948 #if ENABLE_HUSH_TICK
1949 o_free(&subst_result);
1952 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
1955 debug_print_list("expand_vars_to_list[a]", output, n);
1956 /* this part is literal, and it was already pre-quoted
1957 * if needed (much earlier), do not use o_addQstr here! */
1958 o_addstrauto(output, arg);
1959 debug_print_list("expand_vars_to_list[b]", output, n);
1960 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
1961 && !(ored_ch & 0x80) /* and all vars were not quoted. */
1964 /* allow to reuse list[n] later without re-growth */
1965 output->has_empty_slot = 1;
1967 o_addchr(output, '\0');
1972 static char **expand_variables(char **argv, int or_mask)
1977 o_string output = NULL_O_STRING;
1979 if (or_mask & 0x100) {
1980 output.o_escape = 1; /* protect against globbing for "$var" */
1981 /* (unquoted $var will temporarily switch it off) */
1988 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
1991 debug_print_list("expand_variables", &output, n);
1993 /* output.data (malloced in one block) gets returned in "list" */
1994 list = o_finalize_list(&output, n);
1995 debug_print_strings("expand_variables[1]", list);
1999 static char **expand_strvec_to_strvec(char **argv)
2001 return expand_variables(argv, 0x100);
2004 /* Used for expansion of right hand of assignments */
2005 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2007 static char *expand_string_to_string(const char *str)
2009 char *argv[2], **list;
2011 argv[0] = (char*)str;
2013 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2015 if (!list[0] || list[1])
2016 bb_error_msg_and_die("BUG in varexp2");
2017 /* actually, just move string 2*sizeof(char*) bytes back */
2018 overlapping_strcpy((char*)list, list[0]);
2019 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2023 /* Used for "eval" builtin */
2024 static char* expand_strvec_to_string(char **argv)
2028 list = expand_variables(argv, 0x80);
2029 /* Convert all NULs to spaces */
2034 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2035 bb_error_msg_and_die("BUG in varexp3");
2036 list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
2040 overlapping_strcpy((char*)list, list[0]);
2041 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2045 static char **expand_assignments(char **argv, int count)
2049 /* Expand assignments into one string each */
2050 for (i = 0; i < count; i++) {
2051 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2057 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
2058 * and stderr if they are redirected. */
2059 static int setup_redirects(struct command *prog, int squirrel[])
2062 struct redir_struct *redir;
2064 for (redir = prog->redirects; redir; redir = redir->next) {
2065 if (redir->dup == -1 && redir->rd_filename == NULL) {
2066 /* something went wrong in the parse. Pretend it didn't happen */
2069 if (redir->dup == -1) {
2071 mode = redir_table[redir->rd_type].mode;
2072 //TODO: check redir for names like '\\'
2073 p = expand_string_to_string(redir->rd_filename);
2074 openfd = open_or_warn(p, mode);
2077 /* this could get lost if stderr has been redirected, but
2078 bash and ash both lose it as well (though zsh doesn't!) */
2082 openfd = redir->dup;
2085 if (openfd != redir->fd) {
2086 if (squirrel && redir->fd < 3) {
2087 squirrel[redir->fd] = dup(redir->fd);
2090 //close(openfd); // close(-3) ??!
2092 dup2(openfd, redir->fd);
2093 if (redir->dup == -1)
2101 static void restore_redirects(int squirrel[])
2104 for (i = 0; i < 3; i++) {
2107 /* We simply die on error */
2114 #if !defined(DEBUG_CLEAN)
2115 #define free_pipe_list(head, indent) free_pipe_list(head)
2116 #define free_pipe(pi, indent) free_pipe(pi)
2118 static void free_pipe_list(struct pipe *head, int indent);
2120 /* return code is the exit status of the pipe */
2121 static void free_pipe(struct pipe *pi, int indent)
2124 struct command *command;
2125 struct redir_struct *r, *rnext;
2128 if (pi->stopped_cmds > 0)
2130 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2131 for (i = 0; i < pi->num_cmds; i++) {
2132 command = &pi->cmds[i];
2133 debug_printf_clean("%s command %d:\n", indenter(indent), i);
2134 if (command->argv) {
2135 for (a = 0, p = command->argv; *p; a++, p++) {
2136 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
2138 free_strings(command->argv);
2139 command->argv = NULL;
2141 /* not "else if": on syntax error, we may have both! */
2142 if (command->group) {
2143 debug_printf_clean("%s begin group (grp_type:%d)\n", indenter(indent), command->grp_type);
2144 free_pipe_list(command->group, indent+3);
2145 debug_printf_clean("%s end group\n", indenter(indent));
2146 command->group = NULL;
2148 for (r = command->redirects; r; r = rnext) {
2149 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->rd_type].descrip);
2151 /* guard against the case >$FOO, where foo is unset or blank */
2152 if (r->rd_filename) {
2153 debug_printf_clean(" %s\n", r->rd_filename);
2154 free(r->rd_filename);
2155 r->rd_filename = NULL;
2158 debug_printf_clean("&%d\n", r->dup);
2163 command->redirects = NULL;
2165 free(pi->cmds); /* children are an array, they get freed all at once */
2173 static void free_pipe_list(struct pipe *head, int indent)
2175 struct pipe *pi, *next;
2177 for (pi = head; pi; pi = next) {
2179 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
2181 free_pipe(pi, indent);
2182 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
2184 /*pi->next = NULL;*/
2191 typedef struct nommu_save_t {
2197 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
2198 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
2199 #define pseudo_exec(nommu_save, command, argv_expanded) \
2200 pseudo_exec(command, argv_expanded)
2203 /* Called after [v]fork() in run_pipe(), or from builtin_exec().
2205 * XXX no exit() here. If you don't exec, use _exit instead.
2206 * The at_exit handlers apparently confuse the calling process,
2207 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
2208 static void pseudo_exec_argv(nommu_save_t *nommu_save,
2209 char **argv, int assignment_cnt,
2210 char **argv_expanded) NORETURN;
2211 static void pseudo_exec_argv(nommu_save_t *nommu_save,
2212 char **argv, int assignment_cnt,
2213 char **argv_expanded)
2217 const struct built_in_command *x;
2219 /* If a variable is assigned in a forest, and nobody listens,
2220 * was it ever really set?
2222 if (!argv[assignment_cnt])
2223 _exit(EXIT_SUCCESS);
2225 new_env = expand_assignments(argv, assignment_cnt);
2227 putenv_all(new_env);
2228 free(new_env); /* optional */
2230 nommu_save->new_env = new_env;
2231 nommu_save->old_env = putenv_all_and_save_old(new_env);
2233 if (argv_expanded) {
2234 argv = argv_expanded;
2236 argv = expand_strvec_to_strvec(argv + assignment_cnt);
2238 nommu_save->argv = argv;
2243 * Check if the command matches any of the builtins.
2244 * Depending on context, this might be redundant. But it's
2245 * easier to waste a few CPU cycles than it is to figure out
2246 * if this is one of those cases.
2248 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2249 if (strcmp(argv[0], x->cmd) == 0) {
2250 debug_printf_exec("running builtin '%s'\n", argv[0]);
2251 rcode = x->function(argv);
2257 /* Check if the command matches any busybox applets */
2258 #if ENABLE_FEATURE_SH_STANDALONE
2259 if (strchr(argv[0], '/') == NULL) {
2260 int a = find_applet_by_name(argv[0]);
2262 if (APPLET_IS_NOEXEC(a)) {
2263 debug_printf_exec("running applet '%s'\n", argv[0]);
2264 // is it ok that run_applet_no_and_exit() does exit(), not _exit()?
2265 run_applet_no_and_exit(a, argv);
2267 /* re-exec ourselves with the new arguments */
2268 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
2269 execvp(bb_busybox_exec_path, argv);
2270 /* If they called chroot or otherwise made the binary no longer
2271 * executable, fall through */
2276 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2278 debug_printf_exec("execing '%s'\n", argv[0]);
2279 execvp(argv[0], argv);
2280 bb_perror_msg("can't exec '%s'", argv[0]);
2281 _exit(EXIT_FAILURE);
2284 static int run_list(struct pipe *pi);
2286 /* Called after [v]fork() in run_pipe()
2288 static void pseudo_exec(nommu_save_t *nommu_save,
2289 struct command *command,
2290 char **argv_expanded) NORETURN;
2291 static void pseudo_exec(nommu_save_t *nommu_save,
2292 struct command *command,
2293 char **argv_expanded)
2295 if (command->argv) {
2296 pseudo_exec_argv(nommu_save, command->argv,
2297 command->assignment_cnt, argv_expanded);
2300 if (command->group) {
2301 /* Cases when we are here:
2304 * ... | ( list ) | ...
2305 * ... | { list } | ...
2309 debug_printf_exec("pseudo_exec: run_list\n");
2310 rcode = run_list(command->group);
2311 /* OK to leak memory by not calling free_pipe_list,
2312 * since this process is about to exit */
2315 //TODO: re-exec "hush -c command->group_as_a_string"
2316 bb_error_msg_and_die("nested lists are not supported on NOMMU");
2320 /* Can happen. See what bash does with ">foo" by itself. */
2321 debug_printf("pseudo_exec'ed null command\n");
2322 _exit(EXIT_SUCCESS);
2326 static const char *get_cmdtext(struct pipe *pi)
2332 /* This is subtle. ->cmdtext is created only on first backgrounding.
2333 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
2334 * On subsequent bg argv is trashed, but we won't use it */
2337 argv = pi->cmds[0].argv;
2338 if (!argv || !argv[0]) {
2339 pi->cmdtext = xzalloc(1);
2344 do len += strlen(*argv) + 1; while (*++argv);
2345 pi->cmdtext = p = xmalloc(len);
2346 argv = pi->cmds[0].argv;
2348 len = strlen(*argv);
2349 memcpy(p, *argv, len);
2357 static void insert_bg_job(struct pipe *pi)
2359 struct pipe *thejob;
2362 /* Linear search for the ID of the job to use */
2364 for (thejob = G.job_list; thejob; thejob = thejob->next)
2365 if (thejob->jobid >= pi->jobid)
2366 pi->jobid = thejob->jobid + 1;
2368 /* Add thejob to the list of running jobs */
2370 thejob = G.job_list = xmalloc(sizeof(*thejob));
2372 for (thejob = G.job_list; thejob->next; thejob = thejob->next)
2374 thejob->next = xmalloc(sizeof(*thejob));
2375 thejob = thejob->next;
2378 /* Physically copy the struct job */
2379 memcpy(thejob, pi, sizeof(struct pipe));
2380 thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
2381 /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
2382 for (i = 0; i < pi->num_cmds; i++) {
2383 // TODO: do we really need to have so many fields which are just dead weight
2384 // at execution stage?
2385 thejob->cmds[i].pid = pi->cmds[i].pid;
2386 /* all other fields are not used and stay zero */
2388 thejob->next = NULL;
2389 thejob->cmdtext = xstrdup(get_cmdtext(pi));
2391 /* We don't wait for background thejobs to return -- append it
2392 to the list of backgrounded thejobs and leave it alone */
2393 if (G_interactive_fd)
2394 printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
2395 G.last_bg_pid = thejob->cmds[0].pid;
2396 G.last_jobid = thejob->jobid;
2399 static void remove_bg_job(struct pipe *pi)
2401 struct pipe *prev_pipe;
2403 if (pi == G.job_list) {
2404 G.job_list = pi->next;
2406 prev_pipe = G.job_list;
2407 while (prev_pipe->next != pi)
2408 prev_pipe = prev_pipe->next;
2409 prev_pipe->next = pi->next;
2412 G.last_jobid = G.job_list->jobid;
2417 /* Remove a backgrounded job */
2418 static void delete_finished_bg_job(struct pipe *pi)
2421 pi->stopped_cmds = 0;
2427 /* Check to see if any processes have exited -- if they
2428 * have, figure out why and see if a job has completed */
2429 static int checkjobs(struct pipe* fg_pipe)
2439 debug_printf_jobs("checkjobs %p\n", fg_pipe);
2442 // if (G.handled_SIGCHLD == G.count_SIGCHLD)
2443 // /* avoid doing syscall, nothing there anyway */
2446 attributes = WUNTRACED;
2447 if (fg_pipe == NULL)
2448 attributes |= WNOHANG;
2450 /* Do we do this right?
2451 * bash-3.00# sleep 20 | false
2453 * [3]+ Stopped sleep 20 | false
2454 * bash-3.00# echo $?
2455 * 1 <========== bg pipe is not fully done, but exitcode is already known!
2458 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
2459 //are stopped. Testcase: "cat | cat" in a script (not on command line)
2460 // + killall -STOP cat
2467 // i = G.count_SIGCHLD;
2468 childpid = waitpid(-1, &status, attributes);
2469 if (childpid <= 0) {
2470 if (childpid && errno != ECHILD)
2471 bb_perror_msg("waitpid");
2472 // else /* Until next SIGCHLD, waitpid's are useless */
2473 // G.handled_SIGCHLD = i;
2476 dead = WIFEXITED(status) || WIFSIGNALED(status);
2479 if (WIFSTOPPED(status))
2480 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
2481 childpid, WSTOPSIG(status), WEXITSTATUS(status));
2482 if (WIFSIGNALED(status))
2483 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
2484 childpid, WTERMSIG(status), WEXITSTATUS(status));
2485 if (WIFEXITED(status))
2486 debug_printf_jobs("pid %d exited, exitcode %d\n",
2487 childpid, WEXITSTATUS(status));
2489 /* Were we asked to wait for fg pipe? */
2491 for (i = 0; i < fg_pipe->num_cmds; i++) {
2492 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
2493 if (fg_pipe->cmds[i].pid != childpid)
2495 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
2497 fg_pipe->cmds[i].pid = 0;
2498 fg_pipe->alive_cmds--;
2499 if (i == fg_pipe->num_cmds - 1) {
2500 /* last process gives overall exitstatus */
2501 rcode = WEXITSTATUS(status);
2502 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
2505 fg_pipe->cmds[i].is_stopped = 1;
2506 fg_pipe->stopped_cmds++;
2508 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
2509 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
2510 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
2511 /* All processes in fg pipe have exited/stopped */
2513 if (fg_pipe->alive_cmds)
2514 insert_bg_job(fg_pipe);
2518 /* There are still running processes in the fg pipe */
2519 goto wait_more; /* do waitpid again */
2521 /* it wasnt fg_pipe, look for process in bg pipes */
2525 /* We asked to wait for bg or orphaned children */
2526 /* No need to remember exitcode in this case */
2527 for (pi = G.job_list; pi; pi = pi->next) {
2528 for (i = 0; i < pi->num_cmds; i++) {
2529 if (pi->cmds[i].pid == childpid)
2530 goto found_pi_and_prognum;
2533 /* Happens when shell is used as init process (init=/bin/sh) */
2534 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
2535 continue; /* do waitpid again */
2537 found_pi_and_prognum:
2540 pi->cmds[i].pid = 0;
2542 if (!pi->alive_cmds) {
2543 if (G_interactive_fd)
2544 printf(JOB_STATUS_FORMAT, pi->jobid,
2545 "Done", pi->cmdtext);
2546 delete_finished_bg_job(pi);
2550 pi->cmds[i].is_stopped = 1;
2554 } /* while (waitpid succeeds)... */
2560 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
2563 int rcode = checkjobs(fg_pipe);
2564 /* Job finished, move the shell to the foreground */
2565 p = getpgid(0); /* pgid of our process */
2566 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
2567 tcsetpgrp(G_interactive_fd, p);
2572 /* run_pipe() starts all the jobs, but doesn't wait for anything
2573 * to finish. See checkjobs().
2575 * Return code is normally -1, when the caller has to wait for children
2576 * to finish to determine the exit status of the pipe. If the pipe
2577 * is a simple builtin command, however, the action is done by the
2578 * time run_pipe returns, and the exit code is provided as the
2581 * Returns -1 only if started some children. IOW: we have to
2582 * mask out retvals of builtins etc with 0xff!
2584 * The only case when we do not need to [v]fork is when the pipe
2585 * is single, non-backgrounded, non-subshell command. Examples:
2586 * cmd ; ... { list } ; ...
2587 * cmd && ... { list } && ...
2588 * cmd || ... { list } || ...
2589 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
2590 * or (if SH_STANDALONE) an applet, and we can run the { list }
2591 * with run_list(). Otherwise, we fork and exec cmd.
2593 * Cases when we must fork:
2594 * non-single: cmd | cmd
2595 * backgrounded: cmd & { list } &
2596 * subshell: ( list ) [&]
2598 static int run_pipe(struct pipe *pi)
2600 static const char *const null_ptr = NULL;
2603 int pipefds[2]; /* pipefds[0] is for reading */
2604 struct command *command;
2605 char **argv_expanded;
2608 /* it is not always needed, but we aim to smaller code */
2609 int squirrel[] = { -1, -1, -1 };
2612 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
2614 USE_HUSH_JOB(pi->pgrp = -1;)
2615 pi->stopped_cmds = 0;
2616 command = &(pi->cmds[0]);
2617 argv_expanded = NULL;
2619 if (pi->num_cmds != 1
2620 || pi->followup == PIPE_BG
2621 || command->grp_type == GRP_SUBSHELL
2628 debug_printf_exec(": group:%p argv:'%s'\n",
2629 command->group, command->argv ? command->argv[0] : "NONE");
2631 if (command->group) {
2632 #if ENABLE_HUSH_FUNCTIONS
2633 if (command->grp_type == GRP_FUNCTION) {
2634 /* func () { list } */
2635 bb_error_msg("here we ought to remember function definition, and go on");
2636 return EXIT_SUCCESS;
2640 debug_printf("non-subshell group\n");
2641 setup_redirects(command, squirrel);
2642 debug_printf_exec(": run_list\n");
2643 rcode = run_list(command->group) & 0xff;
2644 restore_redirects(squirrel);
2645 debug_printf_exec("run_pipe return %d\n", rcode);
2646 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2650 argv = command->argv ? command->argv : (char **) &null_ptr;
2652 const struct built_in_command *x;
2653 char **new_env = NULL;
2654 char **old_env = NULL;
2656 if (argv[command->assignment_cnt] == NULL) {
2657 /* Assignments, but no command */
2658 /* Ensure redirects take effect. Try "a=t >file" */
2659 setup_redirects(command, squirrel);
2660 restore_redirects(squirrel);
2661 /* Set shell variables */
2663 p = expand_string_to_string(*argv);
2664 debug_printf_exec("set shell var:'%s'->'%s'\n",
2666 set_local_var(p, 0);
2669 /* Do we need to flag set_local_var() errors?
2670 * "assignment to readonly var" and "putenv error"
2672 return EXIT_SUCCESS;
2675 /* Expand the rest into (possibly) many strings each */
2676 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
2678 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2679 if (strcmp(argv_expanded[0], x->cmd) != 0)
2681 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
2682 debug_printf("exec with redirects only\n");
2683 setup_redirects(command, NULL);
2684 rcode = EXIT_SUCCESS;
2685 goto clean_up_and_ret1;
2687 debug_printf("builtin inline %s\n", argv_expanded[0]);
2688 /* XXX setup_redirects acts on file descriptors, not FILEs.
2689 * This is perfect for work that comes after exec().
2690 * Is it really safe for inline use? Experimentally,
2691 * things seem to work with glibc. */
2692 setup_redirects(command, squirrel);
2693 new_env = expand_assignments(argv, command->assignment_cnt);
2694 old_env = putenv_all_and_save_old(new_env);
2695 debug_printf_exec(": builtin '%s' '%s'...\n",
2696 x->cmd, argv_expanded[1]);
2697 rcode = x->function(argv_expanded) & 0xff;
2698 #if ENABLE_FEATURE_SH_STANDALONE
2701 restore_redirects(squirrel);
2702 free_strings_and_unsetenv(new_env, 1);
2703 putenv_all(old_env);
2704 free(old_env); /* not free_strings()! */
2706 free(argv_expanded);
2707 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2708 debug_printf_exec("run_pipe return %d\n", rcode);
2711 #if ENABLE_FEATURE_SH_STANDALONE
2712 i = find_applet_by_name(argv_expanded[0]);
2713 if (i >= 0 && APPLET_IS_NOFORK(i)) {
2714 setup_redirects(command, squirrel);
2715 save_nofork_data(&G.nofork_save);
2716 new_env = expand_assignments(argv, command->assignment_cnt);
2717 old_env = putenv_all_and_save_old(new_env);
2718 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
2719 argv_expanded[0], argv_expanded[1]);
2720 rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
2721 goto clean_up_and_ret;
2724 /* It is neither builtin nor applet. We must fork. */
2728 /* NB: argv_expanded may already be created, and that
2729 * might include `cmd` runs! Do not rerun it! We *must*
2730 * use argv_expanded if it's non-NULL */
2732 /* Going to fork a child per each pipe member */
2736 for (i = 0; i < pi->num_cmds; i++) {
2738 volatile nommu_save_t nommu_save;
2739 nommu_save.new_env = NULL;
2740 nommu_save.old_env = NULL;
2741 nommu_save.argv = NULL;
2743 command = &(pi->cmds[i]);
2744 if (command->argv) {
2745 debug_printf_exec(": pipe member '%s' '%s'...\n",
2746 command->argv[0], command->argv[1]);
2748 debug_printf_exec(": pipe member with no argv\n");
2751 /* pipes are inserted between pairs of commands */
2754 if ((i + 1) < pi->num_cmds)
2757 command->pid = BB_MMU ? fork() : vfork();
2758 if (!command->pid) { /* child */
2760 die_sleep = 0; /* let nofork's xfuncs die */
2762 /* Every child adds itself to new process group
2763 * with pgid == pid_of_first_child_in_pipe */
2764 if (G.run_list_level == 1 && G_interactive_fd) {
2767 if (pgrp < 0) /* true for 1st process only */
2769 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
2770 /* We do it in *every* child, not just first,
2772 tcsetpgrp(G_interactive_fd, pgrp);
2776 xmove_fd(nextin, 0);
2777 xmove_fd(pipefds[1], 1); /* write end */
2779 close(pipefds[0]); /* read end */
2780 /* Like bash, explicit redirects override pipes,
2781 * and the pipe fd is available for dup'ing. */
2782 setup_redirects(command, NULL);
2784 /* Restore default handlers just prior to exec */
2785 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
2787 /* Stores to nommu_save list of env vars putenv'ed
2788 * (NOMMU, on MMU we don't need that) */
2789 /* cast away volatility... */
2790 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
2791 /* pseudo_exec() does not return */
2795 /* Clean up after vforked child */
2796 free(nommu_save.argv);
2797 free_strings_and_unsetenv(nommu_save.new_env, 1);
2798 putenv_all(nommu_save.old_env);
2800 free(argv_expanded);
2801 argv_expanded = NULL;
2802 if (command->pid < 0) { /* [v]fork failed */
2803 /* Clearly indicate, was it fork or vfork */
2804 bb_perror_msg(BB_MMU ? "fork" : "vfork");
2808 /* Second and next children need to know pid of first one */
2810 pi->pgrp = command->pid;
2816 if ((i + 1) < pi->num_cmds)
2817 close(pipefds[1]); /* write end */
2818 /* Pass read (output) pipe end to next iteration */
2819 nextin = pipefds[0];
2822 if (!pi->alive_cmds) {
2823 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
2827 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
2831 #ifndef debug_print_tree
2832 static void debug_print_tree(struct pipe *pi, int lvl)
2834 static const char *const PIPE[] = {
2840 static const char *RES[] = {
2841 [RES_NONE ] = "NONE" ,
2844 [RES_THEN ] = "THEN" ,
2845 [RES_ELIF ] = "ELIF" ,
2846 [RES_ELSE ] = "ELSE" ,
2849 #if ENABLE_HUSH_LOOPS
2850 [RES_FOR ] = "FOR" ,
2851 [RES_WHILE] = "WHILE",
2852 [RES_UNTIL] = "UNTIL",
2854 [RES_DONE ] = "DONE" ,
2856 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2859 #if ENABLE_HUSH_CASE
2860 [RES_CASE ] = "CASE" ,
2861 [RES_MATCH] = "MATCH",
2862 [RES_CASEI] = "CASEI",
2863 [RES_ESAC ] = "ESAC" ,
2865 [RES_XXXX ] = "XXXX" ,
2866 [RES_SNTX ] = "SNTX" ,
2868 static const char *const GRPTYPE[] = {
2871 #if ENABLE_HUSH_FUNCTIONS
2880 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2881 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2883 while (prn < pi->num_cmds) {
2884 struct command *command = &pi->cmds[prn];
2885 char **argv = command->argv;
2887 fprintf(stderr, "%*s prog %d assignment_cnt:%d",
2889 command->assignment_cnt);
2890 if (command->group) {
2891 fprintf(stderr, " group %s: (argv=%p)\n",
2892 GRPTYPE[command->grp_type],
2894 debug_print_tree(command->group, lvl+1);
2898 if (argv) while (*argv) {
2899 fprintf(stderr, " '%s'", *argv);
2902 fprintf(stderr, "\n");
2911 /* NB: called by pseudo_exec, and therefore must not modify any
2912 * global data until exec/_exit (we can be a child after vfork!) */
2913 static int run_list(struct pipe *pi)
2915 #if ENABLE_HUSH_CASE
2916 char *case_word = NULL;
2918 #if ENABLE_HUSH_LOOPS
2919 struct pipe *loop_top = NULL;
2920 char *for_varname = NULL;
2921 char **for_lcur = NULL;
2922 char **for_list = NULL;
2924 smallint flag_skip = 1;
2925 smalluint rcode = 0; /* probably just for compiler */
2926 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
2927 smalluint cond_code = 0;
2929 enum { cond_code = 0, };
2931 /*enum reserved_style*/ smallint rword = RES_NONE;
2932 /*enum reserved_style*/ smallint skip_more_for_this_rword = RES_XXXX;
2934 debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
2936 #if ENABLE_HUSH_LOOPS
2937 /* Check syntax for "for" */
2938 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
2939 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
2941 /* current word is FOR or IN (BOLD in comments below) */
2942 if (cpipe->next == NULL) {
2943 syntax("malformed for");
2944 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
2947 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
2948 if (cpipe->next->res_word == RES_DO)
2950 /* next word is not "do". It must be "in" then ("FOR v in ...") */
2951 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
2952 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
2954 syntax("malformed for");
2955 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
2961 /* Past this point, all code paths should jump to ret: label
2962 * in order to return, no direct "return" statements please.
2963 * This helps to ensure that no memory is leaked. */
2965 ////TODO: ctrl-Z handling needs re-thinking and re-testing
2968 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
2969 * We are saving state before entering outermost list ("while...done")
2970 * so that ctrl-Z will correctly background _entire_ outermost list,
2971 * not just a part of it (like "sleep 1 | exit 2") */
2972 if (++G.run_list_level == 1 && G_interactive_fd) {
2973 if (sigsetjmp(G.toplevel_jb, 1)) {
2974 /* ctrl-Z forked and we are parent; or ctrl-C.
2975 * Sighandler has longjmped us here */
2976 signal(SIGINT, SIG_IGN);
2977 signal(SIGTSTP, SIG_IGN);
2978 /* Restore level (we can be coming from deep inside
2980 G.run_list_level = 1;
2981 #if ENABLE_FEATURE_SH_STANDALONE
2982 if (G.nofork_save.saved) { /* if save area is valid */
2983 debug_printf_jobs("exiting nofork early\n");
2984 restore_nofork_data(&G.nofork_save);
2987 //// if (G.ctrl_z_flag) {
2988 //// /* ctrl-Z has forked and stored pid of the child in pi->pid.
2989 //// * Remember this child as background job */
2990 //// insert_bg_job(pi);
2992 /* ctrl-C. We just stop doing whatever we were doing */
2995 USE_HUSH_LOOPS(loop_top = NULL;)
2996 USE_HUSH_LOOPS(G.depth_of_loop = 0;)
3000 //// /* ctrl-Z handler will store pid etc in pi */
3001 //// G.toplevel_list = pi;
3002 //// G.ctrl_z_flag = 0;
3003 ////#if ENABLE_FEATURE_SH_STANDALONE
3004 //// G.nofork_save.saved = 0; /* in case we will run a nofork later */
3006 //// signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
3007 //// signal(SIGINT, handler_ctrl_c);
3011 /* Go through list of pipes, (maybe) executing them. */
3012 for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
3016 IF_HAS_KEYWORDS(rword = pi->res_word;)
3017 IF_HAS_NO_KEYWORDS(rword = RES_NONE;)
3018 debug_printf_exec(": rword=%d cond_code=%d skip_more=%d\n",
3019 rword, cond_code, skip_more_for_this_rword);
3020 #if ENABLE_HUSH_LOOPS
3021 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
3022 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
3024 /* start of a loop: remember where loop starts */
3029 if (rword == skip_more_for_this_rword && flag_skip) {
3030 if (pi->followup == PIPE_SEQ)
3032 /* it is "<false> && CMD" or "<true> || CMD"
3033 * and we should not execute CMD */
3037 skip_more_for_this_rword = RES_XXXX;
3040 if (rword == RES_THEN) {
3041 /* "if <false> THEN cmd": skip cmd */
3045 if (rword == RES_ELSE || rword == RES_ELIF) {
3046 /* "if <true> then ... ELSE/ELIF cmd":
3047 * skip cmd and all following ones */
3052 #if ENABLE_HUSH_LOOPS
3053 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
3055 /* first loop through for */
3057 static const char encoded_dollar_at[] ALIGN1 = {
3058 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
3059 }; /* encoded representation of "$@" */
3060 static const char *const encoded_dollar_at_argv[] = {
3061 encoded_dollar_at, NULL
3062 }; /* argv list with one element: "$@" */
3065 vals = (char**)encoded_dollar_at_argv;
3066 if (pi->next->res_word == RES_IN) {
3067 /* if no variable values after "in" we skip "for" */
3068 if (!pi->next->cmds[0].argv)
3070 vals = pi->next->cmds[0].argv;
3071 } /* else: "for var; do..." -> assume "$@" list */
3072 /* create list of variable values */
3073 debug_print_strings("for_list made from", vals);
3074 for_list = expand_strvec_to_strvec(vals);
3075 for_lcur = for_list;
3076 debug_print_strings("for_list", for_list);
3077 for_varname = pi->cmds[0].argv[0];
3078 pi->cmds[0].argv[0] = NULL;
3080 free(pi->cmds[0].argv[0]);
3082 /* "for" loop is over, clean up */
3086 pi->cmds[0].argv[0] = for_varname;
3089 /* insert next value from for_lcur */
3090 //TODO: does it need escaping?
3091 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
3092 pi->cmds[0].assignment_cnt = 1;
3094 if (rword == RES_IN) {
3095 continue; /* "for v IN list;..." - "in" has no cmds anyway */
3097 if (rword == RES_DONE) {
3098 continue; /* "done" has no cmds too */
3101 #if ENABLE_HUSH_CASE
3102 if (rword == RES_CASE) {
3103 case_word = expand_strvec_to_string(pi->cmds->argv);
3106 if (rword == RES_MATCH) {
3109 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
3111 /* all prev words didn't match, does this one match? */
3112 argv = pi->cmds->argv;
3114 char *pattern = expand_string_to_string(*argv);
3115 /* TODO: which FNM_xxx flags to use? */
3116 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
3118 if (cond_code == 0) { /* match! we will execute this branch */
3119 free(case_word); /* make future "word)" stop */
3127 if (rword == RES_CASEI) { /* inside of a case branch */
3129 continue; /* not matched yet, skip this pipe */
3132 /* Just pressing <enter> in shell should check for jobs.
3133 * OTOH, in non-interactive shell this is useless
3134 * and only leads to extra job checks */
3135 if (pi->num_cmds == 0) {
3136 if (G_interactive_fd)
3137 goto check_jobs_and_continue;
3141 /* After analyzing all keywords and conditions, we decided
3142 * to execute this pipe. NB: have to do checkjobs(NULL)
3143 * after run_pipe() to collect any background children,
3144 * even if list execution is to be stopped. */
3145 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
3148 #if ENABLE_HUSH_LOOPS
3149 G.flag_break_continue = 0;
3151 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
3153 /* we only ran a builtin: rcode is already known
3154 * and we don't need to wait for anything. */
3155 check_and_run_traps(0);
3156 #if ENABLE_HUSH_LOOPS
3157 /* was it "break" or "continue"? */
3158 if (G.flag_break_continue) {
3159 smallint fbc = G.flag_break_continue;
3160 /* we might fall into outer *loop*,
3161 * don't want to break it too */
3163 G.depth_break_continue--;
3164 if (G.depth_break_continue == 0)
3165 G.flag_break_continue = 0;
3166 /* else: e.g. "continue 2" should *break* once, *then* continue */
3167 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
3168 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
3169 goto check_jobs_and_break;
3170 /* "continue": simulate end of loop */
3175 } else if (pi->followup == PIPE_BG) {
3176 /* what does bash do with attempts to background builtins? */
3177 /* even bash 3.2 doesn't do that well with nested bg:
3178 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
3179 * I'm NOT treating inner &'s as jobs */
3180 check_and_run_traps(0);
3182 if (G.run_list_level == 1)
3185 rcode = 0; /* EXIT_SUCCESS */
3188 if (G.run_list_level == 1 && G_interactive_fd) {
3189 /* waits for completion, then fg's main shell */
3190 rcode = checkjobs_and_fg_shell(pi);
3191 check_and_run_traps(0);
3192 debug_printf_exec(": checkjobs_and_fg_shell returned %d\n", rcode);
3195 { /* this one just waits for completion */
3196 rcode = checkjobs(pi);
3197 check_and_run_traps(0);
3198 debug_printf_exec(": checkjobs returned %d\n", rcode);
3202 debug_printf_exec(": setting last_return_code=%d\n", rcode);
3203 G.last_return_code = rcode;
3205 /* Analyze how result affects subsequent commands */
3207 if (rword == RES_IF || rword == RES_ELIF)
3210 #if ENABLE_HUSH_LOOPS
3211 if (rword == RES_WHILE) {
3213 rcode = 0; /* "while false; do...done" - exitcode 0 */
3214 goto check_jobs_and_break;
3217 if (rword == RES_UNTIL) {
3219 check_jobs_and_break:
3225 if ((rcode == 0 && pi->followup == PIPE_OR)
3226 || (rcode != 0 && pi->followup == PIPE_AND)
3228 skip_more_for_this_rword = rword;
3231 check_jobs_and_continue:
3236 //// if (G.ctrl_z_flag) {
3237 //// /* ctrl-Z forked somewhere in the past, we are the child,
3238 //// * and now we completed running the list. Exit. */
3244 //// if (!G.run_list_level && G_interactive_fd) {
3245 //// signal(SIGTSTP, SIG_IGN);
3246 //// signal(SIGINT, SIG_IGN);
3249 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
3250 #if ENABLE_HUSH_LOOPS
3255 #if ENABLE_HUSH_CASE
3261 /* Select which version we will use */
3262 static int run_and_free_list(struct pipe *pi)
3265 debug_printf_exec("run_and_free_list entered\n");
3267 debug_printf_exec(": run_list with %d members\n", pi->num_cmds);
3268 rcode = run_list(pi);
3270 /* free_pipe_list has the side effect of clearing memory.
3271 * In the long run that function can be merged with run_list,
3272 * but doing that now would hobble the debugging effort. */
3273 free_pipe_list(pi, /* indent: */ 0);
3274 debug_printf_exec("run_and_free_list return %d\n", rcode);
3279 /* Peek ahead in the in_str to find out if we have a "&n" construct,
3280 * as in "2>&1", that represents duplicating a file descriptor.
3281 * Return either -2 (syntax error), -1 (no &), or the number found.
3283 static int redirect_dup_num(struct in_str *input)
3285 int ch, d = 0, ok = 0;
3287 if (ch != '&') return -1;
3289 i_getch(input); /* get the & */
3293 return -3; /* "-" represents "close me" */
3295 while (isdigit(ch)) {
3296 d = d*10 + (ch-'0');
3303 bb_error_msg("ambiguous redirect");
3307 /* The src parameter allows us to peek forward to a possible &n syntax
3308 * for file descriptor duplication, e.g., "2>&1".
3309 * Return code is 0 normally, 1 if a syntax error is detected in src.
3310 * Resource errors (in xmalloc) cause the process to exit */
3311 static int setup_redirect(struct parse_context *ctx,
3314 struct in_str *input)
3316 struct command *command = ctx->command;
3317 struct redir_struct *redir;
3318 struct redir_struct **redirp;
3321 /* Check for a '2>&1' type redirect */
3322 dup_num = redirect_dup_num(input);
3324 return 1; /* syntax error */
3326 /* Create a new redir_struct and drop it onto the end of the linked list */
3327 redirp = &command->redirects;
3328 while ((redir = *redirp) != NULL) {
3329 redirp = &(redir->next);
3331 *redirp = redir = xzalloc(sizeof(*redir));
3332 /* redir->next = NULL; */
3333 /* redir->rd_filename = NULL; */
3334 redir->rd_type = style;
3335 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
3337 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
3339 redir->dup = dup_num;
3340 if (dup_num != -1) {
3341 /* Erik had a check here that the file descriptor in question
3342 * is legit; I postpone that to "run time"
3343 * A "-" representation of "close me" shows up as a -3 here */
3344 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
3346 /* We do _not_ try to open the file that src points to,
3347 * since we need to return and let src be expanded first.
3348 * Set ctx->pending_redirect, so we know what to do at the
3349 * end of the next parsed word. */
3350 ctx->pending_redirect = redir;
3356 static struct pipe *new_pipe(void)
3359 pi = xzalloc(sizeof(struct pipe));
3360 /*pi->followup = 0; - deliberately invalid value */
3361 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3365 /* Command (member of a pipe) is complete. The only possible error here
3366 * is out of memory, in which case xmalloc exits. */
3367 static int done_command(struct parse_context *ctx)
3369 /* The command is really already in the pipe structure, so
3370 * advance the pipe counter and make a new, null command. */
3371 struct pipe *pi = ctx->pipe;
3372 struct command *command = ctx->command;
3375 if (command->group == NULL
3376 && command->argv == NULL
3377 && command->redirects == NULL
3379 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3380 return pi->num_cmds;
3383 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3385 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3388 /* Only real trickiness here is that the uncommitted
3389 * command structure is not counted in pi->num_cmds. */
3390 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3391 command = &pi->cmds[pi->num_cmds];
3392 memset(command, 0, sizeof(*command));
3394 ctx->command = command;
3395 /* but ctx->pipe and ctx->list_head remain unchanged */
3397 return pi->num_cmds; /* used only for 0/nonzero check */
3400 static void done_pipe(struct parse_context *ctx, pipe_style type)
3404 debug_printf_parse("done_pipe entered, followup %d\n", type);
3405 /* Close previous command */
3406 not_null = done_command(ctx);
3407 ctx->pipe->followup = type;
3408 IF_HAS_KEYWORDS(ctx->pipe->pi_inverted = ctx->ctx_inverted;)
3409 IF_HAS_KEYWORDS(ctx->ctx_inverted = 0;)
3410 IF_HAS_KEYWORDS(ctx->pipe->res_word = ctx->ctx_res_w;)
3412 /* Without this check, even just <enter> on command line generates
3413 * tree of three NOPs (!). Which is harmless but annoying.
3414 * IOW: it is safe to do it unconditionally.
3415 * RES_NONE case is for "for a in; do ..." (empty IN set)
3416 * to work, possibly other cases too. */
3417 if (not_null IF_HAS_KEYWORDS(|| ctx->ctx_res_w != RES_NONE)) {
3419 debug_printf_parse("done_pipe: adding new pipe: "
3420 "not_null:%d ctx->ctx_res_w:%d\n",
3421 not_null, ctx->ctx_res_w);
3423 ctx->pipe->next = new_p;
3425 /* RES_THEN, RES_DO etc are "sticky" -
3426 * they remain set for commands inside if/while.
3427 * This is used to control execution.
3428 * RES_FOR and RES_IN are NOT sticky (needed to support
3429 * cases where variable or value happens to match a keyword):
3431 #if ENABLE_HUSH_LOOPS
3432 if (ctx->ctx_res_w == RES_FOR
3433 || ctx->ctx_res_w == RES_IN)
3434 ctx->ctx_res_w = RES_NONE;
3436 #if ENABLE_HUSH_CASE
3437 if (ctx->ctx_res_w == RES_MATCH)
3438 ctx->ctx_res_w = RES_CASEI;
3440 ctx->command = NULL; /* trick done_command below */
3441 /* Create the memory for command, roughly:
3442 * ctx->pipe->cmds = new struct command;
3443 * ctx->command = &ctx->pipe->cmds[0];
3447 debug_printf_parse("done_pipe return\n");
3450 static void initialize_context(struct parse_context *ctx)
3452 memset(ctx, 0, sizeof(*ctx));
3453 ctx->pipe = ctx->list_head = new_pipe();
3454 /* Create the memory for command, roughly:
3455 * ctx->pipe->cmds = new struct command;
3456 * ctx->command = &ctx->pipe->cmds[0];
3462 /* If a reserved word is found and processed, parse context is modified
3463 * and 1 is returned.
3466 struct reserved_combo {
3469 unsigned char assignment_flag;
3473 FLAG_END = (1 << RES_NONE ),
3475 FLAG_IF = (1 << RES_IF ),
3476 FLAG_THEN = (1 << RES_THEN ),
3477 FLAG_ELIF = (1 << RES_ELIF ),
3478 FLAG_ELSE = (1 << RES_ELSE ),
3479 FLAG_FI = (1 << RES_FI ),
3481 #if ENABLE_HUSH_LOOPS
3482 FLAG_FOR = (1 << RES_FOR ),
3483 FLAG_WHILE = (1 << RES_WHILE),
3484 FLAG_UNTIL = (1 << RES_UNTIL),
3485 FLAG_DO = (1 << RES_DO ),
3486 FLAG_DONE = (1 << RES_DONE ),
3487 FLAG_IN = (1 << RES_IN ),
3489 #if ENABLE_HUSH_CASE
3490 FLAG_MATCH = (1 << RES_MATCH),
3491 FLAG_ESAC = (1 << RES_ESAC ),
3493 FLAG_START = (1 << RES_XXXX ),
3496 static const struct reserved_combo* match_reserved_word(o_string *word)
3498 /* Mostly a list of accepted follow-up reserved words.
3499 * FLAG_END means we are done with the sequence, and are ready
3500 * to turn the compound list into a command.
3501 * FLAG_START means the word must start a new compound list.
3503 static const struct reserved_combo reserved_list[] = {
3505 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3506 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
3507 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3508 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
3509 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
3510 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3512 #if ENABLE_HUSH_LOOPS
3513 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3514 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3515 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3516 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3517 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
3518 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3520 #if ENABLE_HUSH_CASE
3521 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3522 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3525 const struct reserved_combo *r;
3527 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3528 if (strcmp(word->data, r->literal) == 0)
3533 static int reserved_word(o_string *word, struct parse_context *ctx)
3535 #if ENABLE_HUSH_CASE
3536 static const struct reserved_combo reserved_match = {
3537 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3540 const struct reserved_combo *r;
3542 r = match_reserved_word(word);
3546 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3547 #if ENABLE_HUSH_CASE
3548 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
3549 /* "case word IN ..." - IN part starts first match part */
3550 r = &reserved_match;
3553 if (r->flag == 0) { /* '!' */
3554 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3555 syntax("! ! command");
3556 IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
3558 ctx->ctx_inverted = 1;
3561 if (r->flag & FLAG_START) {
3562 struct parse_context *old;
3563 old = xmalloc(sizeof(*old));
3564 debug_printf_parse("push stack %p\n", old);
3565 *old = *ctx; /* physical copy */
3566 initialize_context(ctx);
3568 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3570 ctx->ctx_res_w = RES_SNTX;
3573 ctx->ctx_res_w = r->res;
3574 ctx->old_flag = r->flag;
3575 if (ctx->old_flag & FLAG_END) {
3576 struct parse_context *old;
3577 done_pipe(ctx, PIPE_SEQ);
3578 debug_printf_parse("pop stack %p\n", ctx->stack);
3580 old->command->group = ctx->list_head;
3581 old->command->grp_type = GRP_NORMAL;
3582 *ctx = *old; /* physical copy */
3585 word->o_assignment = r->assignment_flag;
3590 /* Word is complete, look at it and update parsing context.
3591 * Normal return is 0. Syntax errors return 1.
3592 * Note: on return, word is reset, but not o_free'd!
3594 static int done_word(o_string *word, struct parse_context *ctx)
3596 struct command *command = ctx->command;
3598 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3599 if (word->length == 0 && word->nonnull == 0) {
3600 debug_printf_parse("done_word return 0: true null, ignored\n");
3603 /* If this word wasn't an assignment, next ones definitely
3604 * can't be assignments. Even if they look like ones. */
3605 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3606 && word->o_assignment != WORD_IS_KEYWORD
3608 word->o_assignment = NOT_ASSIGNMENT;
3610 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3611 command->assignment_cnt++;
3612 word->o_assignment = MAYBE_ASSIGNMENT;
3615 if (ctx->pending_redirect) {
3616 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3617 * only if run as "bash", not "sh" */
3618 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3619 word->o_assignment = NOT_ASSIGNMENT;
3620 debug_printf("word stored in rd_filename: '%s'\n", word->data);
3622 /* "{ echo foo; } echo bar" - bad */
3623 /* NB: bash allows e.g.:
3624 * if true; then { echo foo; } fi
3625 * while if false; then false; fi do break; done
3627 if (command->group) {
3629 debug_printf_parse("done_word return 1: syntax error, "
3630 "groups and arglists don't mix\n");
3634 #if ENABLE_HUSH_CASE
3635 if (ctx->ctx_dsemicolon
3636 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3638 /* already done when ctx_dsemicolon was set to 1: */
3639 /* ctx->ctx_res_w = RES_MATCH; */
3640 ctx->ctx_dsemicolon = 0;
3643 if (!command->argv /* if it's the first word... */
3644 #if ENABLE_HUSH_LOOPS
3645 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3646 && ctx->ctx_res_w != RES_IN
3649 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
3650 if (reserved_word(word, ctx)) {
3652 debug_printf_parse("done_word return %d\n",
3653 (ctx->ctx_res_w == RES_SNTX));
3654 return (ctx->ctx_res_w == RES_SNTX);
3658 if (word->nonnull /* word had "xx" or 'xx' at least as part of it. */
3659 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3660 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3661 /* (otherwise it's known to be not empty and is already safe) */
3663 /* exclude "$@" - it can expand to no word despite "" */
3664 char *p = word->data;
3665 while (p[0] == SPECIAL_VAR_SYMBOL
3666 && (p[1] & 0x7f) == '@'
3667 && p[2] == SPECIAL_VAR_SYMBOL
3671 if (p == word->data || p[0] != '\0') {
3672 /* saw no "$@", or not only "$@" but some
3673 * real text is there too */
3674 /* insert "empty variable" reference, this makes
3675 * e.g. "", $empty"" etc to not disappear */
3676 o_addchr(word, SPECIAL_VAR_SYMBOL);
3677 o_addchr(word, SPECIAL_VAR_SYMBOL);
3680 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3681 debug_print_strings("word appended to argv", command->argv);
3685 ctx->pending_redirect = NULL;
3687 #if ENABLE_HUSH_LOOPS
3688 /* Force FOR to have just one word (variable name) */
3689 /* NB: basically, this makes hush see "for v in ..." syntax as if
3690 * as it is "for v; in ...". FOR and IN become two pipe structs
3692 if (ctx->ctx_res_w == RES_FOR) {
3693 //TODO: check that command->argv[0] is a valid variable name!
3694 done_pipe(ctx, PIPE_SEQ);
3697 #if ENABLE_HUSH_CASE
3698 /* Force CASE to have just one word */
3699 if (ctx->ctx_res_w == RES_CASE) {
3700 done_pipe(ctx, PIPE_SEQ);
3703 debug_printf_parse("done_word return 0\n");
3707 /* If a redirect is immediately preceded by a number, that number is
3708 * supposed to tell which file descriptor to redirect. This routine
3709 * looks for such preceding numbers. In an ideal world this routine
3710 * needs to handle all the following classes of redirects...
3711 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3712 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3713 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3714 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3715 * A -1 output from this program means no valid number was found, so the
3716 * caller should use the appropriate default for this redirection.
3718 static int redirect_opt_num(o_string *o)
3724 for (num = 0; num < o->length; num++) {
3725 if (!isdigit(o->data[num])) {
3729 num = atoi(o->data);
3734 static struct pipe *parse_stream(struct in_str *input, int end_trigger);
3735 static void parse_and_run_string(const char *s);
3737 #if ENABLE_HUSH_TICK
3738 static FILE *generate_stream_from_string(const char *s)
3741 int pid, channel[2];
3744 pid = BB_MMU ? fork() : vfork();
3746 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
3748 if (pid == 0) { /* child */
3749 /* Process substitution is not considered to be usual
3750 * 'command execution'.
3751 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
3758 if (ENABLE_HUSH_JOB)
3759 die_sleep = 0; /* let nofork's xfuncs die */
3760 close(channel[0]); /* NB: close _first_, then move fd! */
3761 xmove_fd(channel[1], 1);
3762 /* Prevent it from trying to handle ctrl-z etc */
3763 USE_HUSH_JOB(G.run_list_level = 1;)
3765 parse_and_run_string(s);
3766 _exit(G.last_return_code);
3768 /* We re-execute after vfork on NOMMU. This makes this script safe:
3769 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >TESTFILE
3770 * huge=`cat TESTFILE` # was blocking here forever
3773 //TODO: pass non-exported variables, traps, and functions
3774 execl(CONFIG_BUSYBOX_EXEC_PATH, "hush", "-c", s, NULL);
3781 pf = fdopen(channel[0], "r");
3785 /* Return code is exit status of the process that is run. */
3786 static int process_command_subs(o_string *dest, const char *s)
3789 struct in_str pipe_str;
3792 pf = generate_stream_from_string(s);
3795 close_on_exec_on(fileno(pf));
3797 /* Now send results of command back into original context */
3798 setup_file_in_str(&pipe_str, pf);
3800 while ((ch = i_getch(&pipe_str)) != EOF) {
3806 o_addchr(dest, '\n');
3809 o_addQchr(dest, ch);
3812 debug_printf("done reading from pipe, pclose()ing\n");
3813 /* Note: we got EOF, and we just close the read end of the pipe.
3814 * We do not wait for the `cmd` child to terminate. bash and ash do.
3816 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
3817 * `false`; echo $? - bash outputs "1"
3820 debug_printf("closed FILE from child. return 0\n");
3825 static int parse_group(o_string *dest, struct parse_context *ctx,
3826 struct in_str *input, int ch)
3828 /* dest contains characters seen prior to ( or {.
3829 * Typically it's empty, but for function defs,
3830 * it contains function name (without '()'). */
3831 struct pipe *pipe_list;
3833 struct command *command = ctx->command;
3835 debug_printf_parse("parse_group entered\n");
3836 #if ENABLE_HUSH_FUNCTIONS
3837 if (ch == 'F') { /* function definition? */
3838 bb_error_msg("aha '%s' is a function, parsing it...", dest->data);
3839 //command->fname = dest->data;
3840 command->grp_type = GRP_FUNCTION;
3841 //TODO: review every o_reset() location... do they handle all o_string fields correctly?
3842 memset(dest, 0, sizeof(*dest));
3845 if (command->argv /* word [word](... */
3846 || dest->length /* word(... */
3847 || dest->nonnull /* ""(... */
3850 debug_printf_parse("parse_group return 1: "
3851 "syntax error, groups and arglists don't mix\n");
3857 command->grp_type = GRP_SUBSHELL;
3859 pipe_list = parse_stream(input, endch);
3860 /* empty ()/{} or parse error? */
3861 if (!pipe_list || pipe_list == ERR_PTR) {
3863 debug_printf_parse("parse_group return 1: "
3864 "parse_stream returned %p\n", pipe_list);
3867 command->group = pipe_list;
3868 debug_printf_parse("parse_group return 0\n");
3870 /* command remains "open", available for possible redirects */
3873 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
3874 /* Subroutines for copying $(...) and `...` things */
3875 static void add_till_backquote(o_string *dest, struct in_str *input);
3877 static void add_till_single_quote(o_string *dest, struct in_str *input)
3880 int ch = i_getch(input);
3888 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3889 static void add_till_double_quote(o_string *dest, struct in_str *input)
3892 int ch = i_getch(input);
3895 if (ch == '\\') { /* \x. Copy both chars. */
3897 ch = i_getch(input);
3903 add_till_backquote(dest, input);
3907 //if (ch == '$') ...
3910 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3912 * "Within the backquoted style of command substitution, backslash
3913 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3914 * The search for the matching backquote shall be satisfied by the first
3915 * backquote found without a preceding backslash; during this search,
3916 * if a non-escaped backquote is encountered within a shell comment,
3917 * a here-document, an embedded command substitution of the $(command)
3918 * form, or a quoted string, undefined results occur. A single-quoted
3919 * or double-quoted string that begins, but does not end, within the
3920 * "`...`" sequence produces undefined results."
3922 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3924 static void add_till_backquote(o_string *dest, struct in_str *input)
3927 int ch = i_getch(input);
3930 if (ch == '\\') { /* \x. Copy both chars unless it is \` */
3931 int ch2 = i_getch(input);
3932 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
3941 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3942 * quoting and nested ()s.
3943 * "With the $(command) style of command substitution, all characters
3944 * following the open parenthesis to the matching closing parenthesis
3945 * constitute the command. Any valid shell script can be used for command,
3946 * except a script consisting solely of redirections which produces
3947 * unspecified results."
3949 * echo $(echo '(TEST)' BEST) (TEST) BEST
3950 * echo $(echo 'TEST)' BEST) TEST) BEST
3951 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3953 static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
3957 int ch = i_getch(input);
3966 if (i_peek(input) == ')') {
3974 add_till_single_quote(dest, input);
3979 add_till_double_quote(dest, input);
3983 if (ch == '\\') { /* \x. Copy verbatim. Important for \(, \) */
3984 ch = i_getch(input);
3992 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
3994 /* Return code: 0 for OK, 1 for syntax error */
3995 static int handle_dollar(o_string *dest, struct in_str *input)
3998 int ch = i_peek(input); /* first character after the $ */
3999 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
4001 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
4005 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4007 debug_printf_parse(": '%c'\n", ch);
4008 o_addchr(dest, ch | quote_mask);
4011 if (!isalnum(ch) && ch != '_')
4015 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4016 } else if (isdigit(ch)) {
4019 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4020 debug_printf_parse(": '%c'\n", ch);
4021 o_addchr(dest, ch | quote_mask);
4022 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4023 } else switch (ch) {
4025 case '!': /* last bg pid */
4026 case '?': /* last exit code */
4027 case '#': /* number of args */
4028 case '*': /* args */
4029 case '@': /* args */
4030 goto make_one_char_var;
4032 bool first_char, all_digits;
4034 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4036 /* XXX maybe someone will try to escape the '}' */
4041 ch = i_getch(input);
4047 /* ${#var}: length of var contents */
4049 else if (isdigit(ch)) {
4056 && ( (all_digits && !isdigit(ch))
4057 || (!all_digits && !isalnum(ch) && ch != '_')
4060 /* handle parameter expansions
4061 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4066 case ':': /* null modifier */
4067 if (expansion == 0) {
4068 debug_printf_parse(": null modifier\n");
4073 #if 0 /* not implemented yet :( */
4074 case '#': /* remove prefix */
4075 case '%': /* remove suffix */
4076 if (expansion == 0) {
4077 debug_printf_parse(": remove suffix/prefix\n");
4083 case '-': /* default value */
4084 case '=': /* assign default */
4085 case '+': /* alternative */
4086 case '?': /* error indicate */
4087 debug_printf_parse(": parameter expansion\n");
4092 syntax("unterminated ${name}");
4093 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
4098 debug_printf_parse(": '%c'\n", ch);
4099 o_addchr(dest, ch | quote_mask);
4103 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4108 #if ENABLE_SH_MATH_SUPPORT
4109 if (i_peek(input) == '(') {
4111 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4112 o_addchr(dest, /*quote_mask |*/ '+');
4113 add_till_closing_paren(dest, input, true);
4114 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4118 #if ENABLE_HUSH_TICK
4119 //int pos = dest->length;
4120 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4121 o_addchr(dest, quote_mask | '`');
4122 add_till_closing_paren(dest, input, false);
4123 //debug_printf_subst("SUBST RES2 '%s'\n", dest->data + pos);
4124 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4131 if (isalnum(ch)) { /* it's $_name or $_123 */
4137 /* $_ Shell or shell script name; or last cmd name */
4138 /* $- Option flags set by set builtin or shell options (-i etc) */
4140 o_addQchr(dest, '$');
4142 debug_printf_parse("handle_dollar return 0\n");
4146 static int parse_stream_dquoted(o_string *dest,
4147 struct in_str *input, int dquote_end)
4153 ch = i_getch(input);
4154 if (ch == dquote_end) { /* may be only '"' or EOF */
4156 if (dest->o_assignment == NOT_ASSIGNMENT)
4157 dest->o_escape ^= 1;
4158 debug_printf_parse("parse_stream_dquoted return 0\n");
4162 syntax("unterminated \"");
4163 debug_printf_parse("parse_stream_dquoted return 1: unterminated \"\n");
4168 next = i_peek(input);
4170 debug_printf_parse(": ch=%c (%d) m=%d escape=%d\n",
4171 ch, ch, m, dest->o_escape);
4175 debug_printf_parse("parse_stream_dquoted return 1: \\<eof>\n");
4179 * "The backslash retains its special meaning [in "..."]
4180 * only when followed by one of the following characters:
4181 * $, `, ", \, or <newline>. A double quote may be quoted
4182 * within double quotes by preceding it with a backslash.
4183 * If enabled, history expansion will be performed unless
4184 * an ! appearing in double quotes is escaped using
4185 * a backslash. The backslash preceding the ! is not removed."
4187 if (strchr("$`\"\\", next) != NULL) {
4188 o_addqchr(dest, i_getch(input));
4190 o_addqchr(dest, '\\');
4195 if (handle_dollar(dest, input) != 0) {
4196 debug_printf_parse("parse_stream_dquoted return 1: "
4197 "handle_dollar returned non-0\n");
4202 #if ENABLE_HUSH_TICK
4204 //int pos = dest->length;
4205 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4206 o_addchr(dest, 0x80 | '`');
4207 add_till_backquote(dest, input);
4208 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4209 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4213 o_addQchr(dest, ch);
4215 && (dest->o_assignment == MAYBE_ASSIGNMENT
4216 || dest->o_assignment == WORD_IS_KEYWORD)
4217 && is_assignment(dest->data)
4219 dest->o_assignment = DEFINITELY_ASSIGNMENT;
4225 * Scan input until EOF or end_trigger char.
4226 * Return a list of pipes to execute, or NULL on EOF
4227 * or if end_trigger character is met.
4228 * On syntax error, exit is shell is not interactive,
4229 * reset parsing machinery and start parsing anew,
4230 * or return ERR_PTR.
4232 static struct pipe *parse_stream(struct in_str *input, int end_trigger)
4234 struct parse_context ctx;
4235 o_string dest = NULL_O_STRING;
4240 redir_type redir_style;
4242 /* Double-quote state is handled in the state variable is_in_dquote.
4243 * A single-quote triggers a bypass of the main loop until its mate is
4244 * found. When recursing, quote state is passed in via dest->o_escape.
4246 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4247 end_trigger ? : 'X');
4249 G.ifs = get_local_var_value("IFS");
4254 #if ENABLE_HUSH_INTERACTIVE
4255 input->promptmode = 0; /* PS1 */
4257 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
4258 initialize_context(&ctx);
4262 const char *is_special;
4265 if (parse_stream_dquoted(&dest, input, '"')) {
4268 /* We reached closing '"' */
4272 ch = i_getch(input);
4273 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4274 ch, ch, dest.o_escape);
4277 if (done_word(&dest, &ctx)) {
4281 done_pipe(&ctx, PIPE_SEQ);
4282 /* If we got nothing... */
4284 if (pi->num_cmds == 0
4285 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4287 free_pipe_list(pi, 0);
4290 debug_printf_parse("parse_stream return %p\n", pi);
4294 next = i_peek(input);
4297 is_ifs = strchr(G.ifs, ch);
4298 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
4299 "\\$\"" USE_HUSH_TICK("`") /* always special */
4302 if (!is_special && !is_ifs) { /* ordinary char */
4303 o_addQchr(&dest, ch);
4304 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4305 || dest.o_assignment == WORD_IS_KEYWORD)
4307 && is_assignment(dest.data)
4309 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4315 if (done_word(&dest, &ctx)) {
4319 #if ENABLE_HUSH_CASE
4320 /* "case ... in <newline> word) ..." -
4321 * newlines are ignored (but ';' wouldn't be) */
4322 if (ctx.command->argv == NULL
4323 && ctx.ctx_res_w == RES_MATCH
4328 /* Treat newline as a command separator. */
4329 done_pipe(&ctx, PIPE_SEQ);
4330 dest.o_assignment = MAYBE_ASSIGNMENT;
4332 /* note: if (is_ifs) continue;
4333 * will still trigger for us */
4336 if (end_trigger && end_trigger == ch) {
4337 //TODO: disallow "{ cmd }" without semicolon
4338 if (done_word(&dest, &ctx)) {
4341 done_pipe(&ctx, PIPE_SEQ);
4342 dest.o_assignment = MAYBE_ASSIGNMENT;
4343 /* Do we sit outside of any if's, loops or case's? */
4345 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4347 debug_printf_parse("parse_stream return %p: "
4348 "end_trigger char found\n",
4351 return ctx.list_head;
4357 if (dest.o_assignment == MAYBE_ASSIGNMENT) {
4358 /* ch is a special char and thus this word
4359 * cannot be an assignment */
4360 dest.o_assignment = NOT_ASSIGNMENT;
4365 if (dest.length == 0) {
4368 if (ch == EOF || ch == '\n')
4373 o_addQchr(&dest, ch);
4381 o_addchr(&dest, '\\');
4382 o_addchr(&dest, i_getch(input));
4385 if (handle_dollar(&dest, input) != 0) {
4386 debug_printf_parse("parse_stream parse error: "
4387 "handle_dollar returned non-0\n");
4394 ch = i_getch(input);
4396 syntax("unterminated '");
4401 if (dest.o_assignment == NOT_ASSIGNMENT)
4402 o_addqchr(&dest, ch);
4404 o_addchr(&dest, ch);
4409 is_in_dquote ^= 1; /* invert */
4410 if (dest.o_assignment == NOT_ASSIGNMENT)
4413 #if ENABLE_HUSH_TICK
4415 //int pos = dest.length;
4416 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4417 o_addchr(&dest, '`');
4418 add_till_backquote(&dest, input);
4419 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4420 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4425 redir_fd = redirect_opt_num(&dest);
4426 if (done_word(&dest, &ctx)) {
4429 redir_style = REDIRECT_OVERWRITE;
4431 redir_style = REDIRECT_APPEND;
4435 else if (next == '(') {
4436 syntax(">(process) not supported");
4440 setup_redirect(&ctx, redir_fd, redir_style, input);
4443 redir_fd = redirect_opt_num(&dest);
4444 if (done_word(&dest, &ctx)) {
4447 redir_style = REDIRECT_INPUT;
4449 redir_style = REDIRECT_HEREIS;
4451 } else if (next == '>') {
4452 redir_style = REDIRECT_IO;
4456 else if (next == '(') {
4457 syntax("<(process) not supported");
4461 setup_redirect(&ctx, redir_fd, redir_style, input);
4464 #if ENABLE_HUSH_CASE
4467 if (done_word(&dest, &ctx)) {
4470 done_pipe(&ctx, PIPE_SEQ);
4471 #if ENABLE_HUSH_CASE
4472 /* Eat multiple semicolons, detect
4473 * whether it means something special */
4479 if (ctx.ctx_res_w == RES_CASEI) {
4480 ctx.ctx_dsemicolon = 1;
4481 ctx.ctx_res_w = RES_MATCH;
4487 /* We just finished a cmd. New one may start
4488 * with an assignment */
4489 dest.o_assignment = MAYBE_ASSIGNMENT;
4492 if (done_word(&dest, &ctx)) {
4497 done_pipe(&ctx, PIPE_AND);
4499 done_pipe(&ctx, PIPE_BG);
4503 if (done_word(&dest, &ctx)) {
4506 #if ENABLE_HUSH_CASE
4507 if (ctx.ctx_res_w == RES_MATCH)
4508 break; /* we are in case's "word | word)" */
4510 if (next == '|') { /* || */
4512 done_pipe(&ctx, PIPE_OR);
4514 /* we could pick up a file descriptor choice here
4515 * with redirect_opt_num(), but bash doesn't do it.
4516 * "echo foo 2| cat" yields "foo 2". */
4521 #if ENABLE_HUSH_CASE
4522 /* "case... in [(]word)..." - skip '(' */
4523 if (ctx.ctx_res_w == RES_MATCH
4524 && ctx.command->argv == NULL /* not (word|(... */
4525 && dest.length == 0 /* not word(... */
4526 && dest.nonnull == 0 /* not ""(... */
4531 #if ENABLE_HUSH_FUNCTIONS
4532 if (dest.length != 0 /* not just () but word() */
4533 && dest.nonnull == 0 /* not a"b"c() */
4534 && ctx.command->argv == NULL /* it's the first word */
4535 //TODO: "func ( ) {...}" - note spaces - is valid format too in bash
4536 && i_peek(input) == ')'
4537 && !match_reserved_word(&dest)
4539 bb_error_msg("seems like a function definition");
4542 //TODO: do it properly.
4543 ch = i_getch(input);
4544 } while (ch == ' ' || ch == '\n');
4546 syntax("was expecting {");
4549 ch = 'F'; /* magic value */
4553 if (parse_group(&dest, &ctx, input, ch) != 0) {
4558 #if ENABLE_HUSH_CASE
4559 if (ctx.ctx_res_w == RES_MATCH)
4563 /* proper use of this character is caught by end_trigger:
4564 * if we see {, we call parse_group(..., end_trigger='}')
4565 * and it will match } earlier (not here). */
4566 syntax("unexpected } or )");
4570 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4576 struct parse_context *pctx;
4577 IF_HAS_KEYWORDS(struct parse_context *p2;)
4579 /* Clean up allocated tree.
4580 * Samples for finding leaks on syntax error recovery path.
4581 * Run them from interactive shell, watch pmap `pidof hush`.
4582 * while if false; then false; fi do break; done
4584 * while if false; then false; fi; do break; fi
4588 /* Update pipe/command counts,
4589 * otherwise freeing may miss some */
4590 done_pipe(pctx, PIPE_SEQ);
4591 debug_printf_clean("freeing list %p from ctx %p\n",
4592 pctx->list_head, pctx);
4593 debug_print_tree(pctx->list_head, 0);
4594 free_pipe_list(pctx->list_head, 0);
4595 debug_printf_clean("freed list %p\n", pctx->list_head);
4596 IF_HAS_KEYWORDS(p2 = pctx->stack;)
4600 IF_HAS_KEYWORDS(pctx = p2;)
4601 } while (HAS_KEYWORDS && pctx);
4602 /* Free text, clear all dest fields */
4604 /* If we are not in top-level parse, we return,
4605 * our caller will propagate error.
4607 if (end_trigger != ';')
4609 /* Discard cached input, force prompt */
4611 USE_HUSH_INTERACTIVE(input->promptme = 1;)
4616 /* Execiting from string: eval, sh -c '...'
4617 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
4618 * end_trigger controls how often we stop parsing
4619 * NUL: parse all, execute, return
4620 * ';': parse till ';' or newline, execute, repeat till EOF
4622 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
4625 struct pipe *pipe_list;
4627 pipe_list = parse_stream(inp, end_trigger);
4628 if (!pipe_list) /* EOF */
4630 debug_print_tree(pipe_list, 0);
4631 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
4632 run_and_free_list(pipe_list);
4636 static void parse_and_run_string(const char *s)
4638 struct in_str input;
4639 setup_string_in_str(&input, s);
4640 parse_and_run_stream(&input, '\0');
4643 static void parse_and_run_file(FILE *f)
4645 struct in_str input;
4646 setup_file_in_str(&input, f);
4647 parse_and_run_stream(&input, ';');
4651 /* Make sure we have a controlling tty. If we get started under a job
4652 * aware app (like bash for example), make sure we are now in charge so
4653 * we don't fight over who gets the foreground */
4654 static void setup_job_control(void)
4658 shell_pgrp = getpgrp();
4660 /* If we were ran as 'hush &',
4661 * sleep until we are in the foreground. */
4662 while (tcgetpgrp(G_interactive_fd) != shell_pgrp) {
4663 /* Send TTIN to ourself (should stop us) */
4664 kill(- shell_pgrp, SIGTTIN);
4665 shell_pgrp = getpgrp();
4668 /* We _must_ restore tty pgrp on fatal signals */
4669 set_fatal_signals_to_sigexit();
4671 /* Put ourselves in our own process group. */
4672 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
4673 /* Grab control of the terminal. */
4674 tcsetpgrp(G_interactive_fd, getpid());
4678 static int set_mode(const char cstate, const char mode)
4680 int state = (cstate == '-' ? 1 : 0);
4682 case 'n': G.fake_mode = state; break;
4683 case 'x': /*G.debug_mode = state;*/ break;
4684 default: return EXIT_FAILURE;
4686 return EXIT_SUCCESS;
4689 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4690 int hush_main(int argc, char **argv)
4692 static const struct variable const_shell_ver = {
4694 .varstr = (char*)hush_version_str,
4695 .max_len = 1, /* 0 can provoke free(name) */
4703 struct variable *cur_var;
4707 G.root_pid = getpid();
4709 /* Deal with HUSH_VERSION */
4710 G.shell_ver = const_shell_ver; /* copying struct here */
4711 G.top_var = &G.shell_ver;
4712 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
4713 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
4714 /* Initialize our shell local variables with the values
4715 * currently living in the environment */
4716 cur_var = G.top_var;
4719 char *value = strchr(*e, '=');
4720 if (value) { /* paranoia */
4721 cur_var->next = xzalloc(sizeof(*cur_var));
4722 cur_var = cur_var->next;
4723 cur_var->varstr = *e;
4724 cur_var->max_len = strlen(*e);
4725 cur_var->flg_export = 1;
4729 debug_printf_env("putenv '%s'\n", hush_version_str);
4730 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
4732 #if ENABLE_FEATURE_EDITING
4733 G.line_input_state = new_line_input_t(FOR_SHELL);
4735 /* XXX what should these be while sourcing /etc/profile? */
4736 G.global_argc = argc;
4737 G.global_argv = argv;
4738 /* Initialize some more globals to non-zero values */
4740 #if ENABLE_HUSH_INTERACTIVE
4741 if (ENABLE_FEATURE_EDITING)
4742 cmdedit_set_initial_prompt();
4746 if (EXIT_SUCCESS) /* otherwise is already done */
4747 G.last_return_code = EXIT_SUCCESS;
4749 if (argv[0] && argv[0][0] == '-') {
4750 debug_printf("sourcing /etc/profile\n");
4751 input = fopen_for_read("/etc/profile");
4752 if (input != NULL) {
4753 close_on_exec_on(fileno(input));
4754 parse_and_run_file(input);
4760 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
4761 while ((opt = getopt(argc, argv, "c:xins")) > 0) {
4764 G.global_argv = argv + optind;
4765 if (!argv[optind]) {
4766 /* -c 'script' (no params): prevent empty $0 */
4767 *--G.global_argv = argv[0];
4769 } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
4770 G.global_argc = argc - optind;
4771 parse_and_run_string(optarg);
4774 /* Well, we cannot just declare interactiveness,
4775 * we have to have some stuff (ctty, etc) */
4776 /* G_interactive_fd++; */
4779 /* "-s" means "read from stdin", but this is how we always
4780 * operate, so simply do nothing here. */
4784 if (!set_mode('-', opt))
4788 fprintf(stderr, "Usage: sh [FILE]...\n"
4789 " or: sh -c command [args]...\n\n");
4797 /* A shell is interactive if the '-i' flag was given, or if all of
4798 * the following conditions are met:
4800 * no arguments remaining or the -s flag given
4801 * standard input is a terminal
4802 * standard output is a terminal
4803 * Refer to Posix.2, the description of the 'sh' utility. */
4804 if (argv[optind] == NULL && input == stdin
4805 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4807 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
4808 debug_printf("saved_tty_pgrp=%d\n", G.saved_tty_pgrp);
4809 if (G.saved_tty_pgrp >= 0) {
4810 /* try to dup to high fd#, >= 255 */
4811 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4812 if (G_interactive_fd < 0) {
4813 /* try to dup to any fd */
4814 G_interactive_fd = dup(STDIN_FILENO);
4815 if (G_interactive_fd < 0)
4817 G_interactive_fd = 0;
4819 // TODO: track & disallow any attempts of user
4820 // to (inadvertently) close/redirect it
4823 init_signal_mask(); /* note: ensures SIGCHLD is not masked */
4824 debug_printf("interactive_fd=%d\n", G_interactive_fd);
4825 if (G_interactive_fd) {
4826 fcntl(G_interactive_fd, F_SETFD, FD_CLOEXEC);
4827 /* Looks like they want an interactive shell */
4828 setup_job_control();
4829 /* -1 is special - makes xfuncs longjmp, not exit
4830 * (we reset die_sleep = 0 whereever we [v]fork) */
4832 if (setjmp(die_jmp)) {
4833 /* xfunc has failed! die die die */
4834 hush_exit(xfunc_error_retval);
4837 #elif ENABLE_HUSH_INTERACTIVE
4838 /* no job control compiled, only prompt/line editing */
4839 if (argv[optind] == NULL && input == stdin
4840 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4842 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4843 if (G_interactive_fd < 0) {
4844 /* try to dup to any fd */
4845 G_interactive_fd = dup(STDIN_FILENO);
4846 if (G_interactive_fd < 0)
4848 G_interactive_fd = 0;
4850 if (G_interactive_fd) {
4851 fcntl(G_interactive_fd, F_SETFD, FD_CLOEXEC);
4854 init_signal_mask(); /* note: ensures SIGCHLD is not masked */
4858 /* POSIX allows shell to re-enable SIGCHLD
4859 * even if it was SIG_IGN on entry */
4860 // G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
4861 signal(SIGCHLD, SIG_DFL); // SIGCHLD_handler);
4863 #if ENABLE_HUSH_INTERACTIVE && !ENABLE_FEATURE_SH_EXTRA_QUIET
4864 if (G_interactive_fd) {
4865 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
4866 printf("Enter 'help' for a list of built-in commands.\n\n");
4870 if (argv[optind] == NULL) {
4871 parse_and_run_file(stdin);
4873 debug_printf("\nrunning script '%s'\n", argv[optind]);
4874 G.global_argv = argv + optind;
4875 G.global_argc = argc - optind;
4876 input = xfopen_for_read(argv[optind]);
4877 fcntl(fileno(input), F_SETFD, FD_CLOEXEC);
4878 parse_and_run_file(input);
4883 #if ENABLE_FEATURE_CLEAN_UP
4885 if (G.cwd != bb_msg_unknown)
4887 cur_var = G.top_var->next;
4889 struct variable *tmp = cur_var;
4890 if (!cur_var->max_len)
4891 free(cur_var->varstr);
4892 cur_var = cur_var->next;
4896 hush_exit(G.last_return_code);
4901 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4902 int lash_main(int argc, char **argv)
4904 //bb_error_msg("lash is deprecated, please use hush instead");
4905 return hush_main(argc, argv);
4913 static int builtin_trap(char **argv)
4920 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
4923 /* No args: print all trapped. This isn't 100% correct as we should
4924 * be escaping the cmd so that it can be pasted back in ...
4926 for (i = 0; i < NSIG; ++i)
4928 printf("trap -- '%s' %s\n", G.traps[i], get_signame(i));
4929 return EXIT_SUCCESS;
4934 /* if first arg is decimal: reset all specified */
4935 sig = bb_strtou(*++argv, NULL, 10);
4941 sig = get_signum(*argv++);
4942 if (sig < 0 || sig >= NSIG) {
4944 /* mimic bash message exactly */
4945 bb_perror_msg("trap: %s: invalid signal specification", argv[i]);
4950 G.traps[sig] = xstrdup(new_cmd);
4952 debug_printf("trap: setting SIG%s (%i) to '%s'",
4953 get_signame(sig), sig, G.traps[sig]);
4955 /* There is no signal for 0 (EXIT) */
4960 sigaddset(&G.blocked_set, sig);
4962 /* there was a trap handler, we are removing it
4963 * (if sig has non-DFL handling,
4964 * we don't need to do anything) */
4965 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
4967 sigdelset(&G.blocked_set, sig);
4969 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
4974 /* first arg is "-": reset all specified to default */
4975 /* first arg is "": ignore all specified */
4976 /* everything else: execute first arg upon signal */
4978 bb_error_msg("trap: invalid arguments");
4979 return EXIT_FAILURE;
4981 if (LONE_DASH(*argv))
4989 static int builtin_true(char **argv UNUSED_PARAM)
4994 static int builtin_test(char **argv)
5001 return test_main(argc, argv - argc);
5004 static int builtin_echo(char **argv)
5011 return echo_main(argc, argv - argc);
5014 static int builtin_eval(char **argv)
5016 int rcode = EXIT_SUCCESS;
5019 char *str = expand_strvec_to_string(argv + 1);
5021 * eval "echo Hi; done" ("done" is syntax error):
5022 * "echo Hi" will not execute too.
5024 parse_and_run_string(str);
5026 rcode = G.last_return_code;
5031 static int builtin_cd(char **argv)
5034 if (argv[1] == NULL) {
5035 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
5036 * bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
5038 newdir = getenv("HOME") ? : "/";
5041 if (chdir(newdir)) {
5042 printf("cd: %s: %s\n", newdir, strerror(errno));
5043 return EXIT_FAILURE;
5046 return EXIT_SUCCESS;
5049 static int builtin_exec(char **argv)
5051 if (argv[1] == NULL)
5052 return EXIT_SUCCESS; /* bash does this */
5057 // FIXME: if exec fails, bash does NOT exit! We do...
5058 pseudo_exec_argv(&dummy, argv + 1, 0, NULL);
5063 static int builtin_exit(char **argv)
5065 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
5066 //puts("exit"); /* bash does it */
5067 // TODO: warn if we have background jobs: "There are stopped jobs"
5068 // On second consecutive 'exit', exit anyway.
5069 if (argv[1] == NULL)
5070 hush_exit(G.last_return_code);
5071 /* mimic bash: exit 123abc == exit 255 + error msg */
5072 xfunc_error_retval = 255;
5073 /* bash: exit -2 == exit 254, no error msg */
5074 hush_exit(xatoi(argv[1]) & 0xff);
5077 static int builtin_export(char **argv)
5080 char *name = argv[1];
5084 // ash emits: export VAR='VAL'
5085 // bash: declare -x VAR="VAL"
5086 // (both also escape as needed (quotes, $, etc))
5091 return EXIT_SUCCESS;
5094 value = strchr(name, '=');
5096 /* They are exporting something without a =VALUE */
5097 struct variable *var;
5099 var = get_local_var(name);
5101 var->flg_export = 1;
5102 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
5103 putenv(var->varstr);
5105 /* bash does not return an error when trying to export
5106 * an undefined variable. Do likewise. */
5107 return EXIT_SUCCESS;
5110 set_local_var(xstrdup(name), 1);
5111 return EXIT_SUCCESS;
5115 /* built-in 'fg' and 'bg' handler */
5116 static int builtin_fg_bg(char **argv)
5121 if (!G_interactive_fd)
5122 return EXIT_FAILURE;
5123 /* If they gave us no args, assume they want the last backgrounded task */
5125 for (pi = G.job_list; pi; pi = pi->next) {
5126 if (pi->jobid == G.last_jobid) {
5130 bb_error_msg("%s: no current job", argv[0]);
5131 return EXIT_FAILURE;
5133 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
5134 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
5135 return EXIT_FAILURE;
5137 for (pi = G.job_list; pi; pi = pi->next) {
5138 if (pi->jobid == jobnum) {
5142 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
5143 return EXIT_FAILURE;
5145 // TODO: bash prints a string representation
5146 // of job being foregrounded (like "sleep 1 | cat")
5147 if (*argv[0] == 'f') {
5148 /* Put the job into the foreground. */
5149 tcsetpgrp(G_interactive_fd, pi->pgrp);
5152 /* Restart the processes in the job */
5153 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
5154 for (i = 0; i < pi->num_cmds; i++) {
5155 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
5156 pi->cmds[i].is_stopped = 0;
5158 pi->stopped_cmds = 0;
5160 i = kill(- pi->pgrp, SIGCONT);
5162 if (errno == ESRCH) {
5163 delete_finished_bg_job(pi);
5164 return EXIT_SUCCESS;
5166 bb_perror_msg("kill (SIGCONT)");
5170 if (*argv[0] == 'f') {
5172 return checkjobs_and_fg_shell(pi);
5174 return EXIT_SUCCESS;
5178 #if ENABLE_HUSH_HELP
5179 static int builtin_help(char **argv UNUSED_PARAM)
5181 const struct built_in_command *x;
5183 printf("\nBuilt-in commands:\n");
5184 printf("-------------------\n");
5185 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
5186 printf("%s\t%s\n", x->cmd, x->descr);
5189 return EXIT_SUCCESS;
5194 static int builtin_jobs(char **argv UNUSED_PARAM)
5197 const char *status_string;
5199 for (job = G.job_list; job; job = job->next) {
5200 if (job->alive_cmds == job->stopped_cmds)
5201 status_string = "Stopped";
5203 status_string = "Running";
5205 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
5207 return EXIT_SUCCESS;
5211 static int builtin_pwd(char **argv UNUSED_PARAM)
5214 return EXIT_SUCCESS;
5217 static int builtin_read(char **argv)
5220 const char *name = argv[1] ? argv[1] : "REPLY";
5222 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
5223 return set_local_var(string, 0);
5226 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
5227 * built-in 'set' handler
5229 * set [-abCefhmnuvx] [-o option] [argument...]
5230 * set [+abCefhmnuvx] [+o option] [argument...]
5231 * set -- [argument...]
5234 * Implementations shall support the options in both their hyphen and
5235 * plus-sign forms. These options can also be specified as options to sh.
5237 * Write out all variables and their values: set
5238 * Set $1, $2, and $3 and set "$#" to 3: set c a b
5239 * Turn on the -x and -v options: set -xv
5240 * Unset all positional parameters: set --
5241 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
5242 * Set the positional parameters to the expansion of x, even if x expands
5243 * with a leading '-' or '+': set -- $x
5245 * So far, we only support "set -- [argument...]" and some of the short names.
5247 static int builtin_set(char **argv)
5250 char **pp, **g_argv;
5251 char *arg = *++argv;
5255 for (e = G.top_var; e; e = e->next)
5257 return EXIT_SUCCESS;
5261 if (!strcmp(arg, "--")) {
5266 if (arg[0] == '+' || arg[0] == '-') {
5267 for (n = 1; arg[n]; ++n)
5268 if (set_mode(arg[0], arg[n]))
5274 } while ((arg = *++argv) != NULL);
5275 /* Now argv[0] is 1st argument */
5277 /* Only reset global_argv if we didn't process anything */
5279 return EXIT_SUCCESS;
5282 /* NB: G.global_argv[0] ($0) is never freed/changed */
5283 g_argv = G.global_argv;
5284 if (G.global_args_malloced) {
5290 G.global_args_malloced = 1;
5291 pp = xzalloc(sizeof(pp[0]) * 2);
5292 pp[0] = g_argv[0]; /* retain $0 */
5295 /* This realloc's G.global_argv */
5296 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
5303 return EXIT_SUCCESS;
5305 /* Nothing known, so abort */
5307 bb_error_msg("set: %s: invalid option", arg);
5308 return EXIT_FAILURE;
5311 static int builtin_shift(char **argv)
5317 if (n >= 0 && n < G.global_argc) {
5318 if (G.global_args_malloced) {
5321 free(G.global_argv[m++]);
5324 memmove(&G.global_argv[1], &G.global_argv[n+1],
5325 G.global_argc * sizeof(G.global_argv[0]));
5326 return EXIT_SUCCESS;
5328 return EXIT_FAILURE;
5331 static int builtin_source(char **argv)
5335 if (argv[1] == NULL)
5336 return EXIT_FAILURE;
5338 /* XXX search through $PATH is missing */
5339 input = fopen_for_read(argv[1]);
5341 bb_error_msg("can't open '%s'", argv[1]);
5342 return EXIT_FAILURE;
5344 close_on_exec_on(fileno(input));
5346 /* Now run the file */
5347 /* XXX argv and argc are broken; need to save old G.global_argv
5348 * (pointer only is OK!) on this stack frame,
5349 * set G.global_argv=argv+1, recurse, and restore. */
5350 parse_and_run_file(input);
5352 return G.last_return_code;
5355 static int builtin_umask(char **argv)
5358 const char *arg = argv[1];
5360 new_umask = bb_strtou(arg, NULL, 8);
5362 return EXIT_FAILURE;
5364 new_umask = umask(0);
5365 printf("%.3o\n", (unsigned) new_umask);
5368 return EXIT_SUCCESS;
5371 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
5372 static int builtin_unset(char **argv)
5379 return EXIT_SUCCESS;
5382 if (argv[1][0] == '-') {
5383 switch (argv[1][1]) {
5385 case 'f': if (ENABLE_HUSH_FUNCTIONS) { var = false; break; }
5387 bb_error_msg("unset: %s: invalid option", argv[1]);
5388 return EXIT_FAILURE;
5396 if (unset_local_var(argv[i]))
5399 #if ENABLE_HUSH_FUNCTIONS
5401 unset_local_func(argv[i]);
5407 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
5408 static int builtin_wait(char **argv)
5410 int ret = EXIT_SUCCESS;
5413 if (*++argv == NULL) {
5414 /* Don't care about wait results */
5415 /* Note 1: must wait until there are no more children */
5416 /* Note 2: must be interruptible */
5418 * $ sleep 3 & sleep 6 & wait
5423 * $ sleep 3 & sleep 6 & wait
5427 * ^C <-- after ~4 sec from keyboard
5430 sigaddset(&G.blocked_set, SIGCHLD);
5431 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5434 if (errno == ECHILD)
5436 /* Wait for SIGCHLD or any other signal of interest */
5437 /* sigtimedwait with infinite timeout: */
5438 sig = sigwaitinfo(&G.blocked_set, NULL);
5440 sig = check_and_run_traps(sig);
5441 if (sig && sig != SIGCHLD) { /* see note 2 */
5447 sigdelset(&G.blocked_set, SIGCHLD);
5448 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5452 /* This is probably buggy wrt interruptible-ness */
5454 pid_t pid = bb_strtou(*argv, NULL, 10);
5456 /* mimic bash message */
5457 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
5458 return EXIT_FAILURE;
5460 if (waitpid(pid, &status, 0) == pid) {
5461 if (WIFSIGNALED(status))
5462 ret = 128 + WTERMSIG(status);
5463 else if (WIFEXITED(status))
5464 ret = WEXITSTATUS(status);
5468 bb_perror_msg("wait %s", *argv);
5477 #if ENABLE_HUSH_LOOPS
5478 static int builtin_break(char **argv)
5480 if (G.depth_of_loop == 0) {
5481 bb_error_msg("%s: only meaningful in a loop", argv[0]);
5482 return EXIT_SUCCESS; /* bash compat */
5484 G.flag_break_continue++; /* BC_BREAK = 1 */
5485 G.depth_break_continue = 1;
5487 G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
5488 if (errno || !G.depth_break_continue || argv[2]) {
5489 bb_error_msg("%s: bad arguments", argv[0]);
5490 G.flag_break_continue = BC_BREAK;
5491 G.depth_break_continue = UINT_MAX;
5494 if (G.depth_of_loop < G.depth_break_continue)
5495 G.depth_break_continue = G.depth_of_loop;
5496 return EXIT_SUCCESS;
5499 static int builtin_continue(char **argv)
5501 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
5502 return builtin_break(argv);