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?
64 * maybe change charmap[] to use 2-bit entries
66 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
69 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
70 //TODO: pull in some .h and find out whether we have SINGLE_APPLET_MAIN?
71 //#include "applet_tables.h" doesn't work
73 /* #include <dmalloc.h> */
80 #define HUSH_VER_STR "0.92"
82 #if defined SINGLE_APPLET_MAIN
83 /* STANDALONE does not make sense, and won't compile */
84 #undef CONFIG_FEATURE_SH_STANDALONE
85 #undef ENABLE_FEATURE_SH_STANDALONE
86 #undef USE_FEATURE_SH_STANDALONE
87 #define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
88 #define ENABLE_FEATURE_SH_STANDALONE 0
89 #define USE_FEATURE_SH_STANDALONE(...)
90 #define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
93 #if !ENABLE_HUSH_INTERACTIVE
94 #undef ENABLE_FEATURE_EDITING
95 #define ENABLE_FEATURE_EDITING 0
96 #undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
97 #define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
100 /* Do we support ANY keywords? */
101 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
102 #define HAS_KEYWORDS 1
103 #define IF_HAS_KEYWORDS(...) __VA_ARGS__
104 #define IF_HAS_NO_KEYWORDS(...)
106 #define HAS_KEYWORDS 0
107 #define IF_HAS_KEYWORDS(...)
108 #define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
111 /* Keep unconditionally on for now */
114 #define ENABLE_HUSH_FUNCTIONS 0
117 /* If you comment out one of these below, it will be #defined later
118 * to perform debug printfs to stderr: */
119 #define debug_printf(...) do {} while (0)
120 /* Finer-grained debug switches */
121 #define debug_printf_parse(...) do {} while (0)
122 #define debug_print_tree(a, b) do {} while (0)
123 #define debug_printf_exec(...) do {} while (0)
124 #define debug_printf_env(...) do {} while (0)
125 #define debug_printf_jobs(...) do {} while (0)
126 #define debug_printf_expand(...) do {} while (0)
127 #define debug_printf_glob(...) do {} while (0)
128 #define debug_printf_list(...) do {} while (0)
129 #define debug_printf_subst(...) do {} while (0)
130 #define debug_printf_clean(...) do {} while (0)
133 #define debug_printf(...) fprintf(stderr, __VA_ARGS__)
136 #ifndef debug_printf_parse
137 #define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
140 #ifndef debug_printf_exec
141 #define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
144 #ifndef debug_printf_env
145 #define debug_printf_env(...) fprintf(stderr, __VA_ARGS__)
148 #ifndef debug_printf_jobs
149 #define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
155 #ifndef debug_printf_expand
156 #define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
157 #define DEBUG_EXPAND 1
159 #define DEBUG_EXPAND 0
162 #ifndef debug_printf_glob
163 #define debug_printf_glob(...) fprintf(stderr, __VA_ARGS__)
169 #ifndef debug_printf_list
170 #define debug_printf_list(...) fprintf(stderr, __VA_ARGS__)
173 #ifndef debug_printf_subst
174 #define debug_printf_subst(...) fprintf(stderr, __VA_ARGS__)
177 #ifndef debug_printf_clean
178 /* broken, of course, but OK for testing */
179 static const char *indenter(int i)
181 static const char blanks[] ALIGN1 =
183 return &blanks[sizeof(blanks) - i - 1];
185 #define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
186 #define DEBUG_CLEAN 1
190 static void debug_print_strings(const char *prefix, char **vv)
192 fprintf(stderr, "%s:\n", prefix);
194 fprintf(stderr, " '%s'\n", *vv++);
197 #define debug_print_strings(prefix, vv) ((void)0)
201 * Leak hunting. Use hush_leaktool.sh for post-processing.
203 #ifdef FOR_HUSH_LEAKTOOL
204 /* suppress "warning: no previous prototype..." */
205 void *xxmalloc(int lineno, size_t size);
206 void *xxrealloc(int lineno, void *ptr, size_t size);
207 char *xxstrdup(int lineno, const char *str);
208 void xxfree(void *ptr);
209 void *xxmalloc(int lineno, size_t size)
211 void *ptr = xmalloc((size + 0xff) & ~0xff);
212 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
215 void *xxrealloc(int lineno, void *ptr, size_t size)
217 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
218 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
221 char *xxstrdup(int lineno, const char *str)
223 char *ptr = xstrdup(str);
224 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
227 void xxfree(void *ptr)
229 fdprintf(2, "free %p\n", ptr);
232 #define xmalloc(s) xxmalloc(__LINE__, s)
233 #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
234 #define xstrdup(s) xxstrdup(__LINE__, s)
235 #define free(p) xxfree(p)
239 #define ERR_PTR ((void*)(long)1)
241 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="HUSH_VER_STR;
243 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
245 #define SPECIAL_VAR_SYMBOL 3
247 typedef enum redir_type {
249 REDIRECT_OVERWRITE = 2,
255 /* The descrip member of this structure is only used to make
256 * debugging output pretty */
257 static const struct {
259 signed char default_fd;
263 { O_RDONLY, 0, "<" },
264 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
265 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
266 { O_RDONLY, -1, "<<" },
270 typedef enum pipe_style {
277 typedef enum reserved_style {
286 #if ENABLE_HUSH_LOOPS
293 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
298 /* two pseudo-keywords support contrived "case" syntax: */
299 RES_MATCH , /* "word)" */
300 RES_CASEI , /* "this command is inside CASE" */
307 struct redir_struct {
308 struct redir_struct *next;
309 char *rd_filename; /* filename */
310 int fd; /* file descriptor being redirected */
311 int dup; /* -1, or file descriptor being duplicated */
312 smallint /*enum redir_type*/ rd_type;
316 pid_t pid; /* 0 if exited */
317 int assignment_cnt; /* how many argv[i] are assignments? */
318 smallint is_stopped; /* is the command currently running? */
319 smallint grp_type; /* GRP_xxx */
320 struct pipe *group; /* if non-NULL, this "prog" is {} group,
321 * subshell, or a compound statement */
322 char **argv; /* command name and arguments */
323 struct redir_struct *redirects; /* I/O redirections */
325 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
326 * and on execution these are substituted with their values.
327 * Substitution can make _several_ words out of one argv[n]!
328 * Example: argv[0]=='.^C*^C.' here: echo .$*.
329 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
332 #define GRP_SUBSHELL 1
333 #if ENABLE_HUSH_FUNCTIONS
334 #define GRP_FUNCTION 2
339 int num_cmds; /* total number of commands in job */
340 int alive_cmds; /* number of commands running (not exited) */
341 int stopped_cmds; /* number of commands alive, but stopped */
343 int jobid; /* job number */
344 pid_t pgrp; /* process group ID for the job */
345 char *cmdtext; /* name of job */
347 struct command *cmds; /* array of commands in pipe */
348 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
349 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
350 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
353 /* This holds pointers to the various results of parsing */
354 struct parse_context {
355 /* linked list of pipes */
356 struct pipe *list_head;
357 /* last pipe (being constructed right now) */
359 /* last command in pipe (being constructed right now) */
360 struct command *command;
361 /* last redirect in command->redirects list */
362 struct redir_struct *pending_redirect;
365 smallint ctx_inverted; /* "! cmd | cmd" */
367 smallint ctx_dsemicolon; /* ";;" seen */
369 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
371 /* group we are enclosed in:
372 * example 1: "{ { false; ..."
373 * example 2: "if true; then { false; ..."
374 * example 3: "if true; then if false; ..."
375 * when we find closing "}" / "fi" / whatever, we move list_head
376 * into stack->command->group and delete ourself.
378 struct parse_context *stack;
382 /* On program start, environ points to initial environment.
383 * putenv adds new pointers into it, unsetenv removes them.
384 * Neither of these (de)allocates the strings.
385 * setenv allocates new strings in malloc space and does putenv,
386 * and thus setenv is unusable (leaky) for shell's purposes */
387 #define setenv(...) setenv_is_leaky_dont_use()
389 struct variable *next;
390 char *varstr; /* points to "name=" portion */
391 int max_len; /* if > 0, name is part of initial env; else name is malloced */
392 smallint flg_export; /* putenv should be done on this var */
393 smallint flg_read_only;
396 typedef struct o_string {
398 int length; /* position where data is appended */
400 /* Protect newly added chars against globbing
401 * (by prepending \ to *, ?, [, \) */
405 smallint has_empty_slot;
406 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
409 MAYBE_ASSIGNMENT = 0,
410 DEFINITELY_ASSIGNMENT = 1,
412 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
414 /* Used for initialization: o_string foo = NULL_O_STRING; */
415 #define NULL_O_STRING { NULL }
417 /* I can almost use ordinary FILE*. Is open_memstream() universally
418 * available? Where is it documented? */
419 typedef struct in_str {
421 /* eof_flag=1: last char in ->p is really an EOF */
422 char eof_flag; /* meaningless if ->p == NULL */
424 #if ENABLE_HUSH_INTERACTIVE
426 smallint promptmode; /* 0: PS1, 1: PS2 */
429 int (*get) (struct in_str *);
430 int (*peek) (struct in_str *);
432 #define i_getch(input) ((input)->get(input))
433 #define i_peek(input) ((input)->peek(input))
437 CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
438 CHAR_IFS = 2, /* treated as ordinary if quoted */
439 CHAR_SPECIAL = 3, /* \, $, ", maybe ` */
448 /* "Globals" within this file */
449 /* Sorted roughly by size (smaller offsets == smaller code) */
451 #if ENABLE_HUSH_INTERACTIVE
452 /* 'interactive_fd' is a fd# open to ctty, if we have one
453 * _AND_ if we decided to act interactively */
457 #define G_interactive_fd (G.interactive_fd)
459 #define G_interactive_fd 0
461 #if ENABLE_FEATURE_EDITING
462 line_input_t *line_input_state;
468 pid_t saved_tty_pgrp;
470 struct pipe *job_list;
471 struct pipe *toplevel_list;
472 //// smallint ctrl_z_flag;
474 smallint flag_SIGINT;
475 #if ENABLE_HUSH_LOOPS
476 smallint flag_break_continue;
479 /* These four support $?, $#, and $1 */
480 smalluint last_return_code;
481 /* is global_argv and global_argv[1..n] malloced? (note: not [0]) */
482 smalluint global_args_malloced;
483 /* how many non-NULL argv's we have. NB: $# + 1 */
486 #if ENABLE_HUSH_LOOPS
487 unsigned depth_break_continue;
488 unsigned depth_of_loop;
492 struct variable *top_var; /* = &G.shell_ver (set in main()) */
493 struct variable shell_ver;
494 #if ENABLE_FEATURE_SH_STANDALONE
495 struct nofork_save_area nofork_save;
498 sigjmp_buf toplevel_jb;
500 unsigned char charmap[256];
501 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
502 /* Signal and trap handling */
503 // unsigned count_SIGCHLD;
504 // unsigned handled_SIGCHLD;
505 /* which signals have non-DFL handler (even with no traps set)? */
506 unsigned non_DFL_mask;
507 char **traps; /* char *traps[NSIG] */
508 sigset_t blocked_set;
509 sigset_t inherited_set;
511 #define G (*ptr_to_globals)
512 /* Not #defining name to G.name - this quickly gets unwieldy
513 * (too many defines). Also, I actually prefer to see when a variable
514 * is global, thus "G." prefix is a useful hint */
515 #define INIT_G() do { \
516 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
520 /* Function prototypes for builtins */
521 static int builtin_cd(char **argv);
522 static int builtin_echo(char **argv);
523 static int builtin_eval(char **argv);
524 static int builtin_exec(char **argv);
525 static int builtin_exit(char **argv);
526 static int builtin_export(char **argv);
528 static int builtin_fg_bg(char **argv);
529 static int builtin_jobs(char **argv);
532 static int builtin_help(char **argv);
534 static int builtin_pwd(char **argv);
535 static int builtin_read(char **argv);
536 static int builtin_test(char **argv);
537 static int builtin_trap(char **argv);
538 static int builtin_true(char **argv);
539 static int builtin_set(char **argv);
540 static int builtin_shift(char **argv);
541 static int builtin_source(char **argv);
542 static int builtin_umask(char **argv);
543 static int builtin_unset(char **argv);
544 static int builtin_wait(char **argv);
545 #if ENABLE_HUSH_LOOPS
546 static int builtin_break(char **argv);
547 static int builtin_continue(char **argv);
549 //static int builtin_not_written(char **argv);
551 /* Table of built-in functions. They can be forked or not, depending on
552 * context: within pipes, they fork. As simple commands, they do not.
553 * When used in non-forking context, they can change global variables
554 * in the parent shell process. If forked, of course they cannot.
555 * For example, 'unset foo | whatever' will parse and run, but foo will
556 * still be set at the end. */
557 struct built_in_command {
559 int (*function)(char **argv);
562 #define BLTIN(cmd, func, help) { cmd, func, help }
564 #define BLTIN(cmd, func, help) { cmd, func }
568 /* For now, echo and test are unconditionally enabled.
569 * Maybe make it configurable? */
570 static const struct built_in_command bltins[] = {
571 BLTIN("." , builtin_source, "Run commands in a file"),
572 BLTIN(":" , builtin_true, "No-op"),
573 BLTIN("[" , builtin_test, "Test condition"),
575 BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"),
577 #if ENABLE_HUSH_LOOPS
578 BLTIN("break" , builtin_break, "Exit from a loop"),
580 BLTIN("cd" , builtin_cd, "Change directory"),
581 #if ENABLE_HUSH_LOOPS
582 BLTIN("continue", builtin_continue, "Start new loop iteration"),
584 BLTIN("echo" , builtin_echo, "Write to stdout"),
585 BLTIN("eval" , builtin_eval, "Construct and run shell command"),
586 BLTIN("exec" , builtin_exec, "Execute command, don't return to shell"),
587 BLTIN("exit" , builtin_exit, "Exit"),
588 BLTIN("export", builtin_export, "Set environment variable"),
590 BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"),
591 BLTIN("jobs" , builtin_jobs, "List active jobs"),
593 BLTIN("pwd" , builtin_pwd, "Print current directory"),
594 BLTIN("read" , builtin_read, "Input environment variable"),
595 // BLTIN("return", builtin_not_written, "Return from a function"),
596 BLTIN("set" , builtin_set, "Set/unset shell local variables"),
597 BLTIN("shift" , builtin_shift, "Shift positional parameters"),
598 BLTIN("test" , builtin_test, "Test condition"),
599 BLTIN("trap" , builtin_trap, "Trap signals"),
600 // BLTIN("ulimit", builtin_not_written, "Control resource limits"),
601 BLTIN("umask" , builtin_umask, "Set file creation mask"),
602 BLTIN("unset" , builtin_unset, "Unset environment variable"),
603 BLTIN("wait" , builtin_wait, "Wait for process"),
605 BLTIN("help" , builtin_help, "List shell built-in commands"),
611 static void maybe_die(const char *notice, const char *msg)
613 /* Was using fancy stuff:
614 * (G_interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
615 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
616 void FAST_FUNC (*fp)(const char *s, ...) = bb_error_msg_and_die;
617 #if ENABLE_HUSH_INTERACTIVE
618 if (G_interactive_fd)
621 fp(msg ? "%s: %s" : notice, notice, msg);
624 #define syntax(msg) maybe_die("syntax error", msg);
626 /* Debug -- trick gcc to expand __LINE__ and convert to string */
627 #define __syntax(msg, line) maybe_die("syntax error hush.c:" # line, msg)
628 #define _syntax(msg, line) __syntax(msg, line)
629 #define syntax(msg) _syntax(msg, __LINE__)
632 static int glob_needed(const char *s)
637 if (*s == '*' || *s == '[' || *s == '?')
644 static int is_assignment(const char *s)
646 if (!s || !(isalpha(*s) || *s == '_'))
649 while (isalnum(*s) || *s == '_')
654 /* Replace each \x with x in place, return ptr past NUL. */
655 static char *unbackslash(char *src)
661 if ((*dst++ = *src++) == '\0')
667 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
688 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
689 v[count1 + count2] = NULL;
692 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
696 static char **add_string_to_strings(char **strings, char *add)
701 return add_strings_to_strings(strings, v, /*dup:*/ 0);
704 static void putenv_all(char **strings)
709 debug_printf_env("putenv '%s'\n", *strings);
714 static char **putenv_all_and_save_old(char **strings)
724 eq = strchr(*strings, '=');
727 v = getenv(*strings);
730 /* v points to VAL in VAR=VAL, go back to VAR */
731 v -= (eq - *strings) + 1;
732 old = add_string_to_strings(old, v);
741 static void free_strings_and_unsetenv(char **strings, int unset)
751 debug_printf_env("unsetenv '%s'\n", *v);
759 static void free_strings(char **strings)
761 free_strings_and_unsetenv(strings, 0);
765 /* Basic theory of signal handling in shell
766 * ========================================
767 * This does not describe what hush does, rather, it is current understanding
768 * what it _should_ do. If it doesn't, it's a bug.
769 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
771 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
772 * is finished or backgrounded. It is the same in interactive and
773 * non-interactive shells, and is the same regardless of whether
774 * a user trap handler is installed or a shell special one is in effect.
775 * ^C or ^Z from keyboard seem to execute "at once" because it usually
776 * backgrounds (i.e. stops) or kills all members of currently running
779 * Wait builtin in interruptible by signals for which user trap is set
780 * or by SIGINT in interactive shell.
782 * Trap handlers will execute even within trap handlers. (right?)
784 * User trap handlers are forgotten when subshell ("(cmd)") is entered. [TODO]
786 * If job control is off, backgrounded commands ("cmd &")
787 * have SIGINT, SIGQUIT set to SIG_IGN.
789 * Commands run in command substitution ("`cmd`")
790 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
792 * Ordinary commands have signals set to SIG_IGN/DFL set as inherited
793 * by the shell from its parent.
795 * Siganls which differ from SIG_DFL action
796 * (note: child (i.e., [v]forked) shell is not an interactive shell):
799 * SIGTERM (interactive): ignore
800 * SIGHUP (interactive):
801 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
802 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
803 * (note that ^Z is handled not by trapping SIGTSTP, but by seeing
804 * that all pipe members are stopped) (right?)
805 * SIGINT (interactive): wait for last pipe, ignore the rest
806 * of the command line, show prompt. NB: ^C does not send SIGINT
807 * to interactive shell while shell is waiting for a pipe,
808 * since shell is bg'ed (is not in foreground process group).
809 * (check/expand this)
810 * Example 1: this waits 5 sec, but does not execute ls:
811 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
812 * Example 2: this does not wait and does not execute ls:
813 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
814 * Example 3: this does not wait 5 sec, but executes ls:
815 * "sleep 5; ls -l" + press ^C
817 * (What happens to signals which are IGN on shell start?)
818 * (What happens with signal mask on shell start?)
820 * Implementation in hush
821 * ======================
822 * We use in-kernel pending signal mask to determine which signals were sent.
823 * We block all signals which we don't want to take action immediately,
824 * i.e. we block all signals which need to have special handling as described
825 * above, and all signals which have traps set.
826 * After each pipe execution, we extract any pending signals via sigtimedwait()
829 * unsigned non_DFL_mask: a mask of such "special" signals
830 * sigset_t blocked_set: current blocked signal set
833 * clear bit in blocked_set unless it is also in non_DFL
834 * "trap 'cmd' SIGxxx":
835 * set bit in blocked_set (even if 'cmd' is '')
836 * after [v]fork, if we plan to be a shell:
837 * nothing for {} child shell (say, "true | { true; true; } | true")
838 * unset all traps if () shell. [TODO]
839 * after [v]fork, if we plan to exec:
840 * POSIX says pending signal mask is cleared in child - no need to clear it.
841 * Restore blocked signal set to one inherited by shell just prior to exec.
843 * Note: as a result, we do not use signal handlers much. The only uses
844 * are to count SIGCHLDs [disabled - bug somewhere, + bloat]
845 * and to restore tty pgrp on signal-induced exit.
847 * TODO: check/fix wait builtin to be interruptible.
850 //static void SIGCHLD_handler(int sig UNUSED_PARAM)
852 // G.count_SIGCHLD++;
855 /* called once at shell init */
856 static void init_signal_mask(void)
859 unsigned mask = (1 << SIGQUIT);
860 if (G_interactive_fd) {
866 | (1 << SIGTTIN) | (1 << SIGTTOU) | (1 << SIGTSTP)
871 G.non_DFL_mask = mask;
873 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
877 sigaddset(&G.blocked_set, sig);
881 sigdelset(&G.blocked_set, SIGCHLD);
882 sigprocmask(SIG_SETMASK, &G.blocked_set, &G.inherited_set);
885 static int check_and_run_traps(int sig)
887 static const struct timespec zero_timespec = { 0, 0 };
888 smalluint save_rcode;
894 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
899 if (G.traps && G.traps[sig]) {
900 if (G.traps[sig][0]) {
901 /* We have user-defined handler */
902 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
903 save_rcode = G.last_return_code;
906 G.last_return_code = save_rcode;
907 } /* else: "" trap, ignoring signal */
910 /* not a trap: special action */
913 // G.count_SIGCHLD++;
922 default: /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
931 /* Restores tty foreground process group, and exits.
932 * May be called as signal handler for fatal signal
933 * (will faithfully resend signal to itself, producing correct exit state)
934 * or called directly with -EXITCODE.
935 * We also call it if xfunc is exiting. */
936 static void sigexit(int sig) NORETURN;
937 static void sigexit(int sig)
939 /* Disable all signals: job control, SIGPIPE, etc. */
940 sigprocmask_allsigs(SIG_BLOCK);
942 /* Careful: we can end up here after [v]fork. Do not restore
943 * tty pgrp then, only top-level shell process does that */
944 if (G_interactive_fd && getpid() == G.root_pid)
945 tcsetpgrp(G_interactive_fd, G.saved_tty_pgrp);
947 /* Not a signal, just exit */
951 kill_myself_with_sig(sig); /* does not return */
955 static void maybe_set_sighandler(int sig)
957 void (*handler)(int);
958 /* non_DFL_mask'ed signals are, well, masked,
959 * no need to set handler for them.
961 if (!((G.non_DFL_mask >> sig) & 1)) {
962 handler = signal(sig, sigexit);
963 if (handler == SIG_IGN) /* oops... restore back to IGN! */
964 signal(sig, handler);
967 /* Used only to set handler to restore pgrp on exit */
968 static void set_fatal_signals_to_sigexit(void)
971 maybe_set_sighandler(SIGILL );
972 maybe_set_sighandler(SIGFPE );
973 maybe_set_sighandler(SIGBUS );
974 maybe_set_sighandler(SIGSEGV);
975 maybe_set_sighandler(SIGTRAP);
976 } /* else: hush is perfect. what SEGV? */
978 maybe_set_sighandler(SIGABRT);
980 /* bash 3.2 seems to handle these just like 'fatal' ones */
981 maybe_set_sighandler(SIGPIPE);
982 maybe_set_sighandler(SIGALRM);
983 maybe_set_sighandler(SIGHUP );
985 /* if we aren't interactive... but in this case
986 * we never want to restore pgrp on exit, and this fn is not called */
987 /*maybe_set_sighandler(SIGTERM);*/
988 /*maybe_set_sighandler(SIGINT );*/
993 #define set_fatal_signals_to_sigexit(handler) ((void)0)
997 /* Restores tty foreground process group, and exits. */
998 static void hush_exit(int exitcode) NORETURN;
999 static void hush_exit(int exitcode)
1001 if (G.traps && G.traps[0] && G.traps[0][0]) {
1002 char *argv[] = { NULL, xstrdup(G.traps[0]), NULL };
1008 fflush(NULL); /* flush all streams */
1009 sigexit(- (exitcode & 0xff));
1016 static const char *set_cwd(void)
1018 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1019 * we must not try to free(bb_msg_unknown) */
1020 if (G.cwd == bb_msg_unknown)
1022 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1024 G.cwd = bb_msg_unknown;
1029 /* Get/check local shell variables */
1030 static struct variable *get_local_var(const char *name)
1032 struct variable *cur;
1038 for (cur = G.top_var; cur; cur = cur->next) {
1039 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1045 /* Basically useful version until someone wants to get fancier,
1046 * see the bash man page under "Parameter Expansion" */
1047 static const char *lookup_param(const char *src)
1049 struct variable *var = get_local_var(src);
1051 return strchr(var->varstr, '=') + 1;
1055 /* str holds "NAME=VAL" and is expected to be malloced.
1056 * We take ownership of it.
1057 * flg_export is used by:
1060 * -1: if NAME is set, leave export status alone
1061 * if NAME is not set, do not export
1063 static int set_local_var(char *str, int flg_export)
1065 struct variable *cur;
1069 value = strchr(str, '=');
1070 if (!value) { /* not expected to ever happen? */
1075 name_len = value - str + 1; /* including '=' */
1076 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
1078 if (strncmp(cur->varstr, str, name_len) != 0) {
1080 /* Bail out. Note that now cur points
1081 * to last var in linked list */
1087 /* We found an existing var with this name */
1089 if (cur->flg_read_only) {
1090 bb_error_msg("%s: readonly variable", str);
1094 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1095 unsetenv(str); /* just in case */
1097 if (strcmp(cur->varstr, str) == 0) {
1102 if (cur->max_len >= strlen(str)) {
1103 /* This one is from startup env, reuse space */
1104 strcpy(cur->varstr, str);
1107 /* max_len == 0 signifies "malloced" var, which we can
1108 * (and has to) free */
1112 goto set_str_and_exp;
1115 /* Not found - create next variable struct */
1116 cur->next = xzalloc(sizeof(*cur));
1122 if (flg_export == 1)
1123 cur->flg_export = 1;
1124 if (cur->flg_export) {
1125 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1126 return putenv(cur->varstr);
1131 static int unset_local_var(const char *name)
1133 struct variable *cur;
1134 struct variable *prev = prev; /* for gcc */
1138 return EXIT_SUCCESS;
1139 name_len = strlen(name);
1142 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1143 if (cur->flg_read_only) {
1144 bb_error_msg("%s: readonly variable", name);
1145 return EXIT_FAILURE;
1147 /* prev is ok to use here because 1st variable, HUSH_VERSION,
1148 * is ro, and we cannot reach this code on the 1st pass */
1149 prev->next = cur->next;
1150 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1151 bb_unsetenv(cur->varstr);
1155 return EXIT_SUCCESS;
1160 return EXIT_SUCCESS;
1163 #if ENABLE_SH_MATH_SUPPORT
1164 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1165 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1166 static char *endofname(const char *name)
1174 if (!is_in_name(*p))
1180 static void arith_set_local_var(const char *name, const char *val, int flags)
1182 /* arith code doesnt malloc space, so do it for it */
1183 char *var = xasprintf("%s=%s", name, val);
1184 set_local_var(var, flags);
1192 static int static_get(struct in_str *i)
1201 static int static_peek(struct in_str *i)
1206 #if ENABLE_HUSH_INTERACTIVE
1208 static void cmdedit_set_initial_prompt(void)
1210 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1211 G.PS1 = getenv("PS1");
1218 static const char* setup_prompt_string(int promptmode)
1220 const char *prompt_str;
1221 debug_printf("setup_prompt_string %d ", promptmode);
1222 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1223 /* Set up the prompt */
1224 if (promptmode == 0) { /* PS1 */
1226 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1231 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1232 debug_printf("result '%s'\n", prompt_str);
1236 static void get_user_input(struct in_str *i)
1239 const char *prompt_str;
1241 prompt_str = setup_prompt_string(i->promptmode);
1242 #if ENABLE_FEATURE_EDITING
1243 /* Enable command line editing only while a command line
1244 * is actually being read */
1247 /* buglet: SIGINT will not make new prompt to appear _at once_,
1248 * only after <Enter>. (^C will work) */
1249 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1250 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1251 check_and_run_traps(0);
1252 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1253 i->eof_flag = (r < 0);
1254 if (i->eof_flag) { /* EOF/error detected */
1255 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1256 G.user_input_buf[1] = '\0';
1261 fputs(prompt_str, stdout);
1263 G.user_input_buf[0] = r = fgetc(i->file);
1264 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1265 //do we need check_and_run_traps(0)? (maybe only if stdin)
1266 } while (G.flag_SIGINT);
1267 i->eof_flag = (r == EOF);
1269 i->p = G.user_input_buf;
1272 #endif /* INTERACTIVE */
1274 /* This is the magic location that prints prompts
1275 * and gets data back from the user */
1276 static int file_get(struct in_str *i)
1280 /* If there is data waiting, eat it up */
1281 if (i->p && *i->p) {
1282 #if ENABLE_HUSH_INTERACTIVE
1286 if (i->eof_flag && !*i->p)
1289 /* need to double check i->file because we might be doing something
1290 * more complicated by now, like sourcing or substituting. */
1291 #if ENABLE_HUSH_INTERACTIVE
1292 if (G_interactive_fd && i->promptme && i->file == stdin) {
1295 } while (!*i->p); /* need non-empty line */
1296 i->promptmode = 1; /* PS2 */
1301 ch = fgetc(i->file);
1303 debug_printf("file_get: got a '%c' %d\n", ch, ch);
1304 #if ENABLE_HUSH_INTERACTIVE
1311 /* All the callers guarantee this routine will never be
1312 * used right after a newline, so prompting is not needed.
1314 static int file_peek(struct in_str *i)
1317 if (i->p && *i->p) {
1318 if (i->eof_flag && !i->p[1])
1322 ch = fgetc(i->file);
1323 i->eof_flag = (ch == EOF);
1324 i->peek_buf[0] = ch;
1325 i->peek_buf[1] = '\0';
1327 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
1331 static void setup_file_in_str(struct in_str *i, FILE *f)
1333 i->peek = file_peek;
1335 #if ENABLE_HUSH_INTERACTIVE
1337 i->promptmode = 0; /* PS1 */
1343 static void setup_string_in_str(struct in_str *i, const char *s)
1345 i->peek = static_peek;
1346 i->get = static_get;
1347 #if ENABLE_HUSH_INTERACTIVE
1349 i->promptmode = 0; /* PS1 */
1359 #define B_CHUNK (32 * sizeof(char*))
1361 static void o_reset(o_string *o)
1369 static void o_free(o_string *o)
1372 memset(o, 0, sizeof(*o));
1375 static void o_grow_by(o_string *o, int len)
1377 if (o->length + len > o->maxlen) {
1378 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1379 o->data = xrealloc(o->data, 1 + o->maxlen);
1383 static void o_addchr(o_string *o, int ch)
1385 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1387 o->data[o->length] = ch;
1389 o->data[o->length] = '\0';
1392 static void o_addstr(o_string *o, const char *str, int len)
1395 memcpy(&o->data[o->length], str, len);
1397 o->data[o->length] = '\0';
1400 static void o_addstrauto(o_string *o, const char *str)
1402 o_addstr(o, str, strlen(str) + 1);
1405 static void o_addstr_duplicate_backslash(o_string *o, const char *str, int len)
1410 && (*str != '*' && *str != '?' && *str != '[')
1418 /* My analysis of quoting semantics tells me that state information
1419 * is associated with a destination, not a source.
1421 static void o_addqchr(o_string *o, int ch)
1424 char *found = strchr("*?[\\", ch);
1429 o->data[o->length] = '\\';
1432 o->data[o->length] = ch;
1434 o->data[o->length] = '\0';
1437 static void o_addQchr(o_string *o, int ch)
1440 if (o->o_escape && strchr("*?[\\", ch)) {
1442 o->data[o->length] = '\\';
1446 o->data[o->length] = ch;
1448 o->data[o->length] = '\0';
1451 static void o_addQstr(o_string *o, const char *str, int len)
1454 o_addstr(o, str, len);
1460 int ordinary_cnt = strcspn(str, "*?[\\");
1461 if (ordinary_cnt > len) /* paranoia */
1463 o_addstr(o, str, ordinary_cnt);
1464 if (ordinary_cnt == len)
1466 str += ordinary_cnt;
1467 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
1471 if (ch) { /* it is necessarily one of "*?[\\" */
1473 o->data[o->length] = '\\';
1477 o->data[o->length] = ch;
1479 o->data[o->length] = '\0';
1483 /* A special kind of o_string for $VAR and `cmd` expansion.
1484 * It contains char* list[] at the beginning, which is grown in 16 element
1485 * increments. Actual string data starts at the next multiple of 16 * (char*).
1486 * list[i] contains an INDEX (int!) into this string data.
1487 * It means that if list[] needs to grow, data needs to be moved higher up
1488 * but list[i]'s need not be modified.
1489 * NB: remembering how many list[i]'s you have there is crucial.
1490 * o_finalize_list() operation post-processes this structure - calculates
1491 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1493 #if DEBUG_EXPAND || DEBUG_GLOB
1494 static void debug_print_list(const char *prefix, o_string *o, int n)
1496 char **list = (char**)o->data;
1497 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1499 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1500 prefix, list, n, string_start, o->length, o->maxlen);
1502 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1503 o->data + (int)list[i] + string_start,
1504 o->data + (int)list[i] + string_start);
1508 const char *p = o->data + (int)list[n - 1] + string_start;
1509 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
1513 #define debug_print_list(prefix, o, n) ((void)0)
1516 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1517 * in list[n] so that it points past last stored byte so far.
1518 * It returns n+1. */
1519 static int o_save_ptr_helper(o_string *o, int n)
1521 char **list = (char**)o->data;
1525 if (!o->has_empty_slot) {
1526 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1527 string_len = o->length - string_start;
1528 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1529 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
1530 /* list[n] points to string_start, make space for 16 more pointers */
1531 o->maxlen += 0x10 * sizeof(list[0]);
1532 o->data = xrealloc(o->data, o->maxlen + 1);
1533 list = (char**)o->data;
1534 memmove(list + n + 0x10, list + n, string_len);
1535 o->length += 0x10 * sizeof(list[0]);
1537 debug_printf_list("list[%d]=%d string_start=%d\n", n, string_len, string_start);
1539 /* We have empty slot at list[n], reuse without growth */
1540 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1541 string_len = o->length - string_start;
1542 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n", n, string_len, string_start);
1543 o->has_empty_slot = 0;
1545 list[n] = (char*)(ptrdiff_t)string_len;
1549 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
1550 static int o_get_last_ptr(o_string *o, int n)
1552 char **list = (char**)o->data;
1553 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1555 return ((int)(ptrdiff_t)list[n-1]) + string_start;
1558 /* o_glob performs globbing on last list[], saving each result
1559 * as a new list[]. */
1560 static int o_glob(o_string *o, int n)
1566 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
1568 return o_save_ptr_helper(o, n);
1569 pattern = o->data + o_get_last_ptr(o, n);
1570 debug_printf_glob("glob pattern '%s'\n", pattern);
1571 if (!glob_needed(pattern)) {
1573 o->length = unbackslash(pattern) - o->data;
1574 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
1575 return o_save_ptr_helper(o, n);
1578 memset(&globdata, 0, sizeof(globdata));
1579 gr = glob(pattern, 0, NULL, &globdata);
1580 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1581 if (gr == GLOB_NOSPACE)
1582 bb_error_msg_and_die("out of memory during glob");
1583 if (gr == GLOB_NOMATCH) {
1584 globfree(&globdata);
1587 if (gr != 0) { /* GLOB_ABORTED ? */
1588 //TODO: testcase for bad glob pattern behavior
1589 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1591 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1592 char **argv = globdata.gl_pathv;
1593 o->length = pattern - o->data; /* "forget" pattern */
1595 o_addstrauto(o, *argv);
1596 n = o_save_ptr_helper(o, n);
1602 globfree(&globdata);
1604 debug_print_list("o_glob returning", o, n);
1608 /* If o->o_glob == 1, glob the string so far remembered.
1609 * Otherwise, just finish current list[] and start new */
1610 static int o_save_ptr(o_string *o, int n)
1612 if (o->o_glob) { /* if globbing is requested */
1613 /* If o->has_empty_slot, list[n] was already globbed
1614 * (if it was requested back then when it was filled)
1615 * so don't do that again! */
1616 if (!o->has_empty_slot)
1617 return o_glob(o, n); /* o_save_ptr_helper is inside */
1619 return o_save_ptr_helper(o, n);
1622 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
1623 static char **o_finalize_list(o_string *o, int n)
1628 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1630 debug_print_list("finalized", o, n);
1631 debug_printf_expand("finalized n:%d\n", n);
1632 list = (char**)o->data;
1633 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1637 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
1643 /* Expansion can recurse */
1644 #if ENABLE_HUSH_TICK
1645 static int process_command_subs(o_string *dest, const char *s);
1647 static char *expand_string_to_string(const char *str);
1648 static int parse_stream_dquoted(o_string *dest, struct in_str *input, int dquote_end);
1650 /* expand_strvec_to_strvec() takes a list of strings, expands
1651 * all variable references within and returns a pointer to
1652 * a list of expanded strings, possibly with larger number
1653 * of strings. (Think VAR="a b"; echo $VAR).
1654 * This new list is allocated as a single malloc block.
1655 * NULL-terminated list of char* pointers is at the beginning of it,
1656 * followed by strings themself.
1657 * Caller can deallocate entire list by single free(list). */
1659 /* Store given string, finalizing the word and starting new one whenever
1660 * we encounter IFS char(s). This is used for expanding variable values.
1661 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
1662 static int expand_on_ifs(o_string *output, int n, const char *str)
1665 int word_len = strcspn(str, G.ifs);
1667 if (output->o_escape || !output->o_glob)
1668 o_addQstr(output, str, word_len);
1669 else /* protect backslashes against globbing up :) */
1670 o_addstr_duplicate_backslash(output, str, word_len);
1673 if (!*str) /* EOL - do not finalize word */
1675 o_addchr(output, '\0');
1676 debug_print_list("expand_on_ifs", output, n);
1677 n = o_save_ptr(output, n);
1678 str += strspn(str, G.ifs); /* skip ifs chars */
1680 debug_print_list("expand_on_ifs[1]", output, n);
1684 /* Expand all variable references in given string, adding words to list[]
1685 * at n, n+1,... positions. Return updated n (so that list[n] is next one
1686 * to be filled). This routine is extremely tricky: has to deal with
1687 * variables/parameters with whitespace, $* and $@, and constructs like
1688 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
1689 static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
1691 /* or_mask is either 0 (normal case) or 0x80
1692 * (expansion of right-hand side of assignment == 1-element expand.
1693 * It will also do no globbing, and thus we must not backslash-quote!) */
1695 char first_ch, ored_ch;
1702 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
1703 debug_print_list("expand_vars_to_list", output, n);
1704 n = o_save_ptr(output, n);
1705 debug_print_list("expand_vars_to_list[0]", output, n);
1707 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
1708 #if ENABLE_HUSH_TICK
1709 o_string subst_result = NULL_O_STRING;
1711 #if ENABLE_SH_MATH_SUPPORT
1712 char arith_buf[sizeof(arith_t)*3 + 2];
1714 o_addstr(output, arg, p - arg);
1715 debug_print_list("expand_vars_to_list[1]", output, n);
1717 p = strchr(p, SPECIAL_VAR_SYMBOL);
1719 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
1720 /* "$@" is special. Even if quoted, it can still
1721 * expand to nothing (not even an empty string) */
1722 if ((first_ch & 0x7f) != '@')
1723 ored_ch |= first_ch;
1726 switch (first_ch & 0x7f) {
1727 /* Highest bit in first_ch indicates that var is double-quoted */
1729 val = utoa(G.root_pid);
1731 case '!': /* bg pid */
1732 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
1734 case '?': /* exitcode */
1735 val = utoa(G.last_return_code);
1737 case '#': /* argc */
1738 if (arg[1] != SPECIAL_VAR_SYMBOL)
1739 /* actually, it's a ${#var} */
1741 val = utoa(G.global_argc ? G.global_argc-1 : 0);
1746 if (!G.global_argv[i])
1748 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
1749 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
1750 smallint sv = output->o_escape;
1751 /* unquoted var's contents should be globbed, so don't escape */
1752 output->o_escape = 0;
1753 while (G.global_argv[i]) {
1754 n = expand_on_ifs(output, n, G.global_argv[i]);
1755 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
1756 if (G.global_argv[i++][0] && G.global_argv[i]) {
1757 /* this argv[] is not empty and not last:
1758 * put terminating NUL, start new word */
1759 o_addchr(output, '\0');
1760 debug_print_list("expand_vars_to_list[2]", output, n);
1761 n = o_save_ptr(output, n);
1762 debug_print_list("expand_vars_to_list[3]", output, n);
1765 output->o_escape = sv;
1767 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
1768 * and in this case should treat it like '$*' - see 'else...' below */
1769 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
1771 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1772 if (++i >= G.global_argc)
1774 o_addchr(output, '\0');
1775 debug_print_list("expand_vars_to_list[4]", output, n);
1776 n = o_save_ptr(output, n);
1778 } else { /* quoted $*: add as one word */
1780 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1781 if (!G.global_argv[++i])
1784 o_addchr(output, G.ifs[0]);
1788 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
1789 /* "Empty variable", used to make "" etc to not disappear */
1793 #if ENABLE_HUSH_TICK
1794 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
1797 //TODO: can we just stuff it into "output" directly?
1798 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
1799 process_command_subs(&subst_result, arg);
1800 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
1801 val = subst_result.data;
1804 #if ENABLE_SH_MATH_SUPPORT
1805 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
1806 arith_eval_hooks_t hooks;
1811 arg++; /* skip '+' */
1812 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
1813 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
1815 /* Optional: skip expansion if expr is simple ("a + 3", "i++" etc) */
1818 unsigned char c = *exp_str++;
1825 if (strchr(" \t+-*/%_", c) != NULL)
1827 c |= 0x20; /* tolower */
1828 if (c >= 'a' && c <= 'z')
1832 /* We need to expand. Example: "echo $(($a + 1)) $((1 + $((2)) ))" */
1834 struct in_str input;
1835 o_string dest = NULL_O_STRING;
1837 setup_string_in_str(&input, arg);
1838 parse_stream_dquoted(&dest, &input, EOF);
1839 //bb_error_msg("'%s' -> '%s'", arg, dest.data);
1840 exp_str = expand_string_to_string(dest.data);
1841 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
1845 hooks.lookupvar = lookup_param;
1846 hooks.setvar = arith_set_local_var;
1847 hooks.endofname = endofname;
1848 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
1853 case -3: maybe_die("arith", "exponent less than 0"); break;
1854 case -2: maybe_die("arith", "divide by zero"); break;
1855 case -5: maybe_die("arith", "expression recursion loop detected"); break;
1856 default: maybe_die("arith", "syntax error"); break;
1859 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
1860 sprintf(arith_buf, arith_t_fmt, res);
1865 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
1867 bool exp_len = false, exp_null = false;
1868 char *var = arg, exp_save, exp_op, *exp_word;
1871 arg[0] = first_ch & 0x7f;
1873 /* prepare for expansions */
1874 if (var[0] == '#') {
1875 /* handle length expansion ${#var} */
1879 /* maybe handle parameter expansion */
1880 exp_off = strcspn(var, ":-=+?");
1884 exp_save = var[exp_off];
1885 exp_null = exp_save == ':';
1886 exp_word = var + exp_off;
1887 if (exp_null) ++exp_word;
1888 exp_op = *exp_word++;
1889 var[exp_off] = '\0';
1893 /* lookup the variable in question */
1894 if (isdigit(var[0])) {
1895 /* handle_dollar() should have vetted var for us */
1897 if (i < G.global_argc)
1898 val = G.global_argv[i];
1899 /* else val remains NULL: $N with too big N */
1901 val = lookup_param(var);
1903 /* handle any expansions */
1905 debug_printf_expand("expand: length of '%s' = ", val);
1906 val = utoa(val ? strlen(val) : 0);
1907 debug_printf_expand("%s\n", val);
1908 } else if (exp_off) {
1909 /* we need to do an expansion */
1910 int exp_test = (!val || (exp_null && !val[0]));
1912 exp_test = !exp_test;
1913 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
1914 exp_null ? "true" : "false", exp_test);
1917 maybe_die(var, *exp_word ? exp_word : "parameter null or not set");
1921 if (exp_op == '=') {
1922 if (isdigit(var[0]) || var[0] == '#') {
1923 maybe_die(var, "special vars cannot assign in this way");
1926 char *new_var = xmalloc(strlen(var) + strlen(val) + 2);
1927 sprintf(new_var, "%s=%s", var, val);
1928 set_local_var(new_var, -1);
1932 var[exp_off] = exp_save;
1937 #if ENABLE_HUSH_TICK
1940 if (!(first_ch & 0x80)) { /* unquoted $VAR */
1941 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
1943 /* unquoted var's contents should be globbed, so don't escape */
1944 smallint sv = output->o_escape;
1945 output->o_escape = 0;
1946 n = expand_on_ifs(output, n, val);
1948 output->o_escape = sv;
1950 } else { /* quoted $VAR, val will be appended below */
1951 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
1954 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
1956 o_addQstr(output, val, strlen(val));
1958 /* Do the check to avoid writing to a const string */
1959 if (*p != SPECIAL_VAR_SYMBOL)
1960 *p = SPECIAL_VAR_SYMBOL;
1962 #if ENABLE_HUSH_TICK
1963 o_free(&subst_result);
1966 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
1969 debug_print_list("expand_vars_to_list[a]", output, n);
1970 /* this part is literal, and it was already pre-quoted
1971 * if needed (much earlier), do not use o_addQstr here! */
1972 o_addstrauto(output, arg);
1973 debug_print_list("expand_vars_to_list[b]", output, n);
1974 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
1975 && !(ored_ch & 0x80) /* and all vars were not quoted. */
1978 /* allow to reuse list[n] later without re-growth */
1979 output->has_empty_slot = 1;
1981 o_addchr(output, '\0');
1986 static char **expand_variables(char **argv, int or_mask)
1991 o_string output = NULL_O_STRING;
1993 if (or_mask & 0x100) {
1994 output.o_escape = 1; /* protect against globbing for "$var" */
1995 /* (unquoted $var will temporarily switch it off) */
2002 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
2005 debug_print_list("expand_variables", &output, n);
2007 /* output.data (malloced in one block) gets returned in "list" */
2008 list = o_finalize_list(&output, n);
2009 debug_print_strings("expand_variables[1]", list);
2013 static char **expand_strvec_to_strvec(char **argv)
2015 return expand_variables(argv, 0x100);
2018 /* Used for expansion of right hand of assignments */
2019 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2021 static char *expand_string_to_string(const char *str)
2023 char *argv[2], **list;
2025 argv[0] = (char*)str;
2027 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2029 if (!list[0] || list[1])
2030 bb_error_msg_and_die("BUG in varexp2");
2031 /* actually, just move string 2*sizeof(char*) bytes back */
2032 overlapping_strcpy((char*)list, list[0]);
2033 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2037 /* Used for "eval" builtin */
2038 static char* expand_strvec_to_string(char **argv)
2042 list = expand_variables(argv, 0x80);
2043 /* Convert all NULs to spaces */
2048 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2049 bb_error_msg_and_die("BUG in varexp3");
2050 list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
2054 overlapping_strcpy((char*)list, list[0]);
2055 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2059 static char **expand_assignments(char **argv, int count)
2063 /* Expand assignments into one string each */
2064 for (i = 0; i < count; i++) {
2065 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2071 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
2072 * and stderr if they are redirected. */
2073 static int setup_redirects(struct command *prog, int squirrel[])
2076 struct redir_struct *redir;
2078 for (redir = prog->redirects; redir; redir = redir->next) {
2079 if (redir->dup == -1 && redir->rd_filename == NULL) {
2080 /* something went wrong in the parse. Pretend it didn't happen */
2083 if (redir->dup == -1) {
2085 mode = redir_table[redir->rd_type].mode;
2086 //TODO: check redir for names like '\\'
2087 p = expand_string_to_string(redir->rd_filename);
2088 openfd = open_or_warn(p, mode);
2091 /* this could get lost if stderr has been redirected, but
2092 bash and ash both lose it as well (though zsh doesn't!) */
2096 openfd = redir->dup;
2099 if (openfd != redir->fd) {
2100 if (squirrel && redir->fd < 3) {
2101 squirrel[redir->fd] = dup(redir->fd);
2104 //close(openfd); // close(-3) ??!
2106 dup2(openfd, redir->fd);
2107 if (redir->dup == -1)
2115 static void restore_redirects(int squirrel[])
2118 for (i = 0; i < 3; i++) {
2121 /* We simply die on error */
2128 #if !defined(DEBUG_CLEAN)
2129 #define free_pipe_list(head, indent) free_pipe_list(head)
2130 #define free_pipe(pi, indent) free_pipe(pi)
2132 static void free_pipe_list(struct pipe *head, int indent);
2134 /* return code is the exit status of the pipe */
2135 static void free_pipe(struct pipe *pi, int indent)
2138 struct command *command;
2139 struct redir_struct *r, *rnext;
2142 if (pi->stopped_cmds > 0)
2144 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2145 for (i = 0; i < pi->num_cmds; i++) {
2146 command = &pi->cmds[i];
2147 debug_printf_clean("%s command %d:\n", indenter(indent), i);
2148 if (command->argv) {
2149 for (a = 0, p = command->argv; *p; a++, p++) {
2150 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
2152 free_strings(command->argv);
2153 command->argv = NULL;
2155 /* not "else if": on syntax error, we may have both! */
2156 if (command->group) {
2157 debug_printf_clean("%s begin group (grp_type:%d)\n", indenter(indent), command->grp_type);
2158 free_pipe_list(command->group, indent+3);
2159 debug_printf_clean("%s end group\n", indenter(indent));
2160 command->group = NULL;
2162 for (r = command->redirects; r; r = rnext) {
2163 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->rd_type].descrip);
2165 /* guard against the case >$FOO, where foo is unset or blank */
2166 if (r->rd_filename) {
2167 debug_printf_clean(" %s\n", r->rd_filename);
2168 free(r->rd_filename);
2169 r->rd_filename = NULL;
2172 debug_printf_clean("&%d\n", r->dup);
2177 command->redirects = NULL;
2179 free(pi->cmds); /* children are an array, they get freed all at once */
2187 static void free_pipe_list(struct pipe *head, int indent)
2189 struct pipe *pi, *next;
2191 for (pi = head; pi; pi = next) {
2193 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
2195 free_pipe(pi, indent);
2196 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
2198 /*pi->next = NULL;*/
2205 typedef struct nommu_save_t {
2211 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
2212 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
2213 #define pseudo_exec(nommu_save, command, argv_expanded) \
2214 pseudo_exec(command, argv_expanded)
2217 /* Called after [v]fork() in run_pipe(), or from builtin_exec().
2219 * XXX no exit() here. If you don't exec, use _exit instead.
2220 * The at_exit handlers apparently confuse the calling process,
2221 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
2222 static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded) NORETURN;
2223 static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded)
2227 const struct built_in_command *x;
2229 /* If a variable is assigned in a forest, and nobody listens,
2230 * was it ever really set?
2232 if (!argv[assignment_cnt])
2233 _exit(EXIT_SUCCESS);
2235 new_env = expand_assignments(argv, assignment_cnt);
2237 putenv_all(new_env);
2238 free(new_env); /* optional */
2240 nommu_save->new_env = new_env;
2241 nommu_save->old_env = putenv_all_and_save_old(new_env);
2243 if (argv_expanded) {
2244 argv = argv_expanded;
2246 argv = expand_strvec_to_strvec(argv + assignment_cnt);
2248 nommu_save->argv = argv;
2253 * Check if the command matches any of the builtins.
2254 * Depending on context, this might be redundant. But it's
2255 * easier to waste a few CPU cycles than it is to figure out
2256 * if this is one of those cases.
2258 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2259 if (strcmp(argv[0], x->cmd) == 0) {
2260 debug_printf_exec("running builtin '%s'\n", argv[0]);
2261 rcode = x->function(argv);
2267 /* Check if the command matches any busybox applets */
2268 #if ENABLE_FEATURE_SH_STANDALONE
2269 if (strchr(argv[0], '/') == NULL) {
2270 int a = find_applet_by_name(argv[0]);
2272 if (APPLET_IS_NOEXEC(a)) {
2273 debug_printf_exec("running applet '%s'\n", argv[0]);
2274 // is it ok that run_applet_no_and_exit() does exit(), not _exit()?
2275 run_applet_no_and_exit(a, argv);
2277 /* re-exec ourselves with the new arguments */
2278 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
2279 execvp(bb_busybox_exec_path, argv);
2280 /* If they called chroot or otherwise made the binary no longer
2281 * executable, fall through */
2286 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2288 debug_printf_exec("execing '%s'\n", argv[0]);
2289 execvp(argv[0], argv);
2290 bb_perror_msg("can't exec '%s'", argv[0]);
2291 _exit(EXIT_FAILURE);
2294 static int run_list(struct pipe *pi);
2296 /* Called after [v]fork() in run_pipe()
2298 static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded) NORETURN;
2299 static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded)
2302 pseudo_exec_argv(nommu_save, command->argv, command->assignment_cnt, argv_expanded);
2304 if (command->group) {
2306 bb_error_msg_and_die("nested lists are not supported on NOMMU");
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 */
2317 /* Can happen. See what bash does with ">foo" by itself. */
2318 debug_printf("trying to pseudo_exec null command\n");
2319 _exit(EXIT_SUCCESS);
2323 static const char *get_cmdtext(struct pipe *pi)
2329 /* This is subtle. ->cmdtext is created only on first backgrounding.
2330 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
2331 * On subsequent bg argv is trashed, but we won't use it */
2334 argv = pi->cmds[0].argv;
2335 if (!argv || !argv[0]) {
2336 pi->cmdtext = xzalloc(1);
2341 do len += strlen(*argv) + 1; while (*++argv);
2342 pi->cmdtext = p = xmalloc(len);
2343 argv = pi->cmds[0].argv;
2345 len = strlen(*argv);
2346 memcpy(p, *argv, len);
2354 static void insert_bg_job(struct pipe *pi)
2356 struct pipe *thejob;
2359 /* Linear search for the ID of the job to use */
2361 for (thejob = G.job_list; thejob; thejob = thejob->next)
2362 if (thejob->jobid >= pi->jobid)
2363 pi->jobid = thejob->jobid + 1;
2365 /* Add thejob to the list of running jobs */
2367 thejob = G.job_list = xmalloc(sizeof(*thejob));
2369 for (thejob = G.job_list; thejob->next; thejob = thejob->next)
2371 thejob->next = xmalloc(sizeof(*thejob));
2372 thejob = thejob->next;
2375 /* Physically copy the struct job */
2376 memcpy(thejob, pi, sizeof(struct pipe));
2377 thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
2378 /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
2379 for (i = 0; i < pi->num_cmds; i++) {
2380 // TODO: do we really need to have so many fields which are just dead weight
2381 // at execution stage?
2382 thejob->cmds[i].pid = pi->cmds[i].pid;
2383 /* all other fields are not used and stay zero */
2385 thejob->next = NULL;
2386 thejob->cmdtext = xstrdup(get_cmdtext(pi));
2388 /* We don't wait for background thejobs to return -- append it
2389 to the list of backgrounded thejobs and leave it alone */
2390 if (G_interactive_fd)
2391 printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
2392 G.last_bg_pid = thejob->cmds[0].pid;
2393 G.last_jobid = thejob->jobid;
2396 static void remove_bg_job(struct pipe *pi)
2398 struct pipe *prev_pipe;
2400 if (pi == G.job_list) {
2401 G.job_list = pi->next;
2403 prev_pipe = G.job_list;
2404 while (prev_pipe->next != pi)
2405 prev_pipe = prev_pipe->next;
2406 prev_pipe->next = pi->next;
2409 G.last_jobid = G.job_list->jobid;
2414 /* Remove a backgrounded job */
2415 static void delete_finished_bg_job(struct pipe *pi)
2418 pi->stopped_cmds = 0;
2424 /* Check to see if any processes have exited -- if they
2425 * have, figure out why and see if a job has completed */
2426 static int checkjobs(struct pipe* fg_pipe)
2436 debug_printf_jobs("checkjobs %p\n", fg_pipe);
2439 // if (G.handled_SIGCHLD == G.count_SIGCHLD)
2440 // /* avoid doing syscall, nothing there anyway */
2443 attributes = WUNTRACED;
2444 if (fg_pipe == NULL)
2445 attributes |= WNOHANG;
2447 /* Do we do this right?
2448 * bash-3.00# sleep 20 | false
2450 * [3]+ Stopped sleep 20 | false
2451 * bash-3.00# echo $?
2452 * 1 <========== bg pipe is not fully done, but exitcode is already known!
2455 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
2456 //are stopped. Testcase: "cat | cat" in a script (not on command line)
2457 // + killall -STOP cat
2464 // i = G.count_SIGCHLD;
2465 childpid = waitpid(-1, &status, attributes);
2466 if (childpid <= 0) {
2467 if (childpid && errno != ECHILD)
2468 bb_perror_msg("waitpid");
2469 // else /* Until next SIGCHLD, waitpid's are useless */
2470 // G.handled_SIGCHLD = i;
2473 dead = WIFEXITED(status) || WIFSIGNALED(status);
2476 if (WIFSTOPPED(status))
2477 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
2478 childpid, WSTOPSIG(status), WEXITSTATUS(status));
2479 if (WIFSIGNALED(status))
2480 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
2481 childpid, WTERMSIG(status), WEXITSTATUS(status));
2482 if (WIFEXITED(status))
2483 debug_printf_jobs("pid %d exited, exitcode %d\n",
2484 childpid, WEXITSTATUS(status));
2486 /* Were we asked to wait for fg pipe? */
2488 for (i = 0; i < fg_pipe->num_cmds; i++) {
2489 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
2490 if (fg_pipe->cmds[i].pid != childpid)
2492 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
2494 fg_pipe->cmds[i].pid = 0;
2495 fg_pipe->alive_cmds--;
2496 if (i == fg_pipe->num_cmds - 1) {
2497 /* last process gives overall exitstatus */
2498 rcode = WEXITSTATUS(status);
2499 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
2502 fg_pipe->cmds[i].is_stopped = 1;
2503 fg_pipe->stopped_cmds++;
2505 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
2506 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
2507 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
2508 /* All processes in fg pipe have exited/stopped */
2510 if (fg_pipe->alive_cmds)
2511 insert_bg_job(fg_pipe);
2515 /* There are still running processes in the fg pipe */
2516 goto wait_more; /* do waitpid again */
2518 /* it wasnt fg_pipe, look for process in bg pipes */
2522 /* We asked to wait for bg or orphaned children */
2523 /* No need to remember exitcode in this case */
2524 for (pi = G.job_list; pi; pi = pi->next) {
2525 for (i = 0; i < pi->num_cmds; i++) {
2526 if (pi->cmds[i].pid == childpid)
2527 goto found_pi_and_prognum;
2530 /* Happens when shell is used as init process (init=/bin/sh) */
2531 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
2532 continue; /* do waitpid again */
2534 found_pi_and_prognum:
2537 pi->cmds[i].pid = 0;
2539 if (!pi->alive_cmds) {
2540 if (G_interactive_fd)
2541 printf(JOB_STATUS_FORMAT, pi->jobid,
2542 "Done", pi->cmdtext);
2543 delete_finished_bg_job(pi);
2547 pi->cmds[i].is_stopped = 1;
2551 } /* while (waitpid succeeds)... */
2557 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
2560 int rcode = checkjobs(fg_pipe);
2561 /* Job finished, move the shell to the foreground */
2562 p = getpgid(0); /* pgid of our process */
2563 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
2564 tcsetpgrp(G_interactive_fd, p);
2569 /* run_pipe() starts all the jobs, but doesn't wait for anything
2570 * to finish. See checkjobs().
2572 * return code is normally -1, when the caller has to wait for children
2573 * to finish to determine the exit status of the pipe. If the pipe
2574 * is a simple builtin command, however, the action is done by the
2575 * time run_pipe returns, and the exit code is provided as the
2578 * The input of the pipe is always stdin, the output is always
2579 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
2580 * because it tries to avoid running the command substitution in
2581 * subshell, when that is in fact necessary. The subshell process
2582 * now has its stdout directed to the input of the appropriate pipe,
2583 * so this routine is noticeably simpler.
2585 * Returns -1 only if started some children. IOW: we have to
2586 * mask out retvals of builtins etc with 0xff!
2588 static int run_pipe(struct pipe *pi)
2592 int pipefds[2]; /* pipefds[0] is for reading */
2593 struct command *command;
2594 char **argv_expanded;
2596 const struct built_in_command *x;
2598 /* it is not always needed, but we aim to smaller code */
2599 int squirrel[] = { -1, -1, -1 };
2601 const int single_and_fg = (pi->num_cmds == 1 && pi->followup != PIPE_BG);
2603 debug_printf_exec("run_pipe start: single_and_fg=%d\n", single_and_fg);
2609 pi->stopped_cmds = 0;
2611 /* Check if this is a simple builtin (not part of a pipe).
2612 * Builtins within pipes have to fork anyway, and are handled in
2613 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
2615 command = &(pi->cmds[0]);
2617 #if ENABLE_HUSH_FUNCTIONS
2618 if (single_and_fg && command->group && command->grp_type == GRP_FUNCTION) {
2619 /* We "execute" function definition */
2620 bb_error_msg("here we ought to remember function definition, and go on");
2621 return EXIT_SUCCESS;
2625 if (single_and_fg && command->group && command->grp_type == GRP_NORMAL) {
2626 debug_printf("non-subshell grouping\n");
2627 setup_redirects(command, squirrel);
2628 debug_printf_exec(": run_list\n");
2629 rcode = run_list(command->group) & 0xff;
2630 restore_redirects(squirrel);
2631 debug_printf_exec("run_pipe return %d\n", rcode);
2632 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2636 argv = command->argv;
2637 argv_expanded = NULL;
2639 if (single_and_fg && argv != NULL) {
2640 char **new_env = NULL;
2641 char **old_env = NULL;
2643 i = command->assignment_cnt;
2644 if (i != 0 && argv[i] == NULL) {
2645 /* assignments, but no command: set local environment */
2646 for (i = 0; argv[i] != NULL; i++) {
2647 debug_printf("local environment set: %s\n", argv[i]);
2648 p = expand_string_to_string(argv[i]);
2649 set_local_var(p, 0);
2651 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
2654 /* Expand the rest into (possibly) many strings each */
2655 argv_expanded = expand_strvec_to_strvec(argv + i);
2657 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2658 if (strcmp(argv_expanded[0], x->cmd) != 0)
2660 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
2661 debug_printf("exec with redirects only\n");
2662 setup_redirects(command, NULL);
2663 rcode = EXIT_SUCCESS;
2664 goto clean_up_and_ret1;
2666 debug_printf("builtin inline %s\n", argv_expanded[0]);
2667 /* XXX setup_redirects acts on file descriptors, not FILEs.
2668 * This is perfect for work that comes after exec().
2669 * Is it really safe for inline use? Experimentally,
2670 * things seem to work with glibc. */
2671 setup_redirects(command, squirrel);
2672 new_env = expand_assignments(argv, command->assignment_cnt);
2673 old_env = putenv_all_and_save_old(new_env);
2674 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv_expanded[1]);
2675 rcode = x->function(argv_expanded) & 0xff;
2676 #if ENABLE_FEATURE_SH_STANDALONE
2679 restore_redirects(squirrel);
2680 free_strings_and_unsetenv(new_env, 1);
2681 putenv_all(old_env);
2682 free(old_env); /* not free_strings()! */
2684 free(argv_expanded);
2685 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2686 debug_printf_exec("run_pipe return %d\n", rcode);
2689 #if ENABLE_FEATURE_SH_STANDALONE
2690 i = find_applet_by_name(argv_expanded[0]);
2691 if (i >= 0 && APPLET_IS_NOFORK(i)) {
2692 setup_redirects(command, squirrel);
2693 save_nofork_data(&G.nofork_save);
2694 new_env = expand_assignments(argv, command->assignment_cnt);
2695 old_env = putenv_all_and_save_old(new_env);
2696 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
2697 rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
2698 goto clean_up_and_ret;
2703 /* NB: argv_expanded may already be created, and that
2704 * might include `cmd` runs! Do not rerun it! We *must*
2705 * use argv_expanded if it's non-NULL */
2707 /* Going to fork a child per each pipe member */
2711 for (i = 0; i < pi->num_cmds; i++) {
2713 volatile nommu_save_t nommu_save;
2714 nommu_save.new_env = NULL;
2715 nommu_save.old_env = NULL;
2716 nommu_save.argv = NULL;
2718 command = &(pi->cmds[i]);
2719 if (command->argv) {
2720 debug_printf_exec(": pipe member '%s' '%s'...\n", command->argv[0], command->argv[1]);
2722 debug_printf_exec(": pipe member with no argv\n");
2724 /* pipes are inserted between pairs of commands */
2727 if ((i + 1) < pi->num_cmds)
2730 command->pid = BB_MMU ? fork() : vfork();
2731 if (!command->pid) { /* child */
2733 die_sleep = 0; /* let nofork's xfuncs die */
2735 /* Every child adds itself to new process group
2736 * with pgid == pid_of_first_child_in_pipe */
2737 if (G.run_list_level == 1 && G_interactive_fd) {
2740 if (pgrp < 0) /* true for 1st process only */
2742 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
2743 /* We do it in *every* child, not just first,
2745 tcsetpgrp(G_interactive_fd, pgrp);
2749 xmove_fd(nextin, 0);
2750 xmove_fd(pipefds[1], 1); /* write end */
2752 close(pipefds[0]); /* read end */
2753 /* Like bash, explicit redirects override pipes,
2754 * and the pipe fd is available for dup'ing. */
2755 setup_redirects(command, NULL);
2757 /* Restore default handlers just prior to exec */
2758 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
2760 /* Stores to nommu_save list of env vars putenv'ed
2761 * (NOMMU, on MMU we don't need that) */
2762 /* cast away volatility... */
2763 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
2764 /* pseudo_exec() does not return */
2768 /* Clean up after vforked child */
2769 free(nommu_save.argv);
2770 free_strings_and_unsetenv(nommu_save.new_env, 1);
2771 putenv_all(nommu_save.old_env);
2773 free(argv_expanded);
2774 argv_expanded = NULL;
2775 if (command->pid < 0) { /* [v]fork failed */
2776 /* Clearly indicate, was it fork or vfork */
2777 bb_perror_msg(BB_MMU ? "fork" : "vfork");
2781 /* Second and next children need to know pid of first one */
2783 pi->pgrp = command->pid;
2789 if ((i + 1) < pi->num_cmds)
2790 close(pipefds[1]); /* write end */
2791 /* Pass read (output) pipe end to next iteration */
2792 nextin = pipefds[0];
2795 if (!pi->alive_cmds) {
2796 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
2800 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
2804 #ifndef debug_print_tree
2805 static void debug_print_tree(struct pipe *pi, int lvl)
2807 static const char *const PIPE[] = {
2813 static const char *RES[] = {
2814 [RES_NONE ] = "NONE" ,
2817 [RES_THEN ] = "THEN" ,
2818 [RES_ELIF ] = "ELIF" ,
2819 [RES_ELSE ] = "ELSE" ,
2822 #if ENABLE_HUSH_LOOPS
2823 [RES_FOR ] = "FOR" ,
2824 [RES_WHILE] = "WHILE",
2825 [RES_UNTIL] = "UNTIL",
2827 [RES_DONE ] = "DONE" ,
2829 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2832 #if ENABLE_HUSH_CASE
2833 [RES_CASE ] = "CASE" ,
2834 [RES_MATCH] = "MATCH",
2835 [RES_CASEI] = "CASEI",
2836 [RES_ESAC ] = "ESAC" ,
2838 [RES_XXXX ] = "XXXX" ,
2839 [RES_SNTX ] = "SNTX" ,
2841 static const char *const GRPTYPE[] = {
2844 #if ENABLE_HUSH_FUNCTIONS
2853 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2854 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2856 while (prn < pi->num_cmds) {
2857 struct command *command = &pi->cmds[prn];
2858 char **argv = command->argv;
2860 fprintf(stderr, "%*s prog %d assignment_cnt:%d", lvl*2, "", prn, command->assignment_cnt);
2861 if (command->group) {
2862 fprintf(stderr, " group %s: (argv=%p)\n",
2863 GRPTYPE[command->grp_type],
2865 debug_print_tree(command->group, lvl+1);
2869 if (argv) while (*argv) {
2870 fprintf(stderr, " '%s'", *argv);
2873 fprintf(stderr, "\n");
2882 /* NB: called by pseudo_exec, and therefore must not modify any
2883 * global data until exec/_exit (we can be a child after vfork!) */
2884 static int run_list(struct pipe *pi)
2886 #if ENABLE_HUSH_CASE
2887 char *case_word = NULL;
2889 #if ENABLE_HUSH_LOOPS
2890 struct pipe *loop_top = NULL;
2891 char *for_varname = NULL;
2892 char **for_lcur = NULL;
2893 char **for_list = NULL;
2895 smallint flag_skip = 1;
2896 smalluint rcode = 0; /* probably just for compiler */
2897 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
2898 smalluint cond_code = 0;
2900 enum { cond_code = 0, };
2902 /*enum reserved_style*/ smallint rword = RES_NONE;
2903 /*enum reserved_style*/ smallint skip_more_for_this_rword = RES_XXXX;
2905 debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
2907 #if ENABLE_HUSH_LOOPS
2908 /* Check syntax for "for" */
2909 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
2910 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
2912 /* current word is FOR or IN (BOLD in comments below) */
2913 if (cpipe->next == NULL) {
2914 syntax("malformed for");
2915 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
2918 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
2919 if (cpipe->next->res_word == RES_DO)
2921 /* next word is not "do". It must be "in" then ("FOR v in ...") */
2922 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
2923 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
2925 syntax("malformed for");
2926 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
2932 /* Past this point, all code paths should jump to ret: label
2933 * in order to return, no direct "return" statements please.
2934 * This helps to ensure that no memory is leaked. */
2936 ////TODO: ctrl-Z handling needs re-thinking and re-testing
2939 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
2940 * We are saving state before entering outermost list ("while...done")
2941 * so that ctrl-Z will correctly background _entire_ outermost list,
2942 * not just a part of it (like "sleep 1 | exit 2") */
2943 if (++G.run_list_level == 1 && G_interactive_fd) {
2944 if (sigsetjmp(G.toplevel_jb, 1)) {
2945 /* ctrl-Z forked and we are parent; or ctrl-C.
2946 * Sighandler has longjmped us here */
2947 signal(SIGINT, SIG_IGN);
2948 signal(SIGTSTP, SIG_IGN);
2949 /* Restore level (we can be coming from deep inside
2951 G.run_list_level = 1;
2952 #if ENABLE_FEATURE_SH_STANDALONE
2953 if (G.nofork_save.saved) { /* if save area is valid */
2954 debug_printf_jobs("exiting nofork early\n");
2955 restore_nofork_data(&G.nofork_save);
2958 //// if (G.ctrl_z_flag) {
2959 //// /* ctrl-Z has forked and stored pid of the child in pi->pid.
2960 //// * Remember this child as background job */
2961 //// insert_bg_job(pi);
2963 /* ctrl-C. We just stop doing whatever we were doing */
2966 USE_HUSH_LOOPS(loop_top = NULL;)
2967 USE_HUSH_LOOPS(G.depth_of_loop = 0;)
2971 //// /* ctrl-Z handler will store pid etc in pi */
2972 //// G.toplevel_list = pi;
2973 //// G.ctrl_z_flag = 0;
2974 ////#if ENABLE_FEATURE_SH_STANDALONE
2975 //// G.nofork_save.saved = 0; /* in case we will run a nofork later */
2977 //// signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
2978 //// signal(SIGINT, handler_ctrl_c);
2982 /* Go through list of pipes, (maybe) executing them. */
2983 for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
2987 IF_HAS_KEYWORDS(rword = pi->res_word;)
2988 IF_HAS_NO_KEYWORDS(rword = RES_NONE;)
2989 debug_printf_exec(": rword=%d cond_code=%d skip_more=%d\n",
2990 rword, cond_code, skip_more_for_this_rword);
2991 #if ENABLE_HUSH_LOOPS
2992 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
2993 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
2995 /* start of a loop: remember where loop starts */
3000 if (rword == skip_more_for_this_rword && flag_skip) {
3001 if (pi->followup == PIPE_SEQ)
3003 /* it is "<false> && CMD" or "<true> || CMD"
3004 * and we should not execute CMD */
3008 skip_more_for_this_rword = RES_XXXX;
3011 if (rword == RES_THEN) {
3012 /* "if <false> THEN cmd": skip cmd */
3016 if (rword == RES_ELSE || rword == RES_ELIF) {
3017 /* "if <true> then ... ELSE/ELIF cmd":
3018 * skip cmd and all following ones */
3023 #if ENABLE_HUSH_LOOPS
3024 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
3026 /* first loop through for */
3028 static const char encoded_dollar_at[] ALIGN1 = {
3029 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
3030 }; /* encoded representation of "$@" */
3031 static const char *const encoded_dollar_at_argv[] = {
3032 encoded_dollar_at, NULL
3033 }; /* argv list with one element: "$@" */
3036 vals = (char**)encoded_dollar_at_argv;
3037 if (pi->next->res_word == RES_IN) {
3038 /* if no variable values after "in" we skip "for" */
3039 if (!pi->next->cmds[0].argv)
3041 vals = pi->next->cmds[0].argv;
3042 } /* else: "for var; do..." -> assume "$@" list */
3043 /* create list of variable values */
3044 debug_print_strings("for_list made from", vals);
3045 for_list = expand_strvec_to_strvec(vals);
3046 for_lcur = for_list;
3047 debug_print_strings("for_list", for_list);
3048 for_varname = pi->cmds[0].argv[0];
3049 pi->cmds[0].argv[0] = NULL;
3051 free(pi->cmds[0].argv[0]);
3053 /* "for" loop is over, clean up */
3057 pi->cmds[0].argv[0] = for_varname;
3060 /* insert next value from for_lcur */
3061 //TODO: does it need escaping?
3062 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
3063 pi->cmds[0].assignment_cnt = 1;
3065 if (rword == RES_IN) /* "for v IN list;..." - "in" has no cmds anyway */
3067 if (rword == RES_DONE) {
3068 continue; /* "done" has no cmds too */
3071 #if ENABLE_HUSH_CASE
3072 if (rword == RES_CASE) {
3073 case_word = expand_strvec_to_string(pi->cmds->argv);
3076 if (rword == RES_MATCH) {
3079 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
3081 /* all prev words didn't match, does this one match? */
3082 argv = pi->cmds->argv;
3084 char *pattern = expand_string_to_string(*argv);
3085 /* TODO: which FNM_xxx flags to use? */
3086 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
3088 if (cond_code == 0) { /* match! we will execute this branch */
3089 free(case_word); /* make future "word)" stop */
3097 if (rword == RES_CASEI) { /* inside of a case branch */
3099 continue; /* not matched yet, skip this pipe */
3102 /* Just pressing <enter> in shell should check for jobs.
3103 * OTOH, in non-interactive shell this is useless
3104 * and only leads to extra job checks */
3105 if (pi->num_cmds == 0) {
3106 if (G_interactive_fd)
3107 goto check_jobs_and_continue;
3111 /* After analyzing all keywords and conditions, we decided
3112 * to execute this pipe. NB: have to do checkjobs(NULL)
3113 * after run_pipe() to collect any background children,
3114 * even if list execution is to be stopped. */
3115 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
3118 #if ENABLE_HUSH_LOOPS
3119 G.flag_break_continue = 0;
3121 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
3123 /* we only ran a builtin: rcode is already known
3124 * and we don't need to wait for anything. */
3125 check_and_run_traps(0);
3126 #if ENABLE_HUSH_LOOPS
3127 /* was it "break" or "continue"? */
3128 if (G.flag_break_continue) {
3129 smallint fbc = G.flag_break_continue;
3130 /* we might fall into outer *loop*,
3131 * don't want to break it too */
3133 G.depth_break_continue--;
3134 if (G.depth_break_continue == 0)
3135 G.flag_break_continue = 0;
3136 /* else: e.g. "continue 2" should *break* once, *then* continue */
3137 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
3138 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
3139 goto check_jobs_and_break;
3140 /* "continue": simulate end of loop */
3145 } else if (pi->followup == PIPE_BG) {
3146 /* what does bash do with attempts to background builtins? */
3147 /* even bash 3.2 doesn't do that well with nested bg:
3148 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
3149 * I'm NOT treating inner &'s as jobs */
3150 check_and_run_traps(0);
3152 if (G.run_list_level == 1)
3155 rcode = 0; /* EXIT_SUCCESS */
3158 if (G.run_list_level == 1 && G_interactive_fd) {
3159 /* waits for completion, then fg's main shell */
3160 rcode = checkjobs_and_fg_shell(pi);
3161 check_and_run_traps(0);
3162 debug_printf_exec(": checkjobs_and_fg_shell returned %d\n", rcode);
3165 { /* this one just waits for completion */
3166 rcode = checkjobs(pi);
3167 check_and_run_traps(0);
3168 debug_printf_exec(": checkjobs returned %d\n", rcode);
3172 debug_printf_exec(": setting last_return_code=%d\n", rcode);
3173 G.last_return_code = rcode;
3175 /* Analyze how result affects subsequent commands */
3177 if (rword == RES_IF || rword == RES_ELIF)
3180 #if ENABLE_HUSH_LOOPS
3181 if (rword == RES_WHILE) {
3183 rcode = 0; /* "while false; do...done" - exitcode 0 */
3184 goto check_jobs_and_break;
3187 if (rword == RES_UNTIL) {
3189 check_jobs_and_break:
3195 if ((rcode == 0 && pi->followup == PIPE_OR)
3196 || (rcode != 0 && pi->followup == PIPE_AND)
3198 skip_more_for_this_rword = rword;
3201 check_jobs_and_continue:
3206 //// if (G.ctrl_z_flag) {
3207 //// /* ctrl-Z forked somewhere in the past, we are the child,
3208 //// * and now we completed running the list. Exit. */
3214 //// if (!G.run_list_level && G_interactive_fd) {
3215 //// signal(SIGTSTP, SIG_IGN);
3216 //// signal(SIGINT, SIG_IGN);
3219 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
3220 #if ENABLE_HUSH_LOOPS
3225 #if ENABLE_HUSH_CASE
3231 /* Select which version we will use */
3232 static int run_and_free_list(struct pipe *pi)
3235 debug_printf_exec("run_and_free_list entered\n");
3237 debug_printf_exec(": run_list with %d members\n", pi->num_cmds);
3238 rcode = run_list(pi);
3240 /* free_pipe_list has the side effect of clearing memory.
3241 * In the long run that function can be merged with run_list,
3242 * but doing that now would hobble the debugging effort. */
3243 free_pipe_list(pi, /* indent: */ 0);
3244 debug_printf_exec("run_and_free_list return %d\n", rcode);
3249 /* Peek ahead in the in_str to find out if we have a "&n" construct,
3250 * as in "2>&1", that represents duplicating a file descriptor.
3251 * Return either -2 (syntax error), -1 (no &), or the number found.
3253 static int redirect_dup_num(struct in_str *input)
3255 int ch, d = 0, ok = 0;
3257 if (ch != '&') return -1;
3259 i_getch(input); /* get the & */
3263 return -3; /* "-" represents "close me" */
3265 while (isdigit(ch)) {
3266 d = d*10 + (ch-'0');
3273 bb_error_msg("ambiguous redirect");
3277 /* The src parameter allows us to peek forward to a possible &n syntax
3278 * for file descriptor duplication, e.g., "2>&1".
3279 * Return code is 0 normally, 1 if a syntax error is detected in src.
3280 * Resource errors (in xmalloc) cause the process to exit */
3281 static int setup_redirect(struct parse_context *ctx,
3284 struct in_str *input)
3286 struct command *command = ctx->command;
3287 struct redir_struct *redir;
3288 struct redir_struct **redirp;
3291 /* Check for a '2>&1' type redirect */
3292 dup_num = redirect_dup_num(input);
3294 return 1; /* syntax error */
3296 /* Create a new redir_struct and drop it onto the end of the linked list */
3297 redirp = &command->redirects;
3298 while ((redir = *redirp) != NULL) {
3299 redirp = &(redir->next);
3301 *redirp = redir = xzalloc(sizeof(*redir));
3302 /* redir->next = NULL; */
3303 /* redir->rd_filename = NULL; */
3304 redir->rd_type = style;
3305 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
3307 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
3309 redir->dup = dup_num;
3310 if (dup_num != -1) {
3311 /* Erik had a check here that the file descriptor in question
3312 * is legit; I postpone that to "run time"
3313 * A "-" representation of "close me" shows up as a -3 here */
3314 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
3316 /* We do _not_ try to open the file that src points to,
3317 * since we need to return and let src be expanded first.
3318 * Set ctx->pending_redirect, so we know what to do at the
3319 * end of the next parsed word. */
3320 ctx->pending_redirect = redir;
3326 static struct pipe *new_pipe(void)
3329 pi = xzalloc(sizeof(struct pipe));
3330 /*pi->followup = 0; - deliberately invalid value */
3331 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3335 /* Command (member of a pipe) is complete. The only possible error here
3336 * is out of memory, in which case xmalloc exits. */
3337 static int done_command(struct parse_context *ctx)
3339 /* The command is really already in the pipe structure, so
3340 * advance the pipe counter and make a new, null command. */
3341 struct pipe *pi = ctx->pipe;
3342 struct command *command = ctx->command;
3345 if (command->group == NULL
3346 && command->argv == NULL
3347 && command->redirects == NULL
3349 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3350 return pi->num_cmds;
3353 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3355 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3358 /* Only real trickiness here is that the uncommitted
3359 * command structure is not counted in pi->num_cmds. */
3360 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3361 command = &pi->cmds[pi->num_cmds];
3362 memset(command, 0, sizeof(*command));
3364 ctx->command = command;
3365 /* but ctx->pipe and ctx->list_head remain unchanged */
3367 return pi->num_cmds; /* used only for 0/nonzero check */
3370 static void done_pipe(struct parse_context *ctx, pipe_style type)
3374 debug_printf_parse("done_pipe entered, followup %d\n", type);
3375 /* Close previous command */
3376 not_null = done_command(ctx);
3377 ctx->pipe->followup = type;
3378 IF_HAS_KEYWORDS(ctx->pipe->pi_inverted = ctx->ctx_inverted;)
3379 IF_HAS_KEYWORDS(ctx->ctx_inverted = 0;)
3380 IF_HAS_KEYWORDS(ctx->pipe->res_word = ctx->ctx_res_w;)
3382 /* Without this check, even just <enter> on command line generates
3383 * tree of three NOPs (!). Which is harmless but annoying.
3384 * IOW: it is safe to do it unconditionally.
3385 * RES_NONE case is for "for a in; do ..." (empty IN set)
3386 * to work, possibly other cases too. */
3387 if (not_null IF_HAS_KEYWORDS(|| ctx->ctx_res_w != RES_NONE)) {
3389 debug_printf_parse("done_pipe: adding new pipe: "
3390 "not_null:%d ctx->ctx_res_w:%d\n",
3391 not_null, ctx->ctx_res_w);
3393 ctx->pipe->next = new_p;
3395 /* RES_THEN, RES_DO etc are "sticky" -
3396 * they remain set for commands inside if/while.
3397 * This is used to control execution.
3398 * RES_FOR and RES_IN are NOT sticky (needed to support
3399 * cases where variable or value happens to match a keyword):
3401 #if ENABLE_HUSH_LOOPS
3402 if (ctx->ctx_res_w == RES_FOR
3403 || ctx->ctx_res_w == RES_IN)
3404 ctx->ctx_res_w = RES_NONE;
3406 #if ENABLE_HUSH_CASE
3407 if (ctx->ctx_res_w == RES_MATCH)
3408 ctx->ctx_res_w = RES_CASEI;
3410 ctx->command = NULL; /* trick done_command below */
3411 /* Create the memory for command, roughly:
3412 * ctx->pipe->cmds = new struct command;
3413 * ctx->command = &ctx->pipe->cmds[0];
3417 debug_printf_parse("done_pipe return\n");
3420 static void initialize_context(struct parse_context *ctx)
3422 memset(ctx, 0, sizeof(*ctx));
3423 ctx->pipe = ctx->list_head = new_pipe();
3424 /* Create the memory for command, roughly:
3425 * ctx->pipe->cmds = new struct command;
3426 * ctx->command = &ctx->pipe->cmds[0];
3432 /* If a reserved word is found and processed, parse context is modified
3433 * and 1 is returned.
3436 struct reserved_combo {
3439 unsigned char assignment_flag;
3443 FLAG_END = (1 << RES_NONE ),
3445 FLAG_IF = (1 << RES_IF ),
3446 FLAG_THEN = (1 << RES_THEN ),
3447 FLAG_ELIF = (1 << RES_ELIF ),
3448 FLAG_ELSE = (1 << RES_ELSE ),
3449 FLAG_FI = (1 << RES_FI ),
3451 #if ENABLE_HUSH_LOOPS
3452 FLAG_FOR = (1 << RES_FOR ),
3453 FLAG_WHILE = (1 << RES_WHILE),
3454 FLAG_UNTIL = (1 << RES_UNTIL),
3455 FLAG_DO = (1 << RES_DO ),
3456 FLAG_DONE = (1 << RES_DONE ),
3457 FLAG_IN = (1 << RES_IN ),
3459 #if ENABLE_HUSH_CASE
3460 FLAG_MATCH = (1 << RES_MATCH),
3461 FLAG_ESAC = (1 << RES_ESAC ),
3463 FLAG_START = (1 << RES_XXXX ),
3466 static const struct reserved_combo* match_reserved_word(o_string *word)
3468 /* Mostly a list of accepted follow-up reserved words.
3469 * FLAG_END means we are done with the sequence, and are ready
3470 * to turn the compound list into a command.
3471 * FLAG_START means the word must start a new compound list.
3473 static const struct reserved_combo reserved_list[] = {
3475 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3476 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
3477 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3478 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
3479 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
3480 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3482 #if ENABLE_HUSH_LOOPS
3483 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3484 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3485 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3486 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3487 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
3488 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3490 #if ENABLE_HUSH_CASE
3491 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3492 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3495 const struct reserved_combo *r;
3497 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3498 if (strcmp(word->data, r->literal) == 0)
3503 static int reserved_word(o_string *word, struct parse_context *ctx)
3505 #if ENABLE_HUSH_CASE
3506 static const struct reserved_combo reserved_match = {
3507 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3510 const struct reserved_combo *r;
3512 r = match_reserved_word(word);
3516 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3517 #if ENABLE_HUSH_CASE
3518 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
3519 /* "case word IN ..." - IN part starts first match part */
3520 r = &reserved_match;
3523 if (r->flag == 0) { /* '!' */
3524 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3525 syntax("! ! command");
3526 IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
3528 ctx->ctx_inverted = 1;
3531 if (r->flag & FLAG_START) {
3532 struct parse_context *old;
3533 old = xmalloc(sizeof(*old));
3534 debug_printf_parse("push stack %p\n", old);
3535 *old = *ctx; /* physical copy */
3536 initialize_context(ctx);
3538 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3540 ctx->ctx_res_w = RES_SNTX;
3543 ctx->ctx_res_w = r->res;
3544 ctx->old_flag = r->flag;
3545 if (ctx->old_flag & FLAG_END) {
3546 struct parse_context *old;
3547 done_pipe(ctx, PIPE_SEQ);
3548 debug_printf_parse("pop stack %p\n", ctx->stack);
3550 old->command->group = ctx->list_head;
3551 old->command->grp_type = GRP_NORMAL;
3552 *ctx = *old; /* physical copy */
3555 word->o_assignment = r->assignment_flag;
3560 /* Word is complete, look at it and update parsing context.
3561 * Normal return is 0. Syntax errors return 1.
3562 * Note: on return, word is reset, but not o_free'd!
3564 static int done_word(o_string *word, struct parse_context *ctx)
3566 struct command *command = ctx->command;
3568 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3569 if (word->length == 0 && word->nonnull == 0) {
3570 debug_printf_parse("done_word return 0: true null, ignored\n");
3573 /* If this word wasn't an assignment, next ones definitely
3574 * can't be assignments. Even if they look like ones. */
3575 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3576 && word->o_assignment != WORD_IS_KEYWORD
3578 word->o_assignment = NOT_ASSIGNMENT;
3580 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3581 command->assignment_cnt++;
3582 word->o_assignment = MAYBE_ASSIGNMENT;
3585 if (ctx->pending_redirect) {
3586 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3587 * only if run as "bash", not "sh" */
3588 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3589 word->o_assignment = NOT_ASSIGNMENT;
3590 debug_printf("word stored in rd_filename: '%s'\n", word->data);
3592 /* "{ echo foo; } echo bar" - bad */
3593 /* NB: bash allows e.g.:
3594 * if true; then { echo foo; } fi
3595 * while if false; then false; fi do break; done
3597 if (command->group) {
3599 debug_printf_parse("done_word return 1: syntax error, "
3600 "groups and arglists don't mix\n");
3604 #if ENABLE_HUSH_CASE
3605 if (ctx->ctx_dsemicolon
3606 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3608 /* already done when ctx_dsemicolon was set to 1: */
3609 /* ctx->ctx_res_w = RES_MATCH; */
3610 ctx->ctx_dsemicolon = 0;
3613 if (!command->argv /* if it's the first word... */
3614 #if ENABLE_HUSH_LOOPS
3615 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3616 && ctx->ctx_res_w != RES_IN
3619 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
3620 if (reserved_word(word, ctx)) {
3622 debug_printf_parse("done_word return %d\n", (ctx->ctx_res_w == RES_SNTX));
3623 return (ctx->ctx_res_w == RES_SNTX);
3627 if (word->nonnull /* word had "xx" or 'xx' at least as part of it. */
3628 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3629 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3630 /* (otherwise it's known to be not empty and is already safe) */
3632 /* exclude "$@" - it can expand to no word despite "" */
3633 char *p = word->data;
3634 while (p[0] == SPECIAL_VAR_SYMBOL
3635 && (p[1] & 0x7f) == '@'
3636 && p[2] == SPECIAL_VAR_SYMBOL
3640 if (p == word->data || p[0] != '\0') {
3641 /* saw no "$@", or not only "$@" but some
3642 * real text is there too */
3643 /* insert "empty variable" reference, this makes
3644 * e.g. "", $empty"" etc to not disappear */
3645 o_addchr(word, SPECIAL_VAR_SYMBOL);
3646 o_addchr(word, SPECIAL_VAR_SYMBOL);
3649 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3650 debug_print_strings("word appended to argv", command->argv);
3654 ctx->pending_redirect = NULL;
3656 #if ENABLE_HUSH_LOOPS
3657 /* Force FOR to have just one word (variable name) */
3658 /* NB: basically, this makes hush see "for v in ..." syntax as if
3659 * as it is "for v; in ...". FOR and IN become two pipe structs
3661 if (ctx->ctx_res_w == RES_FOR) {
3662 //TODO: check that command->argv[0] is a valid variable name!
3663 done_pipe(ctx, PIPE_SEQ);
3666 #if ENABLE_HUSH_CASE
3667 /* Force CASE to have just one word */
3668 if (ctx->ctx_res_w == RES_CASE) {
3669 done_pipe(ctx, PIPE_SEQ);
3672 debug_printf_parse("done_word return 0\n");
3676 /* If a redirect is immediately preceded by a number, that number is
3677 * supposed to tell which file descriptor to redirect. This routine
3678 * looks for such preceding numbers. In an ideal world this routine
3679 * needs to handle all the following classes of redirects...
3680 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3681 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3682 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3683 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3684 * A -1 output from this program means no valid number was found, so the
3685 * caller should use the appropriate default for this redirection.
3687 static int redirect_opt_num(o_string *o)
3693 for (num = 0; num < o->length; num++) {
3694 if (!isdigit(o->data[num])) {
3698 num = atoi(o->data);
3703 static struct pipe *parse_stream(struct in_str *input, int end_trigger);
3704 static void parse_and_run_string(const char *s);
3706 #if ENABLE_HUSH_TICK
3707 static FILE *generate_stream_from_string(const char *s)
3710 int pid, channel[2];
3713 pid = BB_MMU ? fork() : vfork();
3715 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
3717 if (pid == 0) { /* child */
3718 /* Process substitution is not considered to be usual
3719 * 'command execution'.
3720 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
3727 if (ENABLE_HUSH_JOB)
3728 die_sleep = 0; /* let nofork's xfuncs die */
3729 close(channel[0]); /* NB: close _first_, then move fd! */
3730 xmove_fd(channel[1], 1);
3731 /* Prevent it from trying to handle ctrl-z etc */
3732 USE_HUSH_JOB(G.run_list_level = 1;)
3734 parse_and_run_string(s);
3735 _exit(G.last_return_code);
3737 /* We re-execute after vfork on NOMMU. This makes this script safe:
3738 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >TESTFILE
3739 * huge=`cat TESTFILE` # was blocking here forever
3742 //TODO: pass non-exported variables, traps, and functions
3743 execl(CONFIG_BUSYBOX_EXEC_PATH, "hush", "-c", s, NULL);
3750 pf = fdopen(channel[0], "r");
3754 /* Return code is exit status of the process that is run. */
3755 static int process_command_subs(o_string *dest, const char *s)
3758 struct in_str pipe_str;
3761 pf = generate_stream_from_string(s);
3764 close_on_exec_on(fileno(pf));
3766 /* Now send results of command back into original context */
3767 setup_file_in_str(&pipe_str, pf);
3769 while ((ch = i_getch(&pipe_str)) != EOF) {
3775 o_addchr(dest, '\n');
3778 o_addQchr(dest, ch);
3781 debug_printf("done reading from pipe, pclose()ing\n");
3782 /* Note: we got EOF, and we just close the read end of the pipe.
3783 * We do not wait for the `cmd` child to terminate. bash and ash do.
3785 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
3786 * `false`; echo $? - bash outputs "1"
3789 debug_printf("closed FILE from child. return 0\n");
3794 static int parse_group(o_string *dest, struct parse_context *ctx,
3795 struct in_str *input, int ch)
3797 /* dest contains characters seen prior to ( or {.
3798 * Typically it's empty, but for function defs,
3799 * it contains function name (without '()'). */
3800 struct pipe *pipe_list;
3802 struct command *command = ctx->command;
3804 debug_printf_parse("parse_group entered\n");
3805 #if ENABLE_HUSH_FUNCTIONS
3806 if (ch == 'F') { /* function definition? */
3807 bb_error_msg("aha '%s' is a function, parsing it...", dest->data);
3808 //command->fname = dest->data;
3809 command->grp_type = GRP_FUNCTION;
3810 //TODO: review every o_reset() location... do they handle all o_string fields correctly?
3811 memset(dest, 0, sizeof(*dest));
3814 if (command->argv /* word [word](... */
3815 || dest->length /* word(... */
3816 || dest->nonnull /* ""(... */
3819 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3825 command->grp_type = GRP_SUBSHELL;
3827 pipe_list = parse_stream(input, endch);
3828 /* empty ()/{} or parse error? */
3829 if (!pipe_list || pipe_list == ERR_PTR) {
3831 debug_printf_parse("parse_group return 1: parse_stream returned %p\n", pipe_list);
3834 command->group = pipe_list;
3835 debug_printf_parse("parse_group return 0\n");
3837 /* command remains "open", available for possible redirects */
3840 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
3841 /* Subroutines for copying $(...) and `...` things */
3842 static void add_till_backquote(o_string *dest, struct in_str *input);
3844 static void add_till_single_quote(o_string *dest, struct in_str *input)
3847 int ch = i_getch(input);
3855 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3856 static void add_till_double_quote(o_string *dest, struct in_str *input)
3859 int ch = i_getch(input);
3862 if (ch == '\\') { /* \x. Copy both chars. */
3864 ch = i_getch(input);
3870 add_till_backquote(dest, input);
3874 //if (ch == '$') ...
3877 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3879 * "Within the backquoted style of command substitution, backslash
3880 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3881 * The search for the matching backquote shall be satisfied by the first
3882 * backquote found without a preceding backslash; during this search,
3883 * if a non-escaped backquote is encountered within a shell comment,
3884 * a here-document, an embedded command substitution of the $(command)
3885 * form, or a quoted string, undefined results occur. A single-quoted
3886 * or double-quoted string that begins, but does not end, within the
3887 * "`...`" sequence produces undefined results."
3889 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3891 static void add_till_backquote(o_string *dest, struct in_str *input)
3894 int ch = i_getch(input);
3897 if (ch == '\\') { /* \x. Copy both chars unless it is \` */
3898 int ch2 = i_getch(input);
3899 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
3908 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3909 * quoting and nested ()s.
3910 * "With the $(command) style of command substitution, all characters
3911 * following the open parenthesis to the matching closing parenthesis
3912 * constitute the command. Any valid shell script can be used for command,
3913 * except a script consisting solely of redirections which produces
3914 * unspecified results."
3916 * echo $(echo '(TEST)' BEST) (TEST) BEST
3917 * echo $(echo 'TEST)' BEST) TEST) BEST
3918 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3920 static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
3924 int ch = i_getch(input);
3933 if (i_peek(input) == ')') {
3940 add_till_single_quote(dest, input);
3945 add_till_double_quote(dest, input);
3949 if (ch == '\\') { /* \x. Copy verbatim. Important for \(, \) */
3950 ch = i_getch(input);
3958 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
3960 /* Return code: 0 for OK, 1 for syntax error */
3961 static int handle_dollar(o_string *dest, struct in_str *input)
3964 int ch = i_peek(input); /* first character after the $ */
3965 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
3967 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
3971 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3973 debug_printf_parse(": '%c'\n", ch);
3974 o_addchr(dest, ch | quote_mask);
3977 if (!isalnum(ch) && ch != '_')
3981 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3982 } else if (isdigit(ch)) {
3985 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3986 debug_printf_parse(": '%c'\n", ch);
3987 o_addchr(dest, ch | quote_mask);
3988 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3989 } else switch (ch) {
3991 case '!': /* last bg pid */
3992 case '?': /* last exit code */
3993 case '#': /* number of args */
3994 case '*': /* args */
3995 case '@': /* args */
3996 goto make_one_char_var;
3998 bool first_char, all_digits;
4000 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4002 /* XXX maybe someone will try to escape the '}' */
4007 ch = i_getch(input);
4013 /* ${#var}: length of var contents */
4015 else if (isdigit(ch)) {
4021 if (expansion < 2 &&
4022 ((all_digits && !isdigit(ch)) ||
4023 (!all_digits && !isalnum(ch) && ch != '_')))
4025 /* handle parameter expansions
4026 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4031 case ':': /* null modifier */
4032 if (expansion == 0) {
4033 debug_printf_parse(": null modifier\n");
4039 #if 0 /* not implemented yet :( */
4040 case '#': /* remove prefix */
4041 case '%': /* remove suffix */
4042 if (expansion == 0) {
4043 debug_printf_parse(": remove suffix/prefix\n");
4050 case '-': /* default value */
4051 case '=': /* assign default */
4052 case '+': /* alternative */
4053 case '?': /* error indicate */
4054 debug_printf_parse(": parameter expansion\n");
4060 syntax("unterminated ${name}");
4061 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
4067 debug_printf_parse(": '%c'\n", ch);
4068 o_addchr(dest, ch | quote_mask);
4072 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4078 #if ENABLE_SH_MATH_SUPPORT
4079 if (i_peek(input) == '(') {
4081 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4082 o_addchr(dest, /*quote_mask |*/ '+');
4083 add_till_closing_paren(dest, input, true);
4084 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4089 #if ENABLE_HUSH_TICK
4090 //int pos = dest->length;
4091 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4092 o_addchr(dest, quote_mask | '`');
4093 add_till_closing_paren(dest, input, false);
4094 //debug_printf_subst("SUBST RES2 '%s'\n", dest->data + pos);
4095 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4102 if (isalnum(ch)) { /* it's $_name or $_123 */
4108 /* still unhandled, but should be eventually */
4109 bb_error_msg("unhandled syntax: $%c", ch);
4113 o_addQchr(dest, '$');
4115 debug_printf_parse("handle_dollar return 0\n");
4119 static int parse_stream_dquoted(o_string *dest, struct in_str *input, int dquote_end)
4125 ch = i_getch(input);
4126 if (ch == dquote_end) { /* may be only '"' or EOF */
4128 if (dest->o_assignment == NOT_ASSIGNMENT)
4129 dest->o_escape ^= 1;
4130 debug_printf_parse("parse_stream_dquoted return 0\n");
4134 syntax("unterminated \"");
4135 debug_printf_parse("parse_stream_dquoted return 1: unterminated \"\n");
4141 next = i_peek(input);
4143 debug_printf_parse(": ch=%c (%d) m=%d escape=%d\n",
4144 ch, ch, m, dest->o_escape);
4145 /* Basically, checking every CHAR_SPECIAL char except '"' */
4149 debug_printf_parse("parse_stream_dquoted return 1: \\<eof>\n");
4153 * "The backslash retains its special meaning [in "..."]
4154 * only when followed by one of the following characters:
4155 * $, `, ", \, or <newline>. A double quote may be quoted
4156 * within double quotes by preceding it with a backslash.
4157 * If enabled, history expansion will be performed unless
4158 * an ! appearing in double quotes is escaped using
4159 * a backslash. The backslash preceding the ! is not removed."
4161 if (strchr("$`\"\\", next) != NULL) {
4162 o_addqchr(dest, i_getch(input));
4164 o_addqchr(dest, '\\');
4169 if (handle_dollar(dest, input) != 0) {
4170 debug_printf_parse("parse_stream_dquoted return 1: handle_dollar returned non-0\n");
4175 #if ENABLE_HUSH_TICK
4177 //int pos = dest->length;
4178 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4179 o_addchr(dest, 0x80 | '`');
4180 add_till_backquote(dest, input);
4181 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4182 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4186 o_addQchr(dest, ch);
4188 && (dest->o_assignment == MAYBE_ASSIGNMENT
4189 || dest->o_assignment == WORD_IS_KEYWORD)
4190 && is_assignment(dest->data)
4192 dest->o_assignment = DEFINITELY_ASSIGNMENT;
4198 * Scan input until EOF or end_trigger char.
4199 * Return a list of pipes to execute, or NULL on EOF
4200 * or if end_trigger character is met.
4201 * On syntax error, exit is shell is not interactive,
4202 * reset parsing machinery and start parsing anew,
4203 * or return ERR_PTR.
4205 static struct pipe *parse_stream(struct in_str *input, int end_trigger)
4207 struct parse_context ctx;
4208 o_string dest = NULL_O_STRING;
4211 redir_type redir_style;
4215 /* Double-quote state is handled in the state variable is_in_dquote.
4216 * A single-quote triggers a bypass of the main loop until its mate is
4217 * found. When recursing, quote state is passed in via dest->o_escape. */
4219 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4220 end_trigger ? : 'X');
4223 #if ENABLE_HUSH_INTERACTIVE
4224 input->promptmode = 0; /* PS1 */
4226 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
4227 initialize_context(&ctx);
4231 if (parse_stream_dquoted(&dest, input, '"')) {
4234 /* We reached closing '"' */
4239 ch = i_getch(input);
4243 next = i_peek(input);
4246 debug_printf_parse(": ch=%c (%d) m=%d escape=%d\n",
4247 ch, ch, m, dest.o_escape);
4248 if (m == CHAR_ORDINARY) {
4249 o_addQchr(&dest, ch);
4250 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4251 || dest.o_assignment == WORD_IS_KEYWORD)
4253 && is_assignment(dest.data)
4255 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4260 /* m is SPECIAL ($,`), IFS, or ORDINARY_IF_QUOTED (*,#) */
4262 if (m == CHAR_IFS) {
4265 if (done_word(&dest, &ctx)) {
4269 done_pipe(&ctx, PIPE_SEQ);
4270 /* If we got nothing... */
4272 if (pi->num_cmds == 0
4273 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4275 free_pipe_list(pi, 0);
4278 debug_printf_parse("parse_stream return %p\n", pi);
4281 if (done_word(&dest, &ctx)) {
4285 #if ENABLE_HUSH_CASE
4286 /* "case ... in <newline> word) ..." -
4287 * newlines are ignored (but ';' wouldn't be) */
4288 if (ctx.command->argv == NULL
4289 && ctx.ctx_res_w == RES_MATCH
4294 /* Treat newline as a command separator. */
4295 done_pipe(&ctx, PIPE_SEQ);
4296 dest.o_assignment = MAYBE_ASSIGNMENT;
4298 /* note: if (m == CHAR_IFS) continue;
4299 * will still trigger for us */
4302 if (end_trigger && end_trigger == ch) {
4303 //TODO: disallow "{ cmd }" without semicolon
4304 if (done_word(&dest, &ctx)) {
4307 done_pipe(&ctx, PIPE_SEQ);
4308 dest.o_assignment = MAYBE_ASSIGNMENT;
4309 /* Do we sit outside of any if's, loops or case's? */
4311 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4313 debug_printf_parse("parse_stream return %p: "
4314 "end_trigger char found\n",
4317 return ctx.list_head;
4323 /* m is SPECIAL (e.g. $,`) or ORDINARY_IF_QUOTED (*,#) */
4325 if (dest.o_assignment == MAYBE_ASSIGNMENT) {
4326 /* ch is a special char and thus this word
4327 * cannot be an assignment */
4328 dest.o_assignment = NOT_ASSIGNMENT;
4333 if (dest.length == 0) {
4336 if (ch == EOF || ch == '\n')
4341 o_addQchr(&dest, ch);
4349 o_addchr(&dest, '\\');
4350 o_addchr(&dest, i_getch(input));
4353 if (handle_dollar(&dest, input) != 0) {
4354 debug_printf_parse("parse_stream parse error: handle_dollar returned non-0\n");
4361 ch = i_getch(input);
4363 syntax("unterminated '");
4368 if (dest.o_assignment == NOT_ASSIGNMENT)
4369 o_addqchr(&dest, ch);
4371 o_addchr(&dest, ch);
4376 is_in_dquote ^= 1; /* invert */
4377 if (dest.o_assignment == NOT_ASSIGNMENT)
4380 #if ENABLE_HUSH_TICK
4382 //int pos = dest.length;
4383 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4384 o_addchr(&dest, '`');
4385 add_till_backquote(&dest, input);
4386 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4387 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4392 redir_fd = redirect_opt_num(&dest);
4393 if (done_word(&dest, &ctx)) {
4396 redir_style = REDIRECT_OVERWRITE;
4398 redir_style = REDIRECT_APPEND;
4402 else if (next == '(') {
4403 syntax(">(process) not supported");
4407 setup_redirect(&ctx, redir_fd, redir_style, input);
4410 redir_fd = redirect_opt_num(&dest);
4411 if (done_word(&dest, &ctx)) {
4414 redir_style = REDIRECT_INPUT;
4416 redir_style = REDIRECT_HEREIS;
4418 } else if (next == '>') {
4419 redir_style = REDIRECT_IO;
4423 else if (next == '(') {
4424 syntax("<(process) not supported");
4428 setup_redirect(&ctx, redir_fd, redir_style, input);
4431 #if ENABLE_HUSH_CASE
4434 if (done_word(&dest, &ctx)) {
4437 done_pipe(&ctx, PIPE_SEQ);
4438 #if ENABLE_HUSH_CASE
4439 /* Eat multiple semicolons, detect
4440 * whether it means something special */
4446 if (ctx.ctx_res_w == RES_CASEI) {
4447 ctx.ctx_dsemicolon = 1;
4448 ctx.ctx_res_w = RES_MATCH;
4454 /* We just finished a cmd. New one may start
4455 * with an assignment */
4456 dest.o_assignment = MAYBE_ASSIGNMENT;
4459 if (done_word(&dest, &ctx)) {
4464 done_pipe(&ctx, PIPE_AND);
4466 done_pipe(&ctx, PIPE_BG);
4470 if (done_word(&dest, &ctx)) {
4473 #if ENABLE_HUSH_CASE
4474 if (ctx.ctx_res_w == RES_MATCH)
4475 break; /* we are in case's "word | word)" */
4477 if (next == '|') { /* || */
4479 done_pipe(&ctx, PIPE_OR);
4481 /* we could pick up a file descriptor choice here
4482 * with redirect_opt_num(), but bash doesn't do it.
4483 * "echo foo 2| cat" yields "foo 2". */
4488 #if ENABLE_HUSH_CASE
4489 /* "case... in [(]word)..." - skip '(' */
4490 if (ctx.ctx_res_w == RES_MATCH
4491 && ctx.command->argv == NULL /* not (word|(... */
4492 && dest.length == 0 /* not word(... */
4493 && dest.nonnull == 0 /* not ""(... */
4498 #if ENABLE_HUSH_FUNCTIONS
4499 if (dest.length != 0 /* not just () but word() */
4500 && dest.nonnull == 0 /* not a"b"c() */
4501 && ctx.command->argv == NULL /* it's the first word */
4502 //TODO: "func ( ) {...}" - note spaces - is valid format too in bash
4503 && i_peek(input) == ')'
4504 && !match_reserved_word(&dest)
4506 bb_error_msg("seems like a function definition");
4509 //TODO: do it properly.
4510 ch = i_getch(input);
4511 } while (ch == ' ' || ch == '\n');
4513 syntax("was expecting {");
4516 ch = 'F'; /* magic value */
4520 if (parse_group(&dest, &ctx, input, ch) != 0) {
4525 #if ENABLE_HUSH_CASE
4526 if (ctx.ctx_res_w == RES_MATCH)
4530 /* proper use of this character is caught by end_trigger:
4531 * if we see {, we call parse_group(..., end_trigger='}')
4532 * and it will match } earlier (not here). */
4533 syntax("unexpected } or )");
4537 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4543 struct parse_context *pctx;
4544 IF_HAS_KEYWORDS(struct parse_context *p2;)
4546 /* Clean up allocated tree.
4547 * Samples for finding leaks on syntax error recovery path.
4548 * Execute them from interactive shell and watch pmap `pidof hush`.
4549 * while if false; then false; fi do break; done (bash accepts it)
4550 * while if false; then false; fi; do break; fi
4554 /* Update pipe/command counts,
4555 * otherwise freeing may miss some */
4556 done_pipe(pctx, PIPE_SEQ);
4557 debug_printf_clean("freeing list %p from ctx %p\n",
4558 pctx->list_head, pctx);
4559 debug_print_tree(pctx->list_head, 0);
4560 free_pipe_list(pctx->list_head, 0);
4561 debug_printf_clean("freed list %p\n", pctx->list_head);
4562 IF_HAS_KEYWORDS(p2 = pctx->stack;)
4566 IF_HAS_KEYWORDS(pctx = p2;)
4567 } while (HAS_KEYWORDS && pctx);
4568 /* Free text, clear all dest fields */
4570 /* If we are not in top-level parse, we return,
4571 * our caller will propagate error.
4573 if (end_trigger != ';')
4575 /* Discard cached input, force prompt */
4577 USE_HUSH_INTERACTIVE(input->promptme = 1;)
4582 static void set_in_charmap(const char *set, int code)
4585 G.charmap[(unsigned char)*set++] = code;
4588 static void update_charmap(void)
4590 G.ifs = getenv("IFS");
4593 /* Precompute a list of 'flow through' behavior so it can be treated
4594 * quickly up front. Computation is necessary because of IFS.
4595 * Special case handling of IFS == " \t\n" is not implemented.
4596 * The charmap[] array only really needs two bits each,
4597 * and on most machines that would be faster (reduced L1 cache use).
4599 memset(G.charmap, CHAR_ORDINARY, sizeof(G.charmap));
4600 #if ENABLE_HUSH_TICK
4601 set_in_charmap("\\$\"`", CHAR_SPECIAL);
4603 set_in_charmap("\\$\"", CHAR_SPECIAL);
4605 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
4606 set_in_charmap(G.ifs, CHAR_IFS); /* are ordinary if quoted */
4609 /* Execiting from string: eval, sh -c '...'
4610 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
4611 * end_trigger controls how often we stop parsing
4612 * NUL: parse all, execute, return
4613 * ';': parse till ';' or newline, execute, repeat till EOF
4615 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
4618 struct pipe *pipe_list;
4622 pipe_list = parse_stream(inp, end_trigger);
4623 if (!pipe_list) /* EOF */
4625 debug_print_tree(pipe_list, 0);
4626 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
4627 run_and_free_list(pipe_list);
4628 /* Loop on syntax errors, return on EOF: */
4632 static void parse_and_run_string(const char *s)
4634 struct in_str input;
4635 setup_string_in_str(&input, s);
4636 parse_and_run_stream(&input, '\0');
4639 static void parse_and_run_file(FILE *f)
4641 struct in_str input;
4642 setup_file_in_str(&input, f);
4643 parse_and_run_stream(&input, ';');
4647 /* Make sure we have a controlling tty. If we get started under a job
4648 * aware app (like bash for example), make sure we are now in charge so
4649 * we don't fight over who gets the foreground */
4650 static void setup_job_control(void)
4654 shell_pgrp = getpgrp();
4656 /* If we were ran as 'hush &',
4657 * sleep until we are in the foreground. */
4658 while (tcgetpgrp(G_interactive_fd) != shell_pgrp) {
4659 /* Send TTIN to ourself (should stop us) */
4660 kill(- shell_pgrp, SIGTTIN);
4661 shell_pgrp = getpgrp();
4664 /* We _must_ restore tty pgrp on fatal signals */
4665 set_fatal_signals_to_sigexit();
4667 /* Put ourselves in our own process group. */
4668 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
4669 /* Grab control of the terminal. */
4670 tcsetpgrp(G_interactive_fd, getpid());
4674 static int set_mode(const char cstate, const char mode)
4676 int state = (cstate == '-' ? 1 : 0);
4678 case 'n': G.fake_mode = state; break;
4679 case 'x': /*G.debug_mode = state;*/ break;
4680 default: return EXIT_FAILURE;
4682 return EXIT_SUCCESS;
4685 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4686 int hush_main(int argc, char **argv)
4688 static const struct variable const_shell_ver = {
4690 .varstr = (char*)hush_version_str,
4691 .max_len = 1, /* 0 can provoke free(name) */
4699 struct variable *cur_var;
4703 G.root_pid = getpid();
4705 /* Deal with HUSH_VERSION */
4706 G.shell_ver = const_shell_ver; /* copying struct here */
4707 G.top_var = &G.shell_ver;
4708 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
4709 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
4710 /* Initialize our shell local variables with the values
4711 * currently living in the environment */
4712 cur_var = G.top_var;
4715 char *value = strchr(*e, '=');
4716 if (value) { /* paranoia */
4717 cur_var->next = xzalloc(sizeof(*cur_var));
4718 cur_var = cur_var->next;
4719 cur_var->varstr = *e;
4720 cur_var->max_len = strlen(*e);
4721 cur_var->flg_export = 1;
4725 debug_printf_env("putenv '%s'\n", hush_version_str);
4726 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
4728 #if ENABLE_FEATURE_EDITING
4729 G.line_input_state = new_line_input_t(FOR_SHELL);
4731 /* XXX what should these be while sourcing /etc/profile? */
4732 G.global_argc = argc;
4733 G.global_argv = argv;
4734 /* Initialize some more globals to non-zero values */
4736 #if ENABLE_HUSH_INTERACTIVE
4737 if (ENABLE_FEATURE_EDITING)
4738 cmdedit_set_initial_prompt();
4742 if (EXIT_SUCCESS) /* otherwise is already done */
4743 G.last_return_code = EXIT_SUCCESS;
4745 if (argv[0] && argv[0][0] == '-') {
4746 debug_printf("sourcing /etc/profile\n");
4747 input = fopen_for_read("/etc/profile");
4748 if (input != NULL) {
4749 close_on_exec_on(fileno(input));
4750 parse_and_run_file(input);
4756 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
4757 while ((opt = getopt(argc, argv, "c:xins")) > 0) {
4760 G.global_argv = argv + optind;
4761 if (!argv[optind]) {
4762 /* -c 'script' (no params): prevent empty $0 */
4763 *--G.global_argv = argv[0];
4765 } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
4766 G.global_argc = argc - optind;
4767 parse_and_run_string(optarg);
4770 /* Well, we cannot just declare interactiveness,
4771 * we have to have some stuff (ctty, etc) */
4772 /* G_interactive_fd++; */
4775 /* "-s" means "read from stdin", but this is how we always
4776 * operate, so simply do nothing here. */
4780 if (!set_mode('-', opt))
4784 fprintf(stderr, "Usage: sh [FILE]...\n"
4785 " or: sh -c command [args]...\n\n");
4793 /* A shell is interactive if the '-i' flag was given, or if all of
4794 * the following conditions are met:
4796 * no arguments remaining or the -s flag given
4797 * standard input is a terminal
4798 * standard output is a terminal
4799 * Refer to Posix.2, the description of the 'sh' utility. */
4800 if (argv[optind] == NULL && input == stdin
4801 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4803 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
4804 debug_printf("saved_tty_pgrp=%d\n", G.saved_tty_pgrp);
4805 if (G.saved_tty_pgrp >= 0) {
4806 /* try to dup to high fd#, >= 255 */
4807 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4808 if (G_interactive_fd < 0) {
4809 /* try to dup to any fd */
4810 G_interactive_fd = dup(STDIN_FILENO);
4811 if (G_interactive_fd < 0)
4813 G_interactive_fd = 0;
4815 // TODO: track & disallow any attempts of user
4816 // to (inadvertently) close/redirect it
4819 init_signal_mask(); /* note: ensures SIGCHLD is not masked */
4820 debug_printf("interactive_fd=%d\n", G_interactive_fd);
4821 if (G_interactive_fd) {
4822 fcntl(G_interactive_fd, F_SETFD, FD_CLOEXEC);
4823 /* Looks like they want an interactive shell */
4824 setup_job_control();
4825 /* -1 is special - makes xfuncs longjmp, not exit
4826 * (we reset die_sleep = 0 whereever we [v]fork) */
4828 if (setjmp(die_jmp)) {
4829 /* xfunc has failed! die die die */
4830 hush_exit(xfunc_error_retval);
4833 #elif ENABLE_HUSH_INTERACTIVE
4834 /* no job control compiled, only prompt/line editing */
4835 if (argv[optind] == NULL && input == stdin
4836 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4838 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4839 if (G_interactive_fd < 0) {
4840 /* try to dup to any fd */
4841 G_interactive_fd = dup(STDIN_FILENO);
4842 if (G_interactive_fd < 0)
4844 G_interactive_fd = 0;
4846 if (G_interactive_fd) {
4847 fcntl(G_interactive_fd, F_SETFD, FD_CLOEXEC);
4850 init_signal_mask(); /* note: ensures SIGCHLD is not masked */
4854 /* POSIX allows shell to re-enable SIGCHLD
4855 * even if it was SIG_IGN on entry */
4856 // G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
4857 signal(SIGCHLD, SIG_DFL); // SIGCHLD_handler);
4859 #if ENABLE_HUSH_INTERACTIVE && !ENABLE_FEATURE_SH_EXTRA_QUIET
4860 if (G_interactive_fd) {
4861 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
4862 printf("Enter 'help' for a list of built-in commands.\n\n");
4866 if (argv[optind] == NULL) {
4867 parse_and_run_file(stdin);
4869 debug_printf("\nrunning script '%s'\n", argv[optind]);
4870 G.global_argv = argv + optind;
4871 G.global_argc = argc - optind;
4872 input = xfopen_for_read(argv[optind]);
4873 fcntl(fileno(input), F_SETFD, FD_CLOEXEC);
4874 parse_and_run_file(input);
4879 #if ENABLE_FEATURE_CLEAN_UP
4881 if (G.cwd != bb_msg_unknown)
4883 cur_var = G.top_var->next;
4885 struct variable *tmp = cur_var;
4886 if (!cur_var->max_len)
4887 free(cur_var->varstr);
4888 cur_var = cur_var->next;
4892 hush_exit(G.last_return_code);
4897 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4898 int lash_main(int argc, char **argv)
4900 //bb_error_msg("lash is deprecated, please use hush instead");
4901 return hush_main(argc, argv);
4909 static int builtin_trap(char **argv)
4916 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
4919 /* No args: print all trapped. This isn't 100% correct as we should
4920 * be escaping the cmd so that it can be pasted back in ...
4922 for (i = 0; i < NSIG; ++i)
4924 printf("trap -- '%s' %s\n", G.traps[i], get_signame(i));
4925 return EXIT_SUCCESS;
4930 /* if first arg is decimal: reset all specified */
4931 sig = bb_strtou(*++argv, NULL, 10);
4937 sig = get_signum(*argv++);
4938 if (sig < 0 || sig >= NSIG) {
4940 /* mimic bash message exactly */
4941 bb_perror_msg("trap: %s: invalid signal specification", argv[i]);
4946 G.traps[sig] = xstrdup(new_cmd);
4948 debug_printf("trap: setting SIG%s (%i) to '%s'",
4949 get_signame(sig), sig, G.traps[sig]);
4951 /* There is no signal for 0 (EXIT) */
4956 sigaddset(&G.blocked_set, sig);
4958 /* there was a trap handler, we are removing it
4959 * (if sig has non-DFL handling,
4960 * we don't need to do anything) */
4961 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
4963 sigdelset(&G.blocked_set, sig);
4965 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
4970 /* first arg is "-": reset all specified to default */
4971 /* first arg is "": ignore all specified */
4972 /* everything else: execute first arg upon signal */
4974 bb_error_msg("trap: invalid arguments");
4975 return EXIT_FAILURE;
4977 if (LONE_DASH(*argv))
4985 static int builtin_true(char **argv UNUSED_PARAM)
4990 static int builtin_test(char **argv)
4997 return test_main(argc, argv - argc);
5000 static int builtin_echo(char **argv)
5007 return echo_main(argc, argv - argc);
5010 static int builtin_eval(char **argv)
5012 int rcode = EXIT_SUCCESS;
5015 char *str = expand_strvec_to_string(argv + 1);
5017 * eval "echo Hi; done" ("done" is syntax error):
5018 * "echo Hi" will not execute too.
5020 parse_and_run_string(str);
5022 rcode = G.last_return_code;
5027 static int builtin_cd(char **argv)
5030 if (argv[1] == NULL) {
5031 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
5032 * bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
5034 newdir = getenv("HOME") ? : "/";
5037 if (chdir(newdir)) {
5038 printf("cd: %s: %s\n", newdir, strerror(errno));
5039 return EXIT_FAILURE;
5042 return EXIT_SUCCESS;
5045 static int builtin_exec(char **argv)
5047 if (argv[1] == NULL)
5048 return EXIT_SUCCESS; /* bash does this */
5053 // FIXME: if exec fails, bash does NOT exit! We do...
5054 pseudo_exec_argv(&dummy, argv + 1, 0, NULL);
5059 static int builtin_exit(char **argv)
5061 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
5062 //puts("exit"); /* bash does it */
5063 // TODO: warn if we have background jobs: "There are stopped jobs"
5064 // On second consecutive 'exit', exit anyway.
5065 if (argv[1] == NULL)
5066 hush_exit(G.last_return_code);
5067 /* mimic bash: exit 123abc == exit 255 + error msg */
5068 xfunc_error_retval = 255;
5069 /* bash: exit -2 == exit 254, no error msg */
5070 hush_exit(xatoi(argv[1]) & 0xff);
5073 static int builtin_export(char **argv)
5076 char *name = argv[1];
5080 // ash emits: export VAR='VAL'
5081 // bash: declare -x VAR="VAL"
5082 // (both also escape as needed (quotes, $, etc))
5087 return EXIT_SUCCESS;
5090 value = strchr(name, '=');
5092 /* They are exporting something without a =VALUE */
5093 struct variable *var;
5095 var = get_local_var(name);
5097 var->flg_export = 1;
5098 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
5099 putenv(var->varstr);
5101 /* bash does not return an error when trying to export
5102 * an undefined variable. Do likewise. */
5103 return EXIT_SUCCESS;
5106 set_local_var(xstrdup(name), 1);
5107 return EXIT_SUCCESS;
5111 /* built-in 'fg' and 'bg' handler */
5112 static int builtin_fg_bg(char **argv)
5117 if (!G_interactive_fd)
5118 return EXIT_FAILURE;
5119 /* If they gave us no args, assume they want the last backgrounded task */
5121 for (pi = G.job_list; pi; pi = pi->next) {
5122 if (pi->jobid == G.last_jobid) {
5126 bb_error_msg("%s: no current job", argv[0]);
5127 return EXIT_FAILURE;
5129 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
5130 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
5131 return EXIT_FAILURE;
5133 for (pi = G.job_list; pi; pi = pi->next) {
5134 if (pi->jobid == jobnum) {
5138 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
5139 return EXIT_FAILURE;
5141 // TODO: bash prints a string representation
5142 // of job being foregrounded (like "sleep 1 | cat")
5143 if (*argv[0] == 'f') {
5144 /* Put the job into the foreground. */
5145 tcsetpgrp(G_interactive_fd, pi->pgrp);
5148 /* Restart the processes in the job */
5149 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
5150 for (i = 0; i < pi->num_cmds; i++) {
5151 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
5152 pi->cmds[i].is_stopped = 0;
5154 pi->stopped_cmds = 0;
5156 i = kill(- pi->pgrp, SIGCONT);
5158 if (errno == ESRCH) {
5159 delete_finished_bg_job(pi);
5160 return EXIT_SUCCESS;
5162 bb_perror_msg("kill (SIGCONT)");
5166 if (*argv[0] == 'f') {
5168 return checkjobs_and_fg_shell(pi);
5170 return EXIT_SUCCESS;
5174 #if ENABLE_HUSH_HELP
5175 static int builtin_help(char **argv UNUSED_PARAM)
5177 const struct built_in_command *x;
5179 printf("\nBuilt-in commands:\n");
5180 printf("-------------------\n");
5181 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
5182 printf("%s\t%s\n", x->cmd, x->descr);
5185 return EXIT_SUCCESS;
5190 static int builtin_jobs(char **argv UNUSED_PARAM)
5193 const char *status_string;
5195 for (job = G.job_list; job; job = job->next) {
5196 if (job->alive_cmds == job->stopped_cmds)
5197 status_string = "Stopped";
5199 status_string = "Running";
5201 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
5203 return EXIT_SUCCESS;
5207 static int builtin_pwd(char **argv UNUSED_PARAM)
5210 return EXIT_SUCCESS;
5213 static int builtin_read(char **argv)
5216 const char *name = argv[1] ? argv[1] : "REPLY";
5218 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
5219 return set_local_var(string, 0);
5222 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
5223 * built-in 'set' handler
5225 * set [-abCefhmnuvx] [-o option] [argument...]
5226 * set [+abCefhmnuvx] [+o option] [argument...]
5227 * set -- [argument...]
5230 * Implementations shall support the options in both their hyphen and
5231 * plus-sign forms. These options can also be specified as options to sh.
5233 * Write out all variables and their values: set
5234 * Set $1, $2, and $3 and set "$#" to 3: set c a b
5235 * Turn on the -x and -v options: set -xv
5236 * Unset all positional parameters: set --
5237 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
5238 * Set the positional parameters to the expansion of x, even if x expands
5239 * with a leading '-' or '+': set -- $x
5241 * So far, we only support "set -- [argument...]" and some of the short names.
5243 static int builtin_set(char **argv)
5246 char **pp, **g_argv;
5247 char *arg = *++argv;
5251 for (e = G.top_var; e; e = e->next)
5253 return EXIT_SUCCESS;
5257 if (!strcmp(arg, "--")) {
5262 if (arg[0] == '+' || arg[0] == '-') {
5263 for (n = 1; arg[n]; ++n)
5264 if (set_mode(arg[0], arg[n]))
5270 } while ((arg = *++argv) != NULL);
5271 /* Now argv[0] is 1st argument */
5273 /* Only reset global_argv if we didn't process anything */
5275 return EXIT_SUCCESS;
5278 /* NB: G.global_argv[0] ($0) is never freed/changed */
5279 g_argv = G.global_argv;
5280 if (G.global_args_malloced) {
5286 G.global_args_malloced = 1;
5287 pp = xzalloc(sizeof(pp[0]) * 2);
5288 pp[0] = g_argv[0]; /* retain $0 */
5291 /* This realloc's G.global_argv */
5292 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
5299 return EXIT_SUCCESS;
5301 /* Nothing known, so abort */
5303 bb_error_msg("set: %s: invalid option", arg);
5304 return EXIT_FAILURE;
5307 static int builtin_shift(char **argv)
5313 if (n >= 0 && n < G.global_argc) {
5314 if (G.global_args_malloced) {
5317 free(G.global_argv[m++]);
5320 memmove(&G.global_argv[1], &G.global_argv[n+1],
5321 G.global_argc * sizeof(G.global_argv[0]));
5322 return EXIT_SUCCESS;
5324 return EXIT_FAILURE;
5327 static int builtin_source(char **argv)
5331 if (argv[1] == NULL)
5332 return EXIT_FAILURE;
5334 /* XXX search through $PATH is missing */
5335 input = fopen_for_read(argv[1]);
5337 bb_error_msg("can't open '%s'", argv[1]);
5338 return EXIT_FAILURE;
5340 close_on_exec_on(fileno(input));
5342 /* Now run the file */
5343 /* XXX argv and argc are broken; need to save old G.global_argv
5344 * (pointer only is OK!) on this stack frame,
5345 * set G.global_argv=argv+1, recurse, and restore. */
5346 parse_and_run_file(input);
5348 return G.last_return_code;
5351 static int builtin_umask(char **argv)
5354 const char *arg = argv[1];
5356 new_umask = bb_strtou(arg, NULL, 8);
5358 return EXIT_FAILURE;
5360 new_umask = umask(0);
5361 printf("%.3o\n", (unsigned) new_umask);
5364 return EXIT_SUCCESS;
5367 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
5368 static int builtin_unset(char **argv)
5375 return EXIT_SUCCESS;
5378 if (argv[1][0] == '-') {
5379 switch (argv[1][1]) {
5381 case 'f': if (ENABLE_HUSH_FUNCTIONS) { var = false; break; }
5383 bb_error_msg("unset: %s: invalid option", argv[1]);
5384 return EXIT_FAILURE;
5392 if (unset_local_var(argv[i]))
5395 #if ENABLE_HUSH_FUNCTIONS
5397 unset_local_func(argv[i]);
5403 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
5404 static int builtin_wait(char **argv)
5406 int ret = EXIT_SUCCESS;
5409 if (*++argv == NULL) {
5410 /* Don't care about wait results */
5411 /* Note 1: must wait until there are no more children */
5412 /* Note 2: must be interruptible */
5414 * $ sleep 3 & sleep 6 & wait
5419 * $ sleep 3 & sleep 6 & wait
5423 * ^C <-- after ~4 sec from keyboard
5426 sigaddset(&G.blocked_set, SIGCHLD);
5427 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5430 if (errno == ECHILD)
5432 /* Wait for SIGCHLD or any other signal of interest */
5433 /* sigtimedwait with infinite timeout: */
5434 sig = sigwaitinfo(&G.blocked_set, NULL);
5436 sig = check_and_run_traps(sig);
5437 if (sig && sig != SIGCHLD) { /* see note 2 */
5443 sigdelset(&G.blocked_set, SIGCHLD);
5444 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5448 /* This is probably buggy wrt interruptible-ness */
5450 pid_t pid = bb_strtou(*argv, NULL, 10);
5452 /* mimic bash message */
5453 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
5454 return EXIT_FAILURE;
5456 if (waitpid(pid, &status, 0) == pid) {
5457 if (WIFSIGNALED(status))
5458 ret = 128 + WTERMSIG(status);
5459 else if (WIFEXITED(status))
5460 ret = WEXITSTATUS(status);
5464 bb_perror_msg("wait %s", *argv);
5473 #if ENABLE_HUSH_LOOPS
5474 static int builtin_break(char **argv)
5476 if (G.depth_of_loop == 0) {
5477 bb_error_msg("%s: only meaningful in a loop", argv[0]);
5478 return EXIT_SUCCESS; /* bash compat */
5480 G.flag_break_continue++; /* BC_BREAK = 1 */
5481 G.depth_break_continue = 1;
5483 G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
5484 if (errno || !G.depth_break_continue || argv[2]) {
5485 bb_error_msg("%s: bad arguments", argv[0]);
5486 G.flag_break_continue = BC_BREAK;
5487 G.depth_break_continue = UINT_MAX;
5490 if (G.depth_of_loop < G.depth_break_continue)
5491 G.depth_break_continue = G.depth_of_loop;
5492 return EXIT_SUCCESS;
5495 static int builtin_continue(char **argv)
5497 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
5498 return builtin_break(argv);