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 fp = (G_interactive_fd ? bb_error_msg : bb_error_msg_and_die);
620 fp(msg ? "%s: %s" : notice, notice, msg);
623 #define syntax(msg) maybe_die("syntax error", msg);
625 /* Debug -- trick gcc to expand __LINE__ and convert to string */
626 #define __syntax(msg, line) maybe_die("syntax error hush.c:" # line, msg)
627 #define _syntax(msg, line) __syntax(msg, line)
628 #define syntax(msg) _syntax(msg, __LINE__)
631 static int glob_needed(const char *s)
636 if (*s == '*' || *s == '[' || *s == '?')
643 static int is_assignment(const char *s)
645 if (!s || !(isalpha(*s) || *s == '_'))
648 while (isalnum(*s) || *s == '_')
653 /* Replace each \x with x in place, return ptr past NUL. */
654 static char *unbackslash(char *src)
660 if ((*dst++ = *src++) == '\0')
666 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
687 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
688 v[count1 + count2] = NULL;
691 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
695 static char **add_string_to_strings(char **strings, char *add)
700 return add_strings_to_strings(strings, v, /*dup:*/ 0);
703 static void putenv_all(char **strings)
708 debug_printf_env("putenv '%s'\n", *strings);
713 static char **putenv_all_and_save_old(char **strings)
723 eq = strchr(*strings, '=');
726 v = getenv(*strings);
729 /* v points to VAL in VAR=VAL, go back to VAR */
730 v -= (eq - *strings) + 1;
731 old = add_string_to_strings(old, v);
740 static void free_strings_and_unsetenv(char **strings, int unset)
750 debug_printf_env("unsetenv '%s'\n", *v);
758 static void free_strings(char **strings)
760 free_strings_and_unsetenv(strings, 0);
764 /* Basic theory of signal handling in shell
765 * ========================================
766 * This does not describe what hush does, rather, it is current understanding
767 * what it _should_ do. If it doesn't, it's a bug.
768 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
770 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
771 * is finished or backgrounded. It is the same in interactive and
772 * non-interactive shells, and is the same regardless of whether
773 * a user trap handler is installed or a shell special one is in effect.
774 * ^C or ^Z from keyboard seem to execute "at once" because it usually
775 * backgrounds (i.e. stops) or kills all members of currently running
778 * Wait builtin in interruptible by signals for which user trap is set
779 * or by SIGINT in interactive shell.
781 * Trap handlers will execute even within trap handlers. (right?)
783 * User trap handlers are forgotten when subshell ("(cmd)") is entered. [TODO]
785 * If job control is off, backgrounded commands ("cmd &")
786 * have SIGINT, SIGQUIT set to SIG_IGN.
788 * Commands run in command substitution ("`cmd`")
789 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
791 * Ordinary commands have signals set to SIG_IGN/DFL set as inherited
792 * by the shell from its parent.
794 * Siganls which differ from SIG_DFL action
795 * (note: child (i.e., [v]forked) shell is not an interactive shell):
798 * SIGTERM (interactive): ignore
799 * SIGHUP (interactive):
800 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
801 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
802 * (note that ^Z is handled not by trapping SIGTSTP, but by seeing
803 * that all pipe members are stopped) (right?)
804 * SIGINT (interactive): wait for last pipe, ignore the rest
805 * of the command line, show prompt. NB: ^C does not send SIGINT
806 * to interactive shell while shell is waiting for a pipe,
807 * since shell is bg'ed (is not in foreground process group).
808 * (check/expand this)
809 * Example 1: this waits 5 sec, but does not execute ls:
810 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
811 * Example 2: this does not wait and does not execute ls:
812 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
813 * Example 3: this does not wait 5 sec, but executes ls:
814 * "sleep 5; ls -l" + press ^C
816 * (What happens to signals which are IGN on shell start?)
817 * (What happens with signal mask on shell start?)
819 * Implementation in hush
820 * ======================
821 * We use in-kernel pending signal mask to determine which signals were sent.
822 * We block all signals which we don't want to take action immediately,
823 * i.e. we block all signals which need to have special handling as described
824 * above, and all signals which have traps set.
825 * After each pipe execution, we extract any pending signals via sigtimedwait()
828 * unsigned non_DFL_mask: a mask of such "special" signals
829 * sigset_t blocked_set: current blocked signal set
832 * clear bit in blocked_set unless it is also in non_DFL
833 * "trap 'cmd' SIGxxx":
834 * set bit in blocked_set (even if 'cmd' is '')
835 * after [v]fork, if we plan to be a shell:
836 * nothing for {} child shell (say, "true | { true; true; } | true")
837 * unset all traps if () shell. [TODO]
838 * after [v]fork, if we plan to exec:
839 * POSIX says pending signal mask is cleared in child - no need to clear it.
840 * Restore blocked signal set to one inherited by shell just prior to exec.
842 * Note: as a result, we do not use signal handlers much. The only uses
843 * are to count SIGCHLDs [disabled - bug somewhere, + bloat]
844 * and to restore tty pgrp on signal-induced exit.
846 * TODO: check/fix wait builtin to be interruptible.
849 //static void SIGCHLD_handler(int sig UNUSED_PARAM)
851 // G.count_SIGCHLD++;
854 /* called once at shell init */
855 static void init_signal_mask(void)
858 unsigned mask = (1 << SIGQUIT);
859 if (G_interactive_fd) {
865 | (1 << SIGTTIN) | (1 << SIGTTOU) | (1 << SIGTSTP)
870 G.non_DFL_mask = mask;
872 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
876 sigaddset(&G.blocked_set, sig);
880 sigdelset(&G.blocked_set, SIGCHLD);
881 sigprocmask(SIG_SETMASK, &G.blocked_set, &G.inherited_set);
884 static int check_and_run_traps(int sig)
886 static const struct timespec zero_timespec = { 0, 0 };
887 smalluint save_rcode;
893 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
898 if (G.traps && G.traps[sig]) {
899 if (G.traps[sig][0]) {
900 /* We have user-defined handler */
901 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
902 save_rcode = G.last_return_code;
905 G.last_return_code = save_rcode;
906 } /* else: "" trap, ignoring signal */
909 /* not a trap: special action */
912 // G.count_SIGCHLD++;
921 default: /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
930 /* Restores tty foreground process group, and exits.
931 * May be called as signal handler for fatal signal
932 * (will faithfully resend signal to itself, producing correct exit state)
933 * or called directly with -EXITCODE.
934 * We also call it if xfunc is exiting. */
935 static void sigexit(int sig) NORETURN;
936 static void sigexit(int sig)
938 /* Disable all signals: job control, SIGPIPE, etc. */
939 sigprocmask_allsigs(SIG_BLOCK);
941 /* Careful: we can end up here after [v]fork. Do not restore
942 * tty pgrp then, only top-level shell process does that */
943 if (G_interactive_fd && getpid() == G.root_pid)
944 tcsetpgrp(G_interactive_fd, G.saved_tty_pgrp);
946 /* Not a signal, just exit */
950 kill_myself_with_sig(sig); /* does not return */
954 static void maybe_set_sighandler(int sig)
956 void (*handler)(int);
957 /* non_DFL_mask'ed signals are, well, masked,
958 * no need to set handler for them.
960 if (!((G.non_DFL_mask >> sig) & 1)) {
961 handler = signal(sig, sigexit);
962 if (handler == SIG_IGN) /* oops... restore back to IGN! */
963 signal(sig, handler);
966 /* Used only to set handler to restore pgrp on exit */
967 static void set_fatal_signals_to_sigexit(void)
970 maybe_set_sighandler(SIGILL );
971 maybe_set_sighandler(SIGFPE );
972 maybe_set_sighandler(SIGBUS );
973 maybe_set_sighandler(SIGSEGV);
974 maybe_set_sighandler(SIGTRAP);
975 } /* else: hush is perfect. what SEGV? */
977 maybe_set_sighandler(SIGABRT);
979 /* bash 3.2 seems to handle these just like 'fatal' ones */
980 maybe_set_sighandler(SIGPIPE);
981 maybe_set_sighandler(SIGALRM);
982 maybe_set_sighandler(SIGHUP );
984 /* if we aren't interactive... but in this case
985 * we never want to restore pgrp on exit, and this fn is not called */
986 /*maybe_set_sighandler(SIGTERM);*/
987 /*maybe_set_sighandler(SIGINT );*/
992 #define set_fatal_signals_to_sigexit(handler) ((void)0)
996 /* Restores tty foreground process group, and exits. */
997 static void hush_exit(int exitcode) NORETURN;
998 static void hush_exit(int exitcode)
1000 if (G.traps && G.traps[0] && G.traps[0][0]) {
1001 char *argv[] = { NULL, xstrdup(G.traps[0]), NULL };
1007 fflush(NULL); /* flush all streams */
1008 sigexit(- (exitcode & 0xff));
1015 static const char *set_cwd(void)
1017 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1018 * we must not try to free(bb_msg_unknown) */
1019 if (G.cwd == bb_msg_unknown)
1021 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1023 G.cwd = bb_msg_unknown;
1028 /* Get/check local shell variables */
1029 static struct variable *get_local_var(const char *name)
1031 struct variable *cur;
1037 for (cur = G.top_var; cur; cur = cur->next) {
1038 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1044 /* Basically useful version until someone wants to get fancier,
1045 * see the bash man page under "Parameter Expansion" */
1046 static const char *lookup_param(const char *src)
1048 struct variable *var = get_local_var(src);
1050 return strchr(var->varstr, '=') + 1;
1054 /* str holds "NAME=VAL" and is expected to be malloced.
1055 * We take ownership of it.
1056 * flg_export is used by:
1059 * -1: if NAME is set, leave export status alone
1060 * if NAME is not set, do not export
1062 static int set_local_var(char *str, int flg_export)
1064 struct variable *cur;
1068 value = strchr(str, '=');
1069 if (!value) { /* not expected to ever happen? */
1074 name_len = value - str + 1; /* including '=' */
1075 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
1077 if (strncmp(cur->varstr, str, name_len) != 0) {
1079 /* Bail out. Note that now cur points
1080 * to last var in linked list */
1086 /* We found an existing var with this name */
1088 if (cur->flg_read_only) {
1089 bb_error_msg("%s: readonly variable", str);
1093 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1094 unsetenv(str); /* just in case */
1096 if (strcmp(cur->varstr, str) == 0) {
1101 if (cur->max_len >= strlen(str)) {
1102 /* This one is from startup env, reuse space */
1103 strcpy(cur->varstr, str);
1106 /* max_len == 0 signifies "malloced" var, which we can
1107 * (and has to) free */
1111 goto set_str_and_exp;
1114 /* Not found - create next variable struct */
1115 cur->next = xzalloc(sizeof(*cur));
1121 if (flg_export == 1)
1122 cur->flg_export = 1;
1123 if (cur->flg_export) {
1124 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1125 return putenv(cur->varstr);
1130 static int unset_local_var(const char *name)
1132 struct variable *cur;
1133 struct variable *prev = prev; /* for gcc */
1137 return EXIT_SUCCESS;
1138 name_len = strlen(name);
1141 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1142 if (cur->flg_read_only) {
1143 bb_error_msg("%s: readonly variable", name);
1144 return EXIT_FAILURE;
1146 /* prev is ok to use here because 1st variable, HUSH_VERSION,
1147 * is ro, and we cannot reach this code on the 1st pass */
1148 prev->next = cur->next;
1149 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1150 bb_unsetenv(cur->varstr);
1154 return EXIT_SUCCESS;
1159 return EXIT_SUCCESS;
1162 #if ENABLE_SH_MATH_SUPPORT
1163 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1164 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1165 static char *endofname(const char *name)
1173 if (!is_in_name(*p))
1179 static void arith_set_local_var(const char *name, const char *val, int flags)
1181 /* arith code doesnt malloc space, so do it for it */
1182 char *var = xasprintf("%s=%s", name, val);
1183 set_local_var(var, flags);
1191 static int static_get(struct in_str *i)
1200 static int static_peek(struct in_str *i)
1205 #if ENABLE_HUSH_INTERACTIVE
1207 static void cmdedit_set_initial_prompt(void)
1209 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1210 G.PS1 = getenv("PS1");
1217 static const char* setup_prompt_string(int promptmode)
1219 const char *prompt_str;
1220 debug_printf("setup_prompt_string %d ", promptmode);
1221 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1222 /* Set up the prompt */
1223 if (promptmode == 0) { /* PS1 */
1225 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1230 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1231 debug_printf("result '%s'\n", prompt_str);
1235 static void get_user_input(struct in_str *i)
1238 const char *prompt_str;
1240 prompt_str = setup_prompt_string(i->promptmode);
1241 #if ENABLE_FEATURE_EDITING
1242 /* Enable command line editing only while a command line
1243 * is actually being read */
1246 /* buglet: SIGINT will not make new prompt to appear _at once_,
1247 * only after <Enter>. (^C will work) */
1248 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1249 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1250 check_and_run_traps(0);
1251 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1252 i->eof_flag = (r < 0);
1253 if (i->eof_flag) { /* EOF/error detected */
1254 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1255 G.user_input_buf[1] = '\0';
1260 fputs(prompt_str, stdout);
1262 G.user_input_buf[0] = r = fgetc(i->file);
1263 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1264 //do we need check_and_run_traps(0)? (maybe only if stdin)
1265 } while (G.flag_SIGINT);
1266 i->eof_flag = (r == EOF);
1268 i->p = G.user_input_buf;
1271 #endif /* INTERACTIVE */
1273 /* This is the magic location that prints prompts
1274 * and gets data back from the user */
1275 static int file_get(struct in_str *i)
1279 /* If there is data waiting, eat it up */
1280 if (i->p && *i->p) {
1281 #if ENABLE_HUSH_INTERACTIVE
1285 if (i->eof_flag && !*i->p)
1288 /* need to double check i->file because we might be doing something
1289 * more complicated by now, like sourcing or substituting. */
1290 #if ENABLE_HUSH_INTERACTIVE
1291 if (G_interactive_fd && i->promptme && i->file == stdin) {
1294 } while (!*i->p); /* need non-empty line */
1295 i->promptmode = 1; /* PS2 */
1300 ch = fgetc(i->file);
1302 debug_printf("file_get: got a '%c' %d\n", ch, ch);
1303 #if ENABLE_HUSH_INTERACTIVE
1310 /* All the callers guarantee this routine will never be
1311 * used right after a newline, so prompting is not needed.
1313 static int file_peek(struct in_str *i)
1316 if (i->p && *i->p) {
1317 if (i->eof_flag && !i->p[1])
1321 ch = fgetc(i->file);
1322 i->eof_flag = (ch == EOF);
1323 i->peek_buf[0] = ch;
1324 i->peek_buf[1] = '\0';
1326 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
1330 static void setup_file_in_str(struct in_str *i, FILE *f)
1332 i->peek = file_peek;
1334 #if ENABLE_HUSH_INTERACTIVE
1336 i->promptmode = 0; /* PS1 */
1342 static void setup_string_in_str(struct in_str *i, const char *s)
1344 i->peek = static_peek;
1345 i->get = static_get;
1346 #if ENABLE_HUSH_INTERACTIVE
1348 i->promptmode = 0; /* PS1 */
1358 #define B_CHUNK (32 * sizeof(char*))
1360 static void o_reset(o_string *o)
1368 static void o_free(o_string *o)
1371 memset(o, 0, sizeof(*o));
1374 static void o_grow_by(o_string *o, int len)
1376 if (o->length + len > o->maxlen) {
1377 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1378 o->data = xrealloc(o->data, 1 + o->maxlen);
1382 static void o_addchr(o_string *o, int ch)
1384 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1386 o->data[o->length] = ch;
1388 o->data[o->length] = '\0';
1391 static void o_addstr(o_string *o, const char *str, int len)
1394 memcpy(&o->data[o->length], str, len);
1396 o->data[o->length] = '\0';
1399 static void o_addstrauto(o_string *o, const char *str)
1401 o_addstr(o, str, strlen(str) + 1);
1404 static void o_addstr_duplicate_backslash(o_string *o, const char *str, int len)
1409 && (*str != '*' && *str != '?' && *str != '[')
1417 /* My analysis of quoting semantics tells me that state information
1418 * is associated with a destination, not a source.
1420 static void o_addqchr(o_string *o, int ch)
1423 char *found = strchr("*?[\\", ch);
1428 o->data[o->length] = '\\';
1431 o->data[o->length] = ch;
1433 o->data[o->length] = '\0';
1436 static void o_addQchr(o_string *o, int ch)
1439 if (o->o_escape && strchr("*?[\\", ch)) {
1441 o->data[o->length] = '\\';
1445 o->data[o->length] = ch;
1447 o->data[o->length] = '\0';
1450 static void o_addQstr(o_string *o, const char *str, int len)
1453 o_addstr(o, str, len);
1459 int ordinary_cnt = strcspn(str, "*?[\\");
1460 if (ordinary_cnt > len) /* paranoia */
1462 o_addstr(o, str, ordinary_cnt);
1463 if (ordinary_cnt == len)
1465 str += ordinary_cnt;
1466 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
1470 if (ch) { /* it is necessarily one of "*?[\\" */
1472 o->data[o->length] = '\\';
1476 o->data[o->length] = ch;
1478 o->data[o->length] = '\0';
1482 /* A special kind of o_string for $VAR and `cmd` expansion.
1483 * It contains char* list[] at the beginning, which is grown in 16 element
1484 * increments. Actual string data starts at the next multiple of 16 * (char*).
1485 * list[i] contains an INDEX (int!) into this string data.
1486 * It means that if list[] needs to grow, data needs to be moved higher up
1487 * but list[i]'s need not be modified.
1488 * NB: remembering how many list[i]'s you have there is crucial.
1489 * o_finalize_list() operation post-processes this structure - calculates
1490 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1492 #if DEBUG_EXPAND || DEBUG_GLOB
1493 static void debug_print_list(const char *prefix, o_string *o, int n)
1495 char **list = (char**)o->data;
1496 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1498 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1499 prefix, list, n, string_start, o->length, o->maxlen);
1501 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1502 o->data + (int)list[i] + string_start,
1503 o->data + (int)list[i] + string_start);
1507 const char *p = o->data + (int)list[n - 1] + string_start;
1508 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
1512 #define debug_print_list(prefix, o, n) ((void)0)
1515 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1516 * in list[n] so that it points past last stored byte so far.
1517 * It returns n+1. */
1518 static int o_save_ptr_helper(o_string *o, int n)
1520 char **list = (char**)o->data;
1524 if (!o->has_empty_slot) {
1525 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1526 string_len = o->length - string_start;
1527 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1528 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
1529 /* list[n] points to string_start, make space for 16 more pointers */
1530 o->maxlen += 0x10 * sizeof(list[0]);
1531 o->data = xrealloc(o->data, o->maxlen + 1);
1532 list = (char**)o->data;
1533 memmove(list + n + 0x10, list + n, string_len);
1534 o->length += 0x10 * sizeof(list[0]);
1536 debug_printf_list("list[%d]=%d string_start=%d\n", n, string_len, string_start);
1538 /* We have empty slot at list[n], reuse without growth */
1539 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1540 string_len = o->length - string_start;
1541 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n", n, string_len, string_start);
1542 o->has_empty_slot = 0;
1544 list[n] = (char*)(ptrdiff_t)string_len;
1548 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
1549 static int o_get_last_ptr(o_string *o, int n)
1551 char **list = (char**)o->data;
1552 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1554 return ((int)(ptrdiff_t)list[n-1]) + string_start;
1557 /* o_glob performs globbing on last list[], saving each result
1558 * as a new list[]. */
1559 static int o_glob(o_string *o, int n)
1565 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
1567 return o_save_ptr_helper(o, n);
1568 pattern = o->data + o_get_last_ptr(o, n);
1569 debug_printf_glob("glob pattern '%s'\n", pattern);
1570 if (!glob_needed(pattern)) {
1572 o->length = unbackslash(pattern) - o->data;
1573 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
1574 return o_save_ptr_helper(o, n);
1577 memset(&globdata, 0, sizeof(globdata));
1578 gr = glob(pattern, 0, NULL, &globdata);
1579 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1580 if (gr == GLOB_NOSPACE)
1581 bb_error_msg_and_die("out of memory during glob");
1582 if (gr == GLOB_NOMATCH) {
1583 globfree(&globdata);
1586 if (gr != 0) { /* GLOB_ABORTED ? */
1587 //TODO: testcase for bad glob pattern behavior
1588 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1590 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1591 char **argv = globdata.gl_pathv;
1592 o->length = pattern - o->data; /* "forget" pattern */
1594 o_addstrauto(o, *argv);
1595 n = o_save_ptr_helper(o, n);
1601 globfree(&globdata);
1603 debug_print_list("o_glob returning", o, n);
1607 /* If o->o_glob == 1, glob the string so far remembered.
1608 * Otherwise, just finish current list[] and start new */
1609 static int o_save_ptr(o_string *o, int n)
1611 if (o->o_glob) { /* if globbing is requested */
1612 /* If o->has_empty_slot, list[n] was already globbed
1613 * (if it was requested back then when it was filled)
1614 * so don't do that again! */
1615 if (!o->has_empty_slot)
1616 return o_glob(o, n); /* o_save_ptr_helper is inside */
1618 return o_save_ptr_helper(o, n);
1621 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
1622 static char **o_finalize_list(o_string *o, int n)
1627 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1629 debug_print_list("finalized", o, n);
1630 debug_printf_expand("finalized n:%d\n", n);
1631 list = (char**)o->data;
1632 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1636 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
1642 /* Expansion can recurse */
1643 #if ENABLE_HUSH_TICK
1644 static int process_command_subs(o_string *dest, const char *s);
1646 static char *expand_string_to_string(const char *str);
1647 static int parse_stream_dquoted(o_string *dest, struct in_str *input, int dquote_end);
1649 /* expand_strvec_to_strvec() takes a list of strings, expands
1650 * all variable references within and returns a pointer to
1651 * a list of expanded strings, possibly with larger number
1652 * of strings. (Think VAR="a b"; echo $VAR).
1653 * This new list is allocated as a single malloc block.
1654 * NULL-terminated list of char* pointers is at the beginning of it,
1655 * followed by strings themself.
1656 * Caller can deallocate entire list by single free(list). */
1658 /* Store given string, finalizing the word and starting new one whenever
1659 * we encounter IFS char(s). This is used for expanding variable values.
1660 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
1661 static int expand_on_ifs(o_string *output, int n, const char *str)
1664 int word_len = strcspn(str, G.ifs);
1666 if (output->o_escape || !output->o_glob)
1667 o_addQstr(output, str, word_len);
1668 else /* protect backslashes against globbing up :) */
1669 o_addstr_duplicate_backslash(output, str, word_len);
1672 if (!*str) /* EOL - do not finalize word */
1674 o_addchr(output, '\0');
1675 debug_print_list("expand_on_ifs", output, n);
1676 n = o_save_ptr(output, n);
1677 str += strspn(str, G.ifs); /* skip ifs chars */
1679 debug_print_list("expand_on_ifs[1]", output, n);
1683 /* Expand all variable references in given string, adding words to list[]
1684 * at n, n+1,... positions. Return updated n (so that list[n] is next one
1685 * to be filled). This routine is extremely tricky: has to deal with
1686 * variables/parameters with whitespace, $* and $@, and constructs like
1687 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
1688 static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
1690 /* or_mask is either 0 (normal case) or 0x80
1691 * (expansion of right-hand side of assignment == 1-element expand.
1692 * It will also do no globbing, and thus we must not backslash-quote!) */
1694 char first_ch, ored_ch;
1701 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
1702 debug_print_list("expand_vars_to_list", output, n);
1703 n = o_save_ptr(output, n);
1704 debug_print_list("expand_vars_to_list[0]", output, n);
1706 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
1707 #if ENABLE_HUSH_TICK
1708 o_string subst_result = NULL_O_STRING;
1710 #if ENABLE_SH_MATH_SUPPORT
1711 char arith_buf[sizeof(arith_t)*3 + 2];
1713 o_addstr(output, arg, p - arg);
1714 debug_print_list("expand_vars_to_list[1]", output, n);
1716 p = strchr(p, SPECIAL_VAR_SYMBOL);
1718 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
1719 /* "$@" is special. Even if quoted, it can still
1720 * expand to nothing (not even an empty string) */
1721 if ((first_ch & 0x7f) != '@')
1722 ored_ch |= first_ch;
1725 switch (first_ch & 0x7f) {
1726 /* Highest bit in first_ch indicates that var is double-quoted */
1728 val = utoa(G.root_pid);
1730 case '!': /* bg pid */
1731 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
1733 case '?': /* exitcode */
1734 val = utoa(G.last_return_code);
1736 case '#': /* argc */
1737 if (arg[1] != SPECIAL_VAR_SYMBOL)
1738 /* actually, it's a ${#var} */
1740 val = utoa(G.global_argc ? G.global_argc-1 : 0);
1745 if (!G.global_argv[i])
1747 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
1748 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
1749 smallint sv = output->o_escape;
1750 /* unquoted var's contents should be globbed, so don't escape */
1751 output->o_escape = 0;
1752 while (G.global_argv[i]) {
1753 n = expand_on_ifs(output, n, G.global_argv[i]);
1754 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
1755 if (G.global_argv[i++][0] && G.global_argv[i]) {
1756 /* this argv[] is not empty and not last:
1757 * put terminating NUL, start new word */
1758 o_addchr(output, '\0');
1759 debug_print_list("expand_vars_to_list[2]", output, n);
1760 n = o_save_ptr(output, n);
1761 debug_print_list("expand_vars_to_list[3]", output, n);
1764 output->o_escape = sv;
1766 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
1767 * and in this case should treat it like '$*' - see 'else...' below */
1768 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
1770 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1771 if (++i >= G.global_argc)
1773 o_addchr(output, '\0');
1774 debug_print_list("expand_vars_to_list[4]", output, n);
1775 n = o_save_ptr(output, n);
1777 } else { /* quoted $*: add as one word */
1779 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1780 if (!G.global_argv[++i])
1783 o_addchr(output, G.ifs[0]);
1787 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
1788 /* "Empty variable", used to make "" etc to not disappear */
1792 #if ENABLE_HUSH_TICK
1793 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
1796 //TODO: can we just stuff it into "output" directly?
1797 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
1798 process_command_subs(&subst_result, arg);
1799 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
1800 val = subst_result.data;
1803 #if ENABLE_SH_MATH_SUPPORT
1804 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
1805 arith_eval_hooks_t hooks;
1810 arg++; /* skip '+' */
1811 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
1812 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
1814 /* Optional: skip expansion if expr is simple ("a + 3", "i++" etc) */
1817 unsigned char c = *exp_str++;
1824 if (strchr(" \t+-*/%_", c) != NULL)
1826 c |= 0x20; /* tolower */
1827 if (c >= 'a' && c <= 'z')
1831 /* We need to expand. Example: "echo $(($a + 1)) $((1 + $((2)) ))" */
1833 struct in_str input;
1834 o_string dest = NULL_O_STRING;
1836 setup_string_in_str(&input, arg);
1837 parse_stream_dquoted(&dest, &input, EOF);
1838 //bb_error_msg("'%s' -> '%s'", arg, dest.data);
1839 exp_str = expand_string_to_string(dest.data);
1840 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
1844 hooks.lookupvar = lookup_param;
1845 hooks.setvar = arith_set_local_var;
1846 hooks.endofname = endofname;
1847 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
1852 case -3: maybe_die("arith", "exponent less than 0"); break;
1853 case -2: maybe_die("arith", "divide by zero"); break;
1854 case -5: maybe_die("arith", "expression recursion loop detected"); break;
1855 default: maybe_die("arith", "syntax error"); break;
1858 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
1859 sprintf(arith_buf, arith_t_fmt, res);
1864 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
1866 bool exp_len = false, exp_null = false;
1867 char *var = arg, exp_save, exp_op, *exp_word;
1870 arg[0] = first_ch & 0x7f;
1872 /* prepare for expansions */
1873 if (var[0] == '#') {
1874 /* handle length expansion ${#var} */
1878 /* maybe handle parameter expansion */
1879 exp_off = strcspn(var, ":-=+?");
1883 exp_save = var[exp_off];
1884 exp_null = exp_save == ':';
1885 exp_word = var + exp_off;
1886 if (exp_null) ++exp_word;
1887 exp_op = *exp_word++;
1888 var[exp_off] = '\0';
1892 /* lookup the variable in question */
1893 if (isdigit(var[0])) {
1894 /* handle_dollar() should have vetted var for us */
1896 if (i < G.global_argc)
1897 val = G.global_argv[i];
1898 /* else val remains NULL: $N with too big N */
1900 val = lookup_param(var);
1902 /* handle any expansions */
1904 debug_printf_expand("expand: length of '%s' = ", val);
1905 val = utoa(val ? strlen(val) : 0);
1906 debug_printf_expand("%s\n", val);
1907 } else if (exp_off) {
1908 /* we need to do an expansion */
1909 int exp_test = (!val || (exp_null && !val[0]));
1911 exp_test = !exp_test;
1912 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
1913 exp_null ? "true" : "false", exp_test);
1916 maybe_die(var, *exp_word ? exp_word : "parameter null or not set");
1920 if (exp_op == '=') {
1921 if (isdigit(var[0]) || var[0] == '#') {
1922 maybe_die(var, "special vars cannot assign in this way");
1925 char *new_var = xmalloc(strlen(var) + strlen(val) + 2);
1926 sprintf(new_var, "%s=%s", var, val);
1927 set_local_var(new_var, -1);
1931 var[exp_off] = exp_save;
1936 #if ENABLE_HUSH_TICK
1939 if (!(first_ch & 0x80)) { /* unquoted $VAR */
1940 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
1942 /* unquoted var's contents should be globbed, so don't escape */
1943 smallint sv = output->o_escape;
1944 output->o_escape = 0;
1945 n = expand_on_ifs(output, n, val);
1947 output->o_escape = sv;
1949 } else { /* quoted $VAR, val will be appended below */
1950 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
1953 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
1955 o_addQstr(output, val, strlen(val));
1957 /* Do the check to avoid writing to a const string */
1958 if (*p != SPECIAL_VAR_SYMBOL)
1959 *p = SPECIAL_VAR_SYMBOL;
1961 #if ENABLE_HUSH_TICK
1962 o_free(&subst_result);
1965 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
1968 debug_print_list("expand_vars_to_list[a]", output, n);
1969 /* this part is literal, and it was already pre-quoted
1970 * if needed (much earlier), do not use o_addQstr here! */
1971 o_addstrauto(output, arg);
1972 debug_print_list("expand_vars_to_list[b]", output, n);
1973 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
1974 && !(ored_ch & 0x80) /* and all vars were not quoted. */
1977 /* allow to reuse list[n] later without re-growth */
1978 output->has_empty_slot = 1;
1980 o_addchr(output, '\0');
1985 static char **expand_variables(char **argv, int or_mask)
1990 o_string output = NULL_O_STRING;
1992 if (or_mask & 0x100) {
1993 output.o_escape = 1; /* protect against globbing for "$var" */
1994 /* (unquoted $var will temporarily switch it off) */
2001 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
2004 debug_print_list("expand_variables", &output, n);
2006 /* output.data (malloced in one block) gets returned in "list" */
2007 list = o_finalize_list(&output, n);
2008 debug_print_strings("expand_variables[1]", list);
2012 static char **expand_strvec_to_strvec(char **argv)
2014 return expand_variables(argv, 0x100);
2017 /* Used for expansion of right hand of assignments */
2018 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2020 static char *expand_string_to_string(const char *str)
2022 char *argv[2], **list;
2024 argv[0] = (char*)str;
2026 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2028 if (!list[0] || list[1])
2029 bb_error_msg_and_die("BUG in varexp2");
2030 /* actually, just move string 2*sizeof(char*) bytes back */
2031 overlapping_strcpy((char*)list, list[0]);
2032 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2036 /* Used for "eval" builtin */
2037 static char* expand_strvec_to_string(char **argv)
2041 list = expand_variables(argv, 0x80);
2042 /* Convert all NULs to spaces */
2047 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2048 bb_error_msg_and_die("BUG in varexp3");
2049 list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
2053 overlapping_strcpy((char*)list, list[0]);
2054 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2058 static char **expand_assignments(char **argv, int count)
2062 /* Expand assignments into one string each */
2063 for (i = 0; i < count; i++) {
2064 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2070 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
2071 * and stderr if they are redirected. */
2072 static int setup_redirects(struct command *prog, int squirrel[])
2075 struct redir_struct *redir;
2077 for (redir = prog->redirects; redir; redir = redir->next) {
2078 if (redir->dup == -1 && redir->rd_filename == NULL) {
2079 /* something went wrong in the parse. Pretend it didn't happen */
2082 if (redir->dup == -1) {
2084 mode = redir_table[redir->rd_type].mode;
2085 //TODO: check redir for names like '\\'
2086 p = expand_string_to_string(redir->rd_filename);
2087 openfd = open_or_warn(p, mode);
2090 /* this could get lost if stderr has been redirected, but
2091 bash and ash both lose it as well (though zsh doesn't!) */
2095 openfd = redir->dup;
2098 if (openfd != redir->fd) {
2099 if (squirrel && redir->fd < 3) {
2100 squirrel[redir->fd] = dup(redir->fd);
2103 //close(openfd); // close(-3) ??!
2105 dup2(openfd, redir->fd);
2106 if (redir->dup == -1)
2114 static void restore_redirects(int squirrel[])
2117 for (i = 0; i < 3; i++) {
2120 /* We simply die on error */
2127 #if !defined(DEBUG_CLEAN)
2128 #define free_pipe_list(head, indent) free_pipe_list(head)
2129 #define free_pipe(pi, indent) free_pipe(pi)
2131 static void free_pipe_list(struct pipe *head, int indent);
2133 /* return code is the exit status of the pipe */
2134 static void free_pipe(struct pipe *pi, int indent)
2137 struct command *command;
2138 struct redir_struct *r, *rnext;
2141 if (pi->stopped_cmds > 0)
2143 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2144 for (i = 0; i < pi->num_cmds; i++) {
2145 command = &pi->cmds[i];
2146 debug_printf_clean("%s command %d:\n", indenter(indent), i);
2147 if (command->argv) {
2148 for (a = 0, p = command->argv; *p; a++, p++) {
2149 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
2151 free_strings(command->argv);
2152 command->argv = NULL;
2154 /* not "else if": on syntax error, we may have both! */
2155 if (command->group) {
2156 debug_printf_clean("%s begin group (grp_type:%d)\n", indenter(indent), command->grp_type);
2157 free_pipe_list(command->group, indent+3);
2158 debug_printf_clean("%s end group\n", indenter(indent));
2159 command->group = NULL;
2161 for (r = command->redirects; r; r = rnext) {
2162 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->rd_type].descrip);
2164 /* guard against the case >$FOO, where foo is unset or blank */
2165 if (r->rd_filename) {
2166 debug_printf_clean(" %s\n", r->rd_filename);
2167 free(r->rd_filename);
2168 r->rd_filename = NULL;
2171 debug_printf_clean("&%d\n", r->dup);
2176 command->redirects = NULL;
2178 free(pi->cmds); /* children are an array, they get freed all at once */
2186 static void free_pipe_list(struct pipe *head, int indent)
2188 struct pipe *pi, *next;
2190 for (pi = head; pi; pi = next) {
2192 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
2194 free_pipe(pi, indent);
2195 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
2197 /*pi->next = NULL;*/
2204 typedef struct nommu_save_t {
2210 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
2211 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
2212 #define pseudo_exec(nommu_save, command, argv_expanded) \
2213 pseudo_exec(command, argv_expanded)
2216 /* Called after [v]fork() in run_pipe(), or from builtin_exec().
2218 * XXX no exit() here. If you don't exec, use _exit instead.
2219 * The at_exit handlers apparently confuse the calling process,
2220 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
2221 static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded) NORETURN;
2222 static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded)
2226 const struct built_in_command *x;
2228 /* If a variable is assigned in a forest, and nobody listens,
2229 * was it ever really set?
2231 if (!argv[assignment_cnt])
2232 _exit(EXIT_SUCCESS);
2234 new_env = expand_assignments(argv, assignment_cnt);
2236 putenv_all(new_env);
2237 free(new_env); /* optional */
2239 nommu_save->new_env = new_env;
2240 nommu_save->old_env = putenv_all_and_save_old(new_env);
2242 if (argv_expanded) {
2243 argv = argv_expanded;
2245 argv = expand_strvec_to_strvec(argv + assignment_cnt);
2247 nommu_save->argv = argv;
2252 * Check if the command matches any of the builtins.
2253 * Depending on context, this might be redundant. But it's
2254 * easier to waste a few CPU cycles than it is to figure out
2255 * if this is one of those cases.
2257 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2258 if (strcmp(argv[0], x->cmd) == 0) {
2259 debug_printf_exec("running builtin '%s'\n", argv[0]);
2260 rcode = x->function(argv);
2266 /* Check if the command matches any busybox applets */
2267 #if ENABLE_FEATURE_SH_STANDALONE
2268 if (strchr(argv[0], '/') == NULL) {
2269 int a = find_applet_by_name(argv[0]);
2271 if (APPLET_IS_NOEXEC(a)) {
2272 debug_printf_exec("running applet '%s'\n", argv[0]);
2273 // is it ok that run_applet_no_and_exit() does exit(), not _exit()?
2274 run_applet_no_and_exit(a, argv);
2276 /* re-exec ourselves with the new arguments */
2277 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
2278 execvp(bb_busybox_exec_path, argv);
2279 /* If they called chroot or otherwise made the binary no longer
2280 * executable, fall through */
2285 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2287 debug_printf_exec("execing '%s'\n", argv[0]);
2288 execvp(argv[0], argv);
2289 bb_perror_msg("can't exec '%s'", argv[0]);
2290 _exit(EXIT_FAILURE);
2293 static int run_list(struct pipe *pi);
2295 /* Called after [v]fork() in run_pipe()
2297 static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded) NORETURN;
2298 static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded)
2301 pseudo_exec_argv(nommu_save, command->argv, command->assignment_cnt, argv_expanded);
2303 if (command->group) {
2305 bb_error_msg_and_die("nested lists are not supported on NOMMU");
2308 debug_printf_exec("pseudo_exec: run_list\n");
2309 rcode = run_list(command->group);
2310 /* OK to leak memory by not calling free_pipe_list,
2311 * since this process is about to exit */
2316 /* Can happen. See what bash does with ">foo" by itself. */
2317 debug_printf("trying to pseudo_exec null command\n");
2318 _exit(EXIT_SUCCESS);
2322 static const char *get_cmdtext(struct pipe *pi)
2328 /* This is subtle. ->cmdtext is created only on first backgrounding.
2329 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
2330 * On subsequent bg argv is trashed, but we won't use it */
2333 argv = pi->cmds[0].argv;
2334 if (!argv || !argv[0]) {
2335 pi->cmdtext = xzalloc(1);
2340 do len += strlen(*argv) + 1; while (*++argv);
2341 pi->cmdtext = p = xmalloc(len);
2342 argv = pi->cmds[0].argv;
2344 len = strlen(*argv);
2345 memcpy(p, *argv, len);
2353 static void insert_bg_job(struct pipe *pi)
2355 struct pipe *thejob;
2358 /* Linear search for the ID of the job to use */
2360 for (thejob = G.job_list; thejob; thejob = thejob->next)
2361 if (thejob->jobid >= pi->jobid)
2362 pi->jobid = thejob->jobid + 1;
2364 /* Add thejob to the list of running jobs */
2366 thejob = G.job_list = xmalloc(sizeof(*thejob));
2368 for (thejob = G.job_list; thejob->next; thejob = thejob->next)
2370 thejob->next = xmalloc(sizeof(*thejob));
2371 thejob = thejob->next;
2374 /* Physically copy the struct job */
2375 memcpy(thejob, pi, sizeof(struct pipe));
2376 thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
2377 /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
2378 for (i = 0; i < pi->num_cmds; i++) {
2379 // TODO: do we really need to have so many fields which are just dead weight
2380 // at execution stage?
2381 thejob->cmds[i].pid = pi->cmds[i].pid;
2382 /* all other fields are not used and stay zero */
2384 thejob->next = NULL;
2385 thejob->cmdtext = xstrdup(get_cmdtext(pi));
2387 /* We don't wait for background thejobs to return -- append it
2388 to the list of backgrounded thejobs and leave it alone */
2389 if (G_interactive_fd)
2390 printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
2391 G.last_bg_pid = thejob->cmds[0].pid;
2392 G.last_jobid = thejob->jobid;
2395 static void remove_bg_job(struct pipe *pi)
2397 struct pipe *prev_pipe;
2399 if (pi == G.job_list) {
2400 G.job_list = pi->next;
2402 prev_pipe = G.job_list;
2403 while (prev_pipe->next != pi)
2404 prev_pipe = prev_pipe->next;
2405 prev_pipe->next = pi->next;
2408 G.last_jobid = G.job_list->jobid;
2413 /* Remove a backgrounded job */
2414 static void delete_finished_bg_job(struct pipe *pi)
2417 pi->stopped_cmds = 0;
2423 /* Check to see if any processes have exited -- if they
2424 * have, figure out why and see if a job has completed */
2425 static int checkjobs(struct pipe* fg_pipe)
2435 debug_printf_jobs("checkjobs %p\n", fg_pipe);
2438 // if (G.handled_SIGCHLD == G.count_SIGCHLD)
2439 // /* avoid doing syscall, nothing there anyway */
2442 attributes = WUNTRACED;
2443 if (fg_pipe == NULL)
2444 attributes |= WNOHANG;
2446 /* Do we do this right?
2447 * bash-3.00# sleep 20 | false
2449 * [3]+ Stopped sleep 20 | false
2450 * bash-3.00# echo $?
2451 * 1 <========== bg pipe is not fully done, but exitcode is already known!
2454 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
2455 //are stopped. Testcase: "cat | cat" in a script (not on command line)
2456 // + killall -STOP cat
2463 // i = G.count_SIGCHLD;
2464 childpid = waitpid(-1, &status, attributes);
2465 if (childpid <= 0) {
2466 if (childpid && errno != ECHILD)
2467 bb_perror_msg("waitpid");
2468 // else /* Until next SIGCHLD, waitpid's are useless */
2469 // G.handled_SIGCHLD = i;
2472 dead = WIFEXITED(status) || WIFSIGNALED(status);
2475 if (WIFSTOPPED(status))
2476 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
2477 childpid, WSTOPSIG(status), WEXITSTATUS(status));
2478 if (WIFSIGNALED(status))
2479 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
2480 childpid, WTERMSIG(status), WEXITSTATUS(status));
2481 if (WIFEXITED(status))
2482 debug_printf_jobs("pid %d exited, exitcode %d\n",
2483 childpid, WEXITSTATUS(status));
2485 /* Were we asked to wait for fg pipe? */
2487 for (i = 0; i < fg_pipe->num_cmds; i++) {
2488 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
2489 if (fg_pipe->cmds[i].pid != childpid)
2491 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
2493 fg_pipe->cmds[i].pid = 0;
2494 fg_pipe->alive_cmds--;
2495 if (i == fg_pipe->num_cmds - 1) {
2496 /* last process gives overall exitstatus */
2497 rcode = WEXITSTATUS(status);
2498 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
2501 fg_pipe->cmds[i].is_stopped = 1;
2502 fg_pipe->stopped_cmds++;
2504 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
2505 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
2506 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
2507 /* All processes in fg pipe have exited/stopped */
2509 if (fg_pipe->alive_cmds)
2510 insert_bg_job(fg_pipe);
2514 /* There are still running processes in the fg pipe */
2515 goto wait_more; /* do waitpid again */
2517 /* it wasnt fg_pipe, look for process in bg pipes */
2521 /* We asked to wait for bg or orphaned children */
2522 /* No need to remember exitcode in this case */
2523 for (pi = G.job_list; pi; pi = pi->next) {
2524 for (i = 0; i < pi->num_cmds; i++) {
2525 if (pi->cmds[i].pid == childpid)
2526 goto found_pi_and_prognum;
2529 /* Happens when shell is used as init process (init=/bin/sh) */
2530 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
2531 continue; /* do waitpid again */
2533 found_pi_and_prognum:
2536 pi->cmds[i].pid = 0;
2538 if (!pi->alive_cmds) {
2539 if (G_interactive_fd)
2540 printf(JOB_STATUS_FORMAT, pi->jobid,
2541 "Done", pi->cmdtext);
2542 delete_finished_bg_job(pi);
2546 pi->cmds[i].is_stopped = 1;
2550 } /* while (waitpid succeeds)... */
2556 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
2559 int rcode = checkjobs(fg_pipe);
2560 /* Job finished, move the shell to the foreground */
2561 p = getpgid(0); /* pgid of our process */
2562 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
2563 tcsetpgrp(G_interactive_fd, p);
2568 /* run_pipe() starts all the jobs, but doesn't wait for anything
2569 * to finish. See checkjobs().
2571 * return code is normally -1, when the caller has to wait for children
2572 * to finish to determine the exit status of the pipe. If the pipe
2573 * is a simple builtin command, however, the action is done by the
2574 * time run_pipe returns, and the exit code is provided as the
2577 * The input of the pipe is always stdin, the output is always
2578 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
2579 * because it tries to avoid running the command substitution in
2580 * subshell, when that is in fact necessary. The subshell process
2581 * now has its stdout directed to the input of the appropriate pipe,
2582 * so this routine is noticeably simpler.
2584 * Returns -1 only if started some children. IOW: we have to
2585 * mask out retvals of builtins etc with 0xff!
2587 static int run_pipe(struct pipe *pi)
2591 int pipefds[2]; /* pipefds[0] is for reading */
2592 struct command *command;
2593 char **argv_expanded;
2595 const struct built_in_command *x;
2597 /* it is not always needed, but we aim to smaller code */
2598 int squirrel[] = { -1, -1, -1 };
2600 const int single_and_fg = (pi->num_cmds == 1 && pi->followup != PIPE_BG);
2602 debug_printf_exec("run_pipe start: single_and_fg=%d\n", single_and_fg);
2608 pi->stopped_cmds = 0;
2610 /* Check if this is a simple builtin (not part of a pipe).
2611 * Builtins within pipes have to fork anyway, and are handled in
2612 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
2614 command = &(pi->cmds[0]);
2616 #if ENABLE_HUSH_FUNCTIONS
2617 if (single_and_fg && command->group && command->grp_type == GRP_FUNCTION) {
2618 /* We "execute" function definition */
2619 bb_error_msg("here we ought to remember function definition, and go on");
2620 return EXIT_SUCCESS;
2624 if (single_and_fg && command->group && command->grp_type == GRP_NORMAL) {
2625 debug_printf("non-subshell grouping\n");
2626 setup_redirects(command, squirrel);
2627 debug_printf_exec(": run_list\n");
2628 rcode = run_list(command->group) & 0xff;
2629 restore_redirects(squirrel);
2630 debug_printf_exec("run_pipe return %d\n", rcode);
2631 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2635 argv = command->argv;
2636 argv_expanded = NULL;
2638 if (single_and_fg && argv != NULL) {
2639 char **new_env = NULL;
2640 char **old_env = NULL;
2642 i = command->assignment_cnt;
2643 if (i != 0 && argv[i] == NULL) {
2644 /* assignments, but no command: set local environment */
2645 for (i = 0; argv[i] != NULL; i++) {
2646 debug_printf("local environment set: %s\n", argv[i]);
2647 p = expand_string_to_string(argv[i]);
2648 set_local_var(p, 0);
2650 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
2653 /* Expand the rest into (possibly) many strings each */
2654 argv_expanded = expand_strvec_to_strvec(argv + i);
2656 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2657 if (strcmp(argv_expanded[0], x->cmd) != 0)
2659 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
2660 debug_printf("exec with redirects only\n");
2661 setup_redirects(command, NULL);
2662 rcode = EXIT_SUCCESS;
2663 goto clean_up_and_ret1;
2665 debug_printf("builtin inline %s\n", argv_expanded[0]);
2666 /* XXX setup_redirects acts on file descriptors, not FILEs.
2667 * This is perfect for work that comes after exec().
2668 * Is it really safe for inline use? Experimentally,
2669 * things seem to work with glibc. */
2670 setup_redirects(command, squirrel);
2671 new_env = expand_assignments(argv, command->assignment_cnt);
2672 old_env = putenv_all_and_save_old(new_env);
2673 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv_expanded[1]);
2674 rcode = x->function(argv_expanded) & 0xff;
2675 #if ENABLE_FEATURE_SH_STANDALONE
2678 restore_redirects(squirrel);
2679 free_strings_and_unsetenv(new_env, 1);
2680 putenv_all(old_env);
2681 free(old_env); /* not free_strings()! */
2683 free(argv_expanded);
2684 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2685 debug_printf_exec("run_pipe return %d\n", rcode);
2688 #if ENABLE_FEATURE_SH_STANDALONE
2689 i = find_applet_by_name(argv_expanded[0]);
2690 if (i >= 0 && APPLET_IS_NOFORK(i)) {
2691 setup_redirects(command, squirrel);
2692 save_nofork_data(&G.nofork_save);
2693 new_env = expand_assignments(argv, command->assignment_cnt);
2694 old_env = putenv_all_and_save_old(new_env);
2695 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
2696 rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
2697 goto clean_up_and_ret;
2702 /* NB: argv_expanded may already be created, and that
2703 * might include `cmd` runs! Do not rerun it! We *must*
2704 * use argv_expanded if it's non-NULL */
2706 /* Going to fork a child per each pipe member */
2710 for (i = 0; i < pi->num_cmds; i++) {
2712 volatile nommu_save_t nommu_save;
2713 nommu_save.new_env = NULL;
2714 nommu_save.old_env = NULL;
2715 nommu_save.argv = NULL;
2717 command = &(pi->cmds[i]);
2718 if (command->argv) {
2719 debug_printf_exec(": pipe member '%s' '%s'...\n", command->argv[0], command->argv[1]);
2721 debug_printf_exec(": pipe member with no argv\n");
2723 /* pipes are inserted between pairs of commands */
2726 if ((i + 1) < pi->num_cmds)
2729 command->pid = BB_MMU ? fork() : vfork();
2730 if (!command->pid) { /* child */
2732 die_sleep = 0; /* let nofork's xfuncs die */
2734 /* Every child adds itself to new process group
2735 * with pgid == pid_of_first_child_in_pipe */
2736 if (G.run_list_level == 1 && G_interactive_fd) {
2739 if (pgrp < 0) /* true for 1st process only */
2741 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
2742 /* We do it in *every* child, not just first,
2744 tcsetpgrp(G_interactive_fd, pgrp);
2748 xmove_fd(nextin, 0);
2749 xmove_fd(pipefds[1], 1); /* write end */
2751 close(pipefds[0]); /* read end */
2752 /* Like bash, explicit redirects override pipes,
2753 * and the pipe fd is available for dup'ing. */
2754 setup_redirects(command, NULL);
2756 /* Restore default handlers just prior to exec */
2757 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
2759 /* Stores to nommu_save list of env vars putenv'ed
2760 * (NOMMU, on MMU we don't need that) */
2761 /* cast away volatility... */
2762 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
2763 /* pseudo_exec() does not return */
2767 /* Clean up after vforked child */
2768 free(nommu_save.argv);
2769 free_strings_and_unsetenv(nommu_save.new_env, 1);
2770 putenv_all(nommu_save.old_env);
2772 free(argv_expanded);
2773 argv_expanded = NULL;
2774 if (command->pid < 0) { /* [v]fork failed */
2775 /* Clearly indicate, was it fork or vfork */
2776 bb_perror_msg(BB_MMU ? "fork" : "vfork");
2780 /* Second and next children need to know pid of first one */
2782 pi->pgrp = command->pid;
2788 if ((i + 1) < pi->num_cmds)
2789 close(pipefds[1]); /* write end */
2790 /* Pass read (output) pipe end to next iteration */
2791 nextin = pipefds[0];
2794 if (!pi->alive_cmds) {
2795 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
2799 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
2803 #ifndef debug_print_tree
2804 static void debug_print_tree(struct pipe *pi, int lvl)
2806 static const char *const PIPE[] = {
2812 static const char *RES[] = {
2813 [RES_NONE ] = "NONE" ,
2816 [RES_THEN ] = "THEN" ,
2817 [RES_ELIF ] = "ELIF" ,
2818 [RES_ELSE ] = "ELSE" ,
2821 #if ENABLE_HUSH_LOOPS
2822 [RES_FOR ] = "FOR" ,
2823 [RES_WHILE] = "WHILE",
2824 [RES_UNTIL] = "UNTIL",
2826 [RES_DONE ] = "DONE" ,
2828 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2831 #if ENABLE_HUSH_CASE
2832 [RES_CASE ] = "CASE" ,
2833 [RES_MATCH] = "MATCH",
2834 [RES_CASEI] = "CASEI",
2835 [RES_ESAC ] = "ESAC" ,
2837 [RES_XXXX ] = "XXXX" ,
2838 [RES_SNTX ] = "SNTX" ,
2840 static const char *const GRPTYPE[] = {
2843 #if ENABLE_HUSH_FUNCTIONS
2852 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2853 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2855 while (prn < pi->num_cmds) {
2856 struct command *command = &pi->cmds[prn];
2857 char **argv = command->argv;
2859 fprintf(stderr, "%*s prog %d assignment_cnt:%d", lvl*2, "", prn, command->assignment_cnt);
2860 if (command->group) {
2861 fprintf(stderr, " group %s: (argv=%p)\n",
2862 GRPTYPE[command->grp_type],
2864 debug_print_tree(command->group, lvl+1);
2868 if (argv) while (*argv) {
2869 fprintf(stderr, " '%s'", *argv);
2872 fprintf(stderr, "\n");
2881 /* NB: called by pseudo_exec, and therefore must not modify any
2882 * global data until exec/_exit (we can be a child after vfork!) */
2883 static int run_list(struct pipe *pi)
2885 #if ENABLE_HUSH_CASE
2886 char *case_word = NULL;
2888 #if ENABLE_HUSH_LOOPS
2889 struct pipe *loop_top = NULL;
2890 char *for_varname = NULL;
2891 char **for_lcur = NULL;
2892 char **for_list = NULL;
2894 smallint flag_skip = 1;
2895 smalluint rcode = 0; /* probably just for compiler */
2896 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
2897 smalluint cond_code = 0;
2899 enum { cond_code = 0, };
2901 /*enum reserved_style*/ smallint rword = RES_NONE;
2902 /*enum reserved_style*/ smallint skip_more_for_this_rword = RES_XXXX;
2904 debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
2906 #if ENABLE_HUSH_LOOPS
2907 /* Check syntax for "for" */
2908 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
2909 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
2911 /* current word is FOR or IN (BOLD in comments below) */
2912 if (cpipe->next == NULL) {
2913 syntax("malformed for");
2914 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
2917 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
2918 if (cpipe->next->res_word == RES_DO)
2920 /* next word is not "do". It must be "in" then ("FOR v in ...") */
2921 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
2922 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
2924 syntax("malformed for");
2925 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
2931 /* Past this point, all code paths should jump to ret: label
2932 * in order to return, no direct "return" statements please.
2933 * This helps to ensure that no memory is leaked. */
2935 ////TODO: ctrl-Z handling needs re-thinking and re-testing
2938 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
2939 * We are saving state before entering outermost list ("while...done")
2940 * so that ctrl-Z will correctly background _entire_ outermost list,
2941 * not just a part of it (like "sleep 1 | exit 2") */
2942 if (++G.run_list_level == 1 && G_interactive_fd) {
2943 if (sigsetjmp(G.toplevel_jb, 1)) {
2944 /* ctrl-Z forked and we are parent; or ctrl-C.
2945 * Sighandler has longjmped us here */
2946 signal(SIGINT, SIG_IGN);
2947 signal(SIGTSTP, SIG_IGN);
2948 /* Restore level (we can be coming from deep inside
2950 G.run_list_level = 1;
2951 #if ENABLE_FEATURE_SH_STANDALONE
2952 if (G.nofork_save.saved) { /* if save area is valid */
2953 debug_printf_jobs("exiting nofork early\n");
2954 restore_nofork_data(&G.nofork_save);
2957 //// if (G.ctrl_z_flag) {
2958 //// /* ctrl-Z has forked and stored pid of the child in pi->pid.
2959 //// * Remember this child as background job */
2960 //// insert_bg_job(pi);
2962 /* ctrl-C. We just stop doing whatever we were doing */
2965 USE_HUSH_LOOPS(loop_top = NULL;)
2966 USE_HUSH_LOOPS(G.depth_of_loop = 0;)
2970 //// /* ctrl-Z handler will store pid etc in pi */
2971 //// G.toplevel_list = pi;
2972 //// G.ctrl_z_flag = 0;
2973 ////#if ENABLE_FEATURE_SH_STANDALONE
2974 //// G.nofork_save.saved = 0; /* in case we will run a nofork later */
2976 //// signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
2977 //// signal(SIGINT, handler_ctrl_c);
2981 /* Go through list of pipes, (maybe) executing them. */
2982 for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
2986 IF_HAS_KEYWORDS(rword = pi->res_word;)
2987 IF_HAS_NO_KEYWORDS(rword = RES_NONE;)
2988 debug_printf_exec(": rword=%d cond_code=%d skip_more=%d\n",
2989 rword, cond_code, skip_more_for_this_rword);
2990 #if ENABLE_HUSH_LOOPS
2991 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
2992 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
2994 /* start of a loop: remember where loop starts */
2999 if (rword == skip_more_for_this_rword && flag_skip) {
3000 if (pi->followup == PIPE_SEQ)
3002 /* it is "<false> && CMD" or "<true> || CMD"
3003 * and we should not execute CMD */
3007 skip_more_for_this_rword = RES_XXXX;
3010 if (rword == RES_THEN) {
3011 /* "if <false> THEN cmd": skip cmd */
3015 if (rword == RES_ELSE || rword == RES_ELIF) {
3016 /* "if <true> then ... ELSE/ELIF cmd":
3017 * skip cmd and all following ones */
3022 #if ENABLE_HUSH_LOOPS
3023 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
3025 /* first loop through for */
3027 static const char encoded_dollar_at[] ALIGN1 = {
3028 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
3029 }; /* encoded representation of "$@" */
3030 static const char *const encoded_dollar_at_argv[] = {
3031 encoded_dollar_at, NULL
3032 }; /* argv list with one element: "$@" */
3035 vals = (char**)encoded_dollar_at_argv;
3036 if (pi->next->res_word == RES_IN) {
3037 /* if no variable values after "in" we skip "for" */
3038 if (!pi->next->cmds[0].argv)
3040 vals = pi->next->cmds[0].argv;
3041 } /* else: "for var; do..." -> assume "$@" list */
3042 /* create list of variable values */
3043 debug_print_strings("for_list made from", vals);
3044 for_list = expand_strvec_to_strvec(vals);
3045 for_lcur = for_list;
3046 debug_print_strings("for_list", for_list);
3047 for_varname = pi->cmds[0].argv[0];
3048 pi->cmds[0].argv[0] = NULL;
3050 free(pi->cmds[0].argv[0]);
3052 /* "for" loop is over, clean up */
3056 pi->cmds[0].argv[0] = for_varname;
3059 /* insert next value from for_lcur */
3060 //TODO: does it need escaping?
3061 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
3062 pi->cmds[0].assignment_cnt = 1;
3064 if (rword == RES_IN) /* "for v IN list;..." - "in" has no cmds anyway */
3066 if (rword == RES_DONE) {
3067 continue; /* "done" has no cmds too */
3070 #if ENABLE_HUSH_CASE
3071 if (rword == RES_CASE) {
3072 case_word = expand_strvec_to_string(pi->cmds->argv);
3075 if (rword == RES_MATCH) {
3078 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
3080 /* all prev words didn't match, does this one match? */
3081 argv = pi->cmds->argv;
3083 char *pattern = expand_string_to_string(*argv);
3084 /* TODO: which FNM_xxx flags to use? */
3085 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
3087 if (cond_code == 0) { /* match! we will execute this branch */
3088 free(case_word); /* make future "word)" stop */
3096 if (rword == RES_CASEI) { /* inside of a case branch */
3098 continue; /* not matched yet, skip this pipe */
3101 /* Just pressing <enter> in shell should check for jobs.
3102 * OTOH, in non-interactive shell this is useless
3103 * and only leads to extra job checks */
3104 if (pi->num_cmds == 0) {
3105 if (G_interactive_fd)
3106 goto check_jobs_and_continue;
3110 /* After analyzing all keywords and conditions, we decided
3111 * to execute this pipe. NB: have to do checkjobs(NULL)
3112 * after run_pipe() to collect any background children,
3113 * even if list execution is to be stopped. */
3114 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
3117 #if ENABLE_HUSH_LOOPS
3118 G.flag_break_continue = 0;
3120 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
3122 /* we only ran a builtin: rcode is already known
3123 * and we don't need to wait for anything. */
3124 check_and_run_traps(0);
3125 #if ENABLE_HUSH_LOOPS
3126 /* was it "break" or "continue"? */
3127 if (G.flag_break_continue) {
3128 smallint fbc = G.flag_break_continue;
3129 /* we might fall into outer *loop*,
3130 * don't want to break it too */
3132 G.depth_break_continue--;
3133 if (G.depth_break_continue == 0)
3134 G.flag_break_continue = 0;
3135 /* else: e.g. "continue 2" should *break* once, *then* continue */
3136 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
3137 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
3138 goto check_jobs_and_break;
3139 /* "continue": simulate end of loop */
3144 } else if (pi->followup == PIPE_BG) {
3145 /* what does bash do with attempts to background builtins? */
3146 /* even bash 3.2 doesn't do that well with nested bg:
3147 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
3148 * I'm NOT treating inner &'s as jobs */
3149 check_and_run_traps(0);
3151 if (G.run_list_level == 1)
3154 rcode = 0; /* EXIT_SUCCESS */
3157 if (G.run_list_level == 1 && G_interactive_fd) {
3158 /* waits for completion, then fg's main shell */
3159 rcode = checkjobs_and_fg_shell(pi);
3160 check_and_run_traps(0);
3161 debug_printf_exec(": checkjobs_and_fg_shell returned %d\n", rcode);
3164 { /* this one just waits for completion */
3165 rcode = checkjobs(pi);
3166 check_and_run_traps(0);
3167 debug_printf_exec(": checkjobs returned %d\n", rcode);
3171 debug_printf_exec(": setting last_return_code=%d\n", rcode);
3172 G.last_return_code = rcode;
3174 /* Analyze how result affects subsequent commands */
3176 if (rword == RES_IF || rword == RES_ELIF)
3179 #if ENABLE_HUSH_LOOPS
3180 if (rword == RES_WHILE) {
3182 rcode = 0; /* "while false; do...done" - exitcode 0 */
3183 goto check_jobs_and_break;
3186 if (rword == RES_UNTIL) {
3188 check_jobs_and_break:
3194 if ((rcode == 0 && pi->followup == PIPE_OR)
3195 || (rcode != 0 && pi->followup == PIPE_AND)
3197 skip_more_for_this_rword = rword;
3200 check_jobs_and_continue:
3205 //// if (G.ctrl_z_flag) {
3206 //// /* ctrl-Z forked somewhere in the past, we are the child,
3207 //// * and now we completed running the list. Exit. */
3213 //// if (!G.run_list_level && G_interactive_fd) {
3214 //// signal(SIGTSTP, SIG_IGN);
3215 //// signal(SIGINT, SIG_IGN);
3218 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
3219 #if ENABLE_HUSH_LOOPS
3224 #if ENABLE_HUSH_CASE
3230 /* Select which version we will use */
3231 static int run_and_free_list(struct pipe *pi)
3234 debug_printf_exec("run_and_free_list entered\n");
3236 debug_printf_exec(": run_list with %d members\n", pi->num_cmds);
3237 rcode = run_list(pi);
3239 /* free_pipe_list has the side effect of clearing memory.
3240 * In the long run that function can be merged with run_list,
3241 * but doing that now would hobble the debugging effort. */
3242 free_pipe_list(pi, /* indent: */ 0);
3243 debug_printf_exec("run_and_free_list return %d\n", rcode);
3248 /* Peek ahead in the in_str to find out if we have a "&n" construct,
3249 * as in "2>&1", that represents duplicating a file descriptor.
3250 * Return either -2 (syntax error), -1 (no &), or the number found.
3252 static int redirect_dup_num(struct in_str *input)
3254 int ch, d = 0, ok = 0;
3256 if (ch != '&') return -1;
3258 i_getch(input); /* get the & */
3262 return -3; /* "-" represents "close me" */
3264 while (isdigit(ch)) {
3265 d = d*10 + (ch-'0');
3272 bb_error_msg("ambiguous redirect");
3276 /* The src parameter allows us to peek forward to a possible &n syntax
3277 * for file descriptor duplication, e.g., "2>&1".
3278 * Return code is 0 normally, 1 if a syntax error is detected in src.
3279 * Resource errors (in xmalloc) cause the process to exit */
3280 static int setup_redirect(struct parse_context *ctx,
3283 struct in_str *input)
3285 struct command *command = ctx->command;
3286 struct redir_struct *redir;
3287 struct redir_struct **redirp;
3290 /* Check for a '2>&1' type redirect */
3291 dup_num = redirect_dup_num(input);
3293 return 1; /* syntax error */
3295 /* Create a new redir_struct and drop it onto the end of the linked list */
3296 redirp = &command->redirects;
3297 while ((redir = *redirp) != NULL) {
3298 redirp = &(redir->next);
3300 *redirp = redir = xzalloc(sizeof(*redir));
3301 /* redir->next = NULL; */
3302 /* redir->rd_filename = NULL; */
3303 redir->rd_type = style;
3304 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
3306 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
3308 redir->dup = dup_num;
3309 if (dup_num != -1) {
3310 /* Erik had a check here that the file descriptor in question
3311 * is legit; I postpone that to "run time"
3312 * A "-" representation of "close me" shows up as a -3 here */
3313 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
3315 /* We do _not_ try to open the file that src points to,
3316 * since we need to return and let src be expanded first.
3317 * Set ctx->pending_redirect, so we know what to do at the
3318 * end of the next parsed word. */
3319 ctx->pending_redirect = redir;
3325 static struct pipe *new_pipe(void)
3328 pi = xzalloc(sizeof(struct pipe));
3329 /*pi->followup = 0; - deliberately invalid value */
3330 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3334 /* Command (member of a pipe) is complete. The only possible error here
3335 * is out of memory, in which case xmalloc exits. */
3336 static int done_command(struct parse_context *ctx)
3338 /* The command is really already in the pipe structure, so
3339 * advance the pipe counter and make a new, null command. */
3340 struct pipe *pi = ctx->pipe;
3341 struct command *command = ctx->command;
3344 if (command->group == NULL
3345 && command->argv == NULL
3346 && command->redirects == NULL
3348 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3349 return pi->num_cmds;
3352 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3354 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3357 /* Only real trickiness here is that the uncommitted
3358 * command structure is not counted in pi->num_cmds. */
3359 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3360 command = &pi->cmds[pi->num_cmds];
3361 memset(command, 0, sizeof(*command));
3363 ctx->command = command;
3364 /* but ctx->pipe and ctx->list_head remain unchanged */
3366 return pi->num_cmds; /* used only for 0/nonzero check */
3369 static void done_pipe(struct parse_context *ctx, pipe_style type)
3373 debug_printf_parse("done_pipe entered, followup %d\n", type);
3374 /* Close previous command */
3375 not_null = done_command(ctx);
3376 ctx->pipe->followup = type;
3377 IF_HAS_KEYWORDS(ctx->pipe->pi_inverted = ctx->ctx_inverted;)
3378 IF_HAS_KEYWORDS(ctx->ctx_inverted = 0;)
3379 IF_HAS_KEYWORDS(ctx->pipe->res_word = ctx->ctx_res_w;)
3381 /* Without this check, even just <enter> on command line generates
3382 * tree of three NOPs (!). Which is harmless but annoying.
3383 * IOW: it is safe to do it unconditionally.
3384 * RES_NONE case is for "for a in; do ..." (empty IN set)
3385 * to work, possibly other cases too. */
3386 if (not_null IF_HAS_KEYWORDS(|| ctx->ctx_res_w != RES_NONE)) {
3388 debug_printf_parse("done_pipe: adding new pipe: "
3389 "not_null:%d ctx->ctx_res_w:%d\n",
3390 not_null, ctx->ctx_res_w);
3392 ctx->pipe->next = new_p;
3394 /* RES_THEN, RES_DO etc are "sticky" -
3395 * they remain set for commands inside if/while.
3396 * This is used to control execution.
3397 * RES_FOR and RES_IN are NOT sticky (needed to support
3398 * cases where variable or value happens to match a keyword):
3400 #if ENABLE_HUSH_LOOPS
3401 if (ctx->ctx_res_w == RES_FOR
3402 || ctx->ctx_res_w == RES_IN)
3403 ctx->ctx_res_w = RES_NONE;
3405 #if ENABLE_HUSH_CASE
3406 if (ctx->ctx_res_w == RES_MATCH)
3407 ctx->ctx_res_w = RES_CASEI;
3409 ctx->command = NULL; /* trick done_command below */
3410 /* Create the memory for command, roughly:
3411 * ctx->pipe->cmds = new struct command;
3412 * ctx->command = &ctx->pipe->cmds[0];
3416 debug_printf_parse("done_pipe return\n");
3419 static void initialize_context(struct parse_context *ctx)
3421 memset(ctx, 0, sizeof(*ctx));
3422 ctx->pipe = ctx->list_head = new_pipe();
3423 /* Create the memory for command, roughly:
3424 * ctx->pipe->cmds = new struct command;
3425 * ctx->command = &ctx->pipe->cmds[0];
3431 /* If a reserved word is found and processed, parse context is modified
3432 * and 1 is returned.
3435 struct reserved_combo {
3438 unsigned char assignment_flag;
3442 FLAG_END = (1 << RES_NONE ),
3444 FLAG_IF = (1 << RES_IF ),
3445 FLAG_THEN = (1 << RES_THEN ),
3446 FLAG_ELIF = (1 << RES_ELIF ),
3447 FLAG_ELSE = (1 << RES_ELSE ),
3448 FLAG_FI = (1 << RES_FI ),
3450 #if ENABLE_HUSH_LOOPS
3451 FLAG_FOR = (1 << RES_FOR ),
3452 FLAG_WHILE = (1 << RES_WHILE),
3453 FLAG_UNTIL = (1 << RES_UNTIL),
3454 FLAG_DO = (1 << RES_DO ),
3455 FLAG_DONE = (1 << RES_DONE ),
3456 FLAG_IN = (1 << RES_IN ),
3458 #if ENABLE_HUSH_CASE
3459 FLAG_MATCH = (1 << RES_MATCH),
3460 FLAG_ESAC = (1 << RES_ESAC ),
3462 FLAG_START = (1 << RES_XXXX ),
3465 static const struct reserved_combo* match_reserved_word(o_string *word)
3467 /* Mostly a list of accepted follow-up reserved words.
3468 * FLAG_END means we are done with the sequence, and are ready
3469 * to turn the compound list into a command.
3470 * FLAG_START means the word must start a new compound list.
3472 static const struct reserved_combo reserved_list[] = {
3474 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3475 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
3476 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3477 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
3478 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
3479 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3481 #if ENABLE_HUSH_LOOPS
3482 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3483 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3484 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3485 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3486 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
3487 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3489 #if ENABLE_HUSH_CASE
3490 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3491 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3494 const struct reserved_combo *r;
3496 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3497 if (strcmp(word->data, r->literal) == 0)
3502 static int reserved_word(o_string *word, struct parse_context *ctx)
3504 #if ENABLE_HUSH_CASE
3505 static const struct reserved_combo reserved_match = {
3506 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3509 const struct reserved_combo *r;
3511 r = match_reserved_word(word);
3515 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3516 #if ENABLE_HUSH_CASE
3517 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
3518 /* "case word IN ..." - IN part starts first match part */
3519 r = &reserved_match;
3522 if (r->flag == 0) { /* '!' */
3523 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3524 syntax("! ! command");
3525 IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
3527 ctx->ctx_inverted = 1;
3530 if (r->flag & FLAG_START) {
3531 struct parse_context *old;
3532 old = xmalloc(sizeof(*old));
3533 debug_printf_parse("push stack %p\n", old);
3534 *old = *ctx; /* physical copy */
3535 initialize_context(ctx);
3537 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3539 ctx->ctx_res_w = RES_SNTX;
3542 ctx->ctx_res_w = r->res;
3543 ctx->old_flag = r->flag;
3544 if (ctx->old_flag & FLAG_END) {
3545 struct parse_context *old;
3546 done_pipe(ctx, PIPE_SEQ);
3547 debug_printf_parse("pop stack %p\n", ctx->stack);
3549 old->command->group = ctx->list_head;
3550 old->command->grp_type = GRP_NORMAL;
3551 *ctx = *old; /* physical copy */
3554 word->o_assignment = r->assignment_flag;
3559 /* Word is complete, look at it and update parsing context.
3560 * Normal return is 0. Syntax errors return 1.
3561 * Note: on return, word is reset, but not o_free'd!
3563 static int done_word(o_string *word, struct parse_context *ctx)
3565 struct command *command = ctx->command;
3567 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3568 if (word->length == 0 && word->nonnull == 0) {
3569 debug_printf_parse("done_word return 0: true null, ignored\n");
3572 /* If this word wasn't an assignment, next ones definitely
3573 * can't be assignments. Even if they look like ones. */
3574 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3575 && word->o_assignment != WORD_IS_KEYWORD
3577 word->o_assignment = NOT_ASSIGNMENT;
3579 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3580 command->assignment_cnt++;
3581 word->o_assignment = MAYBE_ASSIGNMENT;
3584 if (ctx->pending_redirect) {
3585 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3586 * only if run as "bash", not "sh" */
3587 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3588 word->o_assignment = NOT_ASSIGNMENT;
3589 debug_printf("word stored in rd_filename: '%s'\n", word->data);
3591 /* "{ echo foo; } echo bar" - bad */
3592 /* NB: bash allows e.g.:
3593 * if true; then { echo foo; } fi
3594 * while if false; then false; fi do break; done
3596 if (command->group) {
3598 debug_printf_parse("done_word return 1: syntax error, "
3599 "groups and arglists don't mix\n");
3603 #if ENABLE_HUSH_CASE
3604 if (ctx->ctx_dsemicolon
3605 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3607 /* already done when ctx_dsemicolon was set to 1: */
3608 /* ctx->ctx_res_w = RES_MATCH; */
3609 ctx->ctx_dsemicolon = 0;
3612 if (!command->argv /* if it's the first word... */
3613 #if ENABLE_HUSH_LOOPS
3614 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3615 && ctx->ctx_res_w != RES_IN
3618 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
3619 if (reserved_word(word, ctx)) {
3621 debug_printf_parse("done_word return %d\n", (ctx->ctx_res_w == RES_SNTX));
3622 return (ctx->ctx_res_w == RES_SNTX);
3626 if (word->nonnull /* word had "xx" or 'xx' at least as part of it. */
3627 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3628 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3629 /* (otherwise it's known to be not empty and is already safe) */
3631 /* exclude "$@" - it can expand to no word despite "" */
3632 char *p = word->data;
3633 while (p[0] == SPECIAL_VAR_SYMBOL
3634 && (p[1] & 0x7f) == '@'
3635 && p[2] == SPECIAL_VAR_SYMBOL
3639 if (p == word->data || p[0] != '\0') {
3640 /* saw no "$@", or not only "$@" but some
3641 * real text is there too */
3642 /* insert "empty variable" reference, this makes
3643 * e.g. "", $empty"" etc to not disappear */
3644 o_addchr(word, SPECIAL_VAR_SYMBOL);
3645 o_addchr(word, SPECIAL_VAR_SYMBOL);
3648 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3649 debug_print_strings("word appended to argv", command->argv);
3653 ctx->pending_redirect = NULL;
3655 #if ENABLE_HUSH_LOOPS
3656 /* Force FOR to have just one word (variable name) */
3657 /* NB: basically, this makes hush see "for v in ..." syntax as if
3658 * as it is "for v; in ...". FOR and IN become two pipe structs
3660 if (ctx->ctx_res_w == RES_FOR) {
3661 //TODO: check that command->argv[0] is a valid variable name!
3662 done_pipe(ctx, PIPE_SEQ);
3665 #if ENABLE_HUSH_CASE
3666 /* Force CASE to have just one word */
3667 if (ctx->ctx_res_w == RES_CASE) {
3668 done_pipe(ctx, PIPE_SEQ);
3671 debug_printf_parse("done_word return 0\n");
3675 /* If a redirect is immediately preceded by a number, that number is
3676 * supposed to tell which file descriptor to redirect. This routine
3677 * looks for such preceding numbers. In an ideal world this routine
3678 * needs to handle all the following classes of redirects...
3679 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3680 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3681 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3682 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3683 * A -1 output from this program means no valid number was found, so the
3684 * caller should use the appropriate default for this redirection.
3686 static int redirect_opt_num(o_string *o)
3692 for (num = 0; num < o->length; num++) {
3693 if (!isdigit(o->data[num])) {
3697 num = atoi(o->data);
3702 static struct pipe *parse_stream(struct in_str *input, int end_trigger);
3703 static void parse_and_run_string(const char *s);
3705 #if ENABLE_HUSH_TICK
3706 static FILE *generate_stream_from_string(const char *s)
3709 int pid, channel[2];
3712 pid = BB_MMU ? fork() : vfork();
3714 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
3716 if (pid == 0) { /* child */
3717 /* Process substitution is not considered to be usual
3718 * 'command execution'.
3719 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
3726 if (ENABLE_HUSH_JOB)
3727 die_sleep = 0; /* let nofork's xfuncs die */
3728 close(channel[0]); /* NB: close _first_, then move fd! */
3729 xmove_fd(channel[1], 1);
3730 /* Prevent it from trying to handle ctrl-z etc */
3731 USE_HUSH_JOB(G.run_list_level = 1;)
3733 parse_and_run_string(s);
3734 _exit(G.last_return_code);
3736 /* We re-execute after vfork on NOMMU. This makes this script safe:
3737 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >TESTFILE
3738 * huge=`cat TESTFILE` # was blocking here forever
3741 //TODO: pass non-exported variables, traps, and functions
3742 execl(CONFIG_BUSYBOX_EXEC_PATH, "hush", "-c", s, NULL);
3749 pf = fdopen(channel[0], "r");
3753 /* Return code is exit status of the process that is run. */
3754 static int process_command_subs(o_string *dest, const char *s)
3757 struct in_str pipe_str;
3760 pf = generate_stream_from_string(s);
3763 close_on_exec_on(fileno(pf));
3765 /* Now send results of command back into original context */
3766 setup_file_in_str(&pipe_str, pf);
3768 while ((ch = i_getch(&pipe_str)) != EOF) {
3774 o_addchr(dest, '\n');
3777 o_addQchr(dest, ch);
3780 debug_printf("done reading from pipe, pclose()ing\n");
3781 /* Note: we got EOF, and we just close the read end of the pipe.
3782 * We do not wait for the `cmd` child to terminate. bash and ash do.
3784 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
3785 * `false`; echo $? - bash outputs "1"
3788 debug_printf("closed FILE from child. return 0\n");
3793 static int parse_group(o_string *dest, struct parse_context *ctx,
3794 struct in_str *input, int ch)
3796 /* dest contains characters seen prior to ( or {.
3797 * Typically it's empty, but for function defs,
3798 * it contains function name (without '()'). */
3799 struct pipe *pipe_list;
3801 struct command *command = ctx->command;
3803 debug_printf_parse("parse_group entered\n");
3804 #if ENABLE_HUSH_FUNCTIONS
3805 if (ch == 'F') { /* function definition? */
3806 bb_error_msg("aha '%s' is a function, parsing it...", dest->data);
3807 //command->fname = dest->data;
3808 command->grp_type = GRP_FUNCTION;
3809 //TODO: review every o_reset() location... do they handle all o_string fields correctly?
3810 memset(dest, 0, sizeof(*dest));
3813 if (command->argv /* word [word](... */
3814 || dest->length /* word(... */
3815 || dest->nonnull /* ""(... */
3818 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3824 command->grp_type = GRP_SUBSHELL;
3826 pipe_list = parse_stream(input, endch);
3827 /* empty ()/{} or parse error? */
3828 if (!pipe_list || pipe_list == ERR_PTR) {
3830 debug_printf_parse("parse_group return 1: parse_stream returned %p\n", pipe_list);
3833 command->group = pipe_list;
3834 debug_printf_parse("parse_group return 0\n");
3836 /* command remains "open", available for possible redirects */
3839 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
3840 /* Subroutines for copying $(...) and `...` things */
3841 static void add_till_backquote(o_string *dest, struct in_str *input);
3843 static void add_till_single_quote(o_string *dest, struct in_str *input)
3846 int ch = i_getch(input);
3854 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3855 static void add_till_double_quote(o_string *dest, struct in_str *input)
3858 int ch = i_getch(input);
3861 if (ch == '\\') { /* \x. Copy both chars. */
3863 ch = i_getch(input);
3869 add_till_backquote(dest, input);
3873 //if (ch == '$') ...
3876 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3878 * "Within the backquoted style of command substitution, backslash
3879 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3880 * The search for the matching backquote shall be satisfied by the first
3881 * backquote found without a preceding backslash; during this search,
3882 * if a non-escaped backquote is encountered within a shell comment,
3883 * a here-document, an embedded command substitution of the $(command)
3884 * form, or a quoted string, undefined results occur. A single-quoted
3885 * or double-quoted string that begins, but does not end, within the
3886 * "`...`" sequence produces undefined results."
3888 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3890 static void add_till_backquote(o_string *dest, struct in_str *input)
3893 int ch = i_getch(input);
3896 if (ch == '\\') { /* \x. Copy both chars unless it is \` */
3897 int ch2 = i_getch(input);
3898 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
3907 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3908 * quoting and nested ()s.
3909 * "With the $(command) style of command substitution, all characters
3910 * following the open parenthesis to the matching closing parenthesis
3911 * constitute the command. Any valid shell script can be used for command,
3912 * except a script consisting solely of redirections which produces
3913 * unspecified results."
3915 * echo $(echo '(TEST)' BEST) (TEST) BEST
3916 * echo $(echo 'TEST)' BEST) TEST) BEST
3917 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3919 static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
3923 int ch = i_getch(input);
3932 if (i_peek(input) == ')') {
3939 add_till_single_quote(dest, input);
3944 add_till_double_quote(dest, input);
3948 if (ch == '\\') { /* \x. Copy verbatim. Important for \(, \) */
3949 ch = i_getch(input);
3957 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
3959 /* Return code: 0 for OK, 1 for syntax error */
3960 static int handle_dollar(o_string *dest, struct in_str *input)
3963 int ch = i_peek(input); /* first character after the $ */
3964 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
3966 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
3970 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3972 debug_printf_parse(": '%c'\n", ch);
3973 o_addchr(dest, ch | quote_mask);
3976 if (!isalnum(ch) && ch != '_')
3980 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3981 } else if (isdigit(ch)) {
3984 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3985 debug_printf_parse(": '%c'\n", ch);
3986 o_addchr(dest, ch | quote_mask);
3987 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3988 } else switch (ch) {
3990 case '!': /* last bg pid */
3991 case '?': /* last exit code */
3992 case '#': /* number of args */
3993 case '*': /* args */
3994 case '@': /* args */
3995 goto make_one_char_var;
3997 bool first_char, all_digits;
3999 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4001 /* XXX maybe someone will try to escape the '}' */
4006 ch = i_getch(input);
4012 /* ${#var}: length of var contents */
4014 else if (isdigit(ch)) {
4020 if (expansion < 2 &&
4021 ((all_digits && !isdigit(ch)) ||
4022 (!all_digits && !isalnum(ch) && ch != '_')))
4024 /* handle parameter expansions
4025 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4030 case ':': /* null modifier */
4031 if (expansion == 0) {
4032 debug_printf_parse(": null modifier\n");
4038 #if 0 /* not implemented yet :( */
4039 case '#': /* remove prefix */
4040 case '%': /* remove suffix */
4041 if (expansion == 0) {
4042 debug_printf_parse(": remove suffix/prefix\n");
4049 case '-': /* default value */
4050 case '=': /* assign default */
4051 case '+': /* alternative */
4052 case '?': /* error indicate */
4053 debug_printf_parse(": parameter expansion\n");
4059 syntax("unterminated ${name}");
4060 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
4066 debug_printf_parse(": '%c'\n", ch);
4067 o_addchr(dest, ch | quote_mask);
4071 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4077 #if ENABLE_SH_MATH_SUPPORT
4078 if (i_peek(input) == '(') {
4080 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4081 o_addchr(dest, /*quote_mask |*/ '+');
4082 add_till_closing_paren(dest, input, true);
4083 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4088 #if ENABLE_HUSH_TICK
4089 //int pos = dest->length;
4090 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4091 o_addchr(dest, quote_mask | '`');
4092 add_till_closing_paren(dest, input, false);
4093 //debug_printf_subst("SUBST RES2 '%s'\n", dest->data + pos);
4094 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4101 if (isalnum(ch)) { /* it's $_name or $_123 */
4107 /* still unhandled, but should be eventually */
4108 bb_error_msg("unhandled syntax: $%c", ch);
4112 o_addQchr(dest, '$');
4114 debug_printf_parse("handle_dollar return 0\n");
4118 static int parse_stream_dquoted(o_string *dest, struct in_str *input, int dquote_end)
4124 ch = i_getch(input);
4125 if (ch == dquote_end) { /* may be only '"' or EOF */
4127 if (dest->o_assignment == NOT_ASSIGNMENT)
4128 dest->o_escape ^= 1;
4129 debug_printf_parse("parse_stream_dquoted return 0\n");
4133 syntax("unterminated \"");
4134 debug_printf_parse("parse_stream_dquoted return 1: unterminated \"\n");
4140 next = i_peek(input);
4142 debug_printf_parse(": ch=%c (%d) m=%d escape=%d\n",
4143 ch, ch, m, dest->o_escape);
4144 /* Basically, checking every CHAR_SPECIAL char except '"' */
4148 debug_printf_parse("parse_stream_dquoted return 1: \\<eof>\n");
4152 * "The backslash retains its special meaning [in "..."]
4153 * only when followed by one of the following characters:
4154 * $, `, ", \, or <newline>. A double quote may be quoted
4155 * within double quotes by preceding it with a backslash.
4156 * If enabled, history expansion will be performed unless
4157 * an ! appearing in double quotes is escaped using
4158 * a backslash. The backslash preceding the ! is not removed."
4160 if (strchr("$`\"\\", next) != NULL) {
4161 o_addqchr(dest, i_getch(input));
4163 o_addqchr(dest, '\\');
4168 if (handle_dollar(dest, input) != 0) {
4169 debug_printf_parse("parse_stream_dquoted return 1: handle_dollar returned non-0\n");
4174 #if ENABLE_HUSH_TICK
4176 //int pos = dest->length;
4177 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4178 o_addchr(dest, 0x80 | '`');
4179 add_till_backquote(dest, input);
4180 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4181 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4185 o_addQchr(dest, ch);
4187 && (dest->o_assignment == MAYBE_ASSIGNMENT
4188 || dest->o_assignment == WORD_IS_KEYWORD)
4189 && is_assignment(dest->data)
4191 dest->o_assignment = DEFINITELY_ASSIGNMENT;
4197 * Scan input until EOF or end_trigger char.
4198 * Return a list of pipes to execute, or NULL on EOF
4199 * or if end_trigger character is met.
4200 * On syntax error, exit is shell is not interactive,
4201 * reset parsing machinery and start parsing anew,
4202 * or return ERR_PTR.
4204 static struct pipe *parse_stream(struct in_str *input, int end_trigger)
4206 struct parse_context ctx;
4207 o_string dest = NULL_O_STRING;
4210 redir_type redir_style;
4214 /* Double-quote state is handled in the state variable is_in_dquote.
4215 * A single-quote triggers a bypass of the main loop until its mate is
4216 * found. When recursing, quote state is passed in via dest->o_escape. */
4218 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4219 end_trigger ? : 'X');
4222 #if ENABLE_HUSH_INTERACTIVE
4223 input->promptmode = 0; /* PS1 */
4225 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
4226 initialize_context(&ctx);
4230 if (parse_stream_dquoted(&dest, input, '"')) {
4233 /* We reached closing '"' */
4238 ch = i_getch(input);
4242 next = i_peek(input);
4245 debug_printf_parse(": ch=%c (%d) m=%d escape=%d\n",
4246 ch, ch, m, dest.o_escape);
4247 if (m == CHAR_ORDINARY) {
4248 o_addQchr(&dest, ch);
4249 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4250 || dest.o_assignment == WORD_IS_KEYWORD)
4252 && is_assignment(dest.data)
4254 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4259 /* m is SPECIAL ($,`), IFS, or ORDINARY_IF_QUOTED (*,#) */
4261 if (m == CHAR_IFS) {
4264 if (done_word(&dest, &ctx)) {
4268 done_pipe(&ctx, PIPE_SEQ);
4269 /* If we got nothing... */
4271 if (pi->num_cmds == 0
4272 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4274 free_pipe_list(pi, 0);
4277 debug_printf_parse("parse_stream return %p\n", pi);
4280 if (done_word(&dest, &ctx)) {
4284 #if ENABLE_HUSH_CASE
4285 /* "case ... in <newline> word) ..." -
4286 * newlines are ignored (but ';' wouldn't be) */
4287 if (ctx.command->argv == NULL
4288 && ctx.ctx_res_w == RES_MATCH
4293 /* Treat newline as a command separator. */
4294 done_pipe(&ctx, PIPE_SEQ);
4295 dest.o_assignment = MAYBE_ASSIGNMENT;
4297 /* note: if (m == CHAR_IFS) continue;
4298 * will still trigger for us */
4301 if (end_trigger && end_trigger == ch) {
4302 //TODO: disallow "{ cmd }" without semicolon
4303 if (done_word(&dest, &ctx)) {
4306 done_pipe(&ctx, PIPE_SEQ);
4307 dest.o_assignment = MAYBE_ASSIGNMENT;
4308 /* Do we sit outside of any if's, loops or case's? */
4310 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4312 debug_printf_parse("parse_stream return %p: "
4313 "end_trigger char found\n",
4316 return ctx.list_head;
4322 /* m is SPECIAL (e.g. $,`) or ORDINARY_IF_QUOTED (*,#) */
4324 if (dest.o_assignment == MAYBE_ASSIGNMENT) {
4325 /* ch is a special char and thus this word
4326 * cannot be an assignment */
4327 dest.o_assignment = NOT_ASSIGNMENT;
4332 if (dest.length == 0) {
4335 if (ch == EOF || ch == '\n')
4340 o_addQchr(&dest, ch);
4348 o_addchr(&dest, '\\');
4349 o_addchr(&dest, i_getch(input));
4352 if (handle_dollar(&dest, input) != 0) {
4353 debug_printf_parse("parse_stream parse error: handle_dollar returned non-0\n");
4360 ch = i_getch(input);
4362 syntax("unterminated '");
4367 if (dest.o_assignment == NOT_ASSIGNMENT)
4368 o_addqchr(&dest, ch);
4370 o_addchr(&dest, ch);
4375 is_in_dquote ^= 1; /* invert */
4376 if (dest.o_assignment == NOT_ASSIGNMENT)
4379 #if ENABLE_HUSH_TICK
4381 //int pos = dest.length;
4382 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4383 o_addchr(&dest, '`');
4384 add_till_backquote(&dest, input);
4385 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4386 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4391 redir_fd = redirect_opt_num(&dest);
4392 if (done_word(&dest, &ctx)) {
4395 redir_style = REDIRECT_OVERWRITE;
4397 redir_style = REDIRECT_APPEND;
4401 else if (next == '(') {
4402 syntax(">(process) not supported");
4406 setup_redirect(&ctx, redir_fd, redir_style, input);
4409 redir_fd = redirect_opt_num(&dest);
4410 if (done_word(&dest, &ctx)) {
4413 redir_style = REDIRECT_INPUT;
4415 redir_style = REDIRECT_HEREIS;
4417 } else if (next == '>') {
4418 redir_style = REDIRECT_IO;
4422 else if (next == '(') {
4423 syntax("<(process) not supported");
4427 setup_redirect(&ctx, redir_fd, redir_style, input);
4430 #if ENABLE_HUSH_CASE
4433 if (done_word(&dest, &ctx)) {
4436 done_pipe(&ctx, PIPE_SEQ);
4437 #if ENABLE_HUSH_CASE
4438 /* Eat multiple semicolons, detect
4439 * whether it means something special */
4445 if (ctx.ctx_res_w == RES_CASEI) {
4446 ctx.ctx_dsemicolon = 1;
4447 ctx.ctx_res_w = RES_MATCH;
4453 /* We just finished a cmd. New one may start
4454 * with an assignment */
4455 dest.o_assignment = MAYBE_ASSIGNMENT;
4458 if (done_word(&dest, &ctx)) {
4463 done_pipe(&ctx, PIPE_AND);
4465 done_pipe(&ctx, PIPE_BG);
4469 if (done_word(&dest, &ctx)) {
4472 #if ENABLE_HUSH_CASE
4473 if (ctx.ctx_res_w == RES_MATCH)
4474 break; /* we are in case's "word | word)" */
4476 if (next == '|') { /* || */
4478 done_pipe(&ctx, PIPE_OR);
4480 /* we could pick up a file descriptor choice here
4481 * with redirect_opt_num(), but bash doesn't do it.
4482 * "echo foo 2| cat" yields "foo 2". */
4487 #if ENABLE_HUSH_CASE
4488 /* "case... in [(]word)..." - skip '(' */
4489 if (ctx.ctx_res_w == RES_MATCH
4490 && ctx.command->argv == NULL /* not (word|(... */
4491 && dest.length == 0 /* not word(... */
4492 && dest.nonnull == 0 /* not ""(... */
4497 #if ENABLE_HUSH_FUNCTIONS
4498 if (dest.length != 0 /* not just () but word() */
4499 && dest.nonnull == 0 /* not a"b"c() */
4500 && ctx.command->argv == NULL /* it's the first word */
4501 //TODO: "func ( ) {...}" - note spaces - is valid format too in bash
4502 && i_peek(input) == ')'
4503 && !match_reserved_word(&dest)
4505 bb_error_msg("seems like a function definition");
4508 //TODO: do it properly.
4509 ch = i_getch(input);
4510 } while (ch == ' ' || ch == '\n');
4512 syntax("was expecting {");
4515 ch = 'F'; /* magic value */
4519 if (parse_group(&dest, &ctx, input, ch) != 0) {
4524 #if ENABLE_HUSH_CASE
4525 if (ctx.ctx_res_w == RES_MATCH)
4529 /* proper use of this character is caught by end_trigger:
4530 * if we see {, we call parse_group(..., end_trigger='}')
4531 * and it will match } earlier (not here). */
4532 syntax("unexpected } or )");
4536 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4542 struct parse_context *pctx;
4543 IF_HAS_KEYWORDS(struct parse_context *p2;)
4545 /* Clean up allocated tree.
4546 * Samples for finding leaks on syntax error recovery path.
4547 * Execute them from interactive shell and watch pmap `pidof hush`.
4548 * while if false; then false; fi do break; done (bash accepts it)
4549 * while if false; then false; fi; do break; fi
4553 /* Update pipe/command counts,
4554 * otherwise freeing may miss some */
4555 done_pipe(pctx, PIPE_SEQ);
4556 debug_printf_clean("freeing list %p from ctx %p\n",
4557 pctx->list_head, pctx);
4558 debug_print_tree(pctx->list_head, 0);
4559 free_pipe_list(pctx->list_head, 0);
4560 debug_printf_clean("freed list %p\n", pctx->list_head);
4561 IF_HAS_KEYWORDS(p2 = pctx->stack;)
4565 IF_HAS_KEYWORDS(pctx = p2;)
4566 } while (HAS_KEYWORDS && pctx);
4567 /* Free text, clear all dest fields */
4569 /* If we are not in top-level parse, we return,
4570 * our caller will propagate error.
4572 if (end_trigger != ';')
4574 /* Discard cached input, force prompt */
4576 USE_HUSH_INTERACTIVE(input->promptme = 1;)
4581 static void set_in_charmap(const char *set, int code)
4584 G.charmap[(unsigned char)*set++] = code;
4587 static void update_charmap(void)
4589 G.ifs = getenv("IFS");
4592 /* Precompute a list of 'flow through' behavior so it can be treated
4593 * quickly up front. Computation is necessary because of IFS.
4594 * Special case handling of IFS == " \t\n" is not implemented.
4595 * The charmap[] array only really needs two bits each,
4596 * and on most machines that would be faster (reduced L1 cache use).
4598 memset(G.charmap, CHAR_ORDINARY, sizeof(G.charmap));
4599 #if ENABLE_HUSH_TICK
4600 set_in_charmap("\\$\"`", CHAR_SPECIAL);
4602 set_in_charmap("\\$\"", CHAR_SPECIAL);
4604 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
4605 set_in_charmap(G.ifs, CHAR_IFS); /* are ordinary if quoted */
4608 /* Execiting from string: eval, sh -c '...'
4609 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
4610 * end_trigger controls how often we stop parsing
4611 * NUL: parse all, execute, return
4612 * ';': parse till ';' or newline, execute, repeat till EOF
4614 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
4617 struct pipe *pipe_list;
4621 pipe_list = parse_stream(inp, end_trigger);
4622 if (!pipe_list) /* EOF */
4624 debug_print_tree(pipe_list, 0);
4625 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
4626 run_and_free_list(pipe_list);
4627 /* Loop on syntax errors, return on EOF: */
4631 static void parse_and_run_string(const char *s)
4633 struct in_str input;
4634 setup_string_in_str(&input, s);
4635 parse_and_run_stream(&input, '\0');
4638 static void parse_and_run_file(FILE *f)
4640 struct in_str input;
4641 setup_file_in_str(&input, f);
4642 parse_and_run_stream(&input, ';');
4646 /* Make sure we have a controlling tty. If we get started under a job
4647 * aware app (like bash for example), make sure we are now in charge so
4648 * we don't fight over who gets the foreground */
4649 static void setup_job_control(void)
4653 shell_pgrp = getpgrp();
4655 /* If we were ran as 'hush &',
4656 * sleep until we are in the foreground. */
4657 while (tcgetpgrp(G_interactive_fd) != shell_pgrp) {
4658 /* Send TTIN to ourself (should stop us) */
4659 kill(- shell_pgrp, SIGTTIN);
4660 shell_pgrp = getpgrp();
4663 /* We _must_ restore tty pgrp on fatal signals */
4664 set_fatal_signals_to_sigexit();
4666 /* Put ourselves in our own process group. */
4667 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
4668 /* Grab control of the terminal. */
4669 tcsetpgrp(G_interactive_fd, getpid());
4673 static int set_mode(const char cstate, const char mode)
4675 int state = (cstate == '-' ? 1 : 0);
4677 case 'n': G.fake_mode = state; break;
4678 case 'x': /*G.debug_mode = state;*/ break;
4679 default: return EXIT_FAILURE;
4681 return EXIT_SUCCESS;
4684 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4685 int hush_main(int argc, char **argv)
4687 static const struct variable const_shell_ver = {
4689 .varstr = (char*)hush_version_str,
4690 .max_len = 1, /* 0 can provoke free(name) */
4698 struct variable *cur_var;
4702 G.root_pid = getpid();
4704 /* Deal with HUSH_VERSION */
4705 G.shell_ver = const_shell_ver; /* copying struct here */
4706 G.top_var = &G.shell_ver;
4707 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
4708 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
4709 /* Initialize our shell local variables with the values
4710 * currently living in the environment */
4711 cur_var = G.top_var;
4714 char *value = strchr(*e, '=');
4715 if (value) { /* paranoia */
4716 cur_var->next = xzalloc(sizeof(*cur_var));
4717 cur_var = cur_var->next;
4718 cur_var->varstr = *e;
4719 cur_var->max_len = strlen(*e);
4720 cur_var->flg_export = 1;
4724 debug_printf_env("putenv '%s'\n", hush_version_str);
4725 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
4727 #if ENABLE_FEATURE_EDITING
4728 G.line_input_state = new_line_input_t(FOR_SHELL);
4730 /* XXX what should these be while sourcing /etc/profile? */
4731 G.global_argc = argc;
4732 G.global_argv = argv;
4733 /* Initialize some more globals to non-zero values */
4735 #if ENABLE_HUSH_INTERACTIVE
4736 if (ENABLE_FEATURE_EDITING)
4737 cmdedit_set_initial_prompt();
4741 if (EXIT_SUCCESS) /* otherwise is already done */
4742 G.last_return_code = EXIT_SUCCESS;
4744 if (argv[0] && argv[0][0] == '-') {
4745 debug_printf("sourcing /etc/profile\n");
4746 input = fopen_for_read("/etc/profile");
4747 if (input != NULL) {
4748 close_on_exec_on(fileno(input));
4749 parse_and_run_file(input);
4755 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
4756 while ((opt = getopt(argc, argv, "c:xins")) > 0) {
4759 G.global_argv = argv + optind;
4760 if (!argv[optind]) {
4761 /* -c 'script' (no params): prevent empty $0 */
4762 *--G.global_argv = argv[0];
4764 } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
4765 G.global_argc = argc - optind;
4766 parse_and_run_string(optarg);
4769 /* Well, we cannot just declare interactiveness,
4770 * we have to have some stuff (ctty, etc) */
4771 /* G_interactive_fd++; */
4774 /* "-s" means "read from stdin", but this is how we always
4775 * operate, so simply do nothing here. */
4779 if (!set_mode('-', opt))
4783 fprintf(stderr, "Usage: sh [FILE]...\n"
4784 " or: sh -c command [args]...\n\n");
4792 /* A shell is interactive if the '-i' flag was given, or if all of
4793 * the following conditions are met:
4795 * no arguments remaining or the -s flag given
4796 * standard input is a terminal
4797 * standard output is a terminal
4798 * Refer to Posix.2, the description of the 'sh' utility. */
4799 if (argv[optind] == NULL && input == stdin
4800 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4802 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
4803 debug_printf("saved_tty_pgrp=%d\n", G.saved_tty_pgrp);
4804 if (G.saved_tty_pgrp >= 0) {
4805 /* try to dup to high fd#, >= 255 */
4806 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4807 if (G_interactive_fd < 0) {
4808 /* try to dup to any fd */
4809 G_interactive_fd = dup(STDIN_FILENO);
4810 if (G_interactive_fd < 0)
4812 G_interactive_fd = 0;
4814 // TODO: track & disallow any attempts of user
4815 // to (inadvertently) close/redirect it
4818 init_signal_mask(); /* note: ensures SIGCHLD is not masked */
4819 debug_printf("interactive_fd=%d\n", G_interactive_fd);
4820 if (G_interactive_fd) {
4821 fcntl(G_interactive_fd, F_SETFD, FD_CLOEXEC);
4822 /* Looks like they want an interactive shell */
4823 setup_job_control();
4824 /* -1 is special - makes xfuncs longjmp, not exit
4825 * (we reset die_sleep = 0 whereever we [v]fork) */
4827 if (setjmp(die_jmp)) {
4828 /* xfunc has failed! die die die */
4829 hush_exit(xfunc_error_retval);
4832 #elif ENABLE_HUSH_INTERACTIVE
4833 /* no job control compiled, only prompt/line editing */
4834 if (argv[optind] == NULL && input == stdin
4835 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4837 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4838 if (G_interactive_fd < 0) {
4839 /* try to dup to any fd */
4840 G_interactive_fd = dup(STDIN_FILENO);
4841 if (G_interactive_fd < 0)
4843 G_interactive_fd = 0;
4845 if (G_interactive_fd) {
4846 fcntl(G_interactive_fd, F_SETFD, FD_CLOEXEC);
4849 init_signal_mask(); /* note: ensures SIGCHLD is not masked */
4853 /* POSIX allows shell to re-enable SIGCHLD
4854 * even if it was SIG_IGN on entry */
4855 // G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
4856 signal(SIGCHLD, SIG_DFL); // SIGCHLD_handler);
4858 #if ENABLE_HUSH_INTERACTIVE && !ENABLE_FEATURE_SH_EXTRA_QUIET
4859 if (G_interactive_fd) {
4860 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
4861 printf("Enter 'help' for a list of built-in commands.\n\n");
4865 if (argv[optind] == NULL) {
4866 parse_and_run_file(stdin);
4868 debug_printf("\nrunning script '%s'\n", argv[optind]);
4869 G.global_argv = argv + optind;
4870 G.global_argc = argc - optind;
4871 input = xfopen_for_read(argv[optind]);
4872 fcntl(fileno(input), F_SETFD, FD_CLOEXEC);
4873 parse_and_run_file(input);
4878 #if ENABLE_FEATURE_CLEAN_UP
4880 if (G.cwd != bb_msg_unknown)
4882 cur_var = G.top_var->next;
4884 struct variable *tmp = cur_var;
4885 if (!cur_var->max_len)
4886 free(cur_var->varstr);
4887 cur_var = cur_var->next;
4891 hush_exit(G.last_return_code);
4896 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4897 int lash_main(int argc, char **argv)
4899 //bb_error_msg("lash is deprecated, please use hush instead");
4900 return hush_main(argc, argv);
4908 static int builtin_trap(char **argv)
4915 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
4918 /* No args: print all trapped. This isn't 100% correct as we should
4919 * be escaping the cmd so that it can be pasted back in ...
4921 for (i = 0; i < NSIG; ++i)
4923 printf("trap -- '%s' %s\n", G.traps[i], get_signame(i));
4924 return EXIT_SUCCESS;
4929 /* if first arg is decimal: reset all specified */
4930 sig = bb_strtou(*++argv, NULL, 10);
4936 sig = get_signum(*argv++);
4937 if (sig < 0 || sig >= NSIG) {
4939 /* mimic bash message exactly */
4940 bb_perror_msg("trap: %s: invalid signal specification", argv[i]);
4945 G.traps[sig] = xstrdup(new_cmd);
4947 debug_printf("trap: setting SIG%s (%i) to '%s'",
4948 get_signame(sig), sig, G.traps[sig]);
4950 /* There is no signal for 0 (EXIT) */
4955 sigaddset(&G.blocked_set, sig);
4957 /* there was a trap handler, we are removing it
4958 * (if sig has non-DFL handling,
4959 * we don't need to do anything) */
4960 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
4962 sigdelset(&G.blocked_set, sig);
4964 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
4969 /* first arg is "-": reset all specified to default */
4970 /* first arg is "": ignore all specified */
4971 /* everything else: execute first arg upon signal */
4973 bb_error_msg("trap: invalid arguments");
4974 return EXIT_FAILURE;
4976 if (LONE_DASH(*argv))
4984 static int builtin_true(char **argv UNUSED_PARAM)
4989 static int builtin_test(char **argv)
4996 return test_main(argc, argv - argc);
4999 static int builtin_echo(char **argv)
5006 return echo_main(argc, argv - argc);
5009 static int builtin_eval(char **argv)
5011 int rcode = EXIT_SUCCESS;
5014 char *str = expand_strvec_to_string(argv + 1);
5016 * eval "echo Hi; done" ("done" is syntax error):
5017 * "echo Hi" will not execute too.
5019 parse_and_run_string(str);
5021 rcode = G.last_return_code;
5026 static int builtin_cd(char **argv)
5029 if (argv[1] == NULL) {
5030 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
5031 * bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
5033 newdir = getenv("HOME") ? : "/";
5036 if (chdir(newdir)) {
5037 printf("cd: %s: %s\n", newdir, strerror(errno));
5038 return EXIT_FAILURE;
5041 return EXIT_SUCCESS;
5044 static int builtin_exec(char **argv)
5046 if (argv[1] == NULL)
5047 return EXIT_SUCCESS; /* bash does this */
5052 // FIXME: if exec fails, bash does NOT exit! We do...
5053 pseudo_exec_argv(&dummy, argv + 1, 0, NULL);
5058 static int builtin_exit(char **argv)
5060 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
5061 //puts("exit"); /* bash does it */
5062 // TODO: warn if we have background jobs: "There are stopped jobs"
5063 // On second consecutive 'exit', exit anyway.
5064 if (argv[1] == NULL)
5065 hush_exit(G.last_return_code);
5066 /* mimic bash: exit 123abc == exit 255 + error msg */
5067 xfunc_error_retval = 255;
5068 /* bash: exit -2 == exit 254, no error msg */
5069 hush_exit(xatoi(argv[1]) & 0xff);
5072 static int builtin_export(char **argv)
5075 char *name = argv[1];
5079 // ash emits: export VAR='VAL'
5080 // bash: declare -x VAR="VAL"
5081 // (both also escape as needed (quotes, $, etc))
5086 return EXIT_SUCCESS;
5089 value = strchr(name, '=');
5091 /* They are exporting something without a =VALUE */
5092 struct variable *var;
5094 var = get_local_var(name);
5096 var->flg_export = 1;
5097 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
5098 putenv(var->varstr);
5100 /* bash does not return an error when trying to export
5101 * an undefined variable. Do likewise. */
5102 return EXIT_SUCCESS;
5105 set_local_var(xstrdup(name), 1);
5106 return EXIT_SUCCESS;
5110 /* built-in 'fg' and 'bg' handler */
5111 static int builtin_fg_bg(char **argv)
5116 if (!G_interactive_fd)
5117 return EXIT_FAILURE;
5118 /* If they gave us no args, assume they want the last backgrounded task */
5120 for (pi = G.job_list; pi; pi = pi->next) {
5121 if (pi->jobid == G.last_jobid) {
5125 bb_error_msg("%s: no current job", argv[0]);
5126 return EXIT_FAILURE;
5128 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
5129 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
5130 return EXIT_FAILURE;
5132 for (pi = G.job_list; pi; pi = pi->next) {
5133 if (pi->jobid == jobnum) {
5137 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
5138 return EXIT_FAILURE;
5140 // TODO: bash prints a string representation
5141 // of job being foregrounded (like "sleep 1 | cat")
5142 if (*argv[0] == 'f') {
5143 /* Put the job into the foreground. */
5144 tcsetpgrp(G_interactive_fd, pi->pgrp);
5147 /* Restart the processes in the job */
5148 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
5149 for (i = 0; i < pi->num_cmds; i++) {
5150 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
5151 pi->cmds[i].is_stopped = 0;
5153 pi->stopped_cmds = 0;
5155 i = kill(- pi->pgrp, SIGCONT);
5157 if (errno == ESRCH) {
5158 delete_finished_bg_job(pi);
5159 return EXIT_SUCCESS;
5161 bb_perror_msg("kill (SIGCONT)");
5165 if (*argv[0] == 'f') {
5167 return checkjobs_and_fg_shell(pi);
5169 return EXIT_SUCCESS;
5173 #if ENABLE_HUSH_HELP
5174 static int builtin_help(char **argv UNUSED_PARAM)
5176 const struct built_in_command *x;
5178 printf("\nBuilt-in commands:\n");
5179 printf("-------------------\n");
5180 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
5181 printf("%s\t%s\n", x->cmd, x->descr);
5184 return EXIT_SUCCESS;
5189 static int builtin_jobs(char **argv UNUSED_PARAM)
5192 const char *status_string;
5194 for (job = G.job_list; job; job = job->next) {
5195 if (job->alive_cmds == job->stopped_cmds)
5196 status_string = "Stopped";
5198 status_string = "Running";
5200 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
5202 return EXIT_SUCCESS;
5206 static int builtin_pwd(char **argv UNUSED_PARAM)
5209 return EXIT_SUCCESS;
5212 static int builtin_read(char **argv)
5215 const char *name = argv[1] ? argv[1] : "REPLY";
5217 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
5218 return set_local_var(string, 0);
5221 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
5222 * built-in 'set' handler
5224 * set [-abCefhmnuvx] [-o option] [argument...]
5225 * set [+abCefhmnuvx] [+o option] [argument...]
5226 * set -- [argument...]
5229 * Implementations shall support the options in both their hyphen and
5230 * plus-sign forms. These options can also be specified as options to sh.
5232 * Write out all variables and their values: set
5233 * Set $1, $2, and $3 and set "$#" to 3: set c a b
5234 * Turn on the -x and -v options: set -xv
5235 * Unset all positional parameters: set --
5236 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
5237 * Set the positional parameters to the expansion of x, even if x expands
5238 * with a leading '-' or '+': set -- $x
5240 * So far, we only support "set -- [argument...]" and some of the short names.
5242 static int builtin_set(char **argv)
5245 char **pp, **g_argv;
5246 char *arg = *++argv;
5250 for (e = G.top_var; e; e = e->next)
5252 return EXIT_SUCCESS;
5256 if (!strcmp(arg, "--")) {
5261 if (arg[0] == '+' || arg[0] == '-') {
5262 for (n = 1; arg[n]; ++n)
5263 if (set_mode(arg[0], arg[n]))
5269 } while ((arg = *++argv) != NULL);
5270 /* Now argv[0] is 1st argument */
5272 /* Only reset global_argv if we didn't process anything */
5274 return EXIT_SUCCESS;
5277 /* NB: G.global_argv[0] ($0) is never freed/changed */
5278 g_argv = G.global_argv;
5279 if (G.global_args_malloced) {
5285 G.global_args_malloced = 1;
5286 pp = xzalloc(sizeof(pp[0]) * 2);
5287 pp[0] = g_argv[0]; /* retain $0 */
5290 /* This realloc's G.global_argv */
5291 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
5298 return EXIT_SUCCESS;
5300 /* Nothing known, so abort */
5302 bb_error_msg("set: %s: invalid option", arg);
5303 return EXIT_FAILURE;
5306 static int builtin_shift(char **argv)
5312 if (n >= 0 && n < G.global_argc) {
5313 if (G.global_args_malloced) {
5316 free(G.global_argv[m++]);
5319 memmove(&G.global_argv[1], &G.global_argv[n+1],
5320 G.global_argc * sizeof(G.global_argv[0]));
5321 return EXIT_SUCCESS;
5323 return EXIT_FAILURE;
5326 static int builtin_source(char **argv)
5330 if (argv[1] == NULL)
5331 return EXIT_FAILURE;
5333 /* XXX search through $PATH is missing */
5334 input = fopen_for_read(argv[1]);
5336 bb_error_msg("can't open '%s'", argv[1]);
5337 return EXIT_FAILURE;
5339 close_on_exec_on(fileno(input));
5341 /* Now run the file */
5342 /* XXX argv and argc are broken; need to save old G.global_argv
5343 * (pointer only is OK!) on this stack frame,
5344 * set G.global_argv=argv+1, recurse, and restore. */
5345 parse_and_run_file(input);
5347 return G.last_return_code;
5350 static int builtin_umask(char **argv)
5353 const char *arg = argv[1];
5355 new_umask = bb_strtou(arg, NULL, 8);
5357 return EXIT_FAILURE;
5359 new_umask = umask(0);
5360 printf("%.3o\n", (unsigned) new_umask);
5363 return EXIT_SUCCESS;
5366 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
5367 static int builtin_unset(char **argv)
5374 return EXIT_SUCCESS;
5377 if (argv[1][0] == '-') {
5378 switch (argv[1][1]) {
5380 case 'f': if (ENABLE_HUSH_FUNCTIONS) { var = false; break; }
5382 bb_error_msg("unset: %s: invalid option", argv[1]);
5383 return EXIT_FAILURE;
5391 if (unset_local_var(argv[i]))
5394 #if ENABLE_HUSH_FUNCTIONS
5396 unset_local_func(argv[i]);
5402 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
5403 static int builtin_wait(char **argv)
5405 int ret = EXIT_SUCCESS;
5408 if (*++argv == NULL) {
5409 /* Don't care about wait results */
5410 /* Note 1: must wait until there are no more children */
5411 /* Note 2: must be interruptible */
5413 * $ sleep 3 & sleep 6 & wait
5418 * $ sleep 3 & sleep 6 & wait
5422 * ^C <-- after ~4 sec from keyboard
5425 sigaddset(&G.blocked_set, SIGCHLD);
5426 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5429 if (errno == ECHILD)
5431 /* Wait for SIGCHLD or any other signal of interest */
5432 /* sigtimedwait with infinite timeout: */
5433 sig = sigwaitinfo(&G.blocked_set, NULL);
5435 sig = check_and_run_traps(sig);
5436 if (sig && sig != SIGCHLD) { /* see note 2 */
5442 sigdelset(&G.blocked_set, SIGCHLD);
5443 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5447 /* This is probably buggy wrt interruptible-ness */
5449 pid_t pid = bb_strtou(*argv, NULL, 10);
5451 /* mimic bash message */
5452 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
5453 return EXIT_FAILURE;
5455 if (waitpid(pid, &status, 0) == pid) {
5456 if (WIFSIGNALED(status))
5457 ret = 128 + WTERMSIG(status);
5458 else if (WIFEXITED(status))
5459 ret = WEXITSTATUS(status);
5463 bb_perror_msg("wait %s", *argv);
5472 #if ENABLE_HUSH_LOOPS
5473 static int builtin_break(char **argv)
5475 if (G.depth_of_loop == 0) {
5476 bb_error_msg("%s: only meaningful in a loop", argv[0]);
5477 return EXIT_SUCCESS; /* bash compat */
5479 G.flag_break_continue++; /* BC_BREAK = 1 */
5480 G.depth_break_continue = 1;
5482 G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
5483 if (errno || !G.depth_break_continue || argv[2]) {
5484 bb_error_msg("%s: bad arguments", argv[0]);
5485 G.flag_break_continue = BC_BREAK;
5486 G.depth_break_continue = UINT_MAX;
5489 if (G.depth_of_loop < G.depth_break_continue)
5490 G.depth_break_continue = G.depth_of_loop;
5491 return EXIT_SUCCESS;
5494 static int builtin_continue(char **argv)
5496 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
5497 return builtin_break(argv);