1 /* vi: set sw=4 ts=4: */
3 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
9 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
12 * The parser routines proper are all original material, first
13 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
14 * execution engine, the builtins, and much of the underlying
15 * support has been adapted from busybox-0.49pre's lash, which is
16 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
17 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
18 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
19 * Troan, which they placed in the public domain. I don't know
20 * how much of the Johnson/Troan code has survived the repeated
24 * o_addchr derived from similar w_addchar function in glibc-2.2.
25 * setup_redirect, redirect_opt_num, and big chunks of main
26 * and many builtins derived from contributions by Erik Andersen.
27 * Miscellaneous bugfixes from Matt Kraai.
29 * There are two big (and related) architecture differences between
30 * this parser and the lash parser. One is that this version is
31 * actually designed from the ground up to understand nearly all
32 * of the Bourne grammar. The second, consequential change is that
33 * the parser and input reader have been turned inside out. Now,
34 * the parser is in control, and asks for input as needed. The old
35 * way had the input reader in control, and it asked for parsing to
36 * take place as needed. The new way makes it much easier to properly
37 * handle the recursion implicit in the various substitutions, especially
38 * across continuation lines.
40 * POSIX syntax not implemented:
42 * <(list) and >(list) Process Substitution
43 * Here Documents ( << word )
46 * Parameter Expansion for substring processing ${var#word} ${var%word}
48 * Bash stuff (maybe optionally enable?):
49 * &> and >& redirection of stdout+stderr
51 * reserved words: [[ ]] function select
52 * substrings ${var:1:5}
55 * grep for "TODO" and fix (some of them are easy)
56 * change { and } from special chars to reserved words
57 * builtins: return, ulimit
58 * follow IFS rules more precisely, including update semantics
59 * figure out what to do with backslash-newline
60 * continuation lines, both explicit and implicit - done?
62 * ^Z handling (and explain it in comments for mere humans)
63 * separate job control from interactiveness
64 * (testcase: booting with init=/bin/hush does not show prompt (2009-04))
67 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
70 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
71 //TODO: pull in some .h and find out whether we have SINGLE_APPLET_MAIN?
72 //#include "applet_tables.h" doesn't work
74 /* #include <dmalloc.h> */
80 #ifdef WANT_TO_TEST_NOMMU
85 # define USE_FOR_NOMMU(...) __VA_ARGS__
86 # define USE_FOR_MMU(...)
89 #if defined SINGLE_APPLET_MAIN
90 /* STANDALONE does not make sense, and won't compile */
91 #undef CONFIG_FEATURE_SH_STANDALONE
92 #undef ENABLE_FEATURE_SH_STANDALONE
93 #undef USE_FEATURE_SH_STANDALONE
94 #define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
95 #define ENABLE_FEATURE_SH_STANDALONE 0
96 #define USE_FEATURE_SH_STANDALONE(...)
97 #define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
100 #if !ENABLE_HUSH_INTERACTIVE
101 #undef ENABLE_FEATURE_EDITING
102 #define ENABLE_FEATURE_EDITING 0
103 #undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
104 #define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
107 /* Do we support ANY keywords? */
108 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
109 #define HAS_KEYWORDS 1
110 #define IF_HAS_KEYWORDS(...) __VA_ARGS__
111 #define IF_HAS_NO_KEYWORDS(...)
113 #define HAS_KEYWORDS 0
114 #define IF_HAS_KEYWORDS(...)
115 #define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
118 /* Keep unconditionally on for now */
121 #define ENABLE_HUSH_FUNCTIONS 0
124 /* If you comment out one of these below, it will be #defined later
125 * to perform debug printfs to stderr: */
126 #define debug_printf(...) do {} while (0)
127 /* Finer-grained debug switches */
128 #define debug_printf_parse(...) do {} while (0)
129 #define debug_print_tree(a, b) do {} while (0)
130 #define debug_printf_exec(...) do {} while (0)
131 #define debug_printf_env(...) do {} while (0)
132 #define debug_printf_jobs(...) do {} while (0)
133 #define debug_printf_expand(...) do {} while (0)
134 #define debug_printf_glob(...) do {} while (0)
135 #define debug_printf_list(...) do {} while (0)
136 #define debug_printf_subst(...) do {} while (0)
137 #define debug_printf_clean(...) do {} while (0)
140 #define debug_printf(...) fprintf(stderr, __VA_ARGS__)
143 #ifndef debug_printf_parse
144 #define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
147 #ifndef debug_printf_exec
148 #define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
151 #ifndef debug_printf_env
152 #define debug_printf_env(...) fprintf(stderr, __VA_ARGS__)
155 #ifndef debug_printf_jobs
156 #define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
162 #ifndef debug_printf_expand
163 #define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
164 #define DEBUG_EXPAND 1
166 #define DEBUG_EXPAND 0
169 #ifndef debug_printf_glob
170 #define debug_printf_glob(...) fprintf(stderr, __VA_ARGS__)
176 #ifndef debug_printf_list
177 #define debug_printf_list(...) fprintf(stderr, __VA_ARGS__)
180 #ifndef debug_printf_subst
181 #define debug_printf_subst(...) fprintf(stderr, __VA_ARGS__)
184 #ifndef debug_printf_clean
185 /* broken, of course, but OK for testing */
186 static const char *indenter(int i)
188 static const char blanks[] ALIGN1 =
190 return &blanks[sizeof(blanks) - i - 1];
192 #define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
193 #define DEBUG_CLEAN 1
195 #define DEBUG_CLEAN 0
199 static void debug_print_strings(const char *prefix, char **vv)
201 fprintf(stderr, "%s:\n", prefix);
203 fprintf(stderr, " '%s'\n", *vv++);
206 #define debug_print_strings(prefix, vv) ((void)0)
210 * Leak hunting. Use hush_leaktool.sh for post-processing.
212 #ifdef FOR_HUSH_LEAKTOOL
213 static void *xxmalloc(int lineno, size_t size)
215 void *ptr = xmalloc((size + 0xff) & ~0xff);
216 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
219 static void *xxrealloc(int lineno, void *ptr, size_t size)
221 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
222 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
225 static char *xxstrdup(int lineno, const char *str)
227 char *ptr = xstrdup(str);
228 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
231 static void xxfree(void *ptr)
233 fdprintf(2, "free %p\n", ptr);
236 #define xmalloc(s) xxmalloc(__LINE__, s)
237 #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
238 #define xstrdup(s) xxstrdup(__LINE__, s)
239 #define free(p) xxfree(p)
243 #define ERR_PTR ((void*)(long)1)
245 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
247 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
249 #define SPECIAL_VAR_SYMBOL 3
251 typedef enum redir_type {
252 REDIRECT_INVALID = 0,
254 REDIRECT_OVERWRITE = 2,
256 REDIRECT_HEREDOC = 4,
258 REDIRECT_HEREDOC2 = 6, /* REDIRECT_HEREDOC after heredoc load */
261 /* The descrip member of this structure is only used to make
262 * debugging output pretty */
263 static const struct {
265 signed char default_fd;
269 { O_RDONLY, 0, "<" },
270 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
271 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
272 { O_RDONLY, 0, "<<" },
273 { O_CREAT|O_RDWR, 1, "<>" },
274 /* Should not be needed. Bogus default_fd helps in debugging */
275 /* { O_RDONLY, 77, "<<" }, */
278 typedef enum reserved_style {
287 #if ENABLE_HUSH_LOOPS
294 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
299 /* two pseudo-keywords support contrived "case" syntax: */
300 RES_MATCH , /* "word)" */
301 RES_CASEI , /* "this command is inside CASE" */
308 typedef struct o_string {
310 int length; /* position where data is appended */
312 /* Protect newly added chars against globbing
313 * (by prepending \ to *, ?, [, \) */
317 smallint has_empty_slot;
318 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
321 MAYBE_ASSIGNMENT = 0,
322 DEFINITELY_ASSIGNMENT = 1,
324 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
326 /* Used for initialization: o_string foo = NULL_O_STRING; */
327 #define NULL_O_STRING { NULL }
329 /* I can almost use ordinary FILE*. Is open_memstream() universally
330 * available? Where is it documented? */
331 typedef struct in_str {
333 /* eof_flag=1: last char in ->p is really an EOF */
334 char eof_flag; /* meaningless if ->p == NULL */
336 #if ENABLE_HUSH_INTERACTIVE
338 smallint promptmode; /* 0: PS1, 1: PS2 */
341 int (*get) (struct in_str *);
342 int (*peek) (struct in_str *);
344 #define i_getch(input) ((input)->get(input))
345 #define i_peek(input) ((input)->peek(input))
347 struct redir_struct {
348 struct redir_struct *next;
349 char *rd_filename; /* filename */
350 int fd; /* file descriptor being redirected */
351 int dup; /* -1, or file descriptor being duplicated */
352 smallint /*enum redir_type*/ rd_type;
356 pid_t pid; /* 0 if exited */
357 int assignment_cnt; /* how many argv[i] are assignments? */
358 smallint is_stopped; /* is the command currently running? */
359 smallint grp_type; /* GRP_xxx */
360 struct pipe *group; /* if non-NULL, this "command" is { list },
361 * ( list ), or a compound statement */
363 char *group_as_string;
365 char **argv; /* command name and arguments */
366 struct redir_struct *redirects; /* I/O redirections */
368 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
369 * and on execution these are substituted with their values.
370 * Substitution can make _several_ words out of one argv[n]!
371 * Example: argv[0]=='.^C*^C.' here: echo .$*.
372 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
375 #define GRP_SUBSHELL 1
376 #if ENABLE_HUSH_FUNCTIONS
377 #define GRP_FUNCTION 2
382 int num_cmds; /* total number of commands in job */
383 int alive_cmds; /* number of commands running (not exited) */
384 int stopped_cmds; /* number of commands alive, but stopped */
386 int jobid; /* job number */
387 pid_t pgrp; /* process group ID for the job */
388 char *cmdtext; /* name of job */
390 struct command *cmds; /* array of commands in pipe */
391 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
392 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
393 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
395 typedef enum pipe_style {
402 /* This holds pointers to the various results of parsing */
403 struct parse_context {
404 /* linked list of pipes */
405 struct pipe *list_head;
406 /* last pipe (being constructed right now) */
408 /* last command in pipe (being constructed right now) */
409 struct command *command;
410 /* last redirect in command->redirects list */
411 struct redir_struct *pending_redirect;
417 smallint ctx_inverted; /* "! cmd | cmd" */
419 smallint ctx_dsemicolon; /* ";;" seen */
421 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
423 /* group we are enclosed in:
424 * example: "if pipe1; pipe2; then pipe3; fi"
425 * when we see "if" or "then", we malloc and copy current context,
426 * and make ->stack point to it. then we parse pipeN.
427 * when closing "then" / fi" / whatever is found,
428 * we move list_head into ->stack->command->group,
429 * copy ->stack into current context, and delete ->stack.
430 * (parsing of { list } and ( list ) doesn't use this method)
432 struct parse_context *stack;
436 /* On program start, environ points to initial environment.
437 * putenv adds new pointers into it, unsetenv removes them.
438 * Neither of these (de)allocates the strings.
439 * setenv allocates new strings in malloc space and does putenv,
440 * and thus setenv is unusable (leaky) for shell's purposes */
441 #define setenv(...) setenv_is_leaky_dont_use()
443 struct variable *next;
444 char *varstr; /* points to "name=" portion */
445 int max_len; /* if > 0, name is part of initial env; else name is malloced */
446 smallint flg_export; /* putenv should be done on this var */
447 smallint flg_read_only;
456 /* "Globals" within this file */
457 /* Sorted roughly by size (smaller offsets == smaller code) */
459 #if ENABLE_HUSH_INTERACTIVE
460 /* 'interactive_fd' is a fd# open to ctty, if we have one
461 * _AND_ if we decided to act interactively */
465 #define G_interactive_fd (G.interactive_fd)
467 #define G_interactive_fd 0
469 #if ENABLE_FEATURE_EDITING
470 line_input_t *line_input_state;
476 pid_t saved_tty_pgrp;
478 struct pipe *job_list;
479 struct pipe *toplevel_list;
480 //// smallint ctrl_z_flag;
482 smallint flag_SIGINT;
483 #if ENABLE_HUSH_LOOPS
484 smallint flag_break_continue;
487 /* These four support $?, $#, and $1 */
488 smalluint last_exitcode;
489 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
490 smalluint global_args_malloced;
491 /* how many non-NULL argv's we have. NB: $# + 1 */
495 char *argv0_for_re_execing;
496 char **argv_from_re_execing;
498 #if ENABLE_HUSH_LOOPS
499 unsigned depth_break_continue;
500 unsigned depth_of_loop;
504 struct variable *top_var; /* = &G.shell_ver (set in main()) */
505 struct variable shell_ver;
506 /* Signal and trap handling */
507 // unsigned count_SIGCHLD;
508 // unsigned handled_SIGCHLD;
509 /* which signals have non-DFL handler (even with no traps set)? */
510 unsigned non_DFL_mask;
511 char **traps; /* char *traps[NSIG] */
512 sigset_t blocked_set;
513 sigset_t inherited_set;
514 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
515 #if ENABLE_FEATURE_SH_STANDALONE
516 struct nofork_save_area nofork_save;
519 sigjmp_buf toplevel_jb;
522 #define G (*ptr_to_globals)
523 /* Not #defining name to G.name - this quickly gets unwieldy
524 * (too many defines). Also, I actually prefer to see when a variable
525 * is global, thus "G." prefix is a useful hint */
526 #define INIT_G() do { \
527 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
531 /* Function prototypes for builtins */
532 static int builtin_cd(char **argv);
533 static int builtin_echo(char **argv);
534 static int builtin_eval(char **argv);
535 static int builtin_exec(char **argv);
536 static int builtin_exit(char **argv);
537 static int builtin_export(char **argv);
539 static int builtin_fg_bg(char **argv);
540 static int builtin_jobs(char **argv);
543 static int builtin_help(char **argv);
545 static int builtin_pwd(char **argv);
546 static int builtin_read(char **argv);
547 static int builtin_test(char **argv);
548 static int builtin_trap(char **argv);
549 static int builtin_true(char **argv);
550 static int builtin_set(char **argv);
551 static int builtin_shift(char **argv);
552 static int builtin_source(char **argv);
553 static int builtin_umask(char **argv);
554 static int builtin_unset(char **argv);
555 static int builtin_wait(char **argv);
556 #if ENABLE_HUSH_LOOPS
557 static int builtin_break(char **argv);
558 static int builtin_continue(char **argv);
561 /* Table of built-in functions. They can be forked or not, depending on
562 * context: within pipes, they fork. As simple commands, they do not.
563 * When used in non-forking context, they can change global variables
564 * in the parent shell process. If forked, of course they cannot.
565 * For example, 'unset foo | whatever' will parse and run, but foo will
566 * still be set at the end. */
567 struct built_in_command {
569 int (*function)(char **argv);
572 #define BLTIN(cmd, func, help) { cmd, func, help }
574 #define BLTIN(cmd, func, help) { cmd, func }
578 /* For now, echo and test are unconditionally enabled.
579 * Maybe make it configurable? */
580 static const struct built_in_command bltins[] = {
581 BLTIN("." , builtin_source , "Run commands in a file"),
582 BLTIN(":" , builtin_true , "No-op"),
583 BLTIN("[" , builtin_test , "Test condition"),
585 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
587 #if ENABLE_HUSH_LOOPS
588 BLTIN("break" , builtin_break , "Exit from a loop"),
590 BLTIN("cd" , builtin_cd , "Change directory"),
591 #if ENABLE_HUSH_LOOPS
592 BLTIN("continue", builtin_continue, "Start new loop iteration"),
594 BLTIN("echo" , builtin_echo , "Write to stdout"),
595 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
596 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
597 BLTIN("exit" , builtin_exit , "Exit"),
598 BLTIN("export" , builtin_export , "Set environment variable"),
600 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
603 BLTIN("help" , builtin_help , "List shell built-in commands"),
606 BLTIN("jobs" , builtin_jobs , "List active jobs"),
608 BLTIN("pwd" , builtin_pwd , "Print current directory"),
609 BLTIN("read" , builtin_read , "Input environment variable"),
610 // BLTIN("return" , builtin_return , "Return from a function"),
611 BLTIN("set" , builtin_set , "Set/unset shell local variables"),
612 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
613 BLTIN("test" , builtin_test , "Test condition"),
614 BLTIN("trap" , builtin_trap , "Trap signals"),
615 // BLTIN("ulimit" , builtin_return , "Control resource limits"),
616 BLTIN("umask" , builtin_umask , "Set file creation mask"),
617 BLTIN("unset" , builtin_unset , "Unset environment variable"),
618 BLTIN("wait" , builtin_wait , "Wait for process"),
622 static void maybe_die(const char *notice, const char *msg)
624 /* Was using fancy stuff:
625 * (G_interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
626 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
627 void FAST_FUNC (*fp)(const char *s, ...) = bb_error_msg_and_die;
628 #if ENABLE_HUSH_INTERACTIVE
629 if (G_interactive_fd)
632 fp(msg ? "%s: %s" : notice, notice, msg);
635 #define syntax(msg) maybe_die("syntax error", msg);
637 /* Debug -- trick gcc to expand __LINE__ and convert to string */
638 #define __syntax(msg, line) maybe_die("syntax error hush.c:" # line, msg)
639 #define _syntax(msg, line) __syntax(msg, line)
640 #define syntax(msg) _syntax(msg, __LINE__)
644 static int glob_needed(const char *s)
649 if (*s == '*' || *s == '[' || *s == '?')
656 static int is_assignment(const char *s)
658 if (!s || !(isalpha(*s) || *s == '_'))
661 while (isalnum(*s) || *s == '_')
666 /* Replace each \x with x in place, return ptr past NUL. */
667 static char *unbackslash(char *src)
673 if ((*dst++ = *src++) == '\0')
679 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
700 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
701 v[count1 + count2] = NULL;
704 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
708 static char **add_string_to_strings(char **strings, char *add)
713 return add_strings_to_strings(strings, v, /*dup:*/ 0);
716 static void putenv_all(char **strings)
721 debug_printf_env("putenv '%s'\n", *strings);
726 static char **putenv_all_and_save_old(char **strings)
736 eq = strchr(*strings, '=');
739 v = getenv(*strings);
742 /* v points to VAL in VAR=VAL, go back to VAR */
743 v -= (eq - *strings) + 1;
744 old = add_string_to_strings(old, v);
753 static void free_strings_and_unsetenv(char **strings, int unset)
763 debug_printf_env("unsetenv '%s'\n", *v);
771 static void free_strings(char **strings)
773 free_strings_and_unsetenv(strings, 0);
777 /* Basic theory of signal handling in shell
778 * ========================================
779 * This does not describe what hush does, rather, it is current understanding
780 * what it _should_ do. If it doesn't, it's a bug.
781 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
783 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
784 * is finished or backgrounded. It is the same in interactive and
785 * non-interactive shells, and is the same regardless of whether
786 * a user trap handler is installed or a shell special one is in effect.
787 * ^C or ^Z from keyboard seem to execute "at once" because it usually
788 * backgrounds (i.e. stops) or kills all members of currently running
791 * Wait builtin in interruptible by signals for which user trap is set
792 * or by SIGINT in interactive shell.
794 * Trap handlers will execute even within trap handlers. (right?)
796 * User trap handlers are forgotten when subshell ("(cmd)") is entered. [TODO]
798 * If job control is off, backgrounded commands ("cmd &")
799 * have SIGINT, SIGQUIT set to SIG_IGN.
801 * Commands run in command substitution ("`cmd`")
802 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
804 * Ordinary commands have signals set to SIG_IGN/DFL set as inherited
805 * by the shell from its parent.
807 * Siganls which differ from SIG_DFL action
808 * (note: child (i.e., [v]forked) shell is not an interactive shell):
811 * SIGTERM (interactive): ignore
812 * SIGHUP (interactive):
813 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
814 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
815 * (note that ^Z is handled not by trapping SIGTSTP, but by seeing
816 * that all pipe members are stopped) (right?)
817 * SIGINT (interactive): wait for last pipe, ignore the rest
818 * of the command line, show prompt. NB: ^C does not send SIGINT
819 * to interactive shell while shell is waiting for a pipe,
820 * since shell is bg'ed (is not in foreground process group).
821 * (check/expand this)
822 * Example 1: this waits 5 sec, but does not execute ls:
823 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
824 * Example 2: this does not wait and does not execute ls:
825 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
826 * Example 3: this does not wait 5 sec, but executes ls:
827 * "sleep 5; ls -l" + press ^C
829 * (What happens to signals which are IGN on shell start?)
830 * (What happens with signal mask on shell start?)
832 * Implementation in hush
833 * ======================
834 * We use in-kernel pending signal mask to determine which signals were sent.
835 * We block all signals which we don't want to take action immediately,
836 * i.e. we block all signals which need to have special handling as described
837 * above, and all signals which have traps set.
838 * After each pipe execution, we extract any pending signals via sigtimedwait()
841 * unsigned non_DFL_mask: a mask of such "special" signals
842 * sigset_t blocked_set: current blocked signal set
845 * clear bit in blocked_set unless it is also in non_DFL_mask
846 * "trap 'cmd' SIGxxx":
847 * set bit in blocked_set (even if 'cmd' is '')
848 * after [v]fork, if we plan to be a shell:
849 * nothing for {} child shell (say, "true | { true; true; } | true")
850 * unset all traps if () shell. [TODO]
851 * after [v]fork, if we plan to exec:
852 * POSIX says pending signal mask is cleared in child - no need to clear it.
853 * Restore blocked signal set to one inherited by shell just prior to exec.
855 * Note: as a result, we do not use signal handlers much. The only uses
856 * are to count SIGCHLDs [disabled - bug somewhere, + bloat]
857 * and to restore tty pgrp on signal-induced exit.
860 //static void SIGCHLD_handler(int sig UNUSED_PARAM)
862 // G.count_SIGCHLD++;
865 static int check_and_run_traps(int sig)
867 static const struct timespec zero_timespec = { 0, 0 };
868 smalluint save_rcode;
874 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
879 if (G.traps && G.traps[sig]) {
880 if (G.traps[sig][0]) {
881 /* We have user-defined handler */
882 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
883 save_rcode = G.last_exitcode;
886 G.last_exitcode = save_rcode;
887 } /* else: "" trap, ignoring signal */
890 /* not a trap: special action */
893 // G.count_SIGCHLD++;
902 default: /* ignored: */
903 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
911 /* Restores tty foreground process group, and exits.
912 * May be called as signal handler for fatal signal
913 * (will faithfully resend signal to itself, producing correct exit state)
914 * or called directly with -EXITCODE.
915 * We also call it if xfunc is exiting. */
916 static void sigexit(int sig) NORETURN;
917 static void sigexit(int sig)
919 /* Disable all signals: job control, SIGPIPE, etc. */
920 sigprocmask_allsigs(SIG_BLOCK);
922 /* Careful: we can end up here after [v]fork. Do not restore
923 * tty pgrp then, only top-level shell process does that */
924 if (G_interactive_fd && getpid() == G.root_pid)
925 tcsetpgrp(G_interactive_fd, G.saved_tty_pgrp);
927 /* Not a signal, just exit */
931 kill_myself_with_sig(sig); /* does not return */
935 /* Restores tty foreground process group, and exits. */
936 static void hush_exit(int exitcode) NORETURN;
937 static void hush_exit(int exitcode)
939 if (G.traps && G.traps[0] && G.traps[0][0]) {
940 char *argv[] = { NULL, xstrdup(G.traps[0]), NULL };
941 //TODO: do we need to prevent recursion?
947 fflush(NULL); /* flush all streams */
948 sigexit(- (exitcode & 0xff));
955 static const char *set_cwd(void)
957 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
958 * we must not try to free(bb_msg_unknown) */
959 if (G.cwd == bb_msg_unknown)
961 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
963 G.cwd = bb_msg_unknown;
968 /* Get/check local shell variables */
969 static struct variable *get_local_var(const char *name)
971 struct variable *cur;
977 for (cur = G.top_var; cur; cur = cur->next) {
978 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
984 static const char *get_local_var_value(const char *src)
986 struct variable *var = get_local_var(src);
988 return strchr(var->varstr, '=') + 1;
992 /* str holds "NAME=VAL" and is expected to be malloced.
993 * We take ownership of it.
997 * -1: if NAME is set, leave export status alone
998 * if NAME is not set, do not export
999 * flg_read_only is set only when we handle -R var=val
1002 #define set_local_var(str, flg_export, flg_read_only) \
1003 set_local_var(str, flg_export)
1005 static int set_local_var(char *str, int flg_export, int flg_read_only)
1007 struct variable *cur;
1011 value = strchr(str, '=');
1012 if (!value) { /* not expected to ever happen? */
1017 name_len = value - str + 1; /* including '=' */
1018 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
1020 if (strncmp(cur->varstr, str, name_len) != 0) {
1022 /* Bail out. Note that now cur points
1023 * to last var in linked list */
1029 /* We found an existing var with this name */
1031 if (cur->flg_read_only) {
1035 bb_error_msg("%s: readonly variable", str);
1039 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1040 unsetenv(str); /* just in case */
1042 if (strcmp(cur->varstr, str) == 0) {
1047 if (cur->max_len >= strlen(str)) {
1048 /* This one is from startup env, reuse space */
1049 strcpy(cur->varstr, str);
1052 /* max_len == 0 signifies "malloced" var, which we can
1053 * (and has to) free */
1057 goto set_str_and_exp;
1060 /* Not found - create next variable struct */
1061 cur->next = xzalloc(sizeof(*cur));
1067 cur->flg_read_only = flg_read_only;
1070 if (flg_export == 1)
1071 cur->flg_export = 1;
1072 if (cur->flg_export) {
1073 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1074 return putenv(cur->varstr);
1079 static int unset_local_var(const char *name)
1081 struct variable *cur;
1082 struct variable *prev = prev; /* for gcc */
1086 return EXIT_SUCCESS;
1087 name_len = strlen(name);
1090 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1091 if (cur->flg_read_only) {
1092 bb_error_msg("%s: readonly variable", name);
1093 return EXIT_FAILURE;
1095 /* prev is ok to use here because 1st variable, HUSH_VERSION,
1096 * is ro, and we cannot reach this code on the 1st pass */
1097 prev->next = cur->next;
1098 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1099 bb_unsetenv(cur->varstr);
1103 return EXIT_SUCCESS;
1108 return EXIT_SUCCESS;
1111 #if ENABLE_SH_MATH_SUPPORT
1112 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1113 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1114 static char *endofname(const char *name)
1122 if (!is_in_name(*p))
1128 static void arith_set_local_var(const char *name, const char *val, int flags)
1130 /* arith code doesnt malloc space, so do it for it */
1131 char *var = xasprintf("%s=%s", name, val);
1132 set_local_var(var, flags, 0);
1140 static int static_get(struct in_str *i)
1149 static int static_peek(struct in_str *i)
1154 #if ENABLE_HUSH_INTERACTIVE
1156 static void cmdedit_set_initial_prompt(void)
1158 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1159 G.PS1 = getenv("PS1");
1166 static const char* setup_prompt_string(int promptmode)
1168 const char *prompt_str;
1169 debug_printf("setup_prompt_string %d ", promptmode);
1170 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1171 /* Set up the prompt */
1172 if (promptmode == 0) { /* PS1 */
1174 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1179 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1180 debug_printf("result '%s'\n", prompt_str);
1184 static void get_user_input(struct in_str *i)
1187 const char *prompt_str;
1189 prompt_str = setup_prompt_string(i->promptmode);
1190 #if ENABLE_FEATURE_EDITING
1191 /* Enable command line editing only while a command line
1192 * is actually being read */
1195 /* buglet: SIGINT will not make new prompt to appear _at once_,
1196 * only after <Enter>. (^C will work) */
1197 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1198 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1199 check_and_run_traps(0);
1200 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1201 i->eof_flag = (r < 0);
1202 if (i->eof_flag) { /* EOF/error detected */
1203 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1204 G.user_input_buf[1] = '\0';
1209 fputs(prompt_str, stdout);
1211 G.user_input_buf[0] = r = fgetc(i->file);
1212 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1213 //do we need check_and_run_traps(0)? (maybe only if stdin)
1214 } while (G.flag_SIGINT);
1215 i->eof_flag = (r == EOF);
1217 i->p = G.user_input_buf;
1220 #endif /* INTERACTIVE */
1222 /* This is the magic location that prints prompts
1223 * and gets data back from the user */
1224 static int file_get(struct in_str *i)
1228 /* If there is data waiting, eat it up */
1229 if (i->p && *i->p) {
1230 #if ENABLE_HUSH_INTERACTIVE
1234 if (i->eof_flag && !*i->p)
1236 /* note: ch is never NUL */
1238 /* need to double check i->file because we might be doing something
1239 * more complicated by now, like sourcing or substituting. */
1240 #if ENABLE_HUSH_INTERACTIVE
1241 if (G_interactive_fd && i->promptme && i->file == stdin) {
1244 } while (!*i->p); /* need non-empty line */
1245 i->promptmode = 1; /* PS2 */
1250 do ch = fgetc(i->file); while (ch == '\0');
1252 debug_printf("file_get: got '%c' %d\n", ch, ch);
1253 #if ENABLE_HUSH_INTERACTIVE
1260 /* All callers guarantee this routine will never
1261 * be used right after a newline, so prompting is not needed.
1263 static int file_peek(struct in_str *i)
1266 if (i->p && *i->p) {
1267 if (i->eof_flag && !i->p[1])
1270 /* note: ch is never NUL */
1272 do ch = fgetc(i->file); while (ch == '\0');
1273 i->eof_flag = (ch == EOF);
1274 i->peek_buf[0] = ch;
1275 i->peek_buf[1] = '\0';
1277 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1281 static void setup_file_in_str(struct in_str *i, FILE *f)
1283 i->peek = file_peek;
1285 #if ENABLE_HUSH_INTERACTIVE
1287 i->promptmode = 0; /* PS1 */
1293 static void setup_string_in_str(struct in_str *i, const char *s)
1295 i->peek = static_peek;
1296 i->get = static_get;
1297 #if ENABLE_HUSH_INTERACTIVE
1299 i->promptmode = 0; /* PS1 */
1309 #define B_CHUNK (32 * sizeof(char*))
1311 static void o_reset(o_string *o)
1319 static void o_free(o_string *o)
1322 memset(o, 0, sizeof(*o));
1325 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1330 static void o_grow_by(o_string *o, int len)
1332 if (o->length + len > o->maxlen) {
1333 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1334 o->data = xrealloc(o->data, 1 + o->maxlen);
1338 static void o_addchr(o_string *o, int ch)
1340 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1342 o->data[o->length] = ch;
1344 o->data[o->length] = '\0';
1347 static void o_addblock(o_string *o, const char *str, int len)
1350 memcpy(&o->data[o->length], str, len);
1352 o->data[o->length] = '\0';
1356 static void o_addstr(o_string *o, const char *str)
1358 o_addblock(o, str, strlen(str));
1362 static void o_addstr_with_NUL(o_string *o, const char *str)
1364 o_addblock(o, str, strlen(str) + 1);
1367 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
1372 && (*str != '*' && *str != '?' && *str != '[')
1380 /* My analysis of quoting semantics tells me that state information
1381 * is associated with a destination, not a source.
1383 static void o_addqchr(o_string *o, int ch)
1386 char *found = strchr("*?[\\", ch);
1391 o->data[o->length] = '\\';
1394 o->data[o->length] = ch;
1396 o->data[o->length] = '\0';
1399 static void o_addQchr(o_string *o, int ch)
1402 if (o->o_escape && strchr("*?[\\", ch)) {
1404 o->data[o->length] = '\\';
1408 o->data[o->length] = ch;
1410 o->data[o->length] = '\0';
1413 static void o_addQstr(o_string *o, const char *str, int len)
1416 o_addblock(o, str, len);
1422 int ordinary_cnt = strcspn(str, "*?[\\");
1423 if (ordinary_cnt > len) /* paranoia */
1425 o_addblock(o, str, ordinary_cnt);
1426 if (ordinary_cnt == len)
1428 str += ordinary_cnt;
1429 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
1433 if (ch) { /* it is necessarily one of "*?[\\" */
1435 o->data[o->length] = '\\';
1439 o->data[o->length] = ch;
1441 o->data[o->length] = '\0';
1445 /* A special kind of o_string for $VAR and `cmd` expansion.
1446 * It contains char* list[] at the beginning, which is grown in 16 element
1447 * increments. Actual string data starts at the next multiple of 16 * (char*).
1448 * list[i] contains an INDEX (int!) into this string data.
1449 * It means that if list[] needs to grow, data needs to be moved higher up
1450 * but list[i]'s need not be modified.
1451 * NB: remembering how many list[i]'s you have there is crucial.
1452 * o_finalize_list() operation post-processes this structure - calculates
1453 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1455 #if DEBUG_EXPAND || DEBUG_GLOB
1456 static void debug_print_list(const char *prefix, o_string *o, int n)
1458 char **list = (char**)o->data;
1459 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1461 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1462 prefix, list, n, string_start, o->length, o->maxlen);
1464 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1465 o->data + (int)list[i] + string_start,
1466 o->data + (int)list[i] + string_start);
1470 const char *p = o->data + (int)list[n - 1] + string_start;
1471 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
1475 #define debug_print_list(prefix, o, n) ((void)0)
1478 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1479 * in list[n] so that it points past last stored byte so far.
1480 * It returns n+1. */
1481 static int o_save_ptr_helper(o_string *o, int n)
1483 char **list = (char**)o->data;
1487 if (!o->has_empty_slot) {
1488 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1489 string_len = o->length - string_start;
1490 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1491 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
1492 /* list[n] points to string_start, make space for 16 more pointers */
1493 o->maxlen += 0x10 * sizeof(list[0]);
1494 o->data = xrealloc(o->data, o->maxlen + 1);
1495 list = (char**)o->data;
1496 memmove(list + n + 0x10, list + n, string_len);
1497 o->length += 0x10 * sizeof(list[0]);
1499 debug_printf_list("list[%d]=%d string_start=%d\n",
1500 n, string_len, string_start);
1503 /* We have empty slot at list[n], reuse without growth */
1504 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1505 string_len = o->length - string_start;
1506 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1507 n, string_len, string_start);
1508 o->has_empty_slot = 0;
1510 list[n] = (char*)(ptrdiff_t)string_len;
1514 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
1515 static int o_get_last_ptr(o_string *o, int n)
1517 char **list = (char**)o->data;
1518 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1520 return ((int)(ptrdiff_t)list[n-1]) + string_start;
1523 /* o_glob performs globbing on last list[], saving each result
1524 * as a new list[]. */
1525 static int o_glob(o_string *o, int n)
1531 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
1533 return o_save_ptr_helper(o, n);
1534 pattern = o->data + o_get_last_ptr(o, n);
1535 debug_printf_glob("glob pattern '%s'\n", pattern);
1536 if (!glob_needed(pattern)) {
1538 o->length = unbackslash(pattern) - o->data;
1539 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
1540 return o_save_ptr_helper(o, n);
1543 memset(&globdata, 0, sizeof(globdata));
1544 gr = glob(pattern, 0, NULL, &globdata);
1545 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1546 if (gr == GLOB_NOSPACE)
1547 bb_error_msg_and_die("out of memory during glob");
1548 if (gr == GLOB_NOMATCH) {
1549 globfree(&globdata);
1552 if (gr != 0) { /* GLOB_ABORTED ? */
1553 //TODO: testcase for bad glob pattern behavior
1554 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1556 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1557 char **argv = globdata.gl_pathv;
1558 o->length = pattern - o->data; /* "forget" pattern */
1560 o_addstr_with_NUL(o, *argv);
1561 n = o_save_ptr_helper(o, n);
1567 globfree(&globdata);
1569 debug_print_list("o_glob returning", o, n);
1573 /* If o->o_glob == 1, glob the string so far remembered.
1574 * Otherwise, just finish current list[] and start new */
1575 static int o_save_ptr(o_string *o, int n)
1577 if (o->o_glob) { /* if globbing is requested */
1578 /* If o->has_empty_slot, list[n] was already globbed
1579 * (if it was requested back then when it was filled)
1580 * so don't do that again! */
1581 if (!o->has_empty_slot)
1582 return o_glob(o, n); /* o_save_ptr_helper is inside */
1584 return o_save_ptr_helper(o, n);
1587 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
1588 static char **o_finalize_list(o_string *o, int n)
1593 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1595 debug_print_list("finalized", o, n);
1596 debug_printf_expand("finalized n:%d\n", n);
1597 list = (char**)o->data;
1598 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1602 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
1608 /* Expansion can recurse */
1609 #if ENABLE_HUSH_TICK
1610 static int process_command_subs(o_string *dest, const char *s);
1612 static char *expand_string_to_string(const char *str);
1614 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
1615 parse_stream_dquoted(dest, input, dquote_end)
1617 static int parse_stream_dquoted(o_string *as_string,
1619 struct in_str *input,
1622 /* expand_strvec_to_strvec() takes a list of strings, expands
1623 * all variable references within and returns a pointer to
1624 * a list of expanded strings, possibly with larger number
1625 * of strings. (Think VAR="a b"; echo $VAR).
1626 * This new list is allocated as a single malloc block.
1627 * NULL-terminated list of char* pointers is at the beginning of it,
1628 * followed by strings themself.
1629 * Caller can deallocate entire list by single free(list). */
1631 /* Store given string, finalizing the word and starting new one whenever
1632 * we encounter IFS char(s). This is used for expanding variable values.
1633 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
1634 static int expand_on_ifs(o_string *output, int n, const char *str)
1637 int word_len = strcspn(str, G.ifs);
1639 if (output->o_escape || !output->o_glob)
1640 o_addQstr(output, str, word_len);
1641 else /* protect backslashes against globbing up :) */
1642 o_addblock_duplicate_backslash(output, str, word_len);
1645 if (!*str) /* EOL - do not finalize word */
1647 o_addchr(output, '\0');
1648 debug_print_list("expand_on_ifs", output, n);
1649 n = o_save_ptr(output, n);
1650 str += strspn(str, G.ifs); /* skip ifs chars */
1652 debug_print_list("expand_on_ifs[1]", output, n);
1656 /* Expand all variable references in given string, adding words to list[]
1657 * at n, n+1,... positions. Return updated n (so that list[n] is next one
1658 * to be filled). This routine is extremely tricky: has to deal with
1659 * variables/parameters with whitespace, $* and $@, and constructs like
1660 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
1661 static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
1663 /* or_mask is either 0 (normal case) or 0x80
1664 * (expansion of right-hand side of assignment == 1-element expand.
1665 * It will also do no globbing, and thus we must not backslash-quote!) */
1667 char first_ch, ored_ch;
1674 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
1675 debug_print_list("expand_vars_to_list", output, n);
1676 n = o_save_ptr(output, n);
1677 debug_print_list("expand_vars_to_list[0]", output, n);
1679 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
1680 #if ENABLE_HUSH_TICK
1681 o_string subst_result = NULL_O_STRING;
1683 #if ENABLE_SH_MATH_SUPPORT
1684 char arith_buf[sizeof(arith_t)*3 + 2];
1686 o_addblock(output, arg, p - arg);
1687 debug_print_list("expand_vars_to_list[1]", output, n);
1689 p = strchr(p, SPECIAL_VAR_SYMBOL);
1691 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
1692 /* "$@" is special. Even if quoted, it can still
1693 * expand to nothing (not even an empty string) */
1694 if ((first_ch & 0x7f) != '@')
1695 ored_ch |= first_ch;
1698 switch (first_ch & 0x7f) {
1699 /* Highest bit in first_ch indicates that var is double-quoted */
1701 val = utoa(G.root_pid);
1703 case '!': /* bg pid */
1704 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
1706 case '?': /* exitcode */
1707 val = utoa(G.last_exitcode);
1709 case '#': /* argc */
1710 if (arg[1] != SPECIAL_VAR_SYMBOL)
1711 /* actually, it's a ${#var} */
1713 val = utoa(G.global_argc ? G.global_argc-1 : 0);
1718 if (!G.global_argv[i])
1720 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
1721 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
1722 smallint sv = output->o_escape;
1723 /* unquoted var's contents should be globbed, so don't escape */
1724 output->o_escape = 0;
1725 while (G.global_argv[i]) {
1726 n = expand_on_ifs(output, n, G.global_argv[i]);
1727 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
1728 if (G.global_argv[i++][0] && G.global_argv[i]) {
1729 /* this argv[] is not empty and not last:
1730 * put terminating NUL, start new word */
1731 o_addchr(output, '\0');
1732 debug_print_list("expand_vars_to_list[2]", output, n);
1733 n = o_save_ptr(output, n);
1734 debug_print_list("expand_vars_to_list[3]", output, n);
1737 output->o_escape = sv;
1739 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
1740 * and in this case should treat it like '$*' - see 'else...' below */
1741 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
1743 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1744 if (++i >= G.global_argc)
1746 o_addchr(output, '\0');
1747 debug_print_list("expand_vars_to_list[4]", output, n);
1748 n = o_save_ptr(output, n);
1750 } else { /* quoted $*: add as one word */
1752 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1753 if (!G.global_argv[++i])
1756 o_addchr(output, G.ifs[0]);
1760 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
1761 /* "Empty variable", used to make "" etc to not disappear */
1765 #if ENABLE_HUSH_TICK
1766 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
1769 //TODO: can we just stuff it into "output" directly?
1770 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
1771 process_command_subs(&subst_result, arg);
1772 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
1773 val = subst_result.data;
1776 #if ENABLE_SH_MATH_SUPPORT
1777 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
1778 arith_eval_hooks_t hooks;
1783 arg++; /* skip '+' */
1784 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
1785 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
1787 /* Optional: skip expansion if expr is simple ("a + 3", "i++" etc) */
1789 if (strchr(arg, '$') != NULL
1790 #if ENABLE_HUSH_TICK
1791 || strchr(arg, '`') != NULL
1794 /* We need to expand. Example:
1795 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
1797 struct in_str input;
1798 o_string dest = NULL_O_STRING;
1800 setup_string_in_str(&input, arg);
1801 parse_stream_dquoted(NULL, &dest, &input, EOF);
1802 //bb_error_msg("'%s' -> '%s'", arg, dest.data);
1803 exp_str = expand_string_to_string(dest.data);
1804 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
1805 o_free_unsafe(&dest);
1807 hooks.lookupvar = get_local_var_value;
1808 hooks.setvar = arith_set_local_var;
1809 hooks.endofname = endofname;
1810 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
1815 case -3: maybe_die("arith", "exponent less than 0"); break;
1816 case -2: maybe_die("arith", "divide by zero"); break;
1817 case -5: maybe_die("arith", "expression recursion loop detected"); break;
1818 default: maybe_die("arith", "syntax error"); break;
1821 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
1822 sprintf(arith_buf, arith_t_fmt, res);
1827 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
1829 bool exp_len = false;
1830 bool exp_null = false;
1832 char exp_save = exp_save; /* for compiler */
1833 char exp_op = exp_op; /* for compiler */
1834 char *exp_word = exp_word; /* for compiler */
1838 arg[0] = first_ch & 0x7f;
1840 /* prepare for expansions */
1841 if (var[0] == '#') {
1842 /* handle length expansion ${#var} */
1846 /* maybe handle parameter expansion */
1847 exp_off = strcspn(var, ":-=+?");
1851 exp_save = var[exp_off];
1852 exp_null = exp_save == ':';
1853 exp_word = var + exp_off;
1854 if (exp_null) ++exp_word;
1855 exp_op = *exp_word++;
1856 var[exp_off] = '\0';
1860 /* lookup the variable in question */
1861 if (isdigit(var[0])) {
1862 /* handle_dollar() should have vetted var for us */
1864 if (i < G.global_argc)
1865 val = G.global_argv[i];
1866 /* else val remains NULL: $N with too big N */
1868 val = get_local_var_value(var);
1870 /* handle any expansions */
1872 debug_printf_expand("expand: length of '%s' = ", val);
1873 val = utoa(val ? strlen(val) : 0);
1874 debug_printf_expand("%s\n", val);
1875 } else if (exp_off) {
1876 /* we need to do an expansion */
1877 int exp_test = (!val || (exp_null && !val[0]));
1879 exp_test = !exp_test;
1880 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
1881 exp_null ? "true" : "false", exp_test);
1884 maybe_die(var, *exp_word ? exp_word : "parameter null or not set");
1888 if (exp_op == '=') {
1889 if (isdigit(var[0]) || var[0] == '#') {
1890 maybe_die(var, "special vars cannot assign in this way");
1893 char *new_var = xmalloc(strlen(var) + strlen(val) + 2);
1894 sprintf(new_var, "%s=%s", var, val);
1895 set_local_var(new_var, -1, 0);
1899 var[exp_off] = exp_save;
1903 #if ENABLE_HUSH_TICK
1906 if (!(first_ch & 0x80)) { /* unquoted $VAR */
1907 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
1909 /* unquoted var's contents should be globbed, so don't escape */
1910 smallint sv = output->o_escape;
1911 output->o_escape = 0;
1912 n = expand_on_ifs(output, n, val);
1914 output->o_escape = sv;
1916 } else { /* quoted $VAR, val will be appended below */
1917 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
1920 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
1922 o_addQstr(output, val, strlen(val));
1924 /* Do the check to avoid writing to a const string */
1925 if (*p != SPECIAL_VAR_SYMBOL)
1926 *p = SPECIAL_VAR_SYMBOL;
1928 #if ENABLE_HUSH_TICK
1929 o_free(&subst_result);
1932 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
1935 debug_print_list("expand_vars_to_list[a]", output, n);
1936 /* this part is literal, and it was already pre-quoted
1937 * if needed (much earlier), do not use o_addQstr here! */
1938 o_addstr_with_NUL(output, arg);
1939 debug_print_list("expand_vars_to_list[b]", output, n);
1940 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
1941 && !(ored_ch & 0x80) /* and all vars were not quoted. */
1944 /* allow to reuse list[n] later without re-growth */
1945 output->has_empty_slot = 1;
1947 o_addchr(output, '\0');
1952 static char **expand_variables(char **argv, int or_mask)
1957 o_string output = NULL_O_STRING;
1959 if (or_mask & 0x100) {
1960 output.o_escape = 1; /* protect against globbing for "$var" */
1961 /* (unquoted $var will temporarily switch it off) */
1968 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
1971 debug_print_list("expand_variables", &output, n);
1973 /* output.data (malloced in one block) gets returned in "list" */
1974 list = o_finalize_list(&output, n);
1975 debug_print_strings("expand_variables[1]", list);
1979 static char **expand_strvec_to_strvec(char **argv)
1981 return expand_variables(argv, 0x100);
1984 /* Used for expansion of right hand of assignments */
1985 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
1987 static char *expand_string_to_string(const char *str)
1989 char *argv[2], **list;
1991 argv[0] = (char*)str;
1993 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
1995 if (!list[0] || list[1])
1996 bb_error_msg_and_die("BUG in varexp2");
1997 /* actually, just move string 2*sizeof(char*) bytes back */
1998 overlapping_strcpy((char*)list, list[0]);
1999 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2003 /* Used for "eval" builtin */
2004 static char* expand_strvec_to_string(char **argv)
2008 list = expand_variables(argv, 0x80);
2009 /* Convert all NULs to spaces */
2014 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2015 bb_error_msg_and_die("BUG in varexp3");
2016 list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
2020 overlapping_strcpy((char*)list, list[0]);
2021 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2025 static char **expand_assignments(char **argv, int count)
2029 /* Expand assignments into one string each */
2030 for (i = 0; i < count; i++) {
2031 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2037 //TODO: fix big string case!
2038 static void setup_heredoc(int fd, const char *heredoc)
2040 struct fd_pair pair;
2046 bb_perror_msg_and_die("vfork");
2047 if (pid == 0) { /* child */
2050 xwrite_str(pair.wr, heredoc);
2056 xmove_fd(pair.rd, fd);
2059 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
2060 * and stderr if they are redirected. */
2061 static int setup_redirects(struct command *prog, int squirrel[])
2063 //TODO: no callers ever check return value - ?!
2065 struct redir_struct *redir;
2067 for (redir = prog->redirects; redir; redir = redir->next) {
2068 if (redir->rd_type == REDIRECT_HEREDOC2) {
2069 if (squirrel && redir->fd < 3) {
2070 squirrel[redir->fd] = dup(redir->fd);
2072 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
2074 debug_printf_parse("set heredoc '%s'\n",
2075 redir->rd_filename);
2076 setup_heredoc(redir->fd, redir->rd_filename);
2080 if (redir->dup == -1) {
2082 if (redir->rd_filename == NULL) {
2083 /* Something went wrong in the parse.
2084 * Pretend it didn't happen */
2087 mode = redir_table[redir->rd_type].mode;
2088 //TODO: check redir for names like '\\'
2089 p = expand_string_to_string(redir->rd_filename);
2090 openfd = open_or_warn(p, mode);
2093 /* this could get lost if stderr has been redirected, but
2094 * bash and ash both lose it as well (though zsh doesn't!) */
2095 //what the above comment tries to say?
2099 openfd = redir->dup;
2102 if (openfd != redir->fd) {
2103 if (squirrel && redir->fd < 3) {
2104 squirrel[redir->fd] = dup(redir->fd);
2107 /* "-" means "close me" and we use -3 for that */
2110 dup2(openfd, redir->fd);
2111 if (redir->dup == -1)
2119 static void restore_redirects(int squirrel[])
2122 for (i = 0; i < 3; i++) {
2125 /* We simply die on error */
2133 #define free_pipe_list(head, indent) free_pipe_list(head)
2134 #define free_pipe(pi, indent) free_pipe(pi)
2136 static void free_pipe_list(struct pipe *head, int indent);
2138 /* Return code is the exit status of the pipe */
2139 static void free_pipe(struct pipe *pi, int indent)
2142 struct command *command;
2143 struct redir_struct *r, *rnext;
2146 if (pi->stopped_cmds > 0) /* why? */
2148 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2149 for (i = 0; i < pi->num_cmds; i++) {
2150 command = &pi->cmds[i];
2151 debug_printf_clean("%s command %d:\n", indenter(indent), i);
2152 if (command->argv) {
2153 for (a = 0, p = command->argv; *p; a++, p++) {
2154 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
2156 free_strings(command->argv);
2157 command->argv = NULL;
2159 /* not "else if": on syntax error, we may have both! */
2160 if (command->group) {
2161 debug_printf_clean("%s begin group (grp_type:%d)\n", indenter(indent), command->grp_type);
2162 free_pipe_list(command->group, indent+3);
2163 debug_printf_clean("%s end group\n", indenter(indent));
2164 command->group = NULL;
2167 free(command->group_as_string);
2168 command->group_as_string = NULL;
2170 for (r = command->redirects; r; r = rnext) {
2171 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->rd_type].descrip);
2173 /* guard against the case >$FOO, where foo is unset or blank */
2174 if (r->rd_filename) {
2175 debug_printf_clean(" %s\n", r->rd_filename);
2176 free(r->rd_filename);
2177 r->rd_filename = NULL;
2180 debug_printf_clean("&%d\n", r->dup);
2185 command->redirects = NULL;
2187 free(pi->cmds); /* children are an array, they get freed all at once */
2195 static void free_pipe_list(struct pipe *head, int indent)
2197 struct pipe *pi, *next;
2199 for (pi = head; pi; pi = next) {
2201 debug_printf_clean("%s pipe reserved word %d\n", indenter(indent), pi->res_word);
2203 free_pipe(pi, indent);
2204 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
2206 /*pi->next = NULL;*/
2213 typedef struct nommu_save_t {
2219 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
2220 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
2221 #define pseudo_exec(nommu_save, command, argv_expanded) \
2222 pseudo_exec(command, argv_expanded)
2225 /* Called after [v]fork() in run_pipe, or from builtin_exec.
2227 * XXX no exit() here. If you don't exec, use _exit instead.
2228 * The at_exit handlers apparently confuse the calling process,
2229 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
2230 static void pseudo_exec_argv(nommu_save_t *nommu_save,
2231 char **argv, int assignment_cnt,
2232 char **argv_expanded) NORETURN;
2233 static void pseudo_exec_argv(nommu_save_t *nommu_save,
2234 char **argv, int assignment_cnt,
2235 char **argv_expanded)
2239 /* Case when we are here: ... | var=val | ... */
2240 if (!argv[assignment_cnt])
2241 _exit(EXIT_SUCCESS);
2243 new_env = expand_assignments(argv, assignment_cnt);
2245 putenv_all(new_env);
2246 free(new_env); /* optional */
2248 nommu_save->new_env = new_env;
2249 nommu_save->old_env = putenv_all_and_save_old(new_env);
2251 if (argv_expanded) {
2252 argv = argv_expanded;
2254 argv = expand_strvec_to_strvec(argv + assignment_cnt);
2256 nommu_save->argv = argv;
2260 /* On NOMMU, we must never block!
2261 * Example: { sleep 99999 | read line } & echo Ok
2262 * read builtin will block on read syscall, leaving parent blocked
2263 * in vfork. Therefore we can't do this:
2266 /* Check if the command matches any of the builtins.
2267 * Depending on context, this might be redundant. But it's
2268 * easier to waste a few CPU cycles than it is to figure out
2269 * if this is one of those cases.
2273 const struct built_in_command *x;
2274 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2275 if (strcmp(argv[0], x->cmd) == 0) {
2276 debug_printf_exec("running builtin '%s'\n",
2278 rcode = x->function(argv);
2286 #if ENABLE_FEATURE_SH_STANDALONE
2287 /* Check if the command matches any busybox applets */
2288 if (strchr(argv[0], '/') == NULL) {
2289 int a = find_applet_by_name(argv[0]);
2291 #if BB_MMU /* see above why on NOMMU it is not allowed */
2292 if (APPLET_IS_NOEXEC(a)) {
2293 debug_printf_exec("running applet '%s'\n", argv[0]);
2294 run_applet_no_and_exit(a, argv);
2297 /* Re-exec ourselves */
2298 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
2299 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2300 execv(bb_busybox_exec_path, argv);
2301 /* If they called chroot or otherwise made the binary no longer
2302 * executable, fall through */
2307 debug_printf_exec("execing '%s'\n", argv[0]);
2308 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2309 execvp(argv[0], argv);
2310 bb_perror_msg("can't exec '%s'", argv[0]);
2311 _exit(EXIT_FAILURE);
2315 static void reset_traps_to_defaults(void)
2323 for (sig = 0; sig < NSIG; sig++) {
2327 G.traps[sig] = NULL;
2328 /* There is no signal for 0 (EXIT) */
2331 /* there was a trap handler, we are removing it
2332 * (if sig has non-DFL handling,
2333 * we don't need to do anything) */
2334 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
2336 sigdelset(&G.blocked_set, sig);
2340 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
2342 #define clean_up_after_re_execute() ((void)0)
2346 static void re_execute_shell(const char *s) NORETURN;
2347 static void re_execute_shell(const char *s)
2349 char param_buf[sizeof("-$%x:%x:%x:%x") + sizeof(unsigned) * 4];
2350 struct variable *cur;
2351 char **argv, **pp, **pp2;
2354 sprintf(param_buf, "-$%x:%x:%x" USE_HUSH_LOOPS(":%x")
2355 , (unsigned) G.root_pid
2356 , (unsigned) G.last_bg_pid
2357 , (unsigned) G.last_exitcode
2358 USE_HUSH_LOOPS(, G.depth_of_loop)
2360 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...>
2361 * 3:-c 4:<cmd> <argN...> 5:NULL
2363 cnt = 5 + G.global_argc;
2364 for (cur = G.top_var; cur; cur = cur->next) {
2365 if (!cur->flg_export || cur->flg_read_only)
2368 G.argv_from_re_execing = pp = xzalloc(sizeof(argv[0]) * cnt);
2369 *pp++ = (char *) G.argv0_for_re_execing;
2371 for (cur = G.top_var; cur; cur = cur->next) {
2372 if (cur->varstr == hush_version_str)
2374 if (cur->flg_read_only) {
2375 *pp++ = (char *) "-R";
2376 *pp++ = cur->varstr;
2377 } else if (!cur->flg_export) {
2378 *pp++ = (char *) "-V";
2379 *pp++ = cur->varstr;
2382 //TODO: pass functions
2383 /* We can pass activated traps here. Say, -Tnn:trap_string
2385 * However, POSIX says that subshells reset signals with traps
2387 * I tested bash-3.2 and it not only does that with true subshells
2388 * of the form ( list ), but with any forked children shells.
2389 * I set trap "echo W" WINCH; and then tried:
2391 * { echo 1; sleep 20; echo 2; } &
2392 * while true; do echo 1; sleep 20; echo 2; break; done &
2393 * true | { echo 1; sleep 20; echo 2; } | cat
2395 * In all these cases sending SIGWINCH to the child shell
2396 * did not run the trap. If I add trap "echo V" WINCH;
2397 * _inside_ group (just before echo 1), it works.
2399 * I conclude it means we don't need to pass active traps here.
2400 * exec syscall below resets them to SIG_DFL for us.
2402 *pp++ = (char *) "-c";
2404 pp2 = G.global_argv;
2407 /* *pp = NULL; - is already there */
2409 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
2410 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2411 execv(bb_busybox_exec_path, G.argv_from_re_execing);
2412 /* Fallback. Useful for init=/bin/hush usage etc */
2413 if (G.argv0_for_re_execing[0] == '/')
2414 execv(G.argv0_for_re_execing, G.argv_from_re_execing);
2415 xfunc_error_retval = 127;
2416 bb_error_msg_and_die("can't re-execute the shell");
2419 static void clean_up_after_re_execute(void)
2421 char **pp = G.argv_from_re_execing;
2423 /* Must match re_execute_shell's allocations (if any) */
2425 G.argv_from_re_execing = NULL;
2430 static int run_list(struct pipe *pi);
2432 /* Called after [v]fork() in run_pipe
2434 static void pseudo_exec(nommu_save_t *nommu_save,
2435 struct command *command,
2436 char **argv_expanded) NORETURN;
2437 static void pseudo_exec(nommu_save_t *nommu_save,
2438 struct command *command,
2439 char **argv_expanded)
2441 if (command->argv) {
2442 pseudo_exec_argv(nommu_save, command->argv,
2443 command->assignment_cnt, argv_expanded);
2446 if (command->group) {
2447 /* Cases when we are here:
2450 * ... | ( list ) | ...
2451 * ... | { list } | ...
2455 debug_printf_exec("pseudo_exec: run_list\n");
2456 reset_traps_to_defaults();
2457 rcode = run_list(command->group);
2458 /* OK to leak memory by not calling free_pipe_list,
2459 * since this process is about to exit */
2462 re_execute_shell(command->group_as_string);
2466 /* Case when we are here: ... | >file */
2467 debug_printf_exec("pseudo_exec'ed null command\n");
2468 _exit(EXIT_SUCCESS);
2472 static const char *get_cmdtext(struct pipe *pi)
2478 /* This is subtle. ->cmdtext is created only on first backgrounding.
2479 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
2480 * On subsequent bg argv is trashed, but we won't use it */
2483 argv = pi->cmds[0].argv;
2484 if (!argv || !argv[0]) {
2485 pi->cmdtext = xzalloc(1);
2490 do len += strlen(*argv) + 1; while (*++argv);
2491 pi->cmdtext = p = xmalloc(len);
2492 argv = pi->cmds[0].argv;
2494 len = strlen(*argv);
2495 memcpy(p, *argv, len);
2503 static void insert_bg_job(struct pipe *pi)
2505 struct pipe *thejob;
2508 /* Linear search for the ID of the job to use */
2510 for (thejob = G.job_list; thejob; thejob = thejob->next)
2511 if (thejob->jobid >= pi->jobid)
2512 pi->jobid = thejob->jobid + 1;
2514 /* Add thejob to the list of running jobs */
2516 thejob = G.job_list = xmalloc(sizeof(*thejob));
2518 for (thejob = G.job_list; thejob->next; thejob = thejob->next)
2520 thejob->next = xmalloc(sizeof(*thejob));
2521 thejob = thejob->next;
2524 /* Physically copy the struct job */
2525 memcpy(thejob, pi, sizeof(struct pipe));
2526 thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
2527 /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
2528 for (i = 0; i < pi->num_cmds; i++) {
2529 // TODO: do we really need to have so many fields which are just dead weight
2530 // at execution stage?
2531 thejob->cmds[i].pid = pi->cmds[i].pid;
2532 /* all other fields are not used and stay zero */
2534 thejob->next = NULL;
2535 thejob->cmdtext = xstrdup(get_cmdtext(pi));
2537 /* We don't wait for background thejobs to return -- append it
2538 to the list of backgrounded thejobs and leave it alone */
2539 if (G_interactive_fd)
2540 printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
2541 G.last_bg_pid = thejob->cmds[0].pid;
2542 G.last_jobid = thejob->jobid;
2545 static void remove_bg_job(struct pipe *pi)
2547 struct pipe *prev_pipe;
2549 if (pi == G.job_list) {
2550 G.job_list = pi->next;
2552 prev_pipe = G.job_list;
2553 while (prev_pipe->next != pi)
2554 prev_pipe = prev_pipe->next;
2555 prev_pipe->next = pi->next;
2558 G.last_jobid = G.job_list->jobid;
2563 /* Remove a backgrounded job */
2564 static void delete_finished_bg_job(struct pipe *pi)
2567 pi->stopped_cmds = 0;
2573 /* Check to see if any processes have exited -- if they
2574 * have, figure out why and see if a job has completed */
2575 static int checkjobs(struct pipe* fg_pipe)
2585 debug_printf_jobs("checkjobs %p\n", fg_pipe);
2588 // if (G.handled_SIGCHLD == G.count_SIGCHLD)
2589 // /* avoid doing syscall, nothing there anyway */
2592 attributes = WUNTRACED;
2593 if (fg_pipe == NULL)
2594 attributes |= WNOHANG;
2596 /* Do we do this right?
2597 * bash-3.00# sleep 20 | false
2599 * [3]+ Stopped sleep 20 | false
2600 * bash-3.00# echo $?
2601 * 1 <========== bg pipe is not fully done, but exitcode is already known!
2604 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
2605 //are stopped. Testcase: "cat | cat" in a script (not on command line)
2606 // + killall -STOP cat
2613 // i = G.count_SIGCHLD;
2614 childpid = waitpid(-1, &status, attributes);
2615 if (childpid <= 0) {
2616 if (childpid && errno != ECHILD)
2617 bb_perror_msg("waitpid");
2618 // else /* Until next SIGCHLD, waitpid's are useless */
2619 // G.handled_SIGCHLD = i;
2622 dead = WIFEXITED(status) || WIFSIGNALED(status);
2625 if (WIFSTOPPED(status))
2626 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
2627 childpid, WSTOPSIG(status), WEXITSTATUS(status));
2628 if (WIFSIGNALED(status))
2629 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
2630 childpid, WTERMSIG(status), WEXITSTATUS(status));
2631 if (WIFEXITED(status))
2632 debug_printf_jobs("pid %d exited, exitcode %d\n",
2633 childpid, WEXITSTATUS(status));
2635 /* Were we asked to wait for fg pipe? */
2637 for (i = 0; i < fg_pipe->num_cmds; i++) {
2638 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
2639 if (fg_pipe->cmds[i].pid != childpid)
2641 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
2643 fg_pipe->cmds[i].pid = 0;
2644 fg_pipe->alive_cmds--;
2645 if (i == fg_pipe->num_cmds - 1) {
2646 /* last process gives overall exitstatus */
2647 rcode = WEXITSTATUS(status);
2648 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
2651 fg_pipe->cmds[i].is_stopped = 1;
2652 fg_pipe->stopped_cmds++;
2654 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
2655 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
2656 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
2657 /* All processes in fg pipe have exited/stopped */
2659 if (fg_pipe->alive_cmds)
2660 insert_bg_job(fg_pipe);
2664 /* There are still running processes in the fg pipe */
2665 goto wait_more; /* do waitpid again */
2667 /* it wasnt fg_pipe, look for process in bg pipes */
2671 /* We asked to wait for bg or orphaned children */
2672 /* No need to remember exitcode in this case */
2673 for (pi = G.job_list; pi; pi = pi->next) {
2674 for (i = 0; i < pi->num_cmds; i++) {
2675 if (pi->cmds[i].pid == childpid)
2676 goto found_pi_and_prognum;
2679 /* Happens when shell is used as init process (init=/bin/sh) */
2680 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
2681 continue; /* do waitpid again */
2683 found_pi_and_prognum:
2686 pi->cmds[i].pid = 0;
2688 if (!pi->alive_cmds) {
2689 if (G_interactive_fd)
2690 printf(JOB_STATUS_FORMAT, pi->jobid,
2691 "Done", pi->cmdtext);
2692 delete_finished_bg_job(pi);
2696 pi->cmds[i].is_stopped = 1;
2700 } /* while (waitpid succeeds)... */
2706 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
2709 int rcode = checkjobs(fg_pipe);
2710 /* Job finished, move the shell to the foreground */
2711 p = getpgid(0); /* pgid of our process */
2712 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
2713 tcsetpgrp(G_interactive_fd, p);
2718 /* Start all the jobs, but don't wait for anything to finish.
2721 * Return code is normally -1, when the caller has to wait for children
2722 * to finish to determine the exit status of the pipe. If the pipe
2723 * is a simple builtin command, however, the action is done by the
2724 * time run_pipe returns, and the exit code is provided as the
2727 * Returns -1 only if started some children. IOW: we have to
2728 * mask out retvals of builtins etc with 0xff!
2730 * The only case when we do not need to [v]fork is when the pipe
2731 * is single, non-backgrounded, non-subshell command. Examples:
2732 * cmd ; ... { list } ; ...
2733 * cmd && ... { list } && ...
2734 * cmd || ... { list } || ...
2735 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
2736 * or (if SH_STANDALONE) an applet, and we can run the { list }
2737 * with run_list(). If it isn't one of these, we fork and exec cmd.
2739 * Cases when we must fork:
2740 * non-single: cmd | cmd
2741 * backgrounded: cmd & { list } &
2742 * subshell: ( list ) [&]
2744 static int run_pipe(struct pipe *pi)
2746 static const char *const null_ptr = NULL;
2749 int pipefds[2]; /* pipefds[0] is for reading */
2750 struct command *command;
2751 char **argv_expanded;
2754 /* it is not always needed, but we aim to smaller code */
2755 int squirrel[] = { -1, -1, -1 };
2758 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
2760 USE_HUSH_JOB(pi->pgrp = -1;)
2761 pi->stopped_cmds = 0;
2762 command = &(pi->cmds[0]);
2763 argv_expanded = NULL;
2765 if (pi->num_cmds != 1
2766 || pi->followup == PIPE_BG
2767 || command->grp_type == GRP_SUBSHELL
2774 debug_printf_exec(": group:%p argv:'%s'\n",
2775 command->group, command->argv ? command->argv[0] : "NONE");
2777 if (command->group) {
2778 #if ENABLE_HUSH_FUNCTIONS
2779 if (command->grp_type == GRP_FUNCTION) {
2780 /* func () { list } */
2781 bb_error_msg("here we ought to remember function definition, and go on");
2782 return EXIT_SUCCESS;
2786 debug_printf("non-subshell group\n");
2787 setup_redirects(command, squirrel);
2788 debug_printf_exec(": run_list\n");
2789 rcode = run_list(command->group) & 0xff;
2790 restore_redirects(squirrel);
2791 debug_printf_exec("run_pipe return %d\n", rcode);
2792 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2796 argv = command->argv ? command->argv : (char **) &null_ptr;
2798 const struct built_in_command *x;
2799 char **new_env = NULL;
2800 char **old_env = NULL;
2802 if (argv[command->assignment_cnt] == NULL) {
2803 /* Assignments, but no command */
2804 /* Ensure redirects take effect. Try "a=t >file" */
2805 setup_redirects(command, squirrel);
2806 restore_redirects(squirrel);
2807 /* Set shell variables */
2809 p = expand_string_to_string(*argv);
2810 debug_printf_exec("set shell var:'%s'->'%s'\n",
2812 set_local_var(p, 0, 0);
2815 /* Do we need to flag set_local_var() errors?
2816 * "assignment to readonly var" and "putenv error"
2818 return EXIT_SUCCESS;
2821 /* Expand the rest into (possibly) many strings each */
2822 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
2824 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2825 if (strcmp(argv_expanded[0], x->cmd) != 0)
2827 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
2828 debug_printf("exec with redirects only\n");
2829 setup_redirects(command, NULL);
2830 rcode = EXIT_SUCCESS;
2831 goto clean_up_and_ret1;
2833 debug_printf("builtin inline %s\n", argv_expanded[0]);
2834 /* XXX setup_redirects acts on file descriptors, not FILEs.
2835 * This is perfect for work that comes after exec().
2836 * Is it really safe for inline use? Experimentally,
2837 * things seem to work with glibc. */
2838 setup_redirects(command, squirrel);
2839 new_env = expand_assignments(argv, command->assignment_cnt);
2840 old_env = putenv_all_and_save_old(new_env);
2841 debug_printf_exec(": builtin '%s' '%s'...\n",
2842 x->cmd, argv_expanded[1]);
2843 rcode = x->function(argv_expanded) & 0xff;
2844 #if ENABLE_FEATURE_SH_STANDALONE
2847 restore_redirects(squirrel);
2848 free_strings_and_unsetenv(new_env, 1);
2849 putenv_all(old_env);
2850 free(old_env); /* not free_strings()! */
2852 free(argv_expanded);
2853 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2854 debug_printf_exec("run_pipe return %d\n", rcode);
2857 #if ENABLE_FEATURE_SH_STANDALONE
2858 i = find_applet_by_name(argv_expanded[0]);
2859 if (i >= 0 && APPLET_IS_NOFORK(i)) {
2860 setup_redirects(command, squirrel);
2861 save_nofork_data(&G.nofork_save);
2862 new_env = expand_assignments(argv, command->assignment_cnt);
2863 old_env = putenv_all_and_save_old(new_env);
2864 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
2865 argv_expanded[0], argv_expanded[1]);
2866 rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
2867 goto clean_up_and_ret;
2870 /* It is neither builtin nor applet. We must fork. */
2874 /* NB: argv_expanded may already be created, and that
2875 * might include `cmd` runs! Do not rerun it! We *must*
2876 * use argv_expanded if it's non-NULL */
2878 /* Going to fork a child per each pipe member */
2882 for (i = 0; i < pi->num_cmds; i++) {
2884 volatile nommu_save_t nommu_save;
2885 nommu_save.new_env = NULL;
2886 nommu_save.old_env = NULL;
2887 nommu_save.argv = NULL;
2889 command = &(pi->cmds[i]);
2890 if (command->argv) {
2891 debug_printf_exec(": pipe member '%s' '%s'...\n",
2892 command->argv[0], command->argv[1]);
2894 debug_printf_exec(": pipe member with no argv\n");
2897 /* pipes are inserted between pairs of commands */
2900 if ((i + 1) < pi->num_cmds)
2903 command->pid = BB_MMU ? fork() : vfork();
2904 if (!command->pid) { /* child */
2906 die_sleep = 0; /* do not restore tty pgrp on xfunc death */
2908 /* Every child adds itself to new process group
2909 * with pgid == pid_of_first_child_in_pipe */
2910 if (G.run_list_level == 1 && G_interactive_fd) {
2913 if (pgrp < 0) /* true for 1st process only */
2915 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
2916 /* We do it in *every* child, not just first,
2918 tcsetpgrp(G_interactive_fd, pgrp);
2922 xmove_fd(nextin, 0);
2923 xmove_fd(pipefds[1], 1); /* write end */
2925 close(pipefds[0]); /* read end */
2926 /* Like bash, explicit redirects override pipes,
2927 * and the pipe fd is available for dup'ing. */
2928 setup_redirects(command, NULL);
2930 /* Restore default handlers just prior to exec */
2931 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
2933 /* Stores to nommu_save list of env vars putenv'ed
2934 * (NOMMU, on MMU we don't need that) */
2935 /* cast away volatility... */
2936 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
2937 /* pseudo_exec() does not return */
2940 /* parent or error */
2942 die_sleep = -1; /* restore tty pgrp on xfunc death */
2945 /* Clean up after vforked child */
2946 clean_up_after_re_execute();
2947 free(nommu_save.argv);
2948 free_strings_and_unsetenv(nommu_save.new_env, 1);
2949 putenv_all(nommu_save.old_env);
2951 free(argv_expanded);
2952 argv_expanded = NULL;
2953 if (command->pid < 0) { /* [v]fork failed */
2954 /* Clearly indicate, was it fork or vfork */
2955 bb_perror_msg(BB_MMU ? "fork" : "vfork");
2959 /* Second and next children need to know pid of first one */
2961 pi->pgrp = command->pid;
2967 if ((i + 1) < pi->num_cmds)
2968 close(pipefds[1]); /* write end */
2969 /* Pass read (output) pipe end to next iteration */
2970 nextin = pipefds[0];
2973 if (!pi->alive_cmds) {
2974 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
2978 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
2982 #ifndef debug_print_tree
2983 static void debug_print_tree(struct pipe *pi, int lvl)
2985 static const char *const PIPE[] = {
2991 static const char *RES[] = {
2992 [RES_NONE ] = "NONE" ,
2995 [RES_THEN ] = "THEN" ,
2996 [RES_ELIF ] = "ELIF" ,
2997 [RES_ELSE ] = "ELSE" ,
3000 #if ENABLE_HUSH_LOOPS
3001 [RES_FOR ] = "FOR" ,
3002 [RES_WHILE] = "WHILE",
3003 [RES_UNTIL] = "UNTIL",
3005 [RES_DONE ] = "DONE" ,
3007 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3010 #if ENABLE_HUSH_CASE
3011 [RES_CASE ] = "CASE" ,
3012 [RES_MATCH] = "MATCH",
3013 [RES_CASEI] = "CASEI",
3014 [RES_ESAC ] = "ESAC" ,
3016 [RES_XXXX ] = "XXXX" ,
3017 [RES_SNTX ] = "SNTX" ,
3019 static const char *const GRPTYPE[] = {
3022 #if ENABLE_HUSH_FUNCTIONS
3031 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3032 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3034 while (prn < pi->num_cmds) {
3035 struct command *command = &pi->cmds[prn];
3036 char **argv = command->argv;
3038 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
3040 command->assignment_cnt);
3041 if (command->group) {
3042 fprintf(stderr, " group %s: (argv=%p)\n",
3043 GRPTYPE[command->grp_type],
3045 debug_print_tree(command->group, lvl+1);
3049 if (argv) while (*argv) {
3050 fprintf(stderr, " '%s'", *argv);
3053 fprintf(stderr, "\n");
3062 /* NB: called by pseudo_exec, and therefore must not modify any
3063 * global data until exec/_exit (we can be a child after vfork!) */
3064 static int run_list(struct pipe *pi)
3066 #if ENABLE_HUSH_CASE
3067 char *case_word = NULL;
3069 #if ENABLE_HUSH_LOOPS
3070 struct pipe *loop_top = NULL;
3071 char *for_varname = NULL;
3072 char **for_lcur = NULL;
3073 char **for_list = NULL;
3075 smallint last_followup;
3077 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
3078 smalluint cond_code = 0;
3080 enum { cond_code = 0 };
3083 smallint rword; /* enum reserved_style */
3084 smallint last_rword; /* ditto */
3087 debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
3089 #if ENABLE_HUSH_LOOPS
3090 /* Check syntax for "for" */
3091 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
3092 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
3094 /* current word is FOR or IN (BOLD in comments below) */
3095 if (cpipe->next == NULL) {
3096 syntax("malformed for");
3097 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
3100 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
3101 if (cpipe->next->res_word == RES_DO)
3103 /* next word is not "do". It must be "in" then ("FOR v in ...") */
3104 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
3105 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
3107 syntax("malformed for");
3108 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
3114 /* Past this point, all code paths should jump to ret: label
3115 * in order to return, no direct "return" statements please.
3116 * This helps to ensure that no memory is leaked. */
3118 ////TODO: ctrl-Z handling needs re-thinking and re-testing
3121 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
3122 * We are saving state before entering outermost list ("while...done")
3123 * so that ctrl-Z will correctly background _entire_ outermost list,
3124 * not just a part of it (like "sleep 1 | exit 2") */
3125 if (++G.run_list_level == 1 && G_interactive_fd) {
3126 if (sigsetjmp(G.toplevel_jb, 1)) {
3127 /* ctrl-Z forked and we are parent; or ctrl-C.
3128 * Sighandler has longjmped us here */
3129 signal(SIGINT, SIG_IGN);
3130 signal(SIGTSTP, SIG_IGN);
3131 /* Restore level (we can be coming from deep inside
3133 G.run_list_level = 1;
3134 #if ENABLE_FEATURE_SH_STANDALONE
3135 if (G.nofork_save.saved) { /* if save area is valid */
3136 debug_printf_jobs("exiting nofork early\n");
3137 restore_nofork_data(&G.nofork_save);
3140 //// if (G.ctrl_z_flag) {
3141 //// /* ctrl-Z has forked and stored pid of the child in pi->pid.
3142 //// * Remember this child as background job */
3143 //// insert_bg_job(pi);
3145 /* ctrl-C. We just stop doing whatever we were doing */
3148 USE_HUSH_LOOPS(loop_top = NULL;)
3149 USE_HUSH_LOOPS(G.depth_of_loop = 0;)
3153 //// /* ctrl-Z handler will store pid etc in pi */
3154 //// G.toplevel_list = pi;
3155 //// G.ctrl_z_flag = 0;
3156 ////#if ENABLE_FEATURE_SH_STANDALONE
3157 //// G.nofork_save.saved = 0; /* in case we will run a nofork later */
3159 //// signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
3160 //// signal(SIGINT, handler_ctrl_c);
3166 last_rword = RES_XXXX;
3168 last_followup = PIPE_SEQ;
3169 rcode = G.last_exitcode;
3171 /* Go through list of pipes, (maybe) executing them. */
3172 for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
3176 IF_HAS_KEYWORDS(rword = pi->res_word;)
3177 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
3178 rword, cond_code, last_rword);
3179 #if ENABLE_HUSH_LOOPS
3180 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
3181 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
3183 /* start of a loop: remember where loop starts */
3188 /* Still in the same "if...", "then..." or "do..." branch? */
3189 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
3190 if ((rcode == 0 && last_followup == PIPE_OR)
3191 || (rcode != 0 && last_followup == PIPE_AND)
3193 /* It is "<true> || CMD" or "<false> && CMD"
3194 * and we should not execute CMD */
3195 debug_printf_exec("skipped cmd because of || or &&\n");
3196 last_followup = pi->followup;
3200 last_followup = pi->followup;
3201 IF_HAS_KEYWORDS(last_rword = rword;)
3204 if (rword == RES_THEN) {
3205 /* if false; then ... fi has exitcode 0! */
3206 G.last_exitcode = rcode = EXIT_SUCCESS;
3207 /* "if <false> THEN cmd": skip cmd */
3211 if (rword == RES_ELSE || rword == RES_ELIF) {
3212 /* "if <true> then ... ELSE/ELIF cmd":
3213 * skip cmd and all following ones */
3218 #if ENABLE_HUSH_LOOPS
3219 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
3221 /* first loop through for */
3223 static const char encoded_dollar_at[] ALIGN1 = {
3224 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
3225 }; /* encoded representation of "$@" */
3226 static const char *const encoded_dollar_at_argv[] = {
3227 encoded_dollar_at, NULL
3228 }; /* argv list with one element: "$@" */
3231 vals = (char**)encoded_dollar_at_argv;
3232 if (pi->next->res_word == RES_IN) {
3233 /* if no variable values after "in" we skip "for" */
3234 if (!pi->next->cmds[0].argv) {
3235 G.last_exitcode = rcode = EXIT_SUCCESS;
3236 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
3239 vals = pi->next->cmds[0].argv;
3240 } /* else: "for var; do..." -> assume "$@" list */
3241 /* create list of variable values */
3242 debug_print_strings("for_list made from", vals);
3243 for_list = expand_strvec_to_strvec(vals);
3244 for_lcur = for_list;
3245 debug_print_strings("for_list", for_list);
3246 for_varname = pi->cmds[0].argv[0];
3247 pi->cmds[0].argv[0] = NULL;
3249 free(pi->cmds[0].argv[0]);
3251 /* "for" loop is over, clean up */
3255 pi->cmds[0].argv[0] = for_varname;
3258 /* Insert next value from for_lcur */
3259 //TODO: does it need escaping?
3260 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
3261 pi->cmds[0].assignment_cnt = 1;
3263 if (rword == RES_IN) {
3264 continue; /* "for v IN list;..." - "in" has no cmds anyway */
3266 if (rword == RES_DONE) {
3267 continue; /* "done" has no cmds too */
3270 #if ENABLE_HUSH_CASE
3271 if (rword == RES_CASE) {
3272 case_word = expand_strvec_to_string(pi->cmds->argv);
3275 if (rword == RES_MATCH) {
3278 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
3280 /* all prev words didn't match, does this one match? */
3281 argv = pi->cmds->argv;
3283 char *pattern = expand_string_to_string(*argv);
3284 /* TODO: which FNM_xxx flags to use? */
3285 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
3287 if (cond_code == 0) { /* match! we will execute this branch */
3288 free(case_word); /* make future "word)" stop */
3296 if (rword == RES_CASEI) { /* inside of a case branch */
3298 continue; /* not matched yet, skip this pipe */
3301 /* Just pressing <enter> in shell should check for jobs.
3302 * OTOH, in non-interactive shell this is useless
3303 * and only leads to extra job checks */
3304 if (pi->num_cmds == 0) {
3305 if (G_interactive_fd)
3306 goto check_jobs_and_continue;
3310 /* After analyzing all keywords and conditions, we decided
3311 * to execute this pipe. NB: have to do checkjobs(NULL)
3312 * after run_pipe to collect any background children,
3313 * even if list execution is to be stopped. */
3314 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
3317 #if ENABLE_HUSH_LOOPS
3318 G.flag_break_continue = 0;
3320 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
3322 /* We only ran a builtin: rcode is already known
3323 * and we don't need to wait for anything. */
3324 G.last_exitcode = rcode;
3325 debug_printf_exec(": builtin exitcode %d\n", rcode);
3326 check_and_run_traps(0);
3327 #if ENABLE_HUSH_LOOPS
3328 /* Was it "break" or "continue"? */
3329 if (G.flag_break_continue) {
3330 smallint fbc = G.flag_break_continue;
3331 /* We might fall into outer *loop*,
3332 * don't want to break it too */
3334 G.depth_break_continue--;
3335 if (G.depth_break_continue == 0)
3336 G.flag_break_continue = 0;
3337 /* else: e.g. "continue 2" should *break* once, *then* continue */
3338 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
3339 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
3340 goto check_jobs_and_break;
3341 /* "continue": simulate end of loop */
3346 } else if (pi->followup == PIPE_BG) {
3347 /* What does bash do with attempts to background builtins? */
3348 /* even bash 3.2 doesn't do that well with nested bg:
3349 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
3350 * I'm NOT treating inner &'s as jobs */
3351 check_and_run_traps(0);
3353 if (G.run_list_level == 1)
3356 G.last_exitcode = rcode = EXIT_SUCCESS;
3357 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
3360 if (G.run_list_level == 1 && G_interactive_fd) {
3361 /* Waits for completion, then fg's main shell */
3362 rcode = checkjobs_and_fg_shell(pi);
3363 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
3364 check_and_run_traps(0);
3367 { /* This one just waits for completion */
3368 rcode = checkjobs(pi);
3369 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
3370 check_and_run_traps(0);
3372 G.last_exitcode = rcode;
3376 /* Analyze how result affects subsequent commands */
3378 if (rword == RES_IF || rword == RES_ELIF)
3381 #if ENABLE_HUSH_LOOPS
3382 /* Beware of "while false; true; do ..."! */
3383 if (pi->next && pi->next->res_word == RES_DO) {
3384 if (rword == RES_WHILE) {
3386 /* "while false; do...done" - exitcode 0 */
3387 G.last_exitcode = rcode = EXIT_SUCCESS;
3388 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
3389 goto check_jobs_and_break;
3392 if (rword == RES_UNTIL) {
3394 debug_printf_exec(": until expr is true: breaking\n");
3395 check_jobs_and_break:
3403 check_jobs_and_continue:
3408 //// if (G.ctrl_z_flag) {
3409 //// /* ctrl-Z forked somewhere in the past, we are the child,
3410 //// * and now we completed running the list. Exit. */
3416 //// if (!G.run_list_level && G_interactive_fd) {
3417 //// signal(SIGTSTP, SIG_IGN);
3418 //// signal(SIGINT, SIG_IGN);
3421 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
3422 #if ENABLE_HUSH_LOOPS
3427 #if ENABLE_HUSH_CASE
3433 /* Select which version we will use */
3434 static int run_and_free_list(struct pipe *pi)
3437 debug_printf_exec("run_and_free_list entered\n");
3439 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
3440 rcode = run_list(pi);
3442 /* free_pipe_list has the side effect of clearing memory.
3443 * In the long run that function can be merged with run_list,
3444 * but doing that now would hobble the debugging effort. */
3445 free_pipe_list(pi, /* indent: */ 0);
3446 debug_printf_exec("run_and_free_list return %d\n", rcode);
3451 static struct pipe *new_pipe(void)
3454 pi = xzalloc(sizeof(struct pipe));
3455 /*pi->followup = 0; - deliberately invalid value */
3456 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3460 /* Command (member of a pipe) is complete. The only possible error here
3461 * is out of memory, in which case xmalloc exits. */
3462 static int done_command(struct parse_context *ctx)
3464 /* The command is really already in the pipe structure, so
3465 * advance the pipe counter and make a new, null command. */
3466 struct pipe *pi = ctx->pipe;
3467 struct command *command = ctx->command;
3470 if (command->group == NULL
3471 && command->argv == NULL
3472 && command->redirects == NULL
3474 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3475 memset(command, 0, sizeof(*command)); /* paranoia */
3476 return pi->num_cmds;
3479 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3480 //debug_print_tree(ctx->list_head, 20);
3482 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3485 /* Only real trickiness here is that the uncommitted
3486 * command structure is not counted in pi->num_cmds. */
3487 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3488 command = &pi->cmds[pi->num_cmds];
3489 memset(command, 0, sizeof(*command));
3491 ctx->command = command;
3492 /* but ctx->pipe and ctx->list_head remain unchanged */
3494 return pi->num_cmds; /* used only for 0/nonzero check */
3497 static void done_pipe(struct parse_context *ctx, pipe_style type)
3501 debug_printf_parse("done_pipe entered, followup %d\n", type);
3502 /* Close previous command */
3503 not_null = done_command(ctx);
3504 ctx->pipe->followup = type;
3506 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3507 ctx->ctx_inverted = 0;
3508 ctx->pipe->res_word = ctx->ctx_res_w;
3511 /* Without this check, even just <enter> on command line generates
3512 * tree of three NOPs (!). Which is harmless but annoying.
3513 * IOW: it is safe to do it unconditionally.
3514 * RES_NONE case is for "for a in; do ..." (empty IN set)
3515 * and other cases to work. */
3518 || ctx->ctx_res_w == RES_FI
3519 || ctx->ctx_res_w == RES_DONE
3520 || ctx->ctx_res_w == RES_FOR
3521 || ctx->ctx_res_w == RES_IN
3522 || ctx->ctx_res_w == RES_ESAC
3526 debug_printf_parse("done_pipe: adding new pipe: "
3527 "not_null:%d ctx->ctx_res_w:%d\n",
3528 not_null, ctx->ctx_res_w);
3530 ctx->pipe->next = new_p;
3532 /* RES_THEN, RES_DO etc are "sticky" -
3533 * they remain set for commands inside if/while.
3534 * This is used to control execution.
3535 * RES_FOR and RES_IN are NOT sticky (needed to support
3536 * cases where variable or value happens to match a keyword):
3538 #if ENABLE_HUSH_LOOPS
3539 if (ctx->ctx_res_w == RES_FOR
3540 || ctx->ctx_res_w == RES_IN)
3541 ctx->ctx_res_w = RES_NONE;
3543 #if ENABLE_HUSH_CASE
3544 if (ctx->ctx_res_w == RES_MATCH)
3545 ctx->ctx_res_w = RES_CASEI;
3547 ctx->command = NULL; /* trick done_command below */
3548 /* Create the memory for command, roughly:
3549 * ctx->pipe->cmds = new struct command;
3550 * ctx->command = &ctx->pipe->cmds[0];
3553 //debug_print_tree(ctx->list_head, 10);
3555 debug_printf_parse("done_pipe return\n");
3558 static void initialize_context(struct parse_context *ctx)
3560 memset(ctx, 0, sizeof(*ctx));
3561 ctx->pipe = ctx->list_head = new_pipe();
3562 /* Create the memory for command, roughly:
3563 * ctx->pipe->cmds = new struct command;
3564 * ctx->command = &ctx->pipe->cmds[0];
3569 /* If a reserved word is found and processed, parse context is modified
3570 * and 1 is returned.
3573 struct reserved_combo {
3576 unsigned char assignment_flag;
3580 FLAG_END = (1 << RES_NONE ),
3582 FLAG_IF = (1 << RES_IF ),
3583 FLAG_THEN = (1 << RES_THEN ),
3584 FLAG_ELIF = (1 << RES_ELIF ),
3585 FLAG_ELSE = (1 << RES_ELSE ),
3586 FLAG_FI = (1 << RES_FI ),
3588 #if ENABLE_HUSH_LOOPS
3589 FLAG_FOR = (1 << RES_FOR ),
3590 FLAG_WHILE = (1 << RES_WHILE),
3591 FLAG_UNTIL = (1 << RES_UNTIL),
3592 FLAG_DO = (1 << RES_DO ),
3593 FLAG_DONE = (1 << RES_DONE ),
3594 FLAG_IN = (1 << RES_IN ),
3596 #if ENABLE_HUSH_CASE
3597 FLAG_MATCH = (1 << RES_MATCH),
3598 FLAG_ESAC = (1 << RES_ESAC ),
3600 FLAG_START = (1 << RES_XXXX ),
3603 static const struct reserved_combo* match_reserved_word(o_string *word)
3605 /* Mostly a list of accepted follow-up reserved words.
3606 * FLAG_END means we are done with the sequence, and are ready
3607 * to turn the compound list into a command.
3608 * FLAG_START means the word must start a new compound list.
3610 static const struct reserved_combo reserved_list[] = {
3612 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3613 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
3614 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3615 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
3616 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
3617 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3619 #if ENABLE_HUSH_LOOPS
3620 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3621 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3622 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3623 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3624 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
3625 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3627 #if ENABLE_HUSH_CASE
3628 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3629 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3632 const struct reserved_combo *r;
3634 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3635 if (strcmp(word->data, r->literal) == 0)
3640 static int reserved_word(o_string *word, struct parse_context *ctx)
3642 #if ENABLE_HUSH_CASE
3643 static const struct reserved_combo reserved_match = {
3644 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3647 const struct reserved_combo *r;
3649 r = match_reserved_word(word);
3653 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3654 #if ENABLE_HUSH_CASE
3655 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
3656 /* "case word IN ..." - IN part starts first match part */
3657 r = &reserved_match;
3660 if (r->flag == 0) { /* '!' */
3661 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3662 syntax("! ! command");
3663 IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
3665 ctx->ctx_inverted = 1;
3668 if (r->flag & FLAG_START) {
3669 struct parse_context *old;
3670 old = xmalloc(sizeof(*old));
3671 debug_printf_parse("push stack %p\n", old);
3672 *old = *ctx; /* physical copy */
3673 initialize_context(ctx);
3675 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3677 ctx->ctx_res_w = RES_SNTX;
3680 ctx->ctx_res_w = r->res;
3681 ctx->old_flag = r->flag;
3682 if (ctx->old_flag & FLAG_END) {
3683 struct parse_context *old;
3684 done_pipe(ctx, PIPE_SEQ);
3685 debug_printf_parse("pop stack %p\n", ctx->stack);
3687 old->command->group = ctx->list_head;
3688 old->command->grp_type = GRP_NORMAL;
3690 o_addstr(&old->as_string, ctx->as_string.data);
3691 o_free_unsafe(&ctx->as_string);
3692 old->command->group_as_string = xstrdup(old->as_string.data);
3693 debug_printf_parse("pop, remembering as:'%s'\n",
3694 old->command->group_as_string);
3696 *ctx = *old; /* physical copy */
3699 word->o_assignment = r->assignment_flag;
3704 /* Word is complete, look at it and update parsing context.
3705 * Normal return is 0. Syntax errors return 1.
3706 * Note: on return, word is reset, but not o_free'd!
3708 static int done_word(o_string *word, struct parse_context *ctx)
3710 struct command *command = ctx->command;
3712 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3713 if (word->length == 0 && word->nonnull == 0) {
3714 debug_printf_parse("done_word return 0: true null, ignored\n");
3717 /* If this word wasn't an assignment, next ones definitely
3718 * can't be assignments. Even if they look like ones. */
3719 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3720 && word->o_assignment != WORD_IS_KEYWORD
3722 word->o_assignment = NOT_ASSIGNMENT;
3724 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3725 command->assignment_cnt++;
3726 word->o_assignment = MAYBE_ASSIGNMENT;
3729 if (ctx->pending_redirect) {
3730 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3731 * only if run as "bash", not "sh" */
3732 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3734 * ...the word that follows the redirection operator
3735 * shall be subjected to tilde expansion, parameter expansion,
3736 * command substitution, arithmetic expansion, and quote
3737 * removal. Pathname expansion shall not be performed
3738 * on the word by a non-interactive shell; an interactive
3739 * shell may perform it, but shall do so only when
3740 * the expansion would result in one word."
3742 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3743 word->o_assignment = NOT_ASSIGNMENT;
3744 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3746 /* "{ echo foo; } echo bar" - bad */
3747 /* NB: bash allows e.g.:
3748 * if true; then { echo foo; } fi
3749 * while if false; then false; fi do break; done
3751 * while if false; then false; fi; do; break; done
3753 if (command->group) {
3755 debug_printf_parse("done_word return 1: syntax error, "
3756 "groups and arglists don't mix\n");
3760 #if ENABLE_HUSH_CASE
3761 if (ctx->ctx_dsemicolon
3762 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3764 /* already done when ctx_dsemicolon was set to 1: */
3765 /* ctx->ctx_res_w = RES_MATCH; */
3766 ctx->ctx_dsemicolon = 0;
3769 if (!command->argv /* if it's the first word... */
3770 #if ENABLE_HUSH_LOOPS
3771 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3772 && ctx->ctx_res_w != RES_IN
3775 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
3776 if (reserved_word(word, ctx)) {
3778 debug_printf_parse("done_word return %d\n",
3779 (ctx->ctx_res_w == RES_SNTX));
3780 return (ctx->ctx_res_w == RES_SNTX);
3784 if (word->nonnull /* word had "xx" or 'xx' at least as part of it. */
3785 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3786 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3787 /* (otherwise it's known to be not empty and is already safe) */
3789 /* exclude "$@" - it can expand to no word despite "" */
3790 char *p = word->data;
3791 while (p[0] == SPECIAL_VAR_SYMBOL
3792 && (p[1] & 0x7f) == '@'
3793 && p[2] == SPECIAL_VAR_SYMBOL
3797 if (p == word->data || p[0] != '\0') {
3798 /* saw no "$@", or not only "$@" but some
3799 * real text is there too */
3800 /* insert "empty variable" reference, this makes
3801 * e.g. "", $empty"" etc to not disappear */
3802 o_addchr(word, SPECIAL_VAR_SYMBOL);
3803 o_addchr(word, SPECIAL_VAR_SYMBOL);
3806 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3807 debug_print_strings("word appended to argv", command->argv);
3811 ctx->pending_redirect = NULL;
3813 #if ENABLE_HUSH_LOOPS
3814 /* Force FOR to have just one word (variable name) */
3815 /* NB: basically, this makes hush see "for v in ..." syntax as if
3816 * as it is "for v; in ...". FOR and IN become two pipe structs
3818 if (ctx->ctx_res_w == RES_FOR) {
3819 //TODO: check that command->argv[0] is a valid variable name!
3820 done_pipe(ctx, PIPE_SEQ);
3823 #if ENABLE_HUSH_CASE
3824 /* Force CASE to have just one word */
3825 if (ctx->ctx_res_w == RES_CASE) {
3826 done_pipe(ctx, PIPE_SEQ);
3829 debug_printf_parse("done_word return 0\n");
3834 /* Peek ahead in the input to find out if we have a "&n" construct,
3835 * as in "2>&1", that represents duplicating a file descriptor.
3836 * Return: -3 if >&- "close fd" construct is seen,
3837 * -2 (syntax error), -1 if no & was seen, or the number found.
3840 #define redirect_dup_num(as_string, input) \
3841 redirect_dup_num(input)
3843 static int redirect_dup_num(o_string *as_string, struct in_str *input)
3851 ch = i_getch(input); /* get the & */
3853 o_addchr(as_string, ch);
3857 ch = i_getch(input);
3859 o_addchr(as_string, ch);
3861 return -3; /* "-" represents "close me" */
3865 while (ch != EOF && isdigit(ch)) {
3866 d = d*10 + (ch-'0');
3868 ch = i_getch(input);
3870 o_addchr(as_string, ch);
3876 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3878 bb_error_msg("ambiguous redirect");
3882 /* Return code is 0 normally, 1 if a syntax error is detected
3884 static int parse_redirect(struct parse_context *ctx,
3887 struct in_str *input)
3889 struct command *command = ctx->command;
3890 struct redir_struct *redir;
3891 struct redir_struct **redirp;
3895 if (style != REDIRECT_HEREDOC) {
3896 /* Check for a '2>&1' type redirect */
3897 dup_num = redirect_dup_num(&ctx->as_string, input);
3899 return 1; /* syntax error */
3901 //TODO: else { check for <<-word }
3903 if (style == REDIRECT_OVERWRITE && dup_num == -1) {
3904 int ch = i_peek(input);
3906 /* >|FILE redirect ("clobbering" >).
3907 * Since we do not support "set -o noclobber" yet,
3908 * >| and > are the same for now. Just eat |.
3910 ch = i_getch(input);
3912 o_addchr(&ctx->as_string, ch);
3917 /* Create a new redir_struct and append it to the linked list */
3918 redirp = &command->redirects;
3919 while ((redir = *redirp) != NULL) {
3920 redirp = &(redir->next);
3922 *redirp = redir = xzalloc(sizeof(*redir));
3923 /* redir->next = NULL; */
3924 /* redir->rd_filename = NULL; */
3925 redir->rd_type = style;
3926 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
3928 debug_printf_parse("redirect type %d %s\n", redir->fd, redir_table[style].descrip);
3930 redir->dup = dup_num;
3931 if (dup_num != -1) {
3932 /* Erik had a check here that the file descriptor in question
3933 * is legit; I postpone that to "run time"
3934 * A "-" representation of "close me" shows up as a -3 here */
3935 debug_printf_parse("duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
3937 /* Set ctx->pending_redirect, so we know what to do at the
3938 * end of the next parsed word. */
3939 ctx->pending_redirect = redir;
3944 /* If a redirect is immediately preceded by a number, that number is
3945 * supposed to tell which file descriptor to redirect. This routine
3946 * looks for such preceding numbers. In an ideal world this routine
3947 * needs to handle all the following classes of redirects...
3948 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3949 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3950 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3951 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3953 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3955 * ... If n is quoted, the number shall not be recognized as part of
3956 * the redirection expression. For example:
3958 * writes the character 2 into file a"
3959 * I am not sure we do it right (and not sure we care)
3961 * A -1 return means no valid number was found,
3962 * the caller should use the appropriate default for this redirection.
3964 static int redirect_opt_num(o_string *o)
3968 if (o->data == NULL)
3970 num = bb_strtou(o->data, NULL, 10);
3971 if (errno || num < 0)
3977 //TODO: add NOMMU as_string fill
3978 static char *fetch_till_str(struct in_str *input, const char *word)
3980 o_string heredoc = NULL_O_STRING;
3985 ch = i_getch(input);
3987 o_free_unsafe(&heredoc);
3991 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3992 heredoc.data[past_EOL] = '\0';
3993 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3994 return heredoc.data;
3996 past_EOL = heredoc.length + 1;
3998 o_addchr(&heredoc, ch);
4002 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4004 struct pipe *pi = ctx->list_head;
4008 struct command *cmd = pi->cmds;
4010 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4012 cmd->argv ? cmd->argv[0] : "NONE");
4013 for (i = 0; i < pi->num_cmds; i++) {
4014 struct redir_struct *redirect = cmd->redirects;
4016 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4017 i, cmd->argv ? cmd->argv[0] : "NONE");
4019 if (redirect->rd_type == REDIRECT_HEREDOC) {
4022 if (heredoc_cnt <= 0)
4023 return 1; /* error */
4024 redirect->rd_type = REDIRECT_HEREDOC2;
4025 p = fetch_till_str(input, redirect->rd_filename);
4027 return 1; /* unexpected EOF */
4028 free(redirect->rd_filename);
4029 redirect->rd_filename = p;
4032 redirect = redirect->next;
4038 /* Should be 0. If it isn't, it's a parse error */
4044 #define parse_stream(pstring, input, end_trigger) \
4045 parse_stream(input, end_trigger)
4047 static struct pipe *parse_stream(char **pstring,
4048 struct in_str *input,
4050 static void parse_and_run_string(const char *s);
4052 #if ENABLE_HUSH_TICK
4053 static FILE *generate_stream_from_string(const char *s)
4056 int pid, channel[2];
4059 pid = BB_MMU ? fork() : vfork();
4061 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
4063 if (pid == 0) { /* child */
4065 die_sleep = 0; /* do not restore tty pgrp on xfunc death */
4067 /* Process substitution is not considered to be usual
4068 * 'command execution'.
4069 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
4076 close(channel[0]); /* NB: close _first_, then move fd! */
4077 xmove_fd(channel[1], 1);
4078 /* Prevent it from trying to handle ctrl-z etc */
4079 USE_HUSH_JOB(G.run_list_level = 1;)
4081 reset_traps_to_defaults();
4082 parse_and_run_string(s);
4083 _exit(G.last_exitcode);
4085 /* We re-execute after vfork on NOMMU. This makes this script safe:
4086 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
4087 * huge=`cat BIG` # was blocking here forever
4090 re_execute_shell(s);
4096 die_sleep = -1; /* restore tty pgrp on xfunc death */
4098 clean_up_after_re_execute();
4100 pf = fdopen(channel[0], "r");
4104 /* Return code is exit status of the process that is run. */
4105 static int process_command_subs(o_string *dest, const char *s)
4108 struct in_str pipe_str;
4111 pf = generate_stream_from_string(s);
4114 close_on_exec_on(fileno(pf));
4116 /* Now send results of command back into original context */
4117 setup_file_in_str(&pipe_str, pf);
4119 while ((ch = i_getch(&pipe_str)) != EOF) {
4125 o_addchr(dest, '\n');
4128 o_addQchr(dest, ch);
4131 debug_printf("done reading from pipe, pclose()ing\n");
4132 /* Note: we got EOF, and we just close the read end of the pipe.
4133 * We do not wait for the `cmd` child to terminate. bash and ash do.
4135 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
4136 * `false`; echo $? - bash outputs "1"
4139 debug_printf("closed FILE from child. return 0\n");
4144 static int parse_group(o_string *dest, struct parse_context *ctx,
4145 struct in_str *input, int ch)
4147 /* dest contains characters seen prior to ( or {.
4148 * Typically it's empty, but for function defs,
4149 * it contains function name (without '()'). */
4150 struct pipe *pipe_list;
4152 struct command *command = ctx->command;
4154 debug_printf_parse("parse_group entered\n");
4155 #if ENABLE_HUSH_FUNCTIONS
4156 if (ch == 'F') { /* function definition? */
4157 bb_error_msg("aha '%s' is a function, parsing it...", dest->data);
4158 //command->fname = dest->data;
4159 command->grp_type = GRP_FUNCTION;
4160 //TODO: review every o_reset() location... do they handle all o_string fields correctly?
4161 memset(dest, 0, sizeof(*dest));
4164 if (command->argv /* word [word](... */
4165 || dest->length /* word(... */
4166 || dest->nonnull /* ""(... */
4169 debug_printf_parse("parse_group return 1: "
4170 "syntax error, groups and arglists don't mix\n");
4176 command->grp_type = GRP_SUBSHELL;
4180 char *as_string = NULL;
4182 pipe_list = parse_stream(&as_string, input, endch);
4185 o_addstr(&ctx->as_string, as_string);
4187 /* empty ()/{} or parse error? */
4188 if (!pipe_list || pipe_list == ERR_PTR) {
4193 debug_printf_parse("parse_group return 1: "
4194 "parse_stream returned %p\n", pipe_list);
4197 command->group = pipe_list;
4199 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4200 command->group_as_string = as_string;
4201 debug_printf_parse("end of group, remembering as:'%s'\n",
4202 command->group_as_string);
4205 debug_printf_parse("parse_group return 0\n");
4207 /* command remains "open", available for possible redirects */
4210 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
4211 /* Subroutines for copying $(...) and `...` things */
4212 static void add_till_backquote(o_string *dest, struct in_str *input);
4214 static void add_till_single_quote(o_string *dest, struct in_str *input)
4217 int ch = i_getch(input);
4225 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
4226 static void add_till_double_quote(o_string *dest, struct in_str *input)
4229 int ch = i_getch(input);
4232 if (ch == '\\') { /* \x. Copy both chars. */
4234 ch = i_getch(input);
4240 add_till_backquote(dest, input);
4244 //if (ch == '$') ...
4247 /* Process `cmd` - copy contents until "`" is seen. Complicated by
4249 * "Within the backquoted style of command substitution, backslash
4250 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4251 * The search for the matching backquote shall be satisfied by the first
4252 * backquote found without a preceding backslash; during this search,
4253 * if a non-escaped backquote is encountered within a shell comment,
4254 * a here-document, an embedded command substitution of the $(command)
4255 * form, or a quoted string, undefined results occur. A single-quoted
4256 * or double-quoted string that begins, but does not end, within the
4257 * "`...`" sequence produces undefined results."
4259 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4261 static void add_till_backquote(o_string *dest, struct in_str *input)
4264 int ch = i_getch(input);
4267 if (ch == '\\') { /* \x. Copy both chars unless it is \` */
4268 int ch2 = i_getch(input);
4269 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
4278 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
4279 * quoting and nested ()s.
4280 * "With the $(command) style of command substitution, all characters
4281 * following the open parenthesis to the matching closing parenthesis
4282 * constitute the command. Any valid shell script can be used for command,
4283 * except a script consisting solely of redirections which produces
4284 * unspecified results."
4286 * echo $(echo '(TEST)' BEST) (TEST) BEST
4287 * echo $(echo 'TEST)' BEST) TEST) BEST
4288 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
4290 static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
4294 int ch = i_getch(input);
4303 if (i_peek(input) == ')') {
4311 add_till_single_quote(dest, input);
4316 add_till_double_quote(dest, input);
4320 if (ch == '\\') { /* \x. Copy verbatim. Important for \(, \) */
4321 ch = i_getch(input);
4329 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
4331 /* Return code: 0 for OK, 1 for syntax error */
4333 #define handle_dollar(as_string, dest, input) \
4334 handle_dollar(dest, input)
4336 static int handle_dollar(o_string *as_string,
4338 struct in_str *input)
4341 int ch = i_peek(input); /* first character after the $ */
4342 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
4344 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
4346 ch = i_getch(input);
4348 if (as_string) o_addchr(as_string, ch);
4351 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4353 debug_printf_parse(": '%c'\n", ch);
4354 o_addchr(dest, ch | quote_mask);
4357 if (!isalnum(ch) && ch != '_')
4359 ch = i_getch(input);
4361 if (as_string) o_addchr(as_string, ch);
4364 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4365 } else if (isdigit(ch)) {
4367 ch = i_getch(input);
4369 if (as_string) o_addchr(as_string, ch);
4371 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4372 debug_printf_parse(": '%c'\n", ch);
4373 o_addchr(dest, ch | quote_mask);
4374 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4375 } else switch (ch) {
4377 case '!': /* last bg pid */
4378 case '?': /* last exit code */
4379 case '#': /* number of args */
4380 case '*': /* args */
4381 case '@': /* args */
4382 goto make_one_char_var;
4384 bool first_char, all_digits;
4386 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4387 ch = i_getch(input);
4389 if (as_string) o_addchr(as_string, ch);
4391 /* XXX maybe someone will try to escape the '}' */
4396 ch = i_getch(input);
4398 if (as_string) o_addchr(as_string, ch);
4405 /* ${#var}: length of var contents */
4407 else if (isdigit(ch)) {
4414 && ( (all_digits && !isdigit(ch))
4415 || (!all_digits && !isalnum(ch) && ch != '_')
4418 /* handle parameter expansions
4419 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4424 case ':': /* null modifier */
4425 if (expansion == 0) {
4426 debug_printf_parse(": null modifier\n");
4431 #if 0 /* not implemented yet :( */
4432 case '#': /* remove prefix */
4433 case '%': /* remove suffix */
4434 if (expansion == 0) {
4435 debug_printf_parse(": remove suffix/prefix\n");
4441 case '-': /* default value */
4442 case '=': /* assign default */
4443 case '+': /* alternative */
4444 case '?': /* error indicate */
4445 debug_printf_parse(": parameter expansion\n");
4450 syntax("unterminated ${name}");
4451 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
4456 debug_printf_parse(": '%c'\n", ch);
4457 o_addchr(dest, ch | quote_mask);
4461 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4464 #if (ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK)
4469 ch = i_getch(input);
4471 if (as_string) o_addchr(as_string, ch);
4473 # if ENABLE_SH_MATH_SUPPORT
4474 if (i_peek(input) == '(') {
4475 ch = i_getch(input);
4477 if (as_string) o_addchr(as_string, ch);
4479 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4480 o_addchr(dest, /*quote_mask |*/ '+');
4484 add_till_closing_paren(dest, input, true);
4487 o_addstr(as_string, dest->data + pos);
4488 o_addchr(as_string, ')');
4489 o_addchr(as_string, ')');
4492 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4496 # if ENABLE_HUSH_TICK
4497 //int pos = dest->length;
4498 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4499 o_addchr(dest, quote_mask | '`');
4503 add_till_closing_paren(dest, input, false);
4506 o_addstr(as_string, dest->data + pos);
4507 o_addchr(as_string, '`');
4510 //debug_printf_subst("SUBST RES2 '%s'\n", dest->data + pos);
4511 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4517 ch = i_getch(input);
4519 if (as_string) o_addchr(as_string, ch);
4522 if (isalnum(ch)) { /* it's $_name or $_123 */
4528 /* $_ Shell or shell script name; or last cmd name */
4529 /* $- Option flags set by set builtin or shell options (-i etc) */
4531 o_addQchr(dest, '$');
4533 debug_printf_parse("handle_dollar return 0\n");
4538 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
4539 parse_stream_dquoted(dest, input, dquote_end)
4541 static int parse_stream_dquoted(o_string *as_string,
4543 struct in_str *input,
4550 ch = i_getch(input);
4552 if (as_string && ch != EOF) o_addchr(as_string, ch);
4554 if (ch == dquote_end) { /* may be only '"' or EOF */
4556 if (dest->o_assignment == NOT_ASSIGNMENT)
4557 dest->o_escape ^= 1;
4558 debug_printf_parse("parse_stream_dquoted return 0\n");
4562 syntax("unterminated \"");
4563 debug_printf_parse("parse_stream_dquoted return 1: unterminated \"\n");
4568 next = i_peek(input);
4570 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4571 ch, ch, dest->o_escape);
4575 debug_printf_parse("parse_stream_dquoted return 1: \\<eof>\n");
4579 * "The backslash retains its special meaning [in "..."]
4580 * only when followed by one of the following characters:
4581 * $, `, ", \, or <newline>. A double quote may be quoted
4582 * within double quotes by preceding it with a backslash.
4583 * If enabled, history expansion will be performed unless
4584 * an ! appearing in double quotes is escaped using
4585 * a backslash. The backslash preceding the ! is not removed."
4587 if (strchr("$`\"\\", next) != NULL) {
4588 o_addqchr(dest, i_getch(input));
4590 o_addqchr(dest, '\\');
4595 if (handle_dollar(as_string, dest, input) != 0) {
4596 debug_printf_parse("parse_stream_dquoted return 1: "
4597 "handle_dollar returned non-0\n");
4602 #if ENABLE_HUSH_TICK
4604 //int pos = dest->length;
4605 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4606 o_addchr(dest, 0x80 | '`');
4607 add_till_backquote(dest, input);
4608 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4609 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4613 o_addQchr(dest, ch);
4615 && (dest->o_assignment == MAYBE_ASSIGNMENT
4616 || dest->o_assignment == WORD_IS_KEYWORD)
4617 && is_assignment(dest->data)
4619 dest->o_assignment = DEFINITELY_ASSIGNMENT;
4625 * Scan input until EOF or end_trigger char.
4626 * Return a list of pipes to execute, or NULL on EOF
4627 * or if end_trigger character is met.
4628 * On syntax error, exit is shell is not interactive,
4629 * reset parsing machinery and start parsing anew,
4630 * or return ERR_PTR.
4632 static struct pipe *parse_stream(char **pstring,
4633 struct in_str *input,
4636 struct parse_context ctx;
4637 o_string dest = NULL_O_STRING;
4641 /* Double-quote state is handled in the state variable is_in_dquote.
4642 * A single-quote triggers a bypass of the main loop until its mate is
4643 * found. When recursing, quote state is passed in via dest->o_escape.
4645 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4646 end_trigger ? : 'X');
4648 G.ifs = get_local_var_value("IFS");
4653 #if ENABLE_HUSH_INTERACTIVE
4654 input->promptmode = 0; /* PS1 */
4656 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
4657 initialize_context(&ctx);
4662 const char *is_special;
4666 redir_type redir_style;
4669 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
4672 /* We reached closing '"' */
4675 ch = i_getch(input);
4676 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4677 ch, ch, dest.o_escape);
4682 syntax("unterminated here document");
4685 if (done_word(&dest, &ctx)) {
4689 done_pipe(&ctx, PIPE_SEQ);
4691 /* If we got nothing... */
4692 // TODO: test script consisting of just "&"
4693 if (pi->num_cmds == 0
4694 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4696 free_pipe_list(pi, 0);
4699 debug_printf_parse("parse_stream return %p\n", pi);
4701 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4703 *pstring = ctx.as_string.data;
4705 o_free_unsafe(&ctx.as_string);
4710 o_addchr(&ctx.as_string, ch);
4712 is_ifs = strchr(G.ifs, ch);
4713 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
4714 "\\$\"" USE_HUSH_TICK("`") /* always special */
4717 if (!is_special && !is_ifs) { /* ordinary char */
4718 o_addQchr(&dest, ch);
4719 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4720 || dest.o_assignment == WORD_IS_KEYWORD)
4722 && is_assignment(dest.data)
4724 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4730 if (done_word(&dest, &ctx)) {
4734 #if ENABLE_HUSH_CASE
4735 /* "case ... in <newline> word) ..." -
4736 * newlines are ignored (but ';' wouldn't be) */
4737 if (ctx.command->argv == NULL
4738 && ctx.ctx_res_w == RES_MATCH
4743 /* Treat newline as a command separator. */
4744 done_pipe(&ctx, PIPE_SEQ);
4745 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4747 if (fetch_heredocs(heredoc_cnt, &ctx, input))
4751 dest.o_assignment = MAYBE_ASSIGNMENT;
4753 /* note: if (is_ifs) continue;
4754 * will still trigger for us */
4757 if (end_trigger && end_trigger == ch
4758 && (heredoc_cnt == 0 || end_trigger != ';')
4760 //TODO: disallow "{ cmd }" without semicolon
4762 /* This is technically valid:
4763 * { cat <<HERE; }; echo Ok
4768 * but we don't support this.
4769 * We require heredoc to be in enclosing {}/(),
4772 syntax("unterminated here document");
4775 if (done_word(&dest, &ctx)) {
4778 done_pipe(&ctx, PIPE_SEQ);
4779 dest.o_assignment = MAYBE_ASSIGNMENT;
4780 /* Do we sit outside of any if's, loops or case's? */
4782 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4784 debug_printf_parse("parse_stream return %p: "
4785 "end_trigger char found\n",
4789 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4791 *pstring = ctx.as_string.data;
4793 o_free_unsafe(&ctx.as_string);
4795 return ctx.list_head;
4801 if (dest.o_assignment == MAYBE_ASSIGNMENT) {
4802 /* ch is a special char and thus this word
4803 * cannot be an assignment */
4804 dest.o_assignment = NOT_ASSIGNMENT;
4809 next = i_peek(input);
4814 if (dest.length == 0) {
4817 if (ch == EOF || ch == '\n')
4820 /* note: we do not add it to &ctx.as_string */
4823 //TODO: go back one char?
4824 o_addchr(&ctx.as_string, '\n');
4827 o_addQchr(&dest, ch);
4835 o_addchr(&dest, '\\');
4836 ch = i_getch(input);
4837 o_addchr(&dest, ch);
4839 o_addchr(&ctx.as_string, ch);
4843 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
4844 debug_printf_parse("parse_stream parse error: "
4845 "handle_dollar returned non-0\n");
4852 ch = i_getch(input);
4854 syntax("unterminated '");
4858 o_addchr(&ctx.as_string, ch);
4862 if (dest.o_assignment == NOT_ASSIGNMENT)
4863 o_addqchr(&dest, ch);
4865 o_addchr(&dest, ch);
4870 is_in_dquote ^= 1; /* invert */
4871 if (dest.o_assignment == NOT_ASSIGNMENT)
4874 #if ENABLE_HUSH_TICK
4876 //int pos = dest.length;
4877 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4878 o_addchr(&dest, '`');
4879 add_till_backquote(&dest, input);
4880 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4881 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4886 redir_fd = redirect_opt_num(&dest);
4887 if (done_word(&dest, &ctx)) {
4890 redir_style = REDIRECT_OVERWRITE;
4892 redir_style = REDIRECT_APPEND;
4893 ch = i_getch(input);
4895 o_addchr(&ctx.as_string, ch);
4899 else if (next == '(') {
4900 syntax(">(process) not supported");
4904 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4908 redir_fd = redirect_opt_num(&dest);
4909 if (done_word(&dest, &ctx)) {
4912 redir_style = REDIRECT_INPUT;
4914 redir_style = REDIRECT_HEREDOC;
4916 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4917 ch = i_getch(input);
4919 o_addchr(&ctx.as_string, ch);
4921 } else if (next == '>') {
4922 redir_style = REDIRECT_IO;
4923 ch = i_getch(input);
4925 o_addchr(&ctx.as_string, ch);
4929 else if (next == '(') {
4930 syntax("<(process) not supported");
4934 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4938 #if ENABLE_HUSH_CASE
4941 if (done_word(&dest, &ctx)) {
4944 done_pipe(&ctx, PIPE_SEQ);
4945 #if ENABLE_HUSH_CASE
4946 /* Eat multiple semicolons, detect
4947 * whether it means something special */
4952 ch = i_getch(input);
4954 o_addchr(&ctx.as_string, ch);
4956 if (ctx.ctx_res_w == RES_CASEI) {
4957 ctx.ctx_dsemicolon = 1;
4958 ctx.ctx_res_w = RES_MATCH;
4964 /* We just finished a cmd. New one may start
4965 * with an assignment */
4966 dest.o_assignment = MAYBE_ASSIGNMENT;
4969 if (done_word(&dest, &ctx)) {
4973 ch = i_getch(input);
4975 o_addchr(&ctx.as_string, ch);
4977 done_pipe(&ctx, PIPE_AND);
4979 done_pipe(&ctx, PIPE_BG);
4983 if (done_word(&dest, &ctx)) {
4986 #if ENABLE_HUSH_CASE
4987 if (ctx.ctx_res_w == RES_MATCH)
4988 break; /* we are in case's "word | word)" */
4990 if (next == '|') { /* || */
4991 ch = i_getch(input);
4993 o_addchr(&ctx.as_string, ch);
4995 done_pipe(&ctx, PIPE_OR);
4997 /* we could pick up a file descriptor choice here
4998 * with redirect_opt_num(), but bash doesn't do it.
4999 * "echo foo 2| cat" yields "foo 2". */
5004 #if ENABLE_HUSH_CASE
5005 /* "case... in [(]word)..." - skip '(' */
5006 if (ctx.ctx_res_w == RES_MATCH
5007 && ctx.command->argv == NULL /* not (word|(... */
5008 && dest.length == 0 /* not word(... */
5009 && dest.nonnull == 0 /* not ""(... */
5014 #if ENABLE_HUSH_FUNCTIONS
5015 if (dest.length != 0 /* not just () but word() */
5016 && dest.nonnull == 0 /* not a"b"c() */
5017 && ctx.command->argv == NULL /* it's the first word */
5018 //TODO: "func ( ) {...}" - note spaces - is valid format too in bash
5019 && i_peek(input) == ')'
5020 && !match_reserved_word(&dest)
5022 bb_error_msg("seems like a function definition");
5024 //if !BB_MMU o_addchr(&ctx.as_string...
5026 //TODO: do it properly.
5027 ch = i_getch(input);
5028 } while (ch == ' ' || ch == '\n');
5030 syntax("was expecting {");
5033 ch = 'F'; /* magic value */
5037 if (parse_group(&dest, &ctx, input, ch) != 0) {
5042 #if ENABLE_HUSH_CASE
5043 if (ctx.ctx_res_w == RES_MATCH)
5047 /* proper use of this character is caught by end_trigger:
5048 * if we see {, we call parse_group(..., end_trigger='}')
5049 * and it will match } earlier (not here). */
5050 syntax("unexpected } or )");
5054 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
5060 struct parse_context *pctx;
5061 IF_HAS_KEYWORDS(struct parse_context *p2;)
5063 /* Clean up allocated tree.
5064 * Samples for finding leaks on syntax error recovery path.
5065 * Run them from interactive shell, watch pmap `pidof hush`.
5066 * while if false; then false; fi do break; done
5068 * while if false; then false; fi; do break; fi
5069 * Samples to catch leaks at execution:
5070 * while if (true | {true;}); then echo ok; fi; do break; done
5071 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
5075 /* Update pipe/command counts,
5076 * otherwise freeing may miss some */
5077 done_pipe(pctx, PIPE_SEQ);
5078 debug_printf_clean("freeing list %p from ctx %p\n",
5079 pctx->list_head, pctx);
5080 debug_print_tree(pctx->list_head, 0);
5081 free_pipe_list(pctx->list_head, 0);
5082 debug_printf_clean("freed list %p\n", pctx->list_head);
5084 o_free_unsafe(&pctx->as_string);
5086 IF_HAS_KEYWORDS(p2 = pctx->stack;)
5090 IF_HAS_KEYWORDS(pctx = p2;)
5091 } while (HAS_KEYWORDS && pctx);
5092 /* Free text, clear all dest fields */
5094 /* If we are not in top-level parse, we return,
5095 * our caller will propagate error.
5097 if (end_trigger != ';') {
5104 /* Discard cached input, force prompt */
5106 USE_HUSH_INTERACTIVE(input->promptme = 1;)
5111 /* Executing from string: eval, sh -c '...'
5112 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5113 * end_trigger controls how often we stop parsing
5114 * NUL: parse all, execute, return
5115 * ';': parse till ';' or newline, execute, repeat till EOF
5117 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5120 struct pipe *pipe_list;
5122 pipe_list = parse_stream(NULL, inp, end_trigger);
5123 if (!pipe_list) /* EOF */
5125 debug_print_tree(pipe_list, 0);
5126 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5127 run_and_free_list(pipe_list);
5131 static void parse_and_run_string(const char *s)
5133 struct in_str input;
5134 setup_string_in_str(&input, s);
5135 parse_and_run_stream(&input, '\0');
5138 static void parse_and_run_file(FILE *f)
5140 struct in_str input;
5141 setup_file_in_str(&input, f);
5142 parse_and_run_stream(&input, ';');
5145 /* Called a few times only (or even once if "sh -c") */
5146 static void block_signals(int second_time)
5151 mask = (1 << SIGQUIT);
5152 if (G_interactive_fd) {
5156 //TODO | (1 << SIGHUP)
5158 | (1 << SIGTTIN) | (1 << SIGTTOU) | (1 << SIGTSTP)
5163 G.non_DFL_mask = mask;
5166 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
5170 sigaddset(&G.blocked_set, sig);
5174 sigdelset(&G.blocked_set, SIGCHLD);
5176 sigprocmask(SIG_SETMASK, &G.blocked_set,
5177 second_time ? NULL : &G.inherited_set);
5178 /* POSIX allows shell to re-enable SIGCHLD
5179 * even if it was SIG_IGN on entry */
5180 // G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
5182 signal(SIGCHLD, SIG_DFL); // SIGCHLD_handler);
5187 static void maybe_set_to_sigexit(int sig)
5189 void (*handler)(int);
5190 /* non_DFL_mask'ed signals are, well, masked,
5191 * no need to set handler for them.
5193 if (!((G.non_DFL_mask >> sig) & 1)) {
5194 handler = signal(sig, sigexit);
5195 if (handler == SIG_IGN) /* oops... restore back to IGN! */
5196 signal(sig, handler);
5199 /* Set handlers to restore tty pgrp and exit */
5200 static void set_fatal_handlers(void)
5202 /* We _must_ restore tty pgrp on fatal signals */
5204 maybe_set_to_sigexit(SIGILL );
5205 maybe_set_to_sigexit(SIGFPE );
5206 maybe_set_to_sigexit(SIGBUS );
5207 maybe_set_to_sigexit(SIGSEGV);
5208 maybe_set_to_sigexit(SIGTRAP);
5209 } /* else: hush is perfect. what SEGV? */
5210 maybe_set_to_sigexit(SIGABRT);
5211 /* bash 3.2 seems to handle these just like 'fatal' ones */
5212 maybe_set_to_sigexit(SIGPIPE);
5213 maybe_set_to_sigexit(SIGALRM);
5214 //TODO: disable and move down when proper SIGHUP handling is added
5215 maybe_set_to_sigexit(SIGHUP );
5216 /* if we are interactive, [SIGHUP,] SIGTERM and SIGINT are masked.
5217 * if we aren't interactive... but in this case
5218 * we never want to restore pgrp on exit, and this fn is not called */
5219 /*maybe_set_to_sigexit(SIGTERM);*/
5220 /*maybe_set_to_sigexit(SIGINT );*/
5224 static int set_mode(const char cstate, const char mode)
5226 int state = (cstate == '-' ? 1 : 0);
5228 case 'n': G.fake_mode = state; break;
5229 case 'x': /*G.debug_mode = state;*/ break;
5230 default: return EXIT_FAILURE;
5232 return EXIT_SUCCESS;
5235 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
5236 int hush_main(int argc, char **argv)
5238 static const struct variable const_shell_ver = {
5240 .varstr = (char*)hush_version_str,
5241 .max_len = 1, /* 0 can provoke free(name) */
5245 int signal_mask_is_inited = 0;
5248 struct variable *cur_var;
5251 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
5252 G.last_exitcode = EXIT_SUCCESS;
5254 G.argv0_for_re_execing = argv[0];
5256 /* Deal with HUSH_VERSION */
5257 G.shell_ver = const_shell_ver; /* copying struct here */
5258 G.top_var = &G.shell_ver;
5259 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
5260 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
5261 /* Initialize our shell local variables with the values
5262 * currently living in the environment */
5263 cur_var = G.top_var;
5266 char *value = strchr(*e, '=');
5267 if (value) { /* paranoia */
5268 cur_var->next = xzalloc(sizeof(*cur_var));
5269 cur_var = cur_var->next;
5270 cur_var->varstr = *e;
5271 cur_var->max_len = strlen(*e);
5272 cur_var->flg_export = 1;
5276 debug_printf_env("putenv '%s'\n", hush_version_str);
5277 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
5278 #if ENABLE_FEATURE_EDITING
5279 G.line_input_state = new_line_input_t(FOR_SHELL);
5281 G.global_argc = argc;
5282 G.global_argv = argv;
5283 /* Initialize some more globals to non-zero values */
5285 #if ENABLE_HUSH_INTERACTIVE
5286 if (ENABLE_FEATURE_EDITING)
5287 cmdedit_set_initial_prompt();
5291 /* Shell is non-interactive at first. We need to call
5292 * block_signals(0) if we are going to execute "sh <script>",
5293 * "sh -c <cmds>" or login shell's /etc/profile and friends.
5294 * If we later decide that we are interactive, we run block_signals(0)
5295 * (or re-run block_signals(1) if we ran block_signals(0) before)
5296 * in order to intercept (more) signals.
5300 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
5302 opt = getopt(argc, argv, "c:xins"
5312 G.root_pid = getpid();
5313 G.global_argv = argv + optind;
5314 if (!argv[optind]) {
5315 /* -c 'script' (no params): prevent empty $0 */
5316 *--G.global_argv = argv[0];
5318 } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
5319 G.global_argc = argc - optind;
5320 block_signals(0); /* 0: called 1st time */
5321 parse_and_run_string(optarg);
5324 /* Well, we cannot just declare interactiveness,
5325 * we have to have some stuff (ctty, etc) */
5326 /* G_interactive_fd++; */
5329 /* "-s" means "read from stdin", but this is how we always
5330 * operate, so simply do nothing here. */
5334 G.root_pid = bb_strtou(optarg, &optarg, 16);
5336 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
5338 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
5339 # if ENABLE_HUSH_LOOPS
5341 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
5346 set_local_var(xstrdup(optarg), 0, opt == 'R');
5351 if (!set_mode('-', opt))
5355 fprintf(stderr, "Usage: sh [FILE]...\n"
5356 " or: sh -c command [args]...\n\n");
5362 } /* option parsing loop */
5365 G.root_pid = getpid();
5367 /* If we are login shell... */
5368 if (argv[0] && argv[0][0] == '-') {
5370 /* XXX what should argv be while sourcing /etc/profile? */
5371 debug_printf("sourcing /etc/profile\n");
5372 input = fopen_for_read("/etc/profile");
5373 if (input != NULL) {
5374 close_on_exec_on(fileno(input));
5375 block_signals(0); /* 0: called 1st time */
5376 signal_mask_is_inited = 1;
5377 parse_and_run_file(input);
5380 /* bash: after sourcing /etc/profile,
5381 * tries to source (in the given order):
5382 * ~/.bash_profile, ~/.bash_login, ~/.profile,
5383 * stopping of first found. --noprofile turns this off.
5384 * bash also sources ~/.bash_logout on exit.
5385 * If called as sh, skips .bash_XXX files.
5392 * "bash <script>" (which is never interactive (unless -i?))
5393 * sources $BASH_ENV here (without scanning $PATH).
5394 * If called as sh, does the same but with $ENV.
5396 debug_printf("running script '%s'\n", argv[optind]);
5397 G.global_argv = argv + optind;
5398 G.global_argc = argc - optind;
5399 input = xfopen_for_read(argv[optind]);
5400 close_on_exec_on(fileno(input));
5401 if (!signal_mask_is_inited)
5402 block_signals(0); /* 0: called 1st time */
5403 parse_and_run_file(input);
5404 #if ENABLE_FEATURE_CLEAN_UP
5410 /* Up to here, shell was non-interactive. Now it may become one.
5411 * NB: don't forget to (re)run block_signals(0/1) as needed.
5414 /* A shell is interactive if the '-i' flag was given, or if all of
5415 * the following conditions are met:
5417 * no arguments remaining or the -s flag given
5418 * standard input is a terminal
5419 * standard output is a terminal
5420 * Refer to Posix.2, the description of the 'sh' utility.
5423 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
5424 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
5425 debug_printf("saved_tty_pgrp:%d\n", G.saved_tty_pgrp);
5426 //TODO: "interactive" and "have job control" are two different things.
5427 //If tcgetpgrp fails here, "have job control" is false, but "interactive"
5428 //should stay on! Currently, we mix these into one.
5429 if (G.saved_tty_pgrp >= 0) {
5430 /* try to dup stdin to high fd#, >= 255 */
5431 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
5432 if (G_interactive_fd < 0) {
5433 /* try to dup to any fd */
5434 G_interactive_fd = dup(STDIN_FILENO);
5435 if (G_interactive_fd < 0)
5437 G_interactive_fd = 0;
5439 // TODO: track & disallow any attempts of user
5440 // to (inadvertently) close/redirect it
5443 debug_printf("interactive_fd:%d\n", G_interactive_fd);
5444 if (G_interactive_fd) {
5447 /* We are indeed interactive shell, and we will perform
5448 * job control. Setting up for that. */
5450 close_on_exec_on(G_interactive_fd);
5451 /* If we were run as 'hush &', sleep until we are
5452 * in the foreground (tty pgrp == our pgrp).
5453 * If we get started under a job aware app (like bash),
5454 * make sure we are now in charge so we don't fight over
5455 * who gets the foreground */
5457 shell_pgrp = getpgrp();
5458 G.saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
5459 if (G.saved_tty_pgrp == shell_pgrp)
5461 /* send TTIN to ourself (should stop us) */
5462 kill(- shell_pgrp, SIGTTIN);
5464 /* Block some signals */
5465 block_signals(signal_mask_is_inited);
5466 /* Set other signals to restore saved_tty_pgrp */
5467 set_fatal_handlers();
5468 /* Put ourselves in our own process group */
5469 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
5470 /* Grab control of the terminal */
5471 tcsetpgrp(G_interactive_fd, getpid());
5472 /* -1 is special - makes xfuncs longjmp, not exit
5473 * (we reset die_sleep = 0 whereever we [v]fork) */
5475 if (setjmp(die_jmp)) {
5476 /* xfunc has failed! die die die */
5477 hush_exit(xfunc_error_retval);
5479 } else if (!signal_mask_is_inited) {
5480 block_signals(0); /* 0: called 1st time */
5481 } /* else: block_signals(0) was done before */
5482 #elif ENABLE_HUSH_INTERACTIVE
5483 /* No job control compiled in, only prompt/line editing */
5484 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
5485 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
5486 if (G_interactive_fd < 0) {
5487 /* try to dup to any fd */
5488 G_interactive_fd = dup(STDIN_FILENO);
5489 if (G_interactive_fd < 0)
5491 G_interactive_fd = 0;
5494 if (G_interactive_fd) {
5495 close_on_exec_on(G_interactive_fd);
5496 block_signals(signal_mask_is_inited);
5497 } else if (!signal_mask_is_inited) {
5501 /* We have interactiveness code disabled */
5502 if (!signal_mask_is_inited) {
5507 * if interactive but not a login shell, sources ~/.bashrc
5508 * (--norc turns this off, --rcfile <file> overrides)
5511 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
5512 printf("\n\n%s hush - the humble shell\n", bb_banner);
5513 printf("Enter 'help' for a list of built-in commands.\n\n");
5516 parse_and_run_file(stdin);
5519 #if ENABLE_FEATURE_CLEAN_UP
5520 if (G.cwd != bb_msg_unknown)
5522 cur_var = G.top_var->next;
5524 struct variable *tmp = cur_var;
5525 if (!cur_var->max_len)
5526 free(cur_var->varstr);
5527 cur_var = cur_var->next;
5531 hush_exit(G.last_exitcode);
5536 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
5537 int lash_main(int argc, char **argv)
5539 //bb_error_msg("lash is deprecated, please use hush instead");
5540 return hush_main(argc, argv);
5548 static int builtin_trap(char **argv)
5555 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
5559 /* No args: print all trapped. This isn't 100% correct as we
5560 * should be escaping the cmd so that it can be pasted back in
5562 for (i = 0; i < NSIG; ++i)
5564 printf("trap -- '%s' %s\n", G.traps[i], get_signame(i));
5565 return EXIT_SUCCESS;
5570 /* If first arg is decimal: reset all specified signals */
5571 sig = bb_strtou(*argv, NULL, 10);
5577 sig = get_signum(*argv++);
5578 if (sig < 0 || sig >= NSIG) {
5580 /* Mimic bash message exactly */
5581 bb_perror_msg("trap: %s: invalid signal specification", argv[i]);
5586 G.traps[sig] = xstrdup(new_cmd);
5588 debug_printf("trap: setting SIG%s (%i) to '%s'",
5589 get_signame(sig), sig, G.traps[sig]);
5591 /* There is no signal for 0 (EXIT) */
5596 sigaddset(&G.blocked_set, sig);
5598 /* There was a trap handler, we are removing it
5599 * (if sig has non-DFL handling,
5600 * we don't need to do anything) */
5601 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
5603 sigdelset(&G.blocked_set, sig);
5605 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5610 /* First arg is "-": reset all specified to default */
5611 /* First arg is "": ignore all specified */
5612 /* Everything else: execute first arg upon signal */
5614 bb_error_msg("trap: invalid arguments");
5615 return EXIT_FAILURE;
5617 if (NOT_LONE_DASH(*argv))
5623 static int builtin_true(char **argv UNUSED_PARAM)
5628 static int builtin_test(char **argv)
5635 return test_main(argc, argv - argc);
5638 static int builtin_echo(char **argv)
5645 return echo_main(argc, argv - argc);
5648 static int builtin_eval(char **argv)
5650 int rcode = EXIT_SUCCESS;
5653 char *str = expand_strvec_to_string(argv);
5655 * eval "echo Hi; done" ("done" is syntax error):
5656 * "echo Hi" will not execute too.
5658 parse_and_run_string(str);
5660 rcode = G.last_exitcode;
5665 static int builtin_cd(char **argv)
5667 const char *newdir = argv[1];
5668 if (newdir == NULL) {
5669 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
5670 * bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
5672 newdir = getenv("HOME") ? : "/";
5674 if (chdir(newdir)) {
5675 /* Mimic bash message exactly */
5676 bb_perror_msg("cd: %s", newdir);
5677 return EXIT_FAILURE;
5680 return EXIT_SUCCESS;
5683 static int builtin_exec(char **argv)
5685 if (*++argv == NULL)
5686 return EXIT_SUCCESS; /* bash does this */
5691 // FIXME: if exec fails, bash does NOT exit! We do...
5692 pseudo_exec_argv(&dummy, argv, 0, NULL);
5697 static int builtin_exit(char **argv)
5699 debug_printf_exec("%s()\n", __func__);
5700 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
5701 //puts("exit"); /* bash does it */
5702 // TODO: warn if we have background jobs: "There are stopped jobs"
5703 // On second consecutive 'exit', exit anyway.
5704 if (*++argv == NULL)
5705 hush_exit(G.last_exitcode);
5706 /* mimic bash: exit 123abc == exit 255 + error msg */
5707 xfunc_error_retval = 255;
5708 /* bash: exit -2 == exit 254, no error msg */
5709 hush_exit(xatoi(*argv) & 0xff);
5712 static int builtin_export(char **argv)
5714 if (*++argv == NULL) {
5716 // ash emits: export VAR='VAL'
5717 // bash: declare -x VAR="VAL"
5718 // (both also escape as needed (quotes, $, etc))
5723 return EXIT_SUCCESS;
5730 value = strchr(name, '=');
5732 /* They are exporting something without a =VALUE */
5733 struct variable *var;
5735 var = get_local_var(name);
5737 var->flg_export = 1;
5738 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
5739 putenv(var->varstr);
5741 /* bash does not return an error when trying to export
5742 * an undefined variable. Do likewise. */
5745 set_local_var(xstrdup(name), 1, 0);
5748 return EXIT_SUCCESS;
5752 /* built-in 'fg' and 'bg' handler */
5753 static int builtin_fg_bg(char **argv)
5758 if (!G_interactive_fd)
5759 return EXIT_FAILURE;
5760 /* If they gave us no args, assume they want the last backgrounded task */
5762 for (pi = G.job_list; pi; pi = pi->next) {
5763 if (pi->jobid == G.last_jobid) {
5767 bb_error_msg("%s: no current job", argv[0]);
5768 return EXIT_FAILURE;
5770 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
5771 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
5772 return EXIT_FAILURE;
5774 for (pi = G.job_list; pi; pi = pi->next) {
5775 if (pi->jobid == jobnum) {
5779 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
5780 return EXIT_FAILURE;
5782 // TODO: bash prints a string representation
5783 // of job being foregrounded (like "sleep 1 | cat")
5784 if (argv[0][0] == 'f') {
5785 /* Put the job into the foreground. */
5786 tcsetpgrp(G_interactive_fd, pi->pgrp);
5789 /* Restart the processes in the job */
5790 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
5791 for (i = 0; i < pi->num_cmds; i++) {
5792 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
5793 pi->cmds[i].is_stopped = 0;
5795 pi->stopped_cmds = 0;
5797 i = kill(- pi->pgrp, SIGCONT);
5799 if (errno == ESRCH) {
5800 delete_finished_bg_job(pi);
5801 return EXIT_SUCCESS;
5803 bb_perror_msg("kill (SIGCONT)");
5806 if (argv[0][0] == 'f') {
5808 return checkjobs_and_fg_shell(pi);
5810 return EXIT_SUCCESS;
5814 #if ENABLE_HUSH_HELP
5815 static int builtin_help(char **argv UNUSED_PARAM)
5817 const struct built_in_command *x;
5820 "Built-in commands:\n"
5821 "------------------\n");
5822 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
5823 printf("%s\t%s\n", x->cmd, x->descr);
5826 return EXIT_SUCCESS;
5831 static int builtin_jobs(char **argv UNUSED_PARAM)
5834 const char *status_string;
5836 for (job = G.job_list; job; job = job->next) {
5837 if (job->alive_cmds == job->stopped_cmds)
5838 status_string = "Stopped";
5840 status_string = "Running";
5842 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
5844 return EXIT_SUCCESS;
5848 static int builtin_pwd(char **argv UNUSED_PARAM)
5851 return EXIT_SUCCESS;
5854 static int builtin_read(char **argv)
5857 const char *name = argv[1] ? argv[1] : "REPLY";
5858 //TODO: check that argv[1] is a valid variable name
5860 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
5861 return set_local_var(string, 0, 0);
5864 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
5865 * built-in 'set' handler
5867 * set [-abCefhmnuvx] [-o option] [argument...]
5868 * set [+abCefhmnuvx] [+o option] [argument...]
5869 * set -- [argument...]
5872 * Implementations shall support the options in both their hyphen and
5873 * plus-sign forms. These options can also be specified as options to sh.
5875 * Write out all variables and their values: set
5876 * Set $1, $2, and $3 and set "$#" to 3: set c a b
5877 * Turn on the -x and -v options: set -xv
5878 * Unset all positional parameters: set --
5879 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
5880 * Set the positional parameters to the expansion of x, even if x expands
5881 * with a leading '-' or '+': set -- $x
5883 * So far, we only support "set -- [argument...]" and some of the short names.
5885 static int builtin_set(char **argv)
5888 char **pp, **g_argv;
5889 char *arg = *++argv;
5893 for (e = G.top_var; e; e = e->next)
5895 return EXIT_SUCCESS;
5899 if (!strcmp(arg, "--")) {
5904 if (arg[0] == '+' || arg[0] == '-') {
5905 for (n = 1; arg[n]; ++n)
5906 if (set_mode(arg[0], arg[n]))
5912 } while ((arg = *++argv) != NULL);
5913 /* Now argv[0] is 1st argument */
5915 /* Only reset global_argv if we didn't process anything */
5917 return EXIT_SUCCESS;
5920 /* NB: G.global_argv[0] ($0) is never freed/changed */
5921 g_argv = G.global_argv;
5922 if (G.global_args_malloced) {
5928 G.global_args_malloced = 1;
5929 pp = xzalloc(sizeof(pp[0]) * 2);
5930 pp[0] = g_argv[0]; /* retain $0 */
5933 /* This realloc's G.global_argv */
5934 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
5941 return EXIT_SUCCESS;
5943 /* Nothing known, so abort */
5945 bb_error_msg("set: %s: invalid option", arg);
5946 return EXIT_FAILURE;
5949 static int builtin_shift(char **argv)
5955 if (n >= 0 && n < G.global_argc) {
5956 if (G.global_args_malloced) {
5959 free(G.global_argv[m++]);
5962 memmove(&G.global_argv[1], &G.global_argv[n+1],
5963 G.global_argc * sizeof(G.global_argv[0]));
5964 return EXIT_SUCCESS;
5966 return EXIT_FAILURE;
5969 static int builtin_source(char **argv)
5973 if (*++argv == NULL)
5974 return EXIT_FAILURE;
5976 /* XXX search through $PATH is missing */
5977 input = fopen_or_warn(*argv, "r");
5979 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
5980 return EXIT_FAILURE;
5982 close_on_exec_on(fileno(input));
5984 /* Now run the file */
5986 /* XXX argv and argc are broken; need to save old G.global_argv
5987 * (pointer only is OK!) on this stack frame,
5988 * set G.global_argv=argv+1, recurse, and restore. */
5989 parse_and_run_file(input);
5991 return G.last_exitcode;
5994 static int builtin_umask(char **argv)
5997 const char *arg = argv[1];
5999 //TODO: umask may take chmod-like symbolic masks
6000 new_umask = bb_strtou(arg, NULL, 8);
6002 //Message? bash examples:
6003 //bash: umask: 'q': invalid symbolic mode operator
6004 //bash: umask: 999: octal number out of range
6005 return EXIT_FAILURE;
6008 new_umask = umask(0);
6009 printf("%.3o\n", (unsigned) new_umask);
6010 /* fall through and restore new_umask which we set to 0 */
6013 return EXIT_SUCCESS;
6016 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
6017 static int builtin_unset(char **argv)
6023 return EXIT_SUCCESS;
6026 if (argv[0][0] == '-') {
6027 switch (argv[0][1]) {
6033 bb_error_msg("unset: %s: invalid option", *argv);
6034 return EXIT_FAILURE;
6036 //TODO: disallow "unset -vf ..." too
6043 if (unset_local_var(*argv)) {
6044 /* unset <nonexistent_var> doesn't fail.
6045 * Error is when one tries to unset RO var.
6046 * Message was printed by unset_local_var. */
6050 #if ENABLE_HUSH_FUNCTIONS
6052 unset_local_func(*argv);
6060 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
6061 static int builtin_wait(char **argv)
6063 int ret = EXIT_SUCCESS;
6066 if (*++argv == NULL) {
6067 /* Don't care about wait results */
6068 /* Note 1: must wait until there are no more children */
6069 /* Note 2: must be interruptible */
6071 * $ sleep 3 & sleep 6 & wait
6076 * $ sleep 3 & sleep 6 & wait
6080 * ^C <-- after ~4 sec from keyboard
6083 sigaddset(&G.blocked_set, SIGCHLD);
6084 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6087 if (errno == ECHILD)
6089 /* Wait for SIGCHLD or any other signal of interest */
6090 /* sigtimedwait with infinite timeout: */
6091 sig = sigwaitinfo(&G.blocked_set, NULL);
6093 sig = check_and_run_traps(sig);
6094 if (sig && sig != SIGCHLD) { /* see note 2 */
6100 sigdelset(&G.blocked_set, SIGCHLD);
6101 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6105 /* This is probably buggy wrt interruptible-ness */
6107 pid_t pid = bb_strtou(*argv, NULL, 10);
6109 /* mimic bash message */
6110 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
6111 return EXIT_FAILURE;
6113 if (waitpid(pid, &status, 0) == pid) {
6114 if (WIFSIGNALED(status))
6115 ret = 128 + WTERMSIG(status);
6116 else if (WIFEXITED(status))
6117 ret = WEXITSTATUS(status);
6121 bb_perror_msg("wait %s", *argv);
6130 #if ENABLE_HUSH_LOOPS
6131 static int builtin_break(char **argv)
6133 if (G.depth_of_loop == 0) {
6134 bb_error_msg("%s: only meaningful in a loop", argv[0]);
6135 return EXIT_SUCCESS; /* bash compat */
6137 G.flag_break_continue++; /* BC_BREAK = 1 */
6138 G.depth_break_continue = 1;
6140 G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
6141 if (errno || !G.depth_break_continue || argv[2]) {
6142 bb_error_msg("%s: bad arguments", argv[0]);
6143 G.flag_break_continue = BC_BREAK;
6144 G.depth_break_continue = UINT_MAX;
6147 if (G.depth_of_loop < G.depth_break_continue)
6148 G.depth_break_continue = G.depth_of_loop;
6149 return EXIT_SUCCESS;
6152 static int builtin_continue(char **argv)
6154 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
6155 return builtin_break(argv);