1 /* vi: set sw=4 ts=4: */
3 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
11 * The parser routines proper are all original material, first
12 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
13 * execution engine, the builtins, and much of the underlying
14 * support has been adapted from busybox-0.49pre's lash, which is
15 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
16 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
17 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
18 * Troan, which they placed in the public domain. I don't know
19 * how much of the Johnson/Troan code has survived the repeated
23 * o_addchr() derived from similar w_addchar function in glibc-2.2.
24 * setup_redirect(), redirect_opt_num(), and big chunks of main()
25 * and many builtins derived from contributions by Erik Andersen.
26 * Miscellaneous bugfixes from Matt Kraai.
28 * There are two big (and related) architecture differences between
29 * this parser and the lash parser. One is that this version is
30 * actually designed from the ground up to understand nearly all
31 * of the Bourne grammar. The second, consequential change is that
32 * the parser and input reader have been turned inside out. Now,
33 * the parser is in control, and asks for input as needed. The old
34 * way had the input reader in control, and it asked for parsing to
35 * take place as needed. The new way makes it much easier to properly
36 * handle the recursion implicit in the various substitutions, especially
37 * across continuation lines.
39 * POSIX syntax not implemented:
41 * <(list) and >(list) Process Substitution
42 * Here Documents ( << word )
45 * Parameter Expansion for substring processing ${var#word} ${var%word}
47 * Bash stuff maybe optional enable:
48 * &> and >& redirection of stdout+stderr
50 * reserved words: [[ ]] function select
51 * substrings ${var:1:5}
54 * job handling woefully incomplete and buggy (improved --vda)
56 * port selected bugfixes from post-0.49 busybox lash - done?
57 * change { and } from special chars to reserved words
58 * builtins: return, trap, ulimit
59 * test magic exec with redirection only
60 * follow IFS rules more precisely, including update semantics
61 * figure out what to do with backslash-newline
62 * propagate syntax errors, die on resource errors?
63 * continuation lines, both explicit and implicit - done?
65 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
68 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
69 //TODO: pull in some .h and find out whether we have SINGLE_APPLET_MAIN?
70 //#include "applet_tables.h" doesn't work
72 /* #include <dmalloc.h> */
79 #define HUSH_VER_STR "0.92"
81 #if defined SINGLE_APPLET_MAIN
82 /* STANDALONE does not make sense, and won't compile */
83 #undef CONFIG_FEATURE_SH_STANDALONE
84 #undef ENABLE_FEATURE_SH_STANDALONE
85 #undef USE_FEATURE_SH_STANDALONE
86 #define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
87 #define ENABLE_FEATURE_SH_STANDALONE 0
88 #define USE_FEATURE_SH_STANDALONE(...)
89 #define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
92 #if !ENABLE_HUSH_INTERACTIVE
93 #undef ENABLE_FEATURE_EDITING
94 #define ENABLE_FEATURE_EDITING 0
95 #undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
96 #define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
99 /* Do we support ANY keywords? */
100 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
101 #define HAS_KEYWORDS 1
102 #define IF_HAS_KEYWORDS(...) __VA_ARGS__
103 #define IF_HAS_NO_KEYWORDS(...)
105 #define HAS_KEYWORDS 0
106 #define IF_HAS_KEYWORDS(...)
107 #define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
110 /* Keep unconditionally on for now */
113 #define ENABLE_HUSH_FUNCTIONS 0
116 /* If you comment out one of these below, it will be #defined later
117 * to perform debug printfs to stderr: */
118 #define debug_printf(...) do {} while (0)
119 /* Finer-grained debug switches */
120 #define debug_printf_parse(...) do {} while (0)
121 #define debug_print_tree(a, b) do {} while (0)
122 #define debug_printf_exec(...) do {} while (0)
123 #define debug_printf_env(...) do {} while (0)
124 #define debug_printf_jobs(...) do {} while (0)
125 #define debug_printf_expand(...) do {} while (0)
126 #define debug_printf_glob(...) do {} while (0)
127 #define debug_printf_list(...) do {} while (0)
128 #define debug_printf_subst(...) do {} while (0)
129 #define debug_printf_clean(...) do {} while (0)
132 #define debug_printf(...) fprintf(stderr, __VA_ARGS__)
135 #ifndef debug_printf_parse
136 #define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
139 #ifndef debug_printf_exec
140 #define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
143 #ifndef debug_printf_env
144 #define debug_printf_env(...) fprintf(stderr, __VA_ARGS__)
147 #ifndef debug_printf_jobs
148 #define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
154 #ifndef debug_printf_expand
155 #define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
156 #define DEBUG_EXPAND 1
158 #define DEBUG_EXPAND 0
161 #ifndef debug_printf_glob
162 #define debug_printf_glob(...) fprintf(stderr, __VA_ARGS__)
168 #ifndef debug_printf_list
169 #define debug_printf_list(...) fprintf(stderr, __VA_ARGS__)
172 #ifndef debug_printf_subst
173 #define debug_printf_subst(...) fprintf(stderr, __VA_ARGS__)
176 #ifndef debug_printf_clean
177 /* broken, of course, but OK for testing */
178 static const char *indenter(int i)
180 static const char blanks[] ALIGN1 =
182 return &blanks[sizeof(blanks) - i - 1];
184 #define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
185 #define DEBUG_CLEAN 1
189 static void debug_print_strings(const char *prefix, char **vv)
191 fprintf(stderr, "%s:\n", prefix);
193 fprintf(stderr, " '%s'\n", *vv++);
196 #define debug_print_strings(prefix, vv) ((void)0)
200 * Leak hunting. Use hush_leaktool.sh for post-processing.
202 #ifdef FOR_HUSH_LEAKTOOL
203 static void *xxmalloc(int lineno, size_t size)
205 void *ptr = xmalloc((size + 0xff) & ~0xff);
206 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
209 static void *xxrealloc(int lineno, void *ptr, size_t size)
211 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
212 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
215 static char *xxstrdup(int lineno, const char *str)
217 char *ptr = xstrdup(str);
218 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
221 static void xxfree(void *ptr)
223 fdprintf(2, "free %p\n", ptr);
226 #define xmalloc(s) xxmalloc(__LINE__, s)
227 #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
228 #define xstrdup(s) xxstrdup(__LINE__, s)
229 #define free(p) xxfree(p)
233 #define ERR_PTR ((void*)(long)1)
235 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="HUSH_VER_STR;
237 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
239 #define SPECIAL_VAR_SYMBOL 3
241 typedef enum redir_type {
243 REDIRECT_OVERWRITE = 2,
249 /* The descrip member of this structure is only used to make
250 * debugging output pretty */
251 static const struct {
253 signed char default_fd;
257 { O_RDONLY, 0, "<" },
258 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
259 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
260 { O_RDONLY, -1, "<<" },
264 typedef enum pipe_style {
271 typedef enum reserved_style {
280 #if ENABLE_HUSH_LOOPS
287 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
292 /* two pseudo-keywords support contrived "case" syntax: */
293 RES_MATCH , /* "word)" */
294 RES_CASEI , /* "this command is inside CASE" */
301 struct redir_struct {
302 struct redir_struct *next;
303 char *rd_filename; /* filename */
304 int fd; /* file descriptor being redirected */
305 int dup; /* -1, or file descriptor being duplicated */
306 smallint /*enum redir_type*/ rd_type;
310 pid_t pid; /* 0 if exited */
311 int assignment_cnt; /* how many argv[i] are assignments? */
312 smallint is_stopped; /* is the command currently running? */
313 smallint grp_type; /* GRP_xxx */
314 struct pipe *group; /* if non-NULL, this "prog" is {} group,
315 * subshell, or a compound statement */
316 char **argv; /* command name and arguments */
317 struct redir_struct *redirects; /* I/O redirections */
319 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
320 * and on execution these are substituted with their values.
321 * Substitution can make _several_ words out of one argv[n]!
322 * Example: argv[0]=='.^C*^C.' here: echo .$*.
323 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
326 #define GRP_SUBSHELL 1
327 #if ENABLE_HUSH_FUNCTIONS
328 #define GRP_FUNCTION 2
333 int num_cmds; /* total number of commands in job */
334 int alive_cmds; /* number of commands running (not exited) */
335 int stopped_cmds; /* number of commands alive, but stopped */
337 int jobid; /* job number */
338 pid_t pgrp; /* process group ID for the job */
339 char *cmdtext; /* name of job */
341 struct command *cmds; /* array of commands in pipe */
342 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
343 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
344 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
347 /* This holds pointers to the various results of parsing */
348 struct parse_context {
349 /* linked list of pipes */
350 struct pipe *list_head;
351 /* last pipe (being constructed right now) */
353 /* last command in pipe (being constructed right now) */
354 struct command *command;
355 /* last redirect in command->redirects list */
356 struct redir_struct *pending_redirect;
359 smallint ctx_inverted; /* "! cmd | cmd" */
361 smallint ctx_dsemicolon; /* ";;" seen */
363 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
365 /* group we are enclosed in:
366 * example: "if pipe1; pipe2; then pipe3; fi"
367 * when we see "if" or "then", we malloc and copy current context,
368 * and make ->stack point to it. then we parse pipeN.
369 * when closing "then" / fi" / whatever is found,
370 * we move list_head into ->stack->command->group,
371 * copy ->stack into current context, and delete ->stack.
372 * (parsing of { list } and ( list ) doesn't use this method)
374 struct parse_context *stack;
378 /* On program start, environ points to initial environment.
379 * putenv adds new pointers into it, unsetenv removes them.
380 * Neither of these (de)allocates the strings.
381 * setenv allocates new strings in malloc space and does putenv,
382 * and thus setenv is unusable (leaky) for shell's purposes */
383 #define setenv(...) setenv_is_leaky_dont_use()
385 struct variable *next;
386 char *varstr; /* points to "name=" portion */
387 int max_len; /* if > 0, name is part of initial env; else name is malloced */
388 smallint flg_export; /* putenv should be done on this var */
389 smallint flg_read_only;
392 typedef struct o_string {
394 int length; /* position where data is appended */
396 /* Protect newly added chars against globbing
397 * (by prepending \ to *, ?, [, \) */
401 smallint has_empty_slot;
402 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
405 MAYBE_ASSIGNMENT = 0,
406 DEFINITELY_ASSIGNMENT = 1,
408 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
410 /* Used for initialization: o_string foo = NULL_O_STRING; */
411 #define NULL_O_STRING { NULL }
413 /* I can almost use ordinary FILE*. Is open_memstream() universally
414 * available? Where is it documented? */
415 typedef struct in_str {
417 /* eof_flag=1: last char in ->p is really an EOF */
418 char eof_flag; /* meaningless if ->p == NULL */
420 #if ENABLE_HUSH_INTERACTIVE
422 smallint promptmode; /* 0: PS1, 1: PS2 */
425 int (*get) (struct in_str *);
426 int (*peek) (struct in_str *);
428 #define i_getch(input) ((input)->get(input))
429 #define i_peek(input) ((input)->peek(input))
437 /* "Globals" within this file */
438 /* Sorted roughly by size (smaller offsets == smaller code) */
440 #if ENABLE_HUSH_INTERACTIVE
441 /* 'interactive_fd' is a fd# open to ctty, if we have one
442 * _AND_ if we decided to act interactively */
446 #define G_interactive_fd (G.interactive_fd)
448 #define G_interactive_fd 0
450 #if ENABLE_FEATURE_EDITING
451 line_input_t *line_input_state;
457 pid_t saved_tty_pgrp;
459 struct pipe *job_list;
460 struct pipe *toplevel_list;
461 //// smallint ctrl_z_flag;
463 smallint flag_SIGINT;
464 #if ENABLE_HUSH_LOOPS
465 smallint flag_break_continue;
468 /* These four support $?, $#, and $1 */
469 smalluint last_return_code;
470 /* is global_argv and global_argv[1..n] malloced? (note: not [0]) */
471 smalluint global_args_malloced;
472 /* how many non-NULL argv's we have. NB: $# + 1 */
475 #if ENABLE_HUSH_LOOPS
476 unsigned depth_break_continue;
477 unsigned depth_of_loop;
481 struct variable *top_var; /* = &G.shell_ver (set in main()) */
482 struct variable shell_ver;
483 /* Signal and trap handling */
484 // unsigned count_SIGCHLD;
485 // unsigned handled_SIGCHLD;
486 /* which signals have non-DFL handler (even with no traps set)? */
487 unsigned non_DFL_mask;
488 char **traps; /* char *traps[NSIG] */
489 sigset_t blocked_set;
490 sigset_t inherited_set;
491 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
492 #if ENABLE_FEATURE_SH_STANDALONE
493 struct nofork_save_area nofork_save;
496 sigjmp_buf toplevel_jb;
499 #define G (*ptr_to_globals)
500 /* Not #defining name to G.name - this quickly gets unwieldy
501 * (too many defines). Also, I actually prefer to see when a variable
502 * is global, thus "G." prefix is a useful hint */
503 #define INIT_G() do { \
504 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
508 /* Function prototypes for builtins */
509 static int builtin_cd(char **argv);
510 static int builtin_echo(char **argv);
511 static int builtin_eval(char **argv);
512 static int builtin_exec(char **argv);
513 static int builtin_exit(char **argv);
514 static int builtin_export(char **argv);
516 static int builtin_fg_bg(char **argv);
517 static int builtin_jobs(char **argv);
520 static int builtin_help(char **argv);
522 static int builtin_pwd(char **argv);
523 static int builtin_read(char **argv);
524 static int builtin_test(char **argv);
525 static int builtin_trap(char **argv);
526 static int builtin_true(char **argv);
527 static int builtin_set(char **argv);
528 static int builtin_shift(char **argv);
529 static int builtin_source(char **argv);
530 static int builtin_umask(char **argv);
531 static int builtin_unset(char **argv);
532 static int builtin_wait(char **argv);
533 #if ENABLE_HUSH_LOOPS
534 static int builtin_break(char **argv);
535 static int builtin_continue(char **argv);
538 /* Table of built-in functions. They can be forked or not, depending on
539 * context: within pipes, they fork. As simple commands, they do not.
540 * When used in non-forking context, they can change global variables
541 * in the parent shell process. If forked, of course they cannot.
542 * For example, 'unset foo | whatever' will parse and run, but foo will
543 * still be set at the end. */
544 struct built_in_command {
546 int (*function)(char **argv);
549 #define BLTIN(cmd, func, help) { cmd, func, help }
551 #define BLTIN(cmd, func, help) { cmd, func }
555 /* For now, echo and test are unconditionally enabled.
556 * Maybe make it configurable? */
557 static const struct built_in_command bltins[] = {
558 BLTIN("." , builtin_source , "Run commands in a file"),
559 BLTIN(":" , builtin_true , "No-op"),
560 BLTIN("[" , builtin_test , "Test condition"),
562 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
564 #if ENABLE_HUSH_LOOPS
565 BLTIN("break" , builtin_break , "Exit from a loop"),
567 BLTIN("cd" , builtin_cd , "Change directory"),
568 #if ENABLE_HUSH_LOOPS
569 BLTIN("continue", builtin_continue, "Start new loop iteration"),
571 BLTIN("echo" , builtin_echo , "Write to stdout"),
572 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
573 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
574 BLTIN("exit" , builtin_exit , "Exit"),
575 BLTIN("export" , builtin_export , "Set environment variable"),
577 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
580 BLTIN("help" , builtin_help , "List shell built-in commands"),
583 BLTIN("jobs" , builtin_jobs , "List active jobs"),
585 BLTIN("pwd" , builtin_pwd , "Print current directory"),
586 BLTIN("read" , builtin_read , "Input environment variable"),
587 // BLTIN("return" , builtin_return , "Return from a function"),
588 BLTIN("set" , builtin_set , "Set/unset shell local variables"),
589 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
590 BLTIN("test" , builtin_test , "Test condition"),
591 BLTIN("trap" , builtin_trap , "Trap signals"),
592 // BLTIN("ulimit" , builtin_return , "Control resource limits"),
593 BLTIN("umask" , builtin_umask , "Set file creation mask"),
594 BLTIN("unset" , builtin_unset , "Unset environment variable"),
595 BLTIN("wait" , builtin_wait , "Wait for process"),
599 static void maybe_die(const char *notice, const char *msg)
601 /* Was using fancy stuff:
602 * (G_interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
603 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
604 void FAST_FUNC (*fp)(const char *s, ...) = bb_error_msg_and_die;
605 #if ENABLE_HUSH_INTERACTIVE
606 if (G_interactive_fd)
609 fp(msg ? "%s: %s" : notice, notice, msg);
612 #define syntax(msg) maybe_die("syntax error", msg);
614 /* Debug -- trick gcc to expand __LINE__ and convert to string */
615 #define __syntax(msg, line) maybe_die("syntax error hush.c:" # line, msg)
616 #define _syntax(msg, line) __syntax(msg, line)
617 #define syntax(msg) _syntax(msg, __LINE__)
621 static int glob_needed(const char *s)
626 if (*s == '*' || *s == '[' || *s == '?')
633 static int is_assignment(const char *s)
635 if (!s || !(isalpha(*s) || *s == '_'))
638 while (isalnum(*s) || *s == '_')
643 /* Replace each \x with x in place, return ptr past NUL. */
644 static char *unbackslash(char *src)
650 if ((*dst++ = *src++) == '\0')
656 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
677 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
678 v[count1 + count2] = NULL;
681 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
685 static char **add_string_to_strings(char **strings, char *add)
690 return add_strings_to_strings(strings, v, /*dup:*/ 0);
693 static void putenv_all(char **strings)
698 debug_printf_env("putenv '%s'\n", *strings);
703 static char **putenv_all_and_save_old(char **strings)
713 eq = strchr(*strings, '=');
716 v = getenv(*strings);
719 /* v points to VAL in VAR=VAL, go back to VAR */
720 v -= (eq - *strings) + 1;
721 old = add_string_to_strings(old, v);
730 static void free_strings_and_unsetenv(char **strings, int unset)
740 debug_printf_env("unsetenv '%s'\n", *v);
748 static void free_strings(char **strings)
750 free_strings_and_unsetenv(strings, 0);
754 /* Basic theory of signal handling in shell
755 * ========================================
756 * This does not describe what hush does, rather, it is current understanding
757 * what it _should_ do. If it doesn't, it's a bug.
758 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
760 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
761 * is finished or backgrounded. It is the same in interactive and
762 * non-interactive shells, and is the same regardless of whether
763 * a user trap handler is installed or a shell special one is in effect.
764 * ^C or ^Z from keyboard seem to execute "at once" because it usually
765 * backgrounds (i.e. stops) or kills all members of currently running
768 * Wait builtin in interruptible by signals for which user trap is set
769 * or by SIGINT in interactive shell.
771 * Trap handlers will execute even within trap handlers. (right?)
773 * User trap handlers are forgotten when subshell ("(cmd)") is entered. [TODO]
775 * If job control is off, backgrounded commands ("cmd &")
776 * have SIGINT, SIGQUIT set to SIG_IGN.
778 * Commands run in command substitution ("`cmd`")
779 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
781 * Ordinary commands have signals set to SIG_IGN/DFL set as inherited
782 * by the shell from its parent.
784 * Siganls which differ from SIG_DFL action
785 * (note: child (i.e., [v]forked) shell is not an interactive shell):
788 * SIGTERM (interactive): ignore
789 * SIGHUP (interactive):
790 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
791 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
792 * (note that ^Z is handled not by trapping SIGTSTP, but by seeing
793 * that all pipe members are stopped) (right?)
794 * SIGINT (interactive): wait for last pipe, ignore the rest
795 * of the command line, show prompt. NB: ^C does not send SIGINT
796 * to interactive shell while shell is waiting for a pipe,
797 * since shell is bg'ed (is not in foreground process group).
798 * (check/expand this)
799 * Example 1: this waits 5 sec, but does not execute ls:
800 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
801 * Example 2: this does not wait and does not execute ls:
802 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
803 * Example 3: this does not wait 5 sec, but executes ls:
804 * "sleep 5; ls -l" + press ^C
806 * (What happens to signals which are IGN on shell start?)
807 * (What happens with signal mask on shell start?)
809 * Implementation in hush
810 * ======================
811 * We use in-kernel pending signal mask to determine which signals were sent.
812 * We block all signals which we don't want to take action immediately,
813 * i.e. we block all signals which need to have special handling as described
814 * above, and all signals which have traps set.
815 * After each pipe execution, we extract any pending signals via sigtimedwait()
818 * unsigned non_DFL_mask: a mask of such "special" signals
819 * sigset_t blocked_set: current blocked signal set
822 * clear bit in blocked_set unless it is also in non_DFL_mask
823 * "trap 'cmd' SIGxxx":
824 * set bit in blocked_set (even if 'cmd' is '')
825 * after [v]fork, if we plan to be a shell:
826 * nothing for {} child shell (say, "true | { true; true; } | true")
827 * unset all traps if () shell. [TODO]
828 * after [v]fork, if we plan to exec:
829 * POSIX says pending signal mask is cleared in child - no need to clear it.
830 * Restore blocked signal set to one inherited by shell just prior to exec.
832 * Note: as a result, we do not use signal handlers much. The only uses
833 * are to count SIGCHLDs [disabled - bug somewhere, + bloat]
834 * and to restore tty pgrp on signal-induced exit.
836 * TODO: check/fix wait builtin to be interruptible.
839 //static void SIGCHLD_handler(int sig UNUSED_PARAM)
841 // G.count_SIGCHLD++;
844 /* called once at shell init */
845 static void init_signal_mask(void)
848 unsigned mask = (1 << SIGQUIT);
849 if (G_interactive_fd) {
855 | (1 << SIGTTIN) | (1 << SIGTTOU) | (1 << SIGTSTP)
860 G.non_DFL_mask = mask;
862 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
866 sigaddset(&G.blocked_set, sig);
870 sigdelset(&G.blocked_set, SIGCHLD);
871 sigprocmask(SIG_SETMASK, &G.blocked_set, &G.inherited_set);
874 static int check_and_run_traps(int sig)
876 static const struct timespec zero_timespec = { 0, 0 };
877 smalluint save_rcode;
883 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
888 if (G.traps && G.traps[sig]) {
889 if (G.traps[sig][0]) {
890 /* We have user-defined handler */
891 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
892 save_rcode = G.last_return_code;
895 G.last_return_code = save_rcode;
896 } /* else: "" trap, ignoring signal */
899 /* not a trap: special action */
902 // G.count_SIGCHLD++;
911 default: /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
920 /* Restores tty foreground process group, and exits.
921 * May be called as signal handler for fatal signal
922 * (will faithfully resend signal to itself, producing correct exit state)
923 * or called directly with -EXITCODE.
924 * We also call it if xfunc is exiting. */
925 static void sigexit(int sig) NORETURN;
926 static void sigexit(int sig)
928 /* Disable all signals: job control, SIGPIPE, etc. */
929 sigprocmask_allsigs(SIG_BLOCK);
931 /* Careful: we can end up here after [v]fork. Do not restore
932 * tty pgrp then, only top-level shell process does that */
933 if (G_interactive_fd && getpid() == G.root_pid)
934 tcsetpgrp(G_interactive_fd, G.saved_tty_pgrp);
936 /* Not a signal, just exit */
940 kill_myself_with_sig(sig); /* does not return */
944 static void maybe_set_sighandler(int sig)
946 void (*handler)(int);
947 /* non_DFL_mask'ed signals are, well, masked,
948 * no need to set handler for them.
950 if (!((G.non_DFL_mask >> sig) & 1)) {
951 handler = signal(sig, sigexit);
952 if (handler == SIG_IGN) /* oops... restore back to IGN! */
953 signal(sig, handler);
956 /* Used only to set handler to restore pgrp on exit */
957 static void set_fatal_signals_to_sigexit(void)
960 maybe_set_sighandler(SIGILL );
961 maybe_set_sighandler(SIGFPE );
962 maybe_set_sighandler(SIGBUS );
963 maybe_set_sighandler(SIGSEGV);
964 maybe_set_sighandler(SIGTRAP);
965 } /* else: hush is perfect. what SEGV? */
967 maybe_set_sighandler(SIGABRT);
969 /* bash 3.2 seems to handle these just like 'fatal' ones */
970 maybe_set_sighandler(SIGPIPE);
971 maybe_set_sighandler(SIGALRM);
972 maybe_set_sighandler(SIGHUP );
974 /* if we aren't interactive... but in this case
975 * we never want to restore pgrp on exit, and this fn is not called */
976 /*maybe_set_sighandler(SIGTERM);*/
977 /*maybe_set_sighandler(SIGINT );*/
982 #define set_fatal_signals_to_sigexit(handler) ((void)0)
986 /* Restores tty foreground process group, and exits. */
987 static void hush_exit(int exitcode) NORETURN;
988 static void hush_exit(int exitcode)
990 if (G.traps && G.traps[0] && G.traps[0][0]) {
991 char *argv[] = { NULL, xstrdup(G.traps[0]), NULL };
997 fflush(NULL); /* flush all streams */
998 sigexit(- (exitcode & 0xff));
1005 static const char *set_cwd(void)
1007 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1008 * we must not try to free(bb_msg_unknown) */
1009 if (G.cwd == bb_msg_unknown)
1011 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1013 G.cwd = bb_msg_unknown;
1018 /* Get/check local shell variables */
1019 static struct variable *get_local_var(const char *name)
1021 struct variable *cur;
1027 for (cur = G.top_var; cur; cur = cur->next) {
1028 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1034 static const char *get_local_var_value(const char *src)
1036 struct variable *var = get_local_var(src);
1038 return strchr(var->varstr, '=') + 1;
1042 /* str holds "NAME=VAL" and is expected to be malloced.
1043 * We take ownership of it.
1044 * flg_export is used by:
1047 * -1: if NAME is set, leave export status alone
1048 * if NAME is not set, do not export
1050 static int set_local_var(char *str, int flg_export)
1052 struct variable *cur;
1056 value = strchr(str, '=');
1057 if (!value) { /* not expected to ever happen? */
1062 name_len = value - str + 1; /* including '=' */
1063 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
1065 if (strncmp(cur->varstr, str, name_len) != 0) {
1067 /* Bail out. Note that now cur points
1068 * to last var in linked list */
1074 /* We found an existing var with this name */
1076 if (cur->flg_read_only) {
1077 bb_error_msg("%s: readonly variable", str);
1081 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1082 unsetenv(str); /* just in case */
1084 if (strcmp(cur->varstr, str) == 0) {
1089 if (cur->max_len >= strlen(str)) {
1090 /* This one is from startup env, reuse space */
1091 strcpy(cur->varstr, str);
1094 /* max_len == 0 signifies "malloced" var, which we can
1095 * (and has to) free */
1099 goto set_str_and_exp;
1102 /* Not found - create next variable struct */
1103 cur->next = xzalloc(sizeof(*cur));
1109 if (flg_export == 1)
1110 cur->flg_export = 1;
1111 if (cur->flg_export) {
1112 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1113 return putenv(cur->varstr);
1118 static int unset_local_var(const char *name)
1120 struct variable *cur;
1121 struct variable *prev = prev; /* for gcc */
1125 return EXIT_SUCCESS;
1126 name_len = strlen(name);
1129 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1130 if (cur->flg_read_only) {
1131 bb_error_msg("%s: readonly variable", name);
1132 return EXIT_FAILURE;
1134 /* prev is ok to use here because 1st variable, HUSH_VERSION,
1135 * is ro, and we cannot reach this code on the 1st pass */
1136 prev->next = cur->next;
1137 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1138 bb_unsetenv(cur->varstr);
1142 return EXIT_SUCCESS;
1147 return EXIT_SUCCESS;
1150 #if ENABLE_SH_MATH_SUPPORT
1151 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1152 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1153 static char *endofname(const char *name)
1161 if (!is_in_name(*p))
1167 static void arith_set_local_var(const char *name, const char *val, int flags)
1169 /* arith code doesnt malloc space, so do it for it */
1170 char *var = xasprintf("%s=%s", name, val);
1171 set_local_var(var, flags);
1179 static int static_get(struct in_str *i)
1188 static int static_peek(struct in_str *i)
1193 #if ENABLE_HUSH_INTERACTIVE
1195 static void cmdedit_set_initial_prompt(void)
1197 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1198 G.PS1 = getenv("PS1");
1205 static const char* setup_prompt_string(int promptmode)
1207 const char *prompt_str;
1208 debug_printf("setup_prompt_string %d ", promptmode);
1209 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1210 /* Set up the prompt */
1211 if (promptmode == 0) { /* PS1 */
1213 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1218 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1219 debug_printf("result '%s'\n", prompt_str);
1223 static void get_user_input(struct in_str *i)
1226 const char *prompt_str;
1228 prompt_str = setup_prompt_string(i->promptmode);
1229 #if ENABLE_FEATURE_EDITING
1230 /* Enable command line editing only while a command line
1231 * is actually being read */
1234 /* buglet: SIGINT will not make new prompt to appear _at once_,
1235 * only after <Enter>. (^C will work) */
1236 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1237 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1238 check_and_run_traps(0);
1239 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1240 i->eof_flag = (r < 0);
1241 if (i->eof_flag) { /* EOF/error detected */
1242 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1243 G.user_input_buf[1] = '\0';
1248 fputs(prompt_str, stdout);
1250 G.user_input_buf[0] = r = fgetc(i->file);
1251 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1252 //do we need check_and_run_traps(0)? (maybe only if stdin)
1253 } while (G.flag_SIGINT);
1254 i->eof_flag = (r == EOF);
1256 i->p = G.user_input_buf;
1259 #endif /* INTERACTIVE */
1261 /* This is the magic location that prints prompts
1262 * and gets data back from the user */
1263 static int file_get(struct in_str *i)
1267 /* If there is data waiting, eat it up */
1268 if (i->p && *i->p) {
1269 #if ENABLE_HUSH_INTERACTIVE
1273 if (i->eof_flag && !*i->p)
1276 /* need to double check i->file because we might be doing something
1277 * more complicated by now, like sourcing or substituting. */
1278 #if ENABLE_HUSH_INTERACTIVE
1279 if (G_interactive_fd && i->promptme && i->file == stdin) {
1282 } while (!*i->p); /* need non-empty line */
1283 i->promptmode = 1; /* PS2 */
1288 ch = fgetc(i->file);
1290 debug_printf("file_get: got a '%c' %d\n", ch, ch);
1291 #if ENABLE_HUSH_INTERACTIVE
1298 /* All the callers guarantee this routine will never be
1299 * used right after a newline, so prompting is not needed.
1301 static int file_peek(struct in_str *i)
1304 if (i->p && *i->p) {
1305 if (i->eof_flag && !i->p[1])
1309 ch = fgetc(i->file);
1310 i->eof_flag = (ch == EOF);
1311 i->peek_buf[0] = ch;
1312 i->peek_buf[1] = '\0';
1314 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
1318 static void setup_file_in_str(struct in_str *i, FILE *f)
1320 i->peek = file_peek;
1322 #if ENABLE_HUSH_INTERACTIVE
1324 i->promptmode = 0; /* PS1 */
1330 static void setup_string_in_str(struct in_str *i, const char *s)
1332 i->peek = static_peek;
1333 i->get = static_get;
1334 #if ENABLE_HUSH_INTERACTIVE
1336 i->promptmode = 0; /* PS1 */
1346 #define B_CHUNK (32 * sizeof(char*))
1348 static void o_reset(o_string *o)
1356 static void o_free(o_string *o)
1359 memset(o, 0, sizeof(*o));
1362 static void o_grow_by(o_string *o, int len)
1364 if (o->length + len > o->maxlen) {
1365 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1366 o->data = xrealloc(o->data, 1 + o->maxlen);
1370 static void o_addchr(o_string *o, int ch)
1372 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1374 o->data[o->length] = ch;
1376 o->data[o->length] = '\0';
1379 static void o_addstr(o_string *o, const char *str, int len)
1382 memcpy(&o->data[o->length], str, len);
1384 o->data[o->length] = '\0';
1387 static void o_addstrauto(o_string *o, const char *str)
1389 o_addstr(o, str, strlen(str) + 1);
1392 static void o_addstr_duplicate_backslash(o_string *o, const char *str, int len)
1397 && (*str != '*' && *str != '?' && *str != '[')
1405 /* My analysis of quoting semantics tells me that state information
1406 * is associated with a destination, not a source.
1408 static void o_addqchr(o_string *o, int ch)
1411 char *found = strchr("*?[\\", ch);
1416 o->data[o->length] = '\\';
1419 o->data[o->length] = ch;
1421 o->data[o->length] = '\0';
1424 static void o_addQchr(o_string *o, int ch)
1427 if (o->o_escape && strchr("*?[\\", ch)) {
1429 o->data[o->length] = '\\';
1433 o->data[o->length] = ch;
1435 o->data[o->length] = '\0';
1438 static void o_addQstr(o_string *o, const char *str, int len)
1441 o_addstr(o, str, len);
1447 int ordinary_cnt = strcspn(str, "*?[\\");
1448 if (ordinary_cnt > len) /* paranoia */
1450 o_addstr(o, str, ordinary_cnt);
1451 if (ordinary_cnt == len)
1453 str += ordinary_cnt;
1454 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
1458 if (ch) { /* it is necessarily one of "*?[\\" */
1460 o->data[o->length] = '\\';
1464 o->data[o->length] = ch;
1466 o->data[o->length] = '\0';
1470 /* A special kind of o_string for $VAR and `cmd` expansion.
1471 * It contains char* list[] at the beginning, which is grown in 16 element
1472 * increments. Actual string data starts at the next multiple of 16 * (char*).
1473 * list[i] contains an INDEX (int!) into this string data.
1474 * It means that if list[] needs to grow, data needs to be moved higher up
1475 * but list[i]'s need not be modified.
1476 * NB: remembering how many list[i]'s you have there is crucial.
1477 * o_finalize_list() operation post-processes this structure - calculates
1478 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1480 #if DEBUG_EXPAND || DEBUG_GLOB
1481 static void debug_print_list(const char *prefix, o_string *o, int n)
1483 char **list = (char**)o->data;
1484 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1486 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1487 prefix, list, n, string_start, o->length, o->maxlen);
1489 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1490 o->data + (int)list[i] + string_start,
1491 o->data + (int)list[i] + string_start);
1495 const char *p = o->data + (int)list[n - 1] + string_start;
1496 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
1500 #define debug_print_list(prefix, o, n) ((void)0)
1503 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1504 * in list[n] so that it points past last stored byte so far.
1505 * It returns n+1. */
1506 static int o_save_ptr_helper(o_string *o, int n)
1508 char **list = (char**)o->data;
1512 if (!o->has_empty_slot) {
1513 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1514 string_len = o->length - string_start;
1515 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1516 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
1517 /* list[n] points to string_start, make space for 16 more pointers */
1518 o->maxlen += 0x10 * sizeof(list[0]);
1519 o->data = xrealloc(o->data, o->maxlen + 1);
1520 list = (char**)o->data;
1521 memmove(list + n + 0x10, list + n, string_len);
1522 o->length += 0x10 * sizeof(list[0]);
1524 debug_printf_list("list[%d]=%d string_start=%d\n",
1525 n, string_len, string_start);
1528 /* We have empty slot at list[n], reuse without growth */
1529 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1530 string_len = o->length - string_start;
1531 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1532 n, string_len, string_start);
1533 o->has_empty_slot = 0;
1535 list[n] = (char*)(ptrdiff_t)string_len;
1539 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
1540 static int o_get_last_ptr(o_string *o, int n)
1542 char **list = (char**)o->data;
1543 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1545 return ((int)(ptrdiff_t)list[n-1]) + string_start;
1548 /* o_glob performs globbing on last list[], saving each result
1549 * as a new list[]. */
1550 static int o_glob(o_string *o, int n)
1556 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
1558 return o_save_ptr_helper(o, n);
1559 pattern = o->data + o_get_last_ptr(o, n);
1560 debug_printf_glob("glob pattern '%s'\n", pattern);
1561 if (!glob_needed(pattern)) {
1563 o->length = unbackslash(pattern) - o->data;
1564 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
1565 return o_save_ptr_helper(o, n);
1568 memset(&globdata, 0, sizeof(globdata));
1569 gr = glob(pattern, 0, NULL, &globdata);
1570 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1571 if (gr == GLOB_NOSPACE)
1572 bb_error_msg_and_die("out of memory during glob");
1573 if (gr == GLOB_NOMATCH) {
1574 globfree(&globdata);
1577 if (gr != 0) { /* GLOB_ABORTED ? */
1578 //TODO: testcase for bad glob pattern behavior
1579 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1581 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1582 char **argv = globdata.gl_pathv;
1583 o->length = pattern - o->data; /* "forget" pattern */
1585 o_addstrauto(o, *argv);
1586 n = o_save_ptr_helper(o, n);
1592 globfree(&globdata);
1594 debug_print_list("o_glob returning", o, n);
1598 /* If o->o_glob == 1, glob the string so far remembered.
1599 * Otherwise, just finish current list[] and start new */
1600 static int o_save_ptr(o_string *o, int n)
1602 if (o->o_glob) { /* if globbing is requested */
1603 /* If o->has_empty_slot, list[n] was already globbed
1604 * (if it was requested back then when it was filled)
1605 * so don't do that again! */
1606 if (!o->has_empty_slot)
1607 return o_glob(o, n); /* o_save_ptr_helper is inside */
1609 return o_save_ptr_helper(o, n);
1612 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
1613 static char **o_finalize_list(o_string *o, int n)
1618 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1620 debug_print_list("finalized", o, n);
1621 debug_printf_expand("finalized n:%d\n", n);
1622 list = (char**)o->data;
1623 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1627 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
1633 /* Expansion can recurse */
1634 #if ENABLE_HUSH_TICK
1635 static int process_command_subs(o_string *dest, const char *s);
1637 static char *expand_string_to_string(const char *str);
1638 static int parse_stream_dquoted(o_string *dest, struct in_str *input, int dquote_end);
1640 /* expand_strvec_to_strvec() takes a list of strings, expands
1641 * all variable references within and returns a pointer to
1642 * a list of expanded strings, possibly with larger number
1643 * of strings. (Think VAR="a b"; echo $VAR).
1644 * This new list is allocated as a single malloc block.
1645 * NULL-terminated list of char* pointers is at the beginning of it,
1646 * followed by strings themself.
1647 * Caller can deallocate entire list by single free(list). */
1649 /* Store given string, finalizing the word and starting new one whenever
1650 * we encounter IFS char(s). This is used for expanding variable values.
1651 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
1652 static int expand_on_ifs(o_string *output, int n, const char *str)
1655 int word_len = strcspn(str, G.ifs);
1657 if (output->o_escape || !output->o_glob)
1658 o_addQstr(output, str, word_len);
1659 else /* protect backslashes against globbing up :) */
1660 o_addstr_duplicate_backslash(output, str, word_len);
1663 if (!*str) /* EOL - do not finalize word */
1665 o_addchr(output, '\0');
1666 debug_print_list("expand_on_ifs", output, n);
1667 n = o_save_ptr(output, n);
1668 str += strspn(str, G.ifs); /* skip ifs chars */
1670 debug_print_list("expand_on_ifs[1]", output, n);
1674 /* Expand all variable references in given string, adding words to list[]
1675 * at n, n+1,... positions. Return updated n (so that list[n] is next one
1676 * to be filled). This routine is extremely tricky: has to deal with
1677 * variables/parameters with whitespace, $* and $@, and constructs like
1678 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
1679 static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
1681 /* or_mask is either 0 (normal case) or 0x80
1682 * (expansion of right-hand side of assignment == 1-element expand.
1683 * It will also do no globbing, and thus we must not backslash-quote!) */
1685 char first_ch, ored_ch;
1692 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
1693 debug_print_list("expand_vars_to_list", output, n);
1694 n = o_save_ptr(output, n);
1695 debug_print_list("expand_vars_to_list[0]", output, n);
1697 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
1698 #if ENABLE_HUSH_TICK
1699 o_string subst_result = NULL_O_STRING;
1701 #if ENABLE_SH_MATH_SUPPORT
1702 char arith_buf[sizeof(arith_t)*3 + 2];
1704 o_addstr(output, arg, p - arg);
1705 debug_print_list("expand_vars_to_list[1]", output, n);
1707 p = strchr(p, SPECIAL_VAR_SYMBOL);
1709 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
1710 /* "$@" is special. Even if quoted, it can still
1711 * expand to nothing (not even an empty string) */
1712 if ((first_ch & 0x7f) != '@')
1713 ored_ch |= first_ch;
1716 switch (first_ch & 0x7f) {
1717 /* Highest bit in first_ch indicates that var is double-quoted */
1719 val = utoa(G.root_pid);
1721 case '!': /* bg pid */
1722 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
1724 case '?': /* exitcode */
1725 val = utoa(G.last_return_code);
1727 case '#': /* argc */
1728 if (arg[1] != SPECIAL_VAR_SYMBOL)
1729 /* actually, it's a ${#var} */
1731 val = utoa(G.global_argc ? G.global_argc-1 : 0);
1736 if (!G.global_argv[i])
1738 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
1739 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
1740 smallint sv = output->o_escape;
1741 /* unquoted var's contents should be globbed, so don't escape */
1742 output->o_escape = 0;
1743 while (G.global_argv[i]) {
1744 n = expand_on_ifs(output, n, G.global_argv[i]);
1745 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
1746 if (G.global_argv[i++][0] && G.global_argv[i]) {
1747 /* this argv[] is not empty and not last:
1748 * put terminating NUL, start new word */
1749 o_addchr(output, '\0');
1750 debug_print_list("expand_vars_to_list[2]", output, n);
1751 n = o_save_ptr(output, n);
1752 debug_print_list("expand_vars_to_list[3]", output, n);
1755 output->o_escape = sv;
1757 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
1758 * and in this case should treat it like '$*' - see 'else...' below */
1759 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
1761 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1762 if (++i >= G.global_argc)
1764 o_addchr(output, '\0');
1765 debug_print_list("expand_vars_to_list[4]", output, n);
1766 n = o_save_ptr(output, n);
1768 } else { /* quoted $*: add as one word */
1770 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1771 if (!G.global_argv[++i])
1774 o_addchr(output, G.ifs[0]);
1778 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
1779 /* "Empty variable", used to make "" etc to not disappear */
1783 #if ENABLE_HUSH_TICK
1784 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
1787 //TODO: can we just stuff it into "output" directly?
1788 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
1789 process_command_subs(&subst_result, arg);
1790 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
1791 val = subst_result.data;
1794 #if ENABLE_SH_MATH_SUPPORT
1795 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
1796 arith_eval_hooks_t hooks;
1801 arg++; /* skip '+' */
1802 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
1803 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
1805 /* Optional: skip expansion if expr is simple ("a + 3", "i++" etc) */
1808 unsigned char c = *exp_str++;
1815 if (strchr(" \t+-*/%_", c) != NULL)
1817 c |= 0x20; /* tolower */
1818 if (c >= 'a' && c <= 'z')
1822 /* We need to expand. Example: "echo $(($a + 1)) $((1 + $((2)) ))" */
1824 struct in_str input;
1825 o_string dest = NULL_O_STRING;
1827 setup_string_in_str(&input, arg);
1828 parse_stream_dquoted(&dest, &input, EOF);
1829 //bb_error_msg("'%s' -> '%s'", arg, dest.data);
1830 exp_str = expand_string_to_string(dest.data);
1831 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
1835 hooks.lookupvar = get_local_var_value;
1836 hooks.setvar = arith_set_local_var;
1837 hooks.endofname = endofname;
1838 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
1843 case -3: maybe_die("arith", "exponent less than 0"); break;
1844 case -2: maybe_die("arith", "divide by zero"); break;
1845 case -5: maybe_die("arith", "expression recursion loop detected"); break;
1846 default: maybe_die("arith", "syntax error"); break;
1849 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
1850 sprintf(arith_buf, arith_t_fmt, res);
1855 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
1857 bool exp_len = false, exp_null = false;
1858 char *var = arg, exp_save, exp_op, *exp_word;
1861 arg[0] = first_ch & 0x7f;
1863 /* prepare for expansions */
1864 if (var[0] == '#') {
1865 /* handle length expansion ${#var} */
1869 /* maybe handle parameter expansion */
1870 exp_off = strcspn(var, ":-=+?");
1874 exp_save = var[exp_off];
1875 exp_null = exp_save == ':';
1876 exp_word = var + exp_off;
1877 if (exp_null) ++exp_word;
1878 exp_op = *exp_word++;
1879 var[exp_off] = '\0';
1883 /* lookup the variable in question */
1884 if (isdigit(var[0])) {
1885 /* handle_dollar() should have vetted var for us */
1887 if (i < G.global_argc)
1888 val = G.global_argv[i];
1889 /* else val remains NULL: $N with too big N */
1891 val = get_local_var_value(var);
1893 /* handle any expansions */
1895 debug_printf_expand("expand: length of '%s' = ", val);
1896 val = utoa(val ? strlen(val) : 0);
1897 debug_printf_expand("%s\n", val);
1898 } else if (exp_off) {
1899 /* we need to do an expansion */
1900 int exp_test = (!val || (exp_null && !val[0]));
1902 exp_test = !exp_test;
1903 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
1904 exp_null ? "true" : "false", exp_test);
1907 maybe_die(var, *exp_word ? exp_word : "parameter null or not set");
1911 if (exp_op == '=') {
1912 if (isdigit(var[0]) || var[0] == '#') {
1913 maybe_die(var, "special vars cannot assign in this way");
1916 char *new_var = xmalloc(strlen(var) + strlen(val) + 2);
1917 sprintf(new_var, "%s=%s", var, val);
1918 set_local_var(new_var, -1);
1922 var[exp_off] = exp_save;
1926 #if ENABLE_HUSH_TICK
1929 if (!(first_ch & 0x80)) { /* unquoted $VAR */
1930 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
1932 /* unquoted var's contents should be globbed, so don't escape */
1933 smallint sv = output->o_escape;
1934 output->o_escape = 0;
1935 n = expand_on_ifs(output, n, val);
1937 output->o_escape = sv;
1939 } else { /* quoted $VAR, val will be appended below */
1940 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
1943 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
1945 o_addQstr(output, val, strlen(val));
1947 /* Do the check to avoid writing to a const string */
1948 if (*p != SPECIAL_VAR_SYMBOL)
1949 *p = SPECIAL_VAR_SYMBOL;
1951 #if ENABLE_HUSH_TICK
1952 o_free(&subst_result);
1955 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
1958 debug_print_list("expand_vars_to_list[a]", output, n);
1959 /* this part is literal, and it was already pre-quoted
1960 * if needed (much earlier), do not use o_addQstr here! */
1961 o_addstrauto(output, arg);
1962 debug_print_list("expand_vars_to_list[b]", output, n);
1963 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
1964 && !(ored_ch & 0x80) /* and all vars were not quoted. */
1967 /* allow to reuse list[n] later without re-growth */
1968 output->has_empty_slot = 1;
1970 o_addchr(output, '\0');
1975 static char **expand_variables(char **argv, int or_mask)
1980 o_string output = NULL_O_STRING;
1982 if (or_mask & 0x100) {
1983 output.o_escape = 1; /* protect against globbing for "$var" */
1984 /* (unquoted $var will temporarily switch it off) */
1991 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
1994 debug_print_list("expand_variables", &output, n);
1996 /* output.data (malloced in one block) gets returned in "list" */
1997 list = o_finalize_list(&output, n);
1998 debug_print_strings("expand_variables[1]", list);
2002 static char **expand_strvec_to_strvec(char **argv)
2004 return expand_variables(argv, 0x100);
2007 /* Used for expansion of right hand of assignments */
2008 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2010 static char *expand_string_to_string(const char *str)
2012 char *argv[2], **list;
2014 argv[0] = (char*)str;
2016 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2018 if (!list[0] || list[1])
2019 bb_error_msg_and_die("BUG in varexp2");
2020 /* actually, just move string 2*sizeof(char*) bytes back */
2021 overlapping_strcpy((char*)list, list[0]);
2022 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2026 /* Used for "eval" builtin */
2027 static char* expand_strvec_to_string(char **argv)
2031 list = expand_variables(argv, 0x80);
2032 /* Convert all NULs to spaces */
2037 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2038 bb_error_msg_and_die("BUG in varexp3");
2039 list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
2043 overlapping_strcpy((char*)list, list[0]);
2044 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2048 static char **expand_assignments(char **argv, int count)
2052 /* Expand assignments into one string each */
2053 for (i = 0; i < count; i++) {
2054 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2060 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
2061 * and stderr if they are redirected. */
2062 static int setup_redirects(struct command *prog, int squirrel[])
2065 struct redir_struct *redir;
2067 for (redir = prog->redirects; redir; redir = redir->next) {
2068 if (redir->dup == -1 && redir->rd_filename == NULL) {
2069 /* something went wrong in the parse. Pretend it didn't happen */
2072 if (redir->dup == -1) {
2074 mode = redir_table[redir->rd_type].mode;
2075 //TODO: check redir for names like '\\'
2076 p = expand_string_to_string(redir->rd_filename);
2077 openfd = open_or_warn(p, mode);
2080 /* this could get lost if stderr has been redirected, but
2081 bash and ash both lose it as well (though zsh doesn't!) */
2085 openfd = redir->dup;
2088 if (openfd != redir->fd) {
2089 if (squirrel && redir->fd < 3) {
2090 squirrel[redir->fd] = dup(redir->fd);
2093 //close(openfd); // close(-3) ??!
2095 dup2(openfd, redir->fd);
2096 if (redir->dup == -1)
2104 static void restore_redirects(int squirrel[])
2107 for (i = 0; i < 3; i++) {
2110 /* We simply die on error */
2117 #if !defined(DEBUG_CLEAN)
2118 #define free_pipe_list(head, indent) free_pipe_list(head)
2119 #define free_pipe(pi, indent) free_pipe(pi)
2121 static void free_pipe_list(struct pipe *head, int indent);
2123 /* Return code is the exit status of the pipe */
2124 static void free_pipe(struct pipe *pi, int indent)
2127 struct command *command;
2128 struct redir_struct *r, *rnext;
2131 if (pi->stopped_cmds > 0) /* why? */
2133 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2134 for (i = 0; i < pi->num_cmds; i++) {
2135 command = &pi->cmds[i];
2136 debug_printf_clean("%s command %d:\n", indenter(indent), i);
2137 if (command->argv) {
2138 for (a = 0, p = command->argv; *p; a++, p++) {
2139 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
2141 free_strings(command->argv);
2142 command->argv = NULL;
2144 /* not "else if": on syntax error, we may have both! */
2145 if (command->group) {
2146 debug_printf_clean("%s begin group (grp_type:%d)\n", indenter(indent), command->grp_type);
2147 free_pipe_list(command->group, indent+3);
2148 debug_printf_clean("%s end group\n", indenter(indent));
2149 command->group = NULL;
2151 for (r = command->redirects; r; r = rnext) {
2152 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->rd_type].descrip);
2154 /* guard against the case >$FOO, where foo is unset or blank */
2155 if (r->rd_filename) {
2156 debug_printf_clean(" %s\n", r->rd_filename);
2157 free(r->rd_filename);
2158 r->rd_filename = NULL;
2161 debug_printf_clean("&%d\n", r->dup);
2166 command->redirects = NULL;
2168 free(pi->cmds); /* children are an array, they get freed all at once */
2176 static void free_pipe_list(struct pipe *head, int indent)
2178 struct pipe *pi, *next;
2180 for (pi = head; pi; pi = next) {
2182 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
2184 free_pipe(pi, indent);
2185 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
2187 /*pi->next = NULL;*/
2194 typedef struct nommu_save_t {
2200 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
2201 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
2202 #define pseudo_exec(nommu_save, command, argv_expanded) \
2203 pseudo_exec(command, argv_expanded)
2206 /* Called after [v]fork() in run_pipe(), or from builtin_exec().
2208 * XXX no exit() here. If you don't exec, use _exit instead.
2209 * The at_exit handlers apparently confuse the calling process,
2210 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
2211 static void pseudo_exec_argv(nommu_save_t *nommu_save,
2212 char **argv, int assignment_cnt,
2213 char **argv_expanded) NORETURN;
2214 static void pseudo_exec_argv(nommu_save_t *nommu_save,
2215 char **argv, int assignment_cnt,
2216 char **argv_expanded)
2220 const struct built_in_command *x;
2222 /* Case when we are here: ... | var=val | ... */
2223 if (!argv[assignment_cnt])
2224 _exit(EXIT_SUCCESS);
2226 new_env = expand_assignments(argv, assignment_cnt);
2228 putenv_all(new_env);
2229 free(new_env); /* optional */
2231 nommu_save->new_env = new_env;
2232 nommu_save->old_env = putenv_all_and_save_old(new_env);
2234 if (argv_expanded) {
2235 argv = argv_expanded;
2237 argv = expand_strvec_to_strvec(argv + assignment_cnt);
2239 nommu_save->argv = argv;
2243 /* On NOMMU, we must never block!
2244 * Example: { sleep 99999 | read line } & echo Ok
2245 * read builtin will block on read syscall, leaving parent blocked
2246 * in vfork. Therefore we can't do this:
2249 /* Check if the command matches any of the builtins.
2250 * Depending on context, this might be redundant. But it's
2251 * easier to waste a few CPU cycles than it is to figure out
2252 * if this is one of those cases.
2254 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2255 if (strcmp(argv[0], x->cmd) == 0) {
2256 debug_printf_exec("running builtin '%s'\n", argv[0]);
2257 rcode = x->function(argv);
2264 #if ENABLE_FEATURE_SH_STANDALONE
2265 /* Check if the command matches any busybox applets */
2266 if (strchr(argv[0], '/') == NULL) {
2267 int a = find_applet_by_name(argv[0]);
2269 #if BB_MMU /* see above why on NOMMU it is not allowed */
2270 if (APPLET_IS_NOEXEC(a)) {
2271 debug_printf_exec("running applet '%s'\n", argv[0]);
2272 run_applet_no_and_exit(a, argv);
2275 /* Re-exec ourselves */
2276 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
2277 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2278 execv(bb_busybox_exec_path, argv);
2279 /* If they called chroot or otherwise made the binary no longer
2280 * executable, fall through */
2285 debug_printf_exec("execing '%s'\n", argv[0]);
2286 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2287 execvp(argv[0], argv);
2288 bb_perror_msg("can't exec '%s'", argv[0]);
2289 _exit(EXIT_FAILURE);
2292 static int run_list(struct pipe *pi);
2294 /* Called after [v]fork() in run_pipe()
2296 static void pseudo_exec(nommu_save_t *nommu_save,
2297 struct command *command,
2298 char **argv_expanded) NORETURN;
2299 static void pseudo_exec(nommu_save_t *nommu_save,
2300 struct command *command,
2301 char **argv_expanded)
2303 if (command->argv) {
2304 pseudo_exec_argv(nommu_save, command->argv,
2305 command->assignment_cnt, argv_expanded);
2308 if (command->group) {
2309 /* Cases when we are here:
2312 * ... | ( list ) | ...
2313 * ... | { list } | ...
2317 debug_printf_exec("pseudo_exec: run_list\n");
2318 rcode = run_list(command->group);
2319 /* OK to leak memory by not calling free_pipe_list,
2320 * since this process is about to exit */
2323 //TODO: re-exec "hush -c command->group_as_a_string"
2324 bb_error_msg_and_die("nested lists are not supported on NOMMU");
2328 /* Case when we are here: ... | >file */
2329 debug_printf_exec("pseudo_exec'ed null command\n");
2330 _exit(EXIT_SUCCESS);
2334 static const char *get_cmdtext(struct pipe *pi)
2340 /* This is subtle. ->cmdtext is created only on first backgrounding.
2341 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
2342 * On subsequent bg argv is trashed, but we won't use it */
2345 argv = pi->cmds[0].argv;
2346 if (!argv || !argv[0]) {
2347 pi->cmdtext = xzalloc(1);
2352 do len += strlen(*argv) + 1; while (*++argv);
2353 pi->cmdtext = p = xmalloc(len);
2354 argv = pi->cmds[0].argv;
2356 len = strlen(*argv);
2357 memcpy(p, *argv, len);
2365 static void insert_bg_job(struct pipe *pi)
2367 struct pipe *thejob;
2370 /* Linear search for the ID of the job to use */
2372 for (thejob = G.job_list; thejob; thejob = thejob->next)
2373 if (thejob->jobid >= pi->jobid)
2374 pi->jobid = thejob->jobid + 1;
2376 /* Add thejob to the list of running jobs */
2378 thejob = G.job_list = xmalloc(sizeof(*thejob));
2380 for (thejob = G.job_list; thejob->next; thejob = thejob->next)
2382 thejob->next = xmalloc(sizeof(*thejob));
2383 thejob = thejob->next;
2386 /* Physically copy the struct job */
2387 memcpy(thejob, pi, sizeof(struct pipe));
2388 thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
2389 /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
2390 for (i = 0; i < pi->num_cmds; i++) {
2391 // TODO: do we really need to have so many fields which are just dead weight
2392 // at execution stage?
2393 thejob->cmds[i].pid = pi->cmds[i].pid;
2394 /* all other fields are not used and stay zero */
2396 thejob->next = NULL;
2397 thejob->cmdtext = xstrdup(get_cmdtext(pi));
2399 /* We don't wait for background thejobs to return -- append it
2400 to the list of backgrounded thejobs and leave it alone */
2401 if (G_interactive_fd)
2402 printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
2403 G.last_bg_pid = thejob->cmds[0].pid;
2404 G.last_jobid = thejob->jobid;
2407 static void remove_bg_job(struct pipe *pi)
2409 struct pipe *prev_pipe;
2411 if (pi == G.job_list) {
2412 G.job_list = pi->next;
2414 prev_pipe = G.job_list;
2415 while (prev_pipe->next != pi)
2416 prev_pipe = prev_pipe->next;
2417 prev_pipe->next = pi->next;
2420 G.last_jobid = G.job_list->jobid;
2425 /* Remove a backgrounded job */
2426 static void delete_finished_bg_job(struct pipe *pi)
2429 pi->stopped_cmds = 0;
2435 /* Check to see if any processes have exited -- if they
2436 * have, figure out why and see if a job has completed */
2437 static int checkjobs(struct pipe* fg_pipe)
2447 debug_printf_jobs("checkjobs %p\n", fg_pipe);
2450 // if (G.handled_SIGCHLD == G.count_SIGCHLD)
2451 // /* avoid doing syscall, nothing there anyway */
2454 attributes = WUNTRACED;
2455 if (fg_pipe == NULL)
2456 attributes |= WNOHANG;
2458 /* Do we do this right?
2459 * bash-3.00# sleep 20 | false
2461 * [3]+ Stopped sleep 20 | false
2462 * bash-3.00# echo $?
2463 * 1 <========== bg pipe is not fully done, but exitcode is already known!
2466 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
2467 //are stopped. Testcase: "cat | cat" in a script (not on command line)
2468 // + killall -STOP cat
2475 // i = G.count_SIGCHLD;
2476 childpid = waitpid(-1, &status, attributes);
2477 if (childpid <= 0) {
2478 if (childpid && errno != ECHILD)
2479 bb_perror_msg("waitpid");
2480 // else /* Until next SIGCHLD, waitpid's are useless */
2481 // G.handled_SIGCHLD = i;
2484 dead = WIFEXITED(status) || WIFSIGNALED(status);
2487 if (WIFSTOPPED(status))
2488 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
2489 childpid, WSTOPSIG(status), WEXITSTATUS(status));
2490 if (WIFSIGNALED(status))
2491 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
2492 childpid, WTERMSIG(status), WEXITSTATUS(status));
2493 if (WIFEXITED(status))
2494 debug_printf_jobs("pid %d exited, exitcode %d\n",
2495 childpid, WEXITSTATUS(status));
2497 /* Were we asked to wait for fg pipe? */
2499 for (i = 0; i < fg_pipe->num_cmds; i++) {
2500 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
2501 if (fg_pipe->cmds[i].pid != childpid)
2503 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
2505 fg_pipe->cmds[i].pid = 0;
2506 fg_pipe->alive_cmds--;
2507 if (i == fg_pipe->num_cmds - 1) {
2508 /* last process gives overall exitstatus */
2509 rcode = WEXITSTATUS(status);
2510 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
2513 fg_pipe->cmds[i].is_stopped = 1;
2514 fg_pipe->stopped_cmds++;
2516 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
2517 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
2518 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
2519 /* All processes in fg pipe have exited/stopped */
2521 if (fg_pipe->alive_cmds)
2522 insert_bg_job(fg_pipe);
2526 /* There are still running processes in the fg pipe */
2527 goto wait_more; /* do waitpid again */
2529 /* it wasnt fg_pipe, look for process in bg pipes */
2533 /* We asked to wait for bg or orphaned children */
2534 /* No need to remember exitcode in this case */
2535 for (pi = G.job_list; pi; pi = pi->next) {
2536 for (i = 0; i < pi->num_cmds; i++) {
2537 if (pi->cmds[i].pid == childpid)
2538 goto found_pi_and_prognum;
2541 /* Happens when shell is used as init process (init=/bin/sh) */
2542 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
2543 continue; /* do waitpid again */
2545 found_pi_and_prognum:
2548 pi->cmds[i].pid = 0;
2550 if (!pi->alive_cmds) {
2551 if (G_interactive_fd)
2552 printf(JOB_STATUS_FORMAT, pi->jobid,
2553 "Done", pi->cmdtext);
2554 delete_finished_bg_job(pi);
2558 pi->cmds[i].is_stopped = 1;
2562 } /* while (waitpid succeeds)... */
2568 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
2571 int rcode = checkjobs(fg_pipe);
2572 /* Job finished, move the shell to the foreground */
2573 p = getpgid(0); /* pgid of our process */
2574 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
2575 tcsetpgrp(G_interactive_fd, p);
2580 /* Start all the jobs, but don't wait for anything to finish.
2583 * Return code is normally -1, when the caller has to wait for children
2584 * to finish to determine the exit status of the pipe. If the pipe
2585 * is a simple builtin command, however, the action is done by the
2586 * time run_pipe returns, and the exit code is provided as the
2589 * Returns -1 only if started some children. IOW: we have to
2590 * mask out retvals of builtins etc with 0xff!
2592 * The only case when we do not need to [v]fork is when the pipe
2593 * is single, non-backgrounded, non-subshell command. Examples:
2594 * cmd ; ... { list } ; ...
2595 * cmd && ... { list } && ...
2596 * cmd || ... { list } || ...
2597 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
2598 * or (if SH_STANDALONE) an applet, and we can run the { list }
2599 * with run_list(). If it isn't one of these, we fork and exec cmd.
2601 * Cases when we must fork:
2602 * non-single: cmd | cmd
2603 * backgrounded: cmd & { list } &
2604 * subshell: ( list ) [&]
2606 static int run_pipe(struct pipe *pi)
2608 static const char *const null_ptr = NULL;
2611 int pipefds[2]; /* pipefds[0] is for reading */
2612 struct command *command;
2613 char **argv_expanded;
2616 /* it is not always needed, but we aim to smaller code */
2617 int squirrel[] = { -1, -1, -1 };
2620 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
2622 USE_HUSH_JOB(pi->pgrp = -1;)
2623 pi->stopped_cmds = 0;
2624 command = &(pi->cmds[0]);
2625 argv_expanded = NULL;
2627 if (pi->num_cmds != 1
2628 || pi->followup == PIPE_BG
2629 || command->grp_type == GRP_SUBSHELL
2636 debug_printf_exec(": group:%p argv:'%s'\n",
2637 command->group, command->argv ? command->argv[0] : "NONE");
2639 if (command->group) {
2640 #if ENABLE_HUSH_FUNCTIONS
2641 if (command->grp_type == GRP_FUNCTION) {
2642 /* func () { list } */
2643 bb_error_msg("here we ought to remember function definition, and go on");
2644 return EXIT_SUCCESS;
2648 debug_printf("non-subshell group\n");
2649 setup_redirects(command, squirrel);
2650 debug_printf_exec(": run_list\n");
2651 rcode = run_list(command->group) & 0xff;
2652 restore_redirects(squirrel);
2653 debug_printf_exec("run_pipe return %d\n", rcode);
2654 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2658 argv = command->argv ? command->argv : (char **) &null_ptr;
2660 const struct built_in_command *x;
2661 char **new_env = NULL;
2662 char **old_env = NULL;
2664 if (argv[command->assignment_cnt] == NULL) {
2665 /* Assignments, but no command */
2666 /* Ensure redirects take effect. Try "a=t >file" */
2667 setup_redirects(command, squirrel);
2668 restore_redirects(squirrel);
2669 /* Set shell variables */
2671 p = expand_string_to_string(*argv);
2672 debug_printf_exec("set shell var:'%s'->'%s'\n",
2674 set_local_var(p, 0);
2677 /* Do we need to flag set_local_var() errors?
2678 * "assignment to readonly var" and "putenv error"
2680 return EXIT_SUCCESS;
2683 /* Expand the rest into (possibly) many strings each */
2684 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
2686 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2687 if (strcmp(argv_expanded[0], x->cmd) != 0)
2689 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
2690 debug_printf("exec with redirects only\n");
2691 setup_redirects(command, NULL);
2692 rcode = EXIT_SUCCESS;
2693 goto clean_up_and_ret1;
2695 debug_printf("builtin inline %s\n", argv_expanded[0]);
2696 /* XXX setup_redirects acts on file descriptors, not FILEs.
2697 * This is perfect for work that comes after exec().
2698 * Is it really safe for inline use? Experimentally,
2699 * things seem to work with glibc. */
2700 setup_redirects(command, squirrel);
2701 new_env = expand_assignments(argv, command->assignment_cnt);
2702 old_env = putenv_all_and_save_old(new_env);
2703 debug_printf_exec(": builtin '%s' '%s'...\n",
2704 x->cmd, argv_expanded[1]);
2705 rcode = x->function(argv_expanded) & 0xff;
2706 #if ENABLE_FEATURE_SH_STANDALONE
2709 restore_redirects(squirrel);
2710 free_strings_and_unsetenv(new_env, 1);
2711 putenv_all(old_env);
2712 free(old_env); /* not free_strings()! */
2714 free(argv_expanded);
2715 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2716 debug_printf_exec("run_pipe return %d\n", rcode);
2719 #if ENABLE_FEATURE_SH_STANDALONE
2720 i = find_applet_by_name(argv_expanded[0]);
2721 if (i >= 0 && APPLET_IS_NOFORK(i)) {
2722 setup_redirects(command, squirrel);
2723 save_nofork_data(&G.nofork_save);
2724 new_env = expand_assignments(argv, command->assignment_cnt);
2725 old_env = putenv_all_and_save_old(new_env);
2726 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
2727 argv_expanded[0], argv_expanded[1]);
2728 rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
2729 goto clean_up_and_ret;
2732 /* It is neither builtin nor applet. We must fork. */
2736 /* NB: argv_expanded may already be created, and that
2737 * might include `cmd` runs! Do not rerun it! We *must*
2738 * use argv_expanded if it's non-NULL */
2740 /* Going to fork a child per each pipe member */
2744 for (i = 0; i < pi->num_cmds; i++) {
2746 volatile nommu_save_t nommu_save;
2747 nommu_save.new_env = NULL;
2748 nommu_save.old_env = NULL;
2749 nommu_save.argv = NULL;
2751 command = &(pi->cmds[i]);
2752 if (command->argv) {
2753 debug_printf_exec(": pipe member '%s' '%s'...\n",
2754 command->argv[0], command->argv[1]);
2756 debug_printf_exec(": pipe member with no argv\n");
2759 /* pipes are inserted between pairs of commands */
2762 if ((i + 1) < pi->num_cmds)
2765 command->pid = BB_MMU ? fork() : vfork();
2766 if (!command->pid) { /* child */
2768 die_sleep = 0; /* let nofork's xfuncs die */
2770 /* Every child adds itself to new process group
2771 * with pgid == pid_of_first_child_in_pipe */
2772 if (G.run_list_level == 1 && G_interactive_fd) {
2775 if (pgrp < 0) /* true for 1st process only */
2777 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
2778 /* We do it in *every* child, not just first,
2780 tcsetpgrp(G_interactive_fd, pgrp);
2784 xmove_fd(nextin, 0);
2785 xmove_fd(pipefds[1], 1); /* write end */
2787 close(pipefds[0]); /* read end */
2788 /* Like bash, explicit redirects override pipes,
2789 * and the pipe fd is available for dup'ing. */
2790 setup_redirects(command, NULL);
2792 /* Restore default handlers just prior to exec */
2793 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
2795 /* Stores to nommu_save list of env vars putenv'ed
2796 * (NOMMU, on MMU we don't need that) */
2797 /* cast away volatility... */
2798 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
2799 /* pseudo_exec() does not return */
2803 /* Clean up after vforked child */
2804 free(nommu_save.argv);
2805 free_strings_and_unsetenv(nommu_save.new_env, 1);
2806 putenv_all(nommu_save.old_env);
2808 free(argv_expanded);
2809 argv_expanded = NULL;
2810 if (command->pid < 0) { /* [v]fork failed */
2811 /* Clearly indicate, was it fork or vfork */
2812 bb_perror_msg(BB_MMU ? "fork" : "vfork");
2816 /* Second and next children need to know pid of first one */
2818 pi->pgrp = command->pid;
2824 if ((i + 1) < pi->num_cmds)
2825 close(pipefds[1]); /* write end */
2826 /* Pass read (output) pipe end to next iteration */
2827 nextin = pipefds[0];
2830 if (!pi->alive_cmds) {
2831 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
2835 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
2839 #ifndef debug_print_tree
2840 static void debug_print_tree(struct pipe *pi, int lvl)
2842 static const char *const PIPE[] = {
2848 static const char *RES[] = {
2849 [RES_NONE ] = "NONE" ,
2852 [RES_THEN ] = "THEN" ,
2853 [RES_ELIF ] = "ELIF" ,
2854 [RES_ELSE ] = "ELSE" ,
2857 #if ENABLE_HUSH_LOOPS
2858 [RES_FOR ] = "FOR" ,
2859 [RES_WHILE] = "WHILE",
2860 [RES_UNTIL] = "UNTIL",
2862 [RES_DONE ] = "DONE" ,
2864 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2867 #if ENABLE_HUSH_CASE
2868 [RES_CASE ] = "CASE" ,
2869 [RES_MATCH] = "MATCH",
2870 [RES_CASEI] = "CASEI",
2871 [RES_ESAC ] = "ESAC" ,
2873 [RES_XXXX ] = "XXXX" ,
2874 [RES_SNTX ] = "SNTX" ,
2876 static const char *const GRPTYPE[] = {
2879 #if ENABLE_HUSH_FUNCTIONS
2888 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2889 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2891 while (prn < pi->num_cmds) {
2892 struct command *command = &pi->cmds[prn];
2893 char **argv = command->argv;
2895 fprintf(stderr, "%*s prog %d assignment_cnt:%d",
2897 command->assignment_cnt);
2898 if (command->group) {
2899 fprintf(stderr, " group %s: (argv=%p)\n",
2900 GRPTYPE[command->grp_type],
2902 debug_print_tree(command->group, lvl+1);
2906 if (argv) while (*argv) {
2907 fprintf(stderr, " '%s'", *argv);
2910 fprintf(stderr, "\n");
2919 /* NB: called by pseudo_exec, and therefore must not modify any
2920 * global data until exec/_exit (we can be a child after vfork!) */
2921 static int run_list(struct pipe *pi)
2923 #if ENABLE_HUSH_CASE
2924 char *case_word = NULL;
2926 #if ENABLE_HUSH_LOOPS
2927 struct pipe *loop_top = NULL;
2928 char *for_varname = NULL;
2929 char **for_lcur = NULL;
2930 char **for_list = NULL;
2932 smallint flag_skip = 1;
2933 smalluint rcode = 0; /* probably just for compiler */
2934 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
2935 smalluint cond_code = 0;
2937 enum { cond_code = 0, };
2939 /*enum reserved_style*/ smallint rword = RES_NONE;
2940 /*enum reserved_style*/ smallint skip_more_for_this_rword = RES_XXXX;
2942 debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
2944 #if ENABLE_HUSH_LOOPS
2945 /* Check syntax for "for" */
2946 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
2947 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
2949 /* current word is FOR or IN (BOLD in comments below) */
2950 if (cpipe->next == NULL) {
2951 syntax("malformed for");
2952 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
2955 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
2956 if (cpipe->next->res_word == RES_DO)
2958 /* next word is not "do". It must be "in" then ("FOR v in ...") */
2959 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
2960 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
2962 syntax("malformed for");
2963 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
2969 /* Past this point, all code paths should jump to ret: label
2970 * in order to return, no direct "return" statements please.
2971 * This helps to ensure that no memory is leaked. */
2973 ////TODO: ctrl-Z handling needs re-thinking and re-testing
2976 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
2977 * We are saving state before entering outermost list ("while...done")
2978 * so that ctrl-Z will correctly background _entire_ outermost list,
2979 * not just a part of it (like "sleep 1 | exit 2") */
2980 if (++G.run_list_level == 1 && G_interactive_fd) {
2981 if (sigsetjmp(G.toplevel_jb, 1)) {
2982 /* ctrl-Z forked and we are parent; or ctrl-C.
2983 * Sighandler has longjmped us here */
2984 signal(SIGINT, SIG_IGN);
2985 signal(SIGTSTP, SIG_IGN);
2986 /* Restore level (we can be coming from deep inside
2988 G.run_list_level = 1;
2989 #if ENABLE_FEATURE_SH_STANDALONE
2990 if (G.nofork_save.saved) { /* if save area is valid */
2991 debug_printf_jobs("exiting nofork early\n");
2992 restore_nofork_data(&G.nofork_save);
2995 //// if (G.ctrl_z_flag) {
2996 //// /* ctrl-Z has forked and stored pid of the child in pi->pid.
2997 //// * Remember this child as background job */
2998 //// insert_bg_job(pi);
3000 /* ctrl-C. We just stop doing whatever we were doing */
3003 USE_HUSH_LOOPS(loop_top = NULL;)
3004 USE_HUSH_LOOPS(G.depth_of_loop = 0;)
3008 //// /* ctrl-Z handler will store pid etc in pi */
3009 //// G.toplevel_list = pi;
3010 //// G.ctrl_z_flag = 0;
3011 ////#if ENABLE_FEATURE_SH_STANDALONE
3012 //// G.nofork_save.saved = 0; /* in case we will run a nofork later */
3014 //// signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
3015 //// signal(SIGINT, handler_ctrl_c);
3019 /* Go through list of pipes, (maybe) executing them. */
3020 for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
3024 IF_HAS_KEYWORDS(rword = pi->res_word;)
3025 IF_HAS_NO_KEYWORDS(rword = RES_NONE;)
3026 debug_printf_exec(": rword=%d cond_code=%d skip_more=%d\n",
3027 rword, cond_code, skip_more_for_this_rword);
3028 #if ENABLE_HUSH_LOOPS
3029 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
3030 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
3032 /* start of a loop: remember where loop starts */
3037 if (rword == skip_more_for_this_rword && flag_skip) {
3038 if (pi->followup == PIPE_SEQ)
3040 /* it is "<false> && CMD" or "<true> || CMD"
3041 * and we should not execute CMD */
3045 skip_more_for_this_rword = RES_XXXX;
3048 if (rword == RES_THEN) {
3049 /* "if <false> THEN cmd": skip cmd */
3053 if (rword == RES_ELSE || rword == RES_ELIF) {
3054 /* "if <true> then ... ELSE/ELIF cmd":
3055 * skip cmd and all following ones */
3060 #if ENABLE_HUSH_LOOPS
3061 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
3063 /* first loop through for */
3065 static const char encoded_dollar_at[] ALIGN1 = {
3066 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
3067 }; /* encoded representation of "$@" */
3068 static const char *const encoded_dollar_at_argv[] = {
3069 encoded_dollar_at, NULL
3070 }; /* argv list with one element: "$@" */
3073 vals = (char**)encoded_dollar_at_argv;
3074 if (pi->next->res_word == RES_IN) {
3075 /* if no variable values after "in" we skip "for" */
3076 if (!pi->next->cmds[0].argv)
3078 vals = pi->next->cmds[0].argv;
3079 } /* else: "for var; do..." -> assume "$@" list */
3080 /* create list of variable values */
3081 debug_print_strings("for_list made from", vals);
3082 for_list = expand_strvec_to_strvec(vals);
3083 for_lcur = for_list;
3084 debug_print_strings("for_list", for_list);
3085 for_varname = pi->cmds[0].argv[0];
3086 pi->cmds[0].argv[0] = NULL;
3088 free(pi->cmds[0].argv[0]);
3090 /* "for" loop is over, clean up */
3094 pi->cmds[0].argv[0] = for_varname;
3097 /* insert next value from for_lcur */
3098 //TODO: does it need escaping?
3099 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
3100 pi->cmds[0].assignment_cnt = 1;
3102 if (rword == RES_IN) {
3103 continue; /* "for v IN list;..." - "in" has no cmds anyway */
3105 if (rword == RES_DONE) {
3106 continue; /* "done" has no cmds too */
3109 #if ENABLE_HUSH_CASE
3110 if (rword == RES_CASE) {
3111 case_word = expand_strvec_to_string(pi->cmds->argv);
3114 if (rword == RES_MATCH) {
3117 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
3119 /* all prev words didn't match, does this one match? */
3120 argv = pi->cmds->argv;
3122 char *pattern = expand_string_to_string(*argv);
3123 /* TODO: which FNM_xxx flags to use? */
3124 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
3126 if (cond_code == 0) { /* match! we will execute this branch */
3127 free(case_word); /* make future "word)" stop */
3135 if (rword == RES_CASEI) { /* inside of a case branch */
3137 continue; /* not matched yet, skip this pipe */
3140 /* Just pressing <enter> in shell should check for jobs.
3141 * OTOH, in non-interactive shell this is useless
3142 * and only leads to extra job checks */
3143 if (pi->num_cmds == 0) {
3144 if (G_interactive_fd)
3145 goto check_jobs_and_continue;
3149 /* After analyzing all keywords and conditions, we decided
3150 * to execute this pipe. NB: have to do checkjobs(NULL)
3151 * after run_pipe() to collect any background children,
3152 * even if list execution is to be stopped. */
3153 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
3156 #if ENABLE_HUSH_LOOPS
3157 G.flag_break_continue = 0;
3159 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
3161 /* we only ran a builtin: rcode is already known
3162 * and we don't need to wait for anything. */
3163 check_and_run_traps(0);
3164 #if ENABLE_HUSH_LOOPS
3165 /* was it "break" or "continue"? */
3166 if (G.flag_break_continue) {
3167 smallint fbc = G.flag_break_continue;
3168 /* we might fall into outer *loop*,
3169 * don't want to break it too */
3171 G.depth_break_continue--;
3172 if (G.depth_break_continue == 0)
3173 G.flag_break_continue = 0;
3174 /* else: e.g. "continue 2" should *break* once, *then* continue */
3175 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
3176 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
3177 goto check_jobs_and_break;
3178 /* "continue": simulate end of loop */
3183 } else if (pi->followup == PIPE_BG) {
3184 /* what does bash do with attempts to background builtins? */
3185 /* even bash 3.2 doesn't do that well with nested bg:
3186 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
3187 * I'm NOT treating inner &'s as jobs */
3188 check_and_run_traps(0);
3190 if (G.run_list_level == 1)
3193 rcode = 0; /* EXIT_SUCCESS */
3196 if (G.run_list_level == 1 && G_interactive_fd) {
3197 /* waits for completion, then fg's main shell */
3198 rcode = checkjobs_and_fg_shell(pi);
3199 check_and_run_traps(0);
3200 debug_printf_exec(": checkjobs_and_fg_shell returned %d\n", rcode);
3203 { /* this one just waits for completion */
3204 rcode = checkjobs(pi);
3205 check_and_run_traps(0);
3206 debug_printf_exec(": checkjobs returned %d\n", rcode);
3210 debug_printf_exec(": setting last_return_code=%d\n", rcode);
3211 G.last_return_code = rcode;
3213 /* Analyze how result affects subsequent commands */
3215 if (rword == RES_IF || rword == RES_ELIF)
3218 #if ENABLE_HUSH_LOOPS
3219 if (rword == RES_WHILE) {
3221 rcode = 0; /* "while false; do...done" - exitcode 0 */
3222 goto check_jobs_and_break;
3225 if (rword == RES_UNTIL) {
3227 check_jobs_and_break:
3233 if ((rcode == 0 && pi->followup == PIPE_OR)
3234 || (rcode != 0 && pi->followup == PIPE_AND)
3236 skip_more_for_this_rword = rword;
3239 check_jobs_and_continue:
3244 //// if (G.ctrl_z_flag) {
3245 //// /* ctrl-Z forked somewhere in the past, we are the child,
3246 //// * and now we completed running the list. Exit. */
3252 //// if (!G.run_list_level && G_interactive_fd) {
3253 //// signal(SIGTSTP, SIG_IGN);
3254 //// signal(SIGINT, SIG_IGN);
3257 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
3258 #if ENABLE_HUSH_LOOPS
3263 #if ENABLE_HUSH_CASE
3269 /* Select which version we will use */
3270 static int run_and_free_list(struct pipe *pi)
3273 debug_printf_exec("run_and_free_list entered\n");
3275 debug_printf_exec(": run_list with %d members\n", pi->num_cmds);
3276 rcode = run_list(pi);
3278 /* free_pipe_list has the side effect of clearing memory.
3279 * In the long run that function can be merged with run_list,
3280 * but doing that now would hobble the debugging effort. */
3281 free_pipe_list(pi, /* indent: */ 0);
3282 debug_printf_exec("run_and_free_list return %d\n", rcode);
3287 /* Peek ahead in the in_str to find out if we have a "&n" construct,
3288 * as in "2>&1", that represents duplicating a file descriptor.
3289 * Return either -2 (syntax error), -1 (no &), or the number found.
3291 static int redirect_dup_num(struct in_str *input)
3293 int ch, d = 0, ok = 0;
3295 if (ch != '&') return -1;
3297 i_getch(input); /* get the & */
3301 return -3; /* "-" represents "close me" */
3303 while (isdigit(ch)) {
3304 d = d*10 + (ch-'0');
3311 bb_error_msg("ambiguous redirect");
3315 /* The src parameter allows us to peek forward to a possible &n syntax
3316 * for file descriptor duplication, e.g., "2>&1".
3317 * Return code is 0 normally, 1 if a syntax error is detected in src.
3318 * Resource errors (in xmalloc) cause the process to exit */
3319 static int setup_redirect(struct parse_context *ctx,
3322 struct in_str *input)
3324 struct command *command = ctx->command;
3325 struct redir_struct *redir;
3326 struct redir_struct **redirp;
3329 /* Check for a '2>&1' type redirect */
3330 dup_num = redirect_dup_num(input);
3332 return 1; /* syntax error */
3334 /* Create a new redir_struct and drop it onto the end of the linked list */
3335 redirp = &command->redirects;
3336 while ((redir = *redirp) != NULL) {
3337 redirp = &(redir->next);
3339 *redirp = redir = xzalloc(sizeof(*redir));
3340 /* redir->next = NULL; */
3341 /* redir->rd_filename = NULL; */
3342 redir->rd_type = style;
3343 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
3345 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
3347 redir->dup = dup_num;
3348 if (dup_num != -1) {
3349 /* Erik had a check here that the file descriptor in question
3350 * is legit; I postpone that to "run time"
3351 * A "-" representation of "close me" shows up as a -3 here */
3352 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
3354 /* We do _not_ try to open the file that src points to,
3355 * since we need to return and let src be expanded first.
3356 * Set ctx->pending_redirect, so we know what to do at the
3357 * end of the next parsed word. */
3358 ctx->pending_redirect = redir;
3364 static struct pipe *new_pipe(void)
3367 pi = xzalloc(sizeof(struct pipe));
3368 /*pi->followup = 0; - deliberately invalid value */
3369 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3373 /* Command (member of a pipe) is complete. The only possible error here
3374 * is out of memory, in which case xmalloc exits. */
3375 static int done_command(struct parse_context *ctx)
3377 /* The command is really already in the pipe structure, so
3378 * advance the pipe counter and make a new, null command. */
3379 struct pipe *pi = ctx->pipe;
3380 struct command *command = ctx->command;
3383 if (command->group == NULL
3384 && command->argv == NULL
3385 && command->redirects == NULL
3387 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3388 return pi->num_cmds;
3391 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3393 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3396 /* Only real trickiness here is that the uncommitted
3397 * command structure is not counted in pi->num_cmds. */
3398 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3399 command = &pi->cmds[pi->num_cmds];
3400 memset(command, 0, sizeof(*command));
3402 ctx->command = command;
3403 /* but ctx->pipe and ctx->list_head remain unchanged */
3405 return pi->num_cmds; /* used only for 0/nonzero check */
3408 static void done_pipe(struct parse_context *ctx, pipe_style type)
3412 debug_printf_parse("done_pipe entered, followup %d\n", type);
3413 /* Close previous command */
3414 not_null = done_command(ctx);
3415 ctx->pipe->followup = type;
3416 IF_HAS_KEYWORDS(ctx->pipe->pi_inverted = ctx->ctx_inverted;)
3417 IF_HAS_KEYWORDS(ctx->ctx_inverted = 0;)
3418 IF_HAS_KEYWORDS(ctx->pipe->res_word = ctx->ctx_res_w;)
3420 /* Without this check, even just <enter> on command line generates
3421 * tree of three NOPs (!). Which is harmless but annoying.
3422 * IOW: it is safe to do it unconditionally.
3423 * RES_NONE case is for "for a in; do ..." (empty IN set)
3424 * to work, possibly other cases too. */
3425 if (not_null IF_HAS_KEYWORDS(|| ctx->ctx_res_w != RES_NONE)) {
3427 debug_printf_parse("done_pipe: adding new pipe: "
3428 "not_null:%d ctx->ctx_res_w:%d\n",
3429 not_null, ctx->ctx_res_w);
3431 ctx->pipe->next = new_p;
3433 /* RES_THEN, RES_DO etc are "sticky" -
3434 * they remain set for commands inside if/while.
3435 * This is used to control execution.
3436 * RES_FOR and RES_IN are NOT sticky (needed to support
3437 * cases where variable or value happens to match a keyword):
3439 #if ENABLE_HUSH_LOOPS
3440 if (ctx->ctx_res_w == RES_FOR
3441 || ctx->ctx_res_w == RES_IN)
3442 ctx->ctx_res_w = RES_NONE;
3444 #if ENABLE_HUSH_CASE
3445 if (ctx->ctx_res_w == RES_MATCH)
3446 ctx->ctx_res_w = RES_CASEI;
3448 ctx->command = NULL; /* trick done_command below */
3449 /* Create the memory for command, roughly:
3450 * ctx->pipe->cmds = new struct command;
3451 * ctx->command = &ctx->pipe->cmds[0];
3455 debug_printf_parse("done_pipe return\n");
3458 static void initialize_context(struct parse_context *ctx)
3460 memset(ctx, 0, sizeof(*ctx));
3461 ctx->pipe = ctx->list_head = new_pipe();
3462 /* Create the memory for command, roughly:
3463 * ctx->pipe->cmds = new struct command;
3464 * ctx->command = &ctx->pipe->cmds[0];
3470 /* If a reserved word is found and processed, parse context is modified
3471 * and 1 is returned.
3474 struct reserved_combo {
3477 unsigned char assignment_flag;
3481 FLAG_END = (1 << RES_NONE ),
3483 FLAG_IF = (1 << RES_IF ),
3484 FLAG_THEN = (1 << RES_THEN ),
3485 FLAG_ELIF = (1 << RES_ELIF ),
3486 FLAG_ELSE = (1 << RES_ELSE ),
3487 FLAG_FI = (1 << RES_FI ),
3489 #if ENABLE_HUSH_LOOPS
3490 FLAG_FOR = (1 << RES_FOR ),
3491 FLAG_WHILE = (1 << RES_WHILE),
3492 FLAG_UNTIL = (1 << RES_UNTIL),
3493 FLAG_DO = (1 << RES_DO ),
3494 FLAG_DONE = (1 << RES_DONE ),
3495 FLAG_IN = (1 << RES_IN ),
3497 #if ENABLE_HUSH_CASE
3498 FLAG_MATCH = (1 << RES_MATCH),
3499 FLAG_ESAC = (1 << RES_ESAC ),
3501 FLAG_START = (1 << RES_XXXX ),
3504 static const struct reserved_combo* match_reserved_word(o_string *word)
3506 /* Mostly a list of accepted follow-up reserved words.
3507 * FLAG_END means we are done with the sequence, and are ready
3508 * to turn the compound list into a command.
3509 * FLAG_START means the word must start a new compound list.
3511 static const struct reserved_combo reserved_list[] = {
3513 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3514 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
3515 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3516 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
3517 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
3518 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3520 #if ENABLE_HUSH_LOOPS
3521 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3522 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3523 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3524 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3525 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
3526 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3528 #if ENABLE_HUSH_CASE
3529 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3530 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3533 const struct reserved_combo *r;
3535 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3536 if (strcmp(word->data, r->literal) == 0)
3541 static int reserved_word(o_string *word, struct parse_context *ctx)
3543 #if ENABLE_HUSH_CASE
3544 static const struct reserved_combo reserved_match = {
3545 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3548 const struct reserved_combo *r;
3550 r = match_reserved_word(word);
3554 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3555 #if ENABLE_HUSH_CASE
3556 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
3557 /* "case word IN ..." - IN part starts first match part */
3558 r = &reserved_match;
3561 if (r->flag == 0) { /* '!' */
3562 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3563 syntax("! ! command");
3564 IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
3566 ctx->ctx_inverted = 1;
3569 if (r->flag & FLAG_START) {
3570 struct parse_context *old;
3571 old = xmalloc(sizeof(*old));
3572 debug_printf_parse("push stack %p\n", old);
3573 *old = *ctx; /* physical copy */
3574 initialize_context(ctx);
3576 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3578 ctx->ctx_res_w = RES_SNTX;
3581 ctx->ctx_res_w = r->res;
3582 ctx->old_flag = r->flag;
3583 if (ctx->old_flag & FLAG_END) {
3584 struct parse_context *old;
3585 done_pipe(ctx, PIPE_SEQ);
3586 debug_printf_parse("pop stack %p\n", ctx->stack);
3588 old->command->group = ctx->list_head;
3589 old->command->grp_type = GRP_NORMAL;
3590 *ctx = *old; /* physical copy */
3593 word->o_assignment = r->assignment_flag;
3598 /* Word is complete, look at it and update parsing context.
3599 * Normal return is 0. Syntax errors return 1.
3600 * Note: on return, word is reset, but not o_free'd!
3602 static int done_word(o_string *word, struct parse_context *ctx)
3604 struct command *command = ctx->command;
3606 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3607 if (word->length == 0 && word->nonnull == 0) {
3608 debug_printf_parse("done_word return 0: true null, ignored\n");
3611 /* If this word wasn't an assignment, next ones definitely
3612 * can't be assignments. Even if they look like ones. */
3613 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3614 && word->o_assignment != WORD_IS_KEYWORD
3616 word->o_assignment = NOT_ASSIGNMENT;
3618 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3619 command->assignment_cnt++;
3620 word->o_assignment = MAYBE_ASSIGNMENT;
3623 if (ctx->pending_redirect) {
3624 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3625 * only if run as "bash", not "sh" */
3626 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3627 word->o_assignment = NOT_ASSIGNMENT;
3628 debug_printf("word stored in rd_filename: '%s'\n", word->data);
3630 /* "{ echo foo; } echo bar" - bad */
3631 /* NB: bash allows e.g.:
3632 * if true; then { echo foo; } fi
3633 * while if false; then false; fi do break; done
3635 if (command->group) {
3637 debug_printf_parse("done_word return 1: syntax error, "
3638 "groups and arglists don't mix\n");
3642 #if ENABLE_HUSH_CASE
3643 if (ctx->ctx_dsemicolon
3644 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3646 /* already done when ctx_dsemicolon was set to 1: */
3647 /* ctx->ctx_res_w = RES_MATCH; */
3648 ctx->ctx_dsemicolon = 0;
3651 if (!command->argv /* if it's the first word... */
3652 #if ENABLE_HUSH_LOOPS
3653 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3654 && ctx->ctx_res_w != RES_IN
3657 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
3658 if (reserved_word(word, ctx)) {
3660 debug_printf_parse("done_word return %d\n",
3661 (ctx->ctx_res_w == RES_SNTX));
3662 return (ctx->ctx_res_w == RES_SNTX);
3666 if (word->nonnull /* word had "xx" or 'xx' at least as part of it. */
3667 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3668 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3669 /* (otherwise it's known to be not empty and is already safe) */
3671 /* exclude "$@" - it can expand to no word despite "" */
3672 char *p = word->data;
3673 while (p[0] == SPECIAL_VAR_SYMBOL
3674 && (p[1] & 0x7f) == '@'
3675 && p[2] == SPECIAL_VAR_SYMBOL
3679 if (p == word->data || p[0] != '\0') {
3680 /* saw no "$@", or not only "$@" but some
3681 * real text is there too */
3682 /* insert "empty variable" reference, this makes
3683 * e.g. "", $empty"" etc to not disappear */
3684 o_addchr(word, SPECIAL_VAR_SYMBOL);
3685 o_addchr(word, SPECIAL_VAR_SYMBOL);
3688 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3689 debug_print_strings("word appended to argv", command->argv);
3693 ctx->pending_redirect = NULL;
3695 #if ENABLE_HUSH_LOOPS
3696 /* Force FOR to have just one word (variable name) */
3697 /* NB: basically, this makes hush see "for v in ..." syntax as if
3698 * as it is "for v; in ...". FOR and IN become two pipe structs
3700 if (ctx->ctx_res_w == RES_FOR) {
3701 //TODO: check that command->argv[0] is a valid variable name!
3702 done_pipe(ctx, PIPE_SEQ);
3705 #if ENABLE_HUSH_CASE
3706 /* Force CASE to have just one word */
3707 if (ctx->ctx_res_w == RES_CASE) {
3708 done_pipe(ctx, PIPE_SEQ);
3711 debug_printf_parse("done_word return 0\n");
3715 /* If a redirect is immediately preceded by a number, that number is
3716 * supposed to tell which file descriptor to redirect. This routine
3717 * looks for such preceding numbers. In an ideal world this routine
3718 * needs to handle all the following classes of redirects...
3719 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3720 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3721 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3722 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3723 * A -1 output from this program means no valid number was found, so the
3724 * caller should use the appropriate default for this redirection.
3726 static int redirect_opt_num(o_string *o)
3732 for (num = 0; num < o->length; num++) {
3733 if (!isdigit(o->data[num])) {
3737 num = atoi(o->data);
3742 static struct pipe *parse_stream(struct in_str *input, int end_trigger);
3743 static void parse_and_run_string(const char *s);
3745 #if ENABLE_HUSH_TICK
3746 static FILE *generate_stream_from_string(const char *s)
3749 int pid, channel[2];
3752 pid = BB_MMU ? fork() : vfork();
3754 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
3756 if (pid == 0) { /* child */
3757 /* Process substitution is not considered to be usual
3758 * 'command execution'.
3759 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
3766 if (ENABLE_HUSH_JOB)
3767 die_sleep = 0; /* let nofork's xfuncs die */
3768 close(channel[0]); /* NB: close _first_, then move fd! */
3769 xmove_fd(channel[1], 1);
3770 /* Prevent it from trying to handle ctrl-z etc */
3771 USE_HUSH_JOB(G.run_list_level = 1;)
3773 parse_and_run_string(s);
3774 _exit(G.last_return_code);
3776 /* We re-execute after vfork on NOMMU. This makes this script safe:
3777 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >TESTFILE
3778 * huge=`cat TESTFILE` # was blocking here forever
3781 //TODO: pass non-exported variables, traps, and functions
3782 execl(bb_busybox_exec_path, "hush", "-c", s, NULL);
3789 pf = fdopen(channel[0], "r");
3793 /* Return code is exit status of the process that is run. */
3794 static int process_command_subs(o_string *dest, const char *s)
3797 struct in_str pipe_str;
3800 pf = generate_stream_from_string(s);
3803 close_on_exec_on(fileno(pf));
3805 /* Now send results of command back into original context */
3806 setup_file_in_str(&pipe_str, pf);
3808 while ((ch = i_getch(&pipe_str)) != EOF) {
3814 o_addchr(dest, '\n');
3817 o_addQchr(dest, ch);
3820 debug_printf("done reading from pipe, pclose()ing\n");
3821 /* Note: we got EOF, and we just close the read end of the pipe.
3822 * We do not wait for the `cmd` child to terminate. bash and ash do.
3824 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
3825 * `false`; echo $? - bash outputs "1"
3828 debug_printf("closed FILE from child. return 0\n");
3833 static int parse_group(o_string *dest, struct parse_context *ctx,
3834 struct in_str *input, int ch)
3836 /* dest contains characters seen prior to ( or {.
3837 * Typically it's empty, but for function defs,
3838 * it contains function name (without '()'). */
3839 struct pipe *pipe_list;
3841 struct command *command = ctx->command;
3843 debug_printf_parse("parse_group entered\n");
3844 #if ENABLE_HUSH_FUNCTIONS
3845 if (ch == 'F') { /* function definition? */
3846 bb_error_msg("aha '%s' is a function, parsing it...", dest->data);
3847 //command->fname = dest->data;
3848 command->grp_type = GRP_FUNCTION;
3849 //TODO: review every o_reset() location... do they handle all o_string fields correctly?
3850 memset(dest, 0, sizeof(*dest));
3853 if (command->argv /* word [word](... */
3854 || dest->length /* word(... */
3855 || dest->nonnull /* ""(... */
3858 debug_printf_parse("parse_group return 1: "
3859 "syntax error, groups and arglists don't mix\n");
3865 command->grp_type = GRP_SUBSHELL;
3867 pipe_list = parse_stream(input, endch);
3868 /* empty ()/{} or parse error? */
3869 if (!pipe_list || pipe_list == ERR_PTR) {
3871 debug_printf_parse("parse_group return 1: "
3872 "parse_stream returned %p\n", pipe_list);
3875 command->group = pipe_list;
3876 debug_printf_parse("parse_group return 0\n");
3878 /* command remains "open", available for possible redirects */
3881 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
3882 /* Subroutines for copying $(...) and `...` things */
3883 static void add_till_backquote(o_string *dest, struct in_str *input);
3885 static void add_till_single_quote(o_string *dest, struct in_str *input)
3888 int ch = i_getch(input);
3896 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3897 static void add_till_double_quote(o_string *dest, struct in_str *input)
3900 int ch = i_getch(input);
3903 if (ch == '\\') { /* \x. Copy both chars. */
3905 ch = i_getch(input);
3911 add_till_backquote(dest, input);
3915 //if (ch == '$') ...
3918 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3920 * "Within the backquoted style of command substitution, backslash
3921 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3922 * The search for the matching backquote shall be satisfied by the first
3923 * backquote found without a preceding backslash; during this search,
3924 * if a non-escaped backquote is encountered within a shell comment,
3925 * a here-document, an embedded command substitution of the $(command)
3926 * form, or a quoted string, undefined results occur. A single-quoted
3927 * or double-quoted string that begins, but does not end, within the
3928 * "`...`" sequence produces undefined results."
3930 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3932 static void add_till_backquote(o_string *dest, struct in_str *input)
3935 int ch = i_getch(input);
3938 if (ch == '\\') { /* \x. Copy both chars unless it is \` */
3939 int ch2 = i_getch(input);
3940 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
3949 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3950 * quoting and nested ()s.
3951 * "With the $(command) style of command substitution, all characters
3952 * following the open parenthesis to the matching closing parenthesis
3953 * constitute the command. Any valid shell script can be used for command,
3954 * except a script consisting solely of redirections which produces
3955 * unspecified results."
3957 * echo $(echo '(TEST)' BEST) (TEST) BEST
3958 * echo $(echo 'TEST)' BEST) TEST) BEST
3959 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3961 static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
3965 int ch = i_getch(input);
3974 if (i_peek(input) == ')') {
3982 add_till_single_quote(dest, input);
3987 add_till_double_quote(dest, input);
3991 if (ch == '\\') { /* \x. Copy verbatim. Important for \(, \) */
3992 ch = i_getch(input);
4000 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
4002 /* Return code: 0 for OK, 1 for syntax error */
4003 static int handle_dollar(o_string *dest, struct in_str *input)
4006 int ch = i_peek(input); /* first character after the $ */
4007 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
4009 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
4013 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4015 debug_printf_parse(": '%c'\n", ch);
4016 o_addchr(dest, ch | quote_mask);
4019 if (!isalnum(ch) && ch != '_')
4023 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4024 } else if (isdigit(ch)) {
4027 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4028 debug_printf_parse(": '%c'\n", ch);
4029 o_addchr(dest, ch | quote_mask);
4030 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4031 } else switch (ch) {
4033 case '!': /* last bg pid */
4034 case '?': /* last exit code */
4035 case '#': /* number of args */
4036 case '*': /* args */
4037 case '@': /* args */
4038 goto make_one_char_var;
4040 bool first_char, all_digits;
4042 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4044 /* XXX maybe someone will try to escape the '}' */
4049 ch = i_getch(input);
4055 /* ${#var}: length of var contents */
4057 else if (isdigit(ch)) {
4064 && ( (all_digits && !isdigit(ch))
4065 || (!all_digits && !isalnum(ch) && ch != '_')
4068 /* handle parameter expansions
4069 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4074 case ':': /* null modifier */
4075 if (expansion == 0) {
4076 debug_printf_parse(": null modifier\n");
4081 #if 0 /* not implemented yet :( */
4082 case '#': /* remove prefix */
4083 case '%': /* remove suffix */
4084 if (expansion == 0) {
4085 debug_printf_parse(": remove suffix/prefix\n");
4091 case '-': /* default value */
4092 case '=': /* assign default */
4093 case '+': /* alternative */
4094 case '?': /* error indicate */
4095 debug_printf_parse(": parameter expansion\n");
4100 syntax("unterminated ${name}");
4101 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
4106 debug_printf_parse(": '%c'\n", ch);
4107 o_addchr(dest, ch | quote_mask);
4111 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4116 #if ENABLE_SH_MATH_SUPPORT
4117 if (i_peek(input) == '(') {
4119 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4120 o_addchr(dest, /*quote_mask |*/ '+');
4121 add_till_closing_paren(dest, input, true);
4122 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4126 #if ENABLE_HUSH_TICK
4127 //int pos = dest->length;
4128 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4129 o_addchr(dest, quote_mask | '`');
4130 add_till_closing_paren(dest, input, false);
4131 //debug_printf_subst("SUBST RES2 '%s'\n", dest->data + pos);
4132 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4139 if (isalnum(ch)) { /* it's $_name or $_123 */
4145 /* $_ Shell or shell script name; or last cmd name */
4146 /* $- Option flags set by set builtin or shell options (-i etc) */
4148 o_addQchr(dest, '$');
4150 debug_printf_parse("handle_dollar return 0\n");
4154 static int parse_stream_dquoted(o_string *dest,
4155 struct in_str *input, int dquote_end)
4161 ch = i_getch(input);
4162 if (ch == dquote_end) { /* may be only '"' or EOF */
4164 if (dest->o_assignment == NOT_ASSIGNMENT)
4165 dest->o_escape ^= 1;
4166 debug_printf_parse("parse_stream_dquoted return 0\n");
4170 syntax("unterminated \"");
4171 debug_printf_parse("parse_stream_dquoted return 1: unterminated \"\n");
4176 next = i_peek(input);
4178 debug_printf_parse(": ch=%c (%d) m=%d escape=%d\n",
4179 ch, ch, m, dest->o_escape);
4183 debug_printf_parse("parse_stream_dquoted return 1: \\<eof>\n");
4187 * "The backslash retains its special meaning [in "..."]
4188 * only when followed by one of the following characters:
4189 * $, `, ", \, or <newline>. A double quote may be quoted
4190 * within double quotes by preceding it with a backslash.
4191 * If enabled, history expansion will be performed unless
4192 * an ! appearing in double quotes is escaped using
4193 * a backslash. The backslash preceding the ! is not removed."
4195 if (strchr("$`\"\\", next) != NULL) {
4196 o_addqchr(dest, i_getch(input));
4198 o_addqchr(dest, '\\');
4203 if (handle_dollar(dest, input) != 0) {
4204 debug_printf_parse("parse_stream_dquoted return 1: "
4205 "handle_dollar returned non-0\n");
4210 #if ENABLE_HUSH_TICK
4212 //int pos = dest->length;
4213 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4214 o_addchr(dest, 0x80 | '`');
4215 add_till_backquote(dest, input);
4216 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4217 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4221 o_addQchr(dest, ch);
4223 && (dest->o_assignment == MAYBE_ASSIGNMENT
4224 || dest->o_assignment == WORD_IS_KEYWORD)
4225 && is_assignment(dest->data)
4227 dest->o_assignment = DEFINITELY_ASSIGNMENT;
4233 * Scan input until EOF or end_trigger char.
4234 * Return a list of pipes to execute, or NULL on EOF
4235 * or if end_trigger character is met.
4236 * On syntax error, exit is shell is not interactive,
4237 * reset parsing machinery and start parsing anew,
4238 * or return ERR_PTR.
4240 static struct pipe *parse_stream(struct in_str *input, int end_trigger)
4242 struct parse_context ctx;
4243 o_string dest = NULL_O_STRING;
4248 redir_type redir_style;
4250 /* Double-quote state is handled in the state variable is_in_dquote.
4251 * A single-quote triggers a bypass of the main loop until its mate is
4252 * found. When recursing, quote state is passed in via dest->o_escape.
4254 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4255 end_trigger ? : 'X');
4257 G.ifs = get_local_var_value("IFS");
4262 #if ENABLE_HUSH_INTERACTIVE
4263 input->promptmode = 0; /* PS1 */
4265 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
4266 initialize_context(&ctx);
4270 const char *is_special;
4273 if (parse_stream_dquoted(&dest, input, '"')) {
4276 /* We reached closing '"' */
4280 ch = i_getch(input);
4281 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4282 ch, ch, dest.o_escape);
4285 if (done_word(&dest, &ctx)) {
4289 done_pipe(&ctx, PIPE_SEQ);
4290 /* If we got nothing... */
4292 if (pi->num_cmds == 0
4293 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4295 free_pipe_list(pi, 0);
4298 debug_printf_parse("parse_stream return %p\n", pi);
4302 next = i_peek(input);
4305 is_ifs = strchr(G.ifs, ch);
4306 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
4307 "\\$\"" USE_HUSH_TICK("`") /* always special */
4310 if (!is_special && !is_ifs) { /* ordinary char */
4311 o_addQchr(&dest, ch);
4312 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4313 || dest.o_assignment == WORD_IS_KEYWORD)
4315 && is_assignment(dest.data)
4317 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4323 if (done_word(&dest, &ctx)) {
4327 #if ENABLE_HUSH_CASE
4328 /* "case ... in <newline> word) ..." -
4329 * newlines are ignored (but ';' wouldn't be) */
4330 if (ctx.command->argv == NULL
4331 && ctx.ctx_res_w == RES_MATCH
4336 /* Treat newline as a command separator. */
4337 done_pipe(&ctx, PIPE_SEQ);
4338 dest.o_assignment = MAYBE_ASSIGNMENT;
4340 /* note: if (is_ifs) continue;
4341 * will still trigger for us */
4344 if (end_trigger && end_trigger == ch) {
4345 //TODO: disallow "{ cmd }" without semicolon
4346 if (done_word(&dest, &ctx)) {
4349 done_pipe(&ctx, PIPE_SEQ);
4350 dest.o_assignment = MAYBE_ASSIGNMENT;
4351 /* Do we sit outside of any if's, loops or case's? */
4353 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4355 debug_printf_parse("parse_stream return %p: "
4356 "end_trigger char found\n",
4359 return ctx.list_head;
4365 if (dest.o_assignment == MAYBE_ASSIGNMENT) {
4366 /* ch is a special char and thus this word
4367 * cannot be an assignment */
4368 dest.o_assignment = NOT_ASSIGNMENT;
4373 if (dest.length == 0) {
4376 if (ch == EOF || ch == '\n')
4381 o_addQchr(&dest, ch);
4389 o_addchr(&dest, '\\');
4390 o_addchr(&dest, i_getch(input));
4393 if (handle_dollar(&dest, input) != 0) {
4394 debug_printf_parse("parse_stream parse error: "
4395 "handle_dollar returned non-0\n");
4402 ch = i_getch(input);
4404 syntax("unterminated '");
4409 if (dest.o_assignment == NOT_ASSIGNMENT)
4410 o_addqchr(&dest, ch);
4412 o_addchr(&dest, ch);
4417 is_in_dquote ^= 1; /* invert */
4418 if (dest.o_assignment == NOT_ASSIGNMENT)
4421 #if ENABLE_HUSH_TICK
4423 //int pos = dest.length;
4424 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4425 o_addchr(&dest, '`');
4426 add_till_backquote(&dest, input);
4427 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4428 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4433 redir_fd = redirect_opt_num(&dest);
4434 if (done_word(&dest, &ctx)) {
4437 redir_style = REDIRECT_OVERWRITE;
4439 redir_style = REDIRECT_APPEND;
4443 else if (next == '(') {
4444 syntax(">(process) not supported");
4448 setup_redirect(&ctx, redir_fd, redir_style, input);
4451 redir_fd = redirect_opt_num(&dest);
4452 if (done_word(&dest, &ctx)) {
4455 redir_style = REDIRECT_INPUT;
4457 redir_style = REDIRECT_HEREIS;
4459 } else if (next == '>') {
4460 redir_style = REDIRECT_IO;
4464 else if (next == '(') {
4465 syntax("<(process) not supported");
4469 setup_redirect(&ctx, redir_fd, redir_style, input);
4472 #if ENABLE_HUSH_CASE
4475 if (done_word(&dest, &ctx)) {
4478 done_pipe(&ctx, PIPE_SEQ);
4479 #if ENABLE_HUSH_CASE
4480 /* Eat multiple semicolons, detect
4481 * whether it means something special */
4487 if (ctx.ctx_res_w == RES_CASEI) {
4488 ctx.ctx_dsemicolon = 1;
4489 ctx.ctx_res_w = RES_MATCH;
4495 /* We just finished a cmd. New one may start
4496 * with an assignment */
4497 dest.o_assignment = MAYBE_ASSIGNMENT;
4500 if (done_word(&dest, &ctx)) {
4505 done_pipe(&ctx, PIPE_AND);
4507 done_pipe(&ctx, PIPE_BG);
4511 if (done_word(&dest, &ctx)) {
4514 #if ENABLE_HUSH_CASE
4515 if (ctx.ctx_res_w == RES_MATCH)
4516 break; /* we are in case's "word | word)" */
4518 if (next == '|') { /* || */
4520 done_pipe(&ctx, PIPE_OR);
4522 /* we could pick up a file descriptor choice here
4523 * with redirect_opt_num(), but bash doesn't do it.
4524 * "echo foo 2| cat" yields "foo 2". */
4529 #if ENABLE_HUSH_CASE
4530 /* "case... in [(]word)..." - skip '(' */
4531 if (ctx.ctx_res_w == RES_MATCH
4532 && ctx.command->argv == NULL /* not (word|(... */
4533 && dest.length == 0 /* not word(... */
4534 && dest.nonnull == 0 /* not ""(... */
4539 #if ENABLE_HUSH_FUNCTIONS
4540 if (dest.length != 0 /* not just () but word() */
4541 && dest.nonnull == 0 /* not a"b"c() */
4542 && ctx.command->argv == NULL /* it's the first word */
4543 //TODO: "func ( ) {...}" - note spaces - is valid format too in bash
4544 && i_peek(input) == ')'
4545 && !match_reserved_word(&dest)
4547 bb_error_msg("seems like a function definition");
4550 //TODO: do it properly.
4551 ch = i_getch(input);
4552 } while (ch == ' ' || ch == '\n');
4554 syntax("was expecting {");
4557 ch = 'F'; /* magic value */
4561 if (parse_group(&dest, &ctx, input, ch) != 0) {
4566 #if ENABLE_HUSH_CASE
4567 if (ctx.ctx_res_w == RES_MATCH)
4571 /* proper use of this character is caught by end_trigger:
4572 * if we see {, we call parse_group(..., end_trigger='}')
4573 * and it will match } earlier (not here). */
4574 syntax("unexpected } or )");
4578 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4584 struct parse_context *pctx;
4585 IF_HAS_KEYWORDS(struct parse_context *p2;)
4587 /* Clean up allocated tree.
4588 * Samples for finding leaks on syntax error recovery path.
4589 * Run them from interactive shell, watch pmap `pidof hush`.
4590 * while if false; then false; fi do break; done
4592 * while if false; then false; fi; do break; fi
4596 /* Update pipe/command counts,
4597 * otherwise freeing may miss some */
4598 done_pipe(pctx, PIPE_SEQ);
4599 debug_printf_clean("freeing list %p from ctx %p\n",
4600 pctx->list_head, pctx);
4601 debug_print_tree(pctx->list_head, 0);
4602 free_pipe_list(pctx->list_head, 0);
4603 debug_printf_clean("freed list %p\n", pctx->list_head);
4604 IF_HAS_KEYWORDS(p2 = pctx->stack;)
4608 IF_HAS_KEYWORDS(pctx = p2;)
4609 } while (HAS_KEYWORDS && pctx);
4610 /* Free text, clear all dest fields */
4612 /* If we are not in top-level parse, we return,
4613 * our caller will propagate error.
4615 if (end_trigger != ';')
4617 /* Discard cached input, force prompt */
4619 USE_HUSH_INTERACTIVE(input->promptme = 1;)
4624 /* Execiting from string: eval, sh -c '...'
4625 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
4626 * end_trigger controls how often we stop parsing
4627 * NUL: parse all, execute, return
4628 * ';': parse till ';' or newline, execute, repeat till EOF
4630 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
4633 struct pipe *pipe_list;
4635 pipe_list = parse_stream(inp, end_trigger);
4636 if (!pipe_list) /* EOF */
4638 debug_print_tree(pipe_list, 0);
4639 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
4640 run_and_free_list(pipe_list);
4644 static void parse_and_run_string(const char *s)
4646 struct in_str input;
4647 setup_string_in_str(&input, s);
4648 parse_and_run_stream(&input, '\0');
4651 static void parse_and_run_file(FILE *f)
4653 struct in_str input;
4654 setup_file_in_str(&input, f);
4655 parse_and_run_stream(&input, ';');
4659 /* Make sure we have a controlling tty. If we get started under a job
4660 * aware app (like bash for example), make sure we are now in charge so
4661 * we don't fight over who gets the foreground */
4662 static void setup_job_control(void)
4666 shell_pgrp = getpgrp();
4668 /* If we were ran as 'hush &',
4669 * sleep until we are in the foreground. */
4670 while (tcgetpgrp(G_interactive_fd) != shell_pgrp) {
4671 /* Send TTIN to ourself (should stop us) */
4672 kill(- shell_pgrp, SIGTTIN);
4673 shell_pgrp = getpgrp();
4676 /* We _must_ restore tty pgrp on fatal signals */
4677 set_fatal_signals_to_sigexit();
4679 /* Put ourselves in our own process group. */
4680 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
4681 /* Grab control of the terminal. */
4682 tcsetpgrp(G_interactive_fd, getpid());
4686 static int set_mode(const char cstate, const char mode)
4688 int state = (cstate == '-' ? 1 : 0);
4690 case 'n': G.fake_mode = state; break;
4691 case 'x': /*G.debug_mode = state;*/ break;
4692 default: return EXIT_FAILURE;
4694 return EXIT_SUCCESS;
4697 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4698 int hush_main(int argc, char **argv)
4700 static const struct variable const_shell_ver = {
4702 .varstr = (char*)hush_version_str,
4703 .max_len = 1, /* 0 can provoke free(name) */
4711 struct variable *cur_var;
4715 G.root_pid = getpid();
4717 /* Deal with HUSH_VERSION */
4718 G.shell_ver = const_shell_ver; /* copying struct here */
4719 G.top_var = &G.shell_ver;
4720 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
4721 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
4722 /* Initialize our shell local variables with the values
4723 * currently living in the environment */
4724 cur_var = G.top_var;
4727 char *value = strchr(*e, '=');
4728 if (value) { /* paranoia */
4729 cur_var->next = xzalloc(sizeof(*cur_var));
4730 cur_var = cur_var->next;
4731 cur_var->varstr = *e;
4732 cur_var->max_len = strlen(*e);
4733 cur_var->flg_export = 1;
4737 debug_printf_env("putenv '%s'\n", hush_version_str);
4738 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
4740 #if ENABLE_FEATURE_EDITING
4741 G.line_input_state = new_line_input_t(FOR_SHELL);
4743 /* XXX what should these be while sourcing /etc/profile? */
4744 G.global_argc = argc;
4745 G.global_argv = argv;
4746 /* Initialize some more globals to non-zero values */
4748 #if ENABLE_HUSH_INTERACTIVE
4749 if (ENABLE_FEATURE_EDITING)
4750 cmdedit_set_initial_prompt();
4754 if (EXIT_SUCCESS) /* otherwise is already done */
4755 G.last_return_code = EXIT_SUCCESS;
4757 if (argv[0] && argv[0][0] == '-') {
4758 debug_printf("sourcing /etc/profile\n");
4759 input = fopen_for_read("/etc/profile");
4760 if (input != NULL) {
4761 close_on_exec_on(fileno(input));
4762 parse_and_run_file(input);
4768 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
4769 while ((opt = getopt(argc, argv, "c:xins")) > 0) {
4772 G.global_argv = argv + optind;
4773 if (!argv[optind]) {
4774 /* -c 'script' (no params): prevent empty $0 */
4775 *--G.global_argv = argv[0];
4777 } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
4778 G.global_argc = argc - optind;
4779 parse_and_run_string(optarg);
4782 /* Well, we cannot just declare interactiveness,
4783 * we have to have some stuff (ctty, etc) */
4784 /* G_interactive_fd++; */
4787 /* "-s" means "read from stdin", but this is how we always
4788 * operate, so simply do nothing here. */
4792 if (!set_mode('-', opt))
4796 fprintf(stderr, "Usage: sh [FILE]...\n"
4797 " or: sh -c command [args]...\n\n");
4805 /* A shell is interactive if the '-i' flag was given, or if all of
4806 * the following conditions are met:
4808 * no arguments remaining or the -s flag given
4809 * standard input is a terminal
4810 * standard output is a terminal
4811 * Refer to Posix.2, the description of the 'sh' utility. */
4812 if (argv[optind] == NULL && input == stdin
4813 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4815 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
4816 debug_printf("saved_tty_pgrp=%d\n", G.saved_tty_pgrp);
4817 if (G.saved_tty_pgrp >= 0) {
4818 /* try to dup to high fd#, >= 255 */
4819 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4820 if (G_interactive_fd < 0) {
4821 /* try to dup to any fd */
4822 G_interactive_fd = dup(STDIN_FILENO);
4823 if (G_interactive_fd < 0)
4825 G_interactive_fd = 0;
4827 // TODO: track & disallow any attempts of user
4828 // to (inadvertently) close/redirect it
4831 init_signal_mask(); /* note: ensures SIGCHLD is not masked */
4832 debug_printf("interactive_fd=%d\n", G_interactive_fd);
4833 if (G_interactive_fd) {
4834 fcntl(G_interactive_fd, F_SETFD, FD_CLOEXEC);
4835 /* Looks like they want an interactive shell */
4836 setup_job_control();
4837 /* -1 is special - makes xfuncs longjmp, not exit
4838 * (we reset die_sleep = 0 whereever we [v]fork) */
4840 if (setjmp(die_jmp)) {
4841 /* xfunc has failed! die die die */
4842 hush_exit(xfunc_error_retval);
4845 #elif ENABLE_HUSH_INTERACTIVE
4846 /* no job control compiled, only prompt/line editing */
4847 if (argv[optind] == NULL && input == stdin
4848 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4850 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4851 if (G_interactive_fd < 0) {
4852 /* try to dup to any fd */
4853 G_interactive_fd = dup(STDIN_FILENO);
4854 if (G_interactive_fd < 0)
4856 G_interactive_fd = 0;
4858 if (G_interactive_fd) {
4859 fcntl(G_interactive_fd, F_SETFD, FD_CLOEXEC);
4862 init_signal_mask(); /* note: ensures SIGCHLD is not masked */
4866 /* POSIX allows shell to re-enable SIGCHLD
4867 * even if it was SIG_IGN on entry */
4868 // G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
4869 signal(SIGCHLD, SIG_DFL); // SIGCHLD_handler);
4871 #if ENABLE_HUSH_INTERACTIVE && !ENABLE_FEATURE_SH_EXTRA_QUIET
4872 if (G_interactive_fd) {
4873 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
4874 printf("Enter 'help' for a list of built-in commands.\n\n");
4878 if (argv[optind] == NULL) {
4879 parse_and_run_file(stdin);
4881 debug_printf("\nrunning script '%s'\n", argv[optind]);
4882 G.global_argv = argv + optind;
4883 G.global_argc = argc - optind;
4884 input = xfopen_for_read(argv[optind]);
4885 fcntl(fileno(input), F_SETFD, FD_CLOEXEC);
4886 parse_and_run_file(input);
4891 #if ENABLE_FEATURE_CLEAN_UP
4893 if (G.cwd != bb_msg_unknown)
4895 cur_var = G.top_var->next;
4897 struct variable *tmp = cur_var;
4898 if (!cur_var->max_len)
4899 free(cur_var->varstr);
4900 cur_var = cur_var->next;
4904 hush_exit(G.last_return_code);
4909 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4910 int lash_main(int argc, char **argv)
4912 //bb_error_msg("lash is deprecated, please use hush instead");
4913 return hush_main(argc, argv);
4921 static int builtin_trap(char **argv)
4928 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
4931 /* No args: print all trapped. This isn't 100% correct as we should
4932 * be escaping the cmd so that it can be pasted back in ...
4934 for (i = 0; i < NSIG; ++i)
4936 printf("trap -- '%s' %s\n", G.traps[i], get_signame(i));
4937 return EXIT_SUCCESS;
4942 /* if first arg is decimal: reset all specified */
4943 sig = bb_strtou(*++argv, NULL, 10);
4949 sig = get_signum(*argv++);
4950 if (sig < 0 || sig >= NSIG) {
4952 /* mimic bash message exactly */
4953 bb_perror_msg("trap: %s: invalid signal specification", argv[i]);
4958 G.traps[sig] = xstrdup(new_cmd);
4960 debug_printf("trap: setting SIG%s (%i) to '%s'",
4961 get_signame(sig), sig, G.traps[sig]);
4963 /* There is no signal for 0 (EXIT) */
4968 sigaddset(&G.blocked_set, sig);
4970 /* there was a trap handler, we are removing it
4971 * (if sig has non-DFL handling,
4972 * we don't need to do anything) */
4973 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
4975 sigdelset(&G.blocked_set, sig);
4977 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
4982 /* first arg is "-": reset all specified to default */
4983 /* first arg is "": ignore all specified */
4984 /* everything else: execute first arg upon signal */
4986 bb_error_msg("trap: invalid arguments");
4987 return EXIT_FAILURE;
4989 if (LONE_DASH(*argv))
4997 static int builtin_true(char **argv UNUSED_PARAM)
5002 static int builtin_test(char **argv)
5009 return test_main(argc, argv - argc);
5012 static int builtin_echo(char **argv)
5019 return echo_main(argc, argv - argc);
5022 static int builtin_eval(char **argv)
5024 int rcode = EXIT_SUCCESS;
5027 char *str = expand_strvec_to_string(argv + 1);
5029 * eval "echo Hi; done" ("done" is syntax error):
5030 * "echo Hi" will not execute too.
5032 parse_and_run_string(str);
5034 rcode = G.last_return_code;
5039 static int builtin_cd(char **argv)
5042 if (argv[1] == NULL) {
5043 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
5044 * bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
5046 newdir = getenv("HOME") ? : "/";
5049 if (chdir(newdir)) {
5050 printf("cd: %s: %s\n", newdir, strerror(errno));
5051 return EXIT_FAILURE;
5054 return EXIT_SUCCESS;
5057 static int builtin_exec(char **argv)
5059 if (argv[1] == NULL)
5060 return EXIT_SUCCESS; /* bash does this */
5065 // FIXME: if exec fails, bash does NOT exit! We do...
5066 pseudo_exec_argv(&dummy, argv + 1, 0, NULL);
5071 static int builtin_exit(char **argv)
5073 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
5074 //puts("exit"); /* bash does it */
5075 // TODO: warn if we have background jobs: "There are stopped jobs"
5076 // On second consecutive 'exit', exit anyway.
5077 if (argv[1] == NULL)
5078 hush_exit(G.last_return_code);
5079 /* mimic bash: exit 123abc == exit 255 + error msg */
5080 xfunc_error_retval = 255;
5081 /* bash: exit -2 == exit 254, no error msg */
5082 hush_exit(xatoi(argv[1]) & 0xff);
5085 static int builtin_export(char **argv)
5088 char *name = argv[1];
5092 // ash emits: export VAR='VAL'
5093 // bash: declare -x VAR="VAL"
5094 // (both also escape as needed (quotes, $, etc))
5099 return EXIT_SUCCESS;
5102 value = strchr(name, '=');
5104 /* They are exporting something without a =VALUE */
5105 struct variable *var;
5107 var = get_local_var(name);
5109 var->flg_export = 1;
5110 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
5111 putenv(var->varstr);
5113 /* bash does not return an error when trying to export
5114 * an undefined variable. Do likewise. */
5115 return EXIT_SUCCESS;
5118 set_local_var(xstrdup(name), 1);
5119 return EXIT_SUCCESS;
5123 /* built-in 'fg' and 'bg' handler */
5124 static int builtin_fg_bg(char **argv)
5129 if (!G_interactive_fd)
5130 return EXIT_FAILURE;
5131 /* If they gave us no args, assume they want the last backgrounded task */
5133 for (pi = G.job_list; pi; pi = pi->next) {
5134 if (pi->jobid == G.last_jobid) {
5138 bb_error_msg("%s: no current job", argv[0]);
5139 return EXIT_FAILURE;
5141 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
5142 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
5143 return EXIT_FAILURE;
5145 for (pi = G.job_list; pi; pi = pi->next) {
5146 if (pi->jobid == jobnum) {
5150 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
5151 return EXIT_FAILURE;
5153 // TODO: bash prints a string representation
5154 // of job being foregrounded (like "sleep 1 | cat")
5155 if (argv[0][0] == 'f') {
5156 /* Put the job into the foreground. */
5157 tcsetpgrp(G_interactive_fd, pi->pgrp);
5160 /* Restart the processes in the job */
5161 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
5162 for (i = 0; i < pi->num_cmds; i++) {
5163 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
5164 pi->cmds[i].is_stopped = 0;
5166 pi->stopped_cmds = 0;
5168 i = kill(- pi->pgrp, SIGCONT);
5170 if (errno == ESRCH) {
5171 delete_finished_bg_job(pi);
5172 return EXIT_SUCCESS;
5174 bb_perror_msg("kill (SIGCONT)");
5177 if (argv[0][0] == 'f') {
5179 return checkjobs_and_fg_shell(pi);
5181 return EXIT_SUCCESS;
5185 #if ENABLE_HUSH_HELP
5186 static int builtin_help(char **argv UNUSED_PARAM)
5188 const struct built_in_command *x;
5191 "Built-in commands:\n"
5192 "------------------\n");
5193 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
5194 printf("%s\t%s\n", x->cmd, x->descr);
5197 return EXIT_SUCCESS;
5202 static int builtin_jobs(char **argv UNUSED_PARAM)
5205 const char *status_string;
5207 for (job = G.job_list; job; job = job->next) {
5208 if (job->alive_cmds == job->stopped_cmds)
5209 status_string = "Stopped";
5211 status_string = "Running";
5213 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
5215 return EXIT_SUCCESS;
5219 static int builtin_pwd(char **argv UNUSED_PARAM)
5222 return EXIT_SUCCESS;
5225 static int builtin_read(char **argv)
5228 const char *name = argv[1] ? argv[1] : "REPLY";
5230 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
5231 return set_local_var(string, 0);
5234 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
5235 * built-in 'set' handler
5237 * set [-abCefhmnuvx] [-o option] [argument...]
5238 * set [+abCefhmnuvx] [+o option] [argument...]
5239 * set -- [argument...]
5242 * Implementations shall support the options in both their hyphen and
5243 * plus-sign forms. These options can also be specified as options to sh.
5245 * Write out all variables and their values: set
5246 * Set $1, $2, and $3 and set "$#" to 3: set c a b
5247 * Turn on the -x and -v options: set -xv
5248 * Unset all positional parameters: set --
5249 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
5250 * Set the positional parameters to the expansion of x, even if x expands
5251 * with a leading '-' or '+': set -- $x
5253 * So far, we only support "set -- [argument...]" and some of the short names.
5255 static int builtin_set(char **argv)
5258 char **pp, **g_argv;
5259 char *arg = *++argv;
5263 for (e = G.top_var; e; e = e->next)
5265 return EXIT_SUCCESS;
5269 if (!strcmp(arg, "--")) {
5274 if (arg[0] == '+' || arg[0] == '-') {
5275 for (n = 1; arg[n]; ++n)
5276 if (set_mode(arg[0], arg[n]))
5282 } while ((arg = *++argv) != NULL);
5283 /* Now argv[0] is 1st argument */
5285 /* Only reset global_argv if we didn't process anything */
5287 return EXIT_SUCCESS;
5290 /* NB: G.global_argv[0] ($0) is never freed/changed */
5291 g_argv = G.global_argv;
5292 if (G.global_args_malloced) {
5298 G.global_args_malloced = 1;
5299 pp = xzalloc(sizeof(pp[0]) * 2);
5300 pp[0] = g_argv[0]; /* retain $0 */
5303 /* This realloc's G.global_argv */
5304 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
5311 return EXIT_SUCCESS;
5313 /* Nothing known, so abort */
5315 bb_error_msg("set: %s: invalid option", arg);
5316 return EXIT_FAILURE;
5319 static int builtin_shift(char **argv)
5325 if (n >= 0 && n < G.global_argc) {
5326 if (G.global_args_malloced) {
5329 free(G.global_argv[m++]);
5332 memmove(&G.global_argv[1], &G.global_argv[n+1],
5333 G.global_argc * sizeof(G.global_argv[0]));
5334 return EXIT_SUCCESS;
5336 return EXIT_FAILURE;
5339 static int builtin_source(char **argv)
5343 if (argv[1] == NULL)
5344 return EXIT_FAILURE;
5346 /* XXX search through $PATH is missing */
5347 input = fopen_for_read(argv[1]);
5349 bb_error_msg("can't open '%s'", argv[1]);
5350 return EXIT_FAILURE;
5352 close_on_exec_on(fileno(input));
5354 /* Now run the file */
5355 /* XXX argv and argc are broken; need to save old G.global_argv
5356 * (pointer only is OK!) on this stack frame,
5357 * set G.global_argv=argv+1, recurse, and restore. */
5358 parse_and_run_file(input);
5360 return G.last_return_code;
5363 static int builtin_umask(char **argv)
5366 const char *arg = argv[1];
5368 new_umask = bb_strtou(arg, NULL, 8);
5370 return EXIT_FAILURE;
5372 new_umask = umask(0);
5373 printf("%.3o\n", (unsigned) new_umask);
5376 return EXIT_SUCCESS;
5379 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
5380 static int builtin_unset(char **argv)
5387 return EXIT_SUCCESS;
5390 if (argv[1][0] == '-') {
5391 switch (argv[1][1]) {
5393 case 'f': if (ENABLE_HUSH_FUNCTIONS) { var = false; break; }
5395 bb_error_msg("unset: %s: invalid option", argv[1]);
5396 return EXIT_FAILURE;
5404 if (unset_local_var(argv[i]))
5407 #if ENABLE_HUSH_FUNCTIONS
5409 unset_local_func(argv[i]);
5415 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
5416 static int builtin_wait(char **argv)
5418 int ret = EXIT_SUCCESS;
5421 if (*++argv == NULL) {
5422 /* Don't care about wait results */
5423 /* Note 1: must wait until there are no more children */
5424 /* Note 2: must be interruptible */
5426 * $ sleep 3 & sleep 6 & wait
5431 * $ sleep 3 & sleep 6 & wait
5435 * ^C <-- after ~4 sec from keyboard
5438 sigaddset(&G.blocked_set, SIGCHLD);
5439 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5442 if (errno == ECHILD)
5444 /* Wait for SIGCHLD or any other signal of interest */
5445 /* sigtimedwait with infinite timeout: */
5446 sig = sigwaitinfo(&G.blocked_set, NULL);
5448 sig = check_and_run_traps(sig);
5449 if (sig && sig != SIGCHLD) { /* see note 2 */
5455 sigdelset(&G.blocked_set, SIGCHLD);
5456 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5460 /* This is probably buggy wrt interruptible-ness */
5462 pid_t pid = bb_strtou(*argv, NULL, 10);
5464 /* mimic bash message */
5465 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
5466 return EXIT_FAILURE;
5468 if (waitpid(pid, &status, 0) == pid) {
5469 if (WIFSIGNALED(status))
5470 ret = 128 + WTERMSIG(status);
5471 else if (WIFEXITED(status))
5472 ret = WEXITSTATUS(status);
5476 bb_perror_msg("wait %s", *argv);
5485 #if ENABLE_HUSH_LOOPS
5486 static int builtin_break(char **argv)
5488 if (G.depth_of_loop == 0) {
5489 bb_error_msg("%s: only meaningful in a loop", argv[0]);
5490 return EXIT_SUCCESS; /* bash compat */
5492 G.flag_break_continue++; /* BC_BREAK = 1 */
5493 G.depth_break_continue = 1;
5495 G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
5496 if (errno || !G.depth_break_continue || argv[2]) {
5497 bb_error_msg("%s: bad arguments", argv[0]);
5498 G.flag_break_continue = BC_BREAK;
5499 G.depth_break_continue = UINT_MAX;
5502 if (G.depth_of_loop < G.depth_break_continue)
5503 G.depth_break_continue = G.depth_of_loop;
5504 return EXIT_SUCCESS;
5507 static int builtin_continue(char **argv)
5509 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
5510 return builtin_break(argv);