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 )
47 * Bash stuff (maybe optionally enable?):
48 * &> and >& redirection of stdout+stderr
50 * reserved words: [[ ]] function select
51 * substrings ${var:1:5}
54 * grep for "TODO" and fix (some of them are easy)
55 * change { and } from special chars to reserved words
56 * builtins: return, ulimit
57 * follow IFS rules more precisely, including update semantics
58 * figure out what to do with backslash-newline
59 * continuation lines, both explicit and implicit - done?
61 * ^Z handling (and explain it in comments for mere humans)
62 * separate job control from interactiveness
63 * (testcase: booting with init=/bin/hush does not show prompt (2009-04))
66 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
69 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
70 //TODO: pull in some .h and find out whether we have SINGLE_APPLET_MAIN?
71 //#include "applet_tables.h" doesn't work
73 /* #include <dmalloc.h> */
80 #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;
1675 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
1676 debug_print_list("expand_vars_to_list", output, n);
1677 n = o_save_ptr(output, n);
1678 debug_print_list("expand_vars_to_list[0]", output, n);
1680 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
1681 #if ENABLE_HUSH_TICK
1682 o_string subst_result = NULL_O_STRING;
1684 #if ENABLE_SH_MATH_SUPPORT
1685 char arith_buf[sizeof(arith_t)*3 + 2];
1687 o_addblock(output, arg, p - arg);
1688 debug_print_list("expand_vars_to_list[1]", output, n);
1690 p = strchr(p, SPECIAL_VAR_SYMBOL);
1692 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
1693 /* "$@" is special. Even if quoted, it can still
1694 * expand to nothing (not even an empty string) */
1695 if ((first_ch & 0x7f) != '@')
1696 ored_ch |= first_ch;
1699 switch (first_ch & 0x7f) {
1700 /* Highest bit in first_ch indicates that var is double-quoted */
1702 val = utoa(G.root_pid);
1704 case '!': /* bg pid */
1705 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
1707 case '?': /* exitcode */
1708 val = utoa(G.last_exitcode);
1710 case '#': /* argc */
1711 if (arg[1] != SPECIAL_VAR_SYMBOL)
1712 /* actually, it's a ${#var} */
1714 val = utoa(G.global_argc ? G.global_argc-1 : 0);
1719 if (!G.global_argv[i])
1721 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
1722 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
1723 smallint sv = output->o_escape;
1724 /* unquoted var's contents should be globbed, so don't escape */
1725 output->o_escape = 0;
1726 while (G.global_argv[i]) {
1727 n = expand_on_ifs(output, n, G.global_argv[i]);
1728 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
1729 if (G.global_argv[i++][0] && G.global_argv[i]) {
1730 /* this argv[] is not empty and not last:
1731 * put terminating NUL, start new word */
1732 o_addchr(output, '\0');
1733 debug_print_list("expand_vars_to_list[2]", output, n);
1734 n = o_save_ptr(output, n);
1735 debug_print_list("expand_vars_to_list[3]", output, n);
1738 output->o_escape = sv;
1740 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
1741 * and in this case should treat it like '$*' - see 'else...' below */
1742 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
1744 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1745 if (++i >= G.global_argc)
1747 o_addchr(output, '\0');
1748 debug_print_list("expand_vars_to_list[4]", output, n);
1749 n = o_save_ptr(output, n);
1751 } else { /* quoted $*: add as one word */
1753 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1754 if (!G.global_argv[++i])
1757 o_addchr(output, G.ifs[0]);
1761 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
1762 /* "Empty variable", used to make "" etc to not disappear */
1766 #if ENABLE_HUSH_TICK
1767 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
1770 //TODO: can we just stuff it into "output" directly?
1771 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
1772 process_command_subs(&subst_result, arg);
1773 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
1774 val = subst_result.data;
1777 #if ENABLE_SH_MATH_SUPPORT
1778 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
1779 arith_eval_hooks_t hooks;
1784 arg++; /* skip '+' */
1785 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
1786 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
1788 /* Optional: skip expansion if expr is simple ("a + 3", "i++" etc) */
1790 if (strchr(arg, '$') != NULL
1791 #if ENABLE_HUSH_TICK
1792 || strchr(arg, '`') != NULL
1795 /* We need to expand. Example:
1796 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
1798 struct in_str input;
1799 o_string dest = NULL_O_STRING;
1801 setup_string_in_str(&input, arg);
1802 parse_stream_dquoted(NULL, &dest, &input, EOF);
1803 //bb_error_msg("'%s' -> '%s'", arg, dest.data);
1804 exp_str = expand_string_to_string(dest.data);
1805 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
1806 o_free_unsafe(&dest);
1808 hooks.lookupvar = get_local_var_value;
1809 hooks.setvar = arith_set_local_var;
1810 hooks.endofname = endofname;
1811 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
1816 case -3: maybe_die("arith", "exponent less than 0"); break;
1817 case -2: maybe_die("arith", "divide by zero"); break;
1818 case -5: maybe_die("arith", "expression recursion loop detected"); break;
1819 default: maybe_die("arith", "syntax error"); break;
1822 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
1823 sprintf(arith_buf, arith_t_fmt, res);
1828 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
1830 bool exp_len = false;
1831 bool exp_null = false;
1833 char exp_save = exp_save; /* for compiler */
1834 char exp_op = exp_op; /* for compiler */
1835 char *exp_word = exp_word; /* for compiler */
1839 arg[0] = first_ch & 0x7f;
1841 /* prepare for expansions */
1842 if (var[0] == '#') {
1843 /* handle length expansion ${#var} */
1847 /* maybe handle parameter expansion */
1848 exp_off = strcspn(var, ":-=+?%#");
1852 exp_save = var[exp_off];
1853 exp_null = exp_save == ':';
1854 exp_word = var + exp_off;
1855 if (exp_null) ++exp_word;
1856 exp_op = *exp_word++;
1857 var[exp_off] = '\0';
1861 /* lookup the variable in question */
1862 if (isdigit(var[0])) {
1863 /* handle_dollar() should have vetted var for us */
1865 if (i < G.global_argc)
1866 val = G.global_argv[i];
1867 /* else val remains NULL: $N with too big N */
1869 val = get_local_var_value(var);
1871 /* handle any expansions */
1873 debug_printf_expand("expand: length of '%s' = ", val);
1874 val = utoa(val ? strlen(val) : 0);
1875 debug_printf_expand("%s\n", val);
1876 } else if (exp_off) {
1877 if (exp_op == '%' || exp_op == '#') {
1878 /* we need to do a pattern match */
1881 scan_t scan = pick_scan(exp_op, *exp_word, &zero);
1882 if (exp_op == *exp_word) /* ## or %% */
1884 val = dyn_val = xstrdup(val);
1885 loc = scan(dyn_val, exp_word, zero);
1891 /* we need to do an expansion */
1892 int exp_test = (!val || (exp_null && !val[0]));
1894 exp_test = !exp_test;
1895 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
1896 exp_null ? "true" : "false", exp_test);
1899 maybe_die(var, *exp_word ? exp_word : "parameter null or not set");
1903 if (exp_op == '=') {
1904 if (isdigit(var[0]) || var[0] == '#') {
1905 maybe_die(var, "special vars cannot assign in this way");
1908 char *new_var = xmalloc(strlen(var) + strlen(val) + 2);
1909 sprintf(new_var, "%s=%s", var, val);
1910 set_local_var(new_var, -1, 0);
1916 var[exp_off] = exp_save;
1920 #if ENABLE_HUSH_TICK
1923 if (!(first_ch & 0x80)) { /* unquoted $VAR */
1924 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
1926 /* unquoted var's contents should be globbed, so don't escape */
1927 smallint sv = output->o_escape;
1928 output->o_escape = 0;
1929 n = expand_on_ifs(output, n, val);
1931 output->o_escape = sv;
1933 } else { /* quoted $VAR, val will be appended below */
1934 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
1937 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
1939 o_addQstr(output, val, strlen(val));
1943 /* Do the check to avoid writing to a const string */
1944 if (*p != SPECIAL_VAR_SYMBOL)
1945 *p = SPECIAL_VAR_SYMBOL;
1947 #if ENABLE_HUSH_TICK
1948 o_free(&subst_result);
1951 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
1954 debug_print_list("expand_vars_to_list[a]", output, n);
1955 /* this part is literal, and it was already pre-quoted
1956 * if needed (much earlier), do not use o_addQstr here! */
1957 o_addstr_with_NUL(output, arg);
1958 debug_print_list("expand_vars_to_list[b]", output, n);
1959 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
1960 && !(ored_ch & 0x80) /* and all vars were not quoted. */
1963 /* allow to reuse list[n] later without re-growth */
1964 output->has_empty_slot = 1;
1966 o_addchr(output, '\0');
1971 static char **expand_variables(char **argv, int or_mask)
1976 o_string output = NULL_O_STRING;
1978 if (or_mask & 0x100) {
1979 output.o_escape = 1; /* protect against globbing for "$var" */
1980 /* (unquoted $var will temporarily switch it off) */
1987 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
1990 debug_print_list("expand_variables", &output, n);
1992 /* output.data (malloced in one block) gets returned in "list" */
1993 list = o_finalize_list(&output, n);
1994 debug_print_strings("expand_variables[1]", list);
1998 static char **expand_strvec_to_strvec(char **argv)
2000 return expand_variables(argv, 0x100);
2003 /* Used for expansion of right hand of assignments */
2004 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2006 static char *expand_string_to_string(const char *str)
2008 char *argv[2], **list;
2010 argv[0] = (char*)str;
2012 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2014 if (!list[0] || list[1])
2015 bb_error_msg_and_die("BUG in varexp2");
2016 /* actually, just move string 2*sizeof(char*) bytes back */
2017 overlapping_strcpy((char*)list, list[0]);
2018 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2022 /* Used for "eval" builtin */
2023 static char* expand_strvec_to_string(char **argv)
2027 list = expand_variables(argv, 0x80);
2028 /* Convert all NULs to spaces */
2033 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2034 bb_error_msg_and_die("BUG in varexp3");
2035 list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
2039 overlapping_strcpy((char*)list, list[0]);
2040 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2044 static char **expand_assignments(char **argv, int count)
2048 /* Expand assignments into one string each */
2049 for (i = 0; i < count; i++) {
2050 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2056 //TODO: fix big string case!
2057 static void setup_heredoc(int fd, const char *heredoc)
2059 struct fd_pair pair;
2065 bb_perror_msg_and_die("vfork");
2066 if (pid == 0) { /* child */
2069 xwrite_str(pair.wr, heredoc);
2075 xmove_fd(pair.rd, fd);
2078 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
2079 * and stderr if they are redirected. */
2080 static int setup_redirects(struct command *prog, int squirrel[])
2082 //TODO: no callers ever check return value - ?!
2084 struct redir_struct *redir;
2086 for (redir = prog->redirects; redir; redir = redir->next) {
2087 if (redir->rd_type == REDIRECT_HEREDOC2) {
2088 if (squirrel && redir->fd < 3) {
2089 squirrel[redir->fd] = dup(redir->fd);
2091 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
2093 debug_printf_parse("set heredoc '%s'\n",
2094 redir->rd_filename);
2095 setup_heredoc(redir->fd, redir->rd_filename);
2099 if (redir->dup == -1) {
2101 if (redir->rd_filename == NULL) {
2102 /* Something went wrong in the parse.
2103 * Pretend it didn't happen */
2106 mode = redir_table[redir->rd_type].mode;
2107 //TODO: check redir for names like '\\'
2108 p = expand_string_to_string(redir->rd_filename);
2109 openfd = open_or_warn(p, mode);
2112 /* this could get lost if stderr has been redirected, but
2113 * bash and ash both lose it as well (though zsh doesn't!) */
2114 //what the above comment tries to say?
2118 openfd = redir->dup;
2121 if (openfd != redir->fd) {
2122 if (squirrel && redir->fd < 3) {
2123 squirrel[redir->fd] = dup(redir->fd);
2126 /* "-" means "close me" and we use -3 for that */
2129 dup2(openfd, redir->fd);
2130 if (redir->dup == -1)
2138 static void restore_redirects(int squirrel[])
2141 for (i = 0; i < 3; i++) {
2144 /* We simply die on error */
2152 #define free_pipe_list(head, indent) free_pipe_list(head)
2153 #define free_pipe(pi, indent) free_pipe(pi)
2155 static void free_pipe_list(struct pipe *head, int indent);
2157 /* Return code is the exit status of the pipe */
2158 static void free_pipe(struct pipe *pi, int indent)
2161 struct command *command;
2162 struct redir_struct *r, *rnext;
2165 if (pi->stopped_cmds > 0) /* why? */
2167 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2168 for (i = 0; i < pi->num_cmds; i++) {
2169 command = &pi->cmds[i];
2170 debug_printf_clean("%s command %d:\n", indenter(indent), i);
2171 if (command->argv) {
2172 for (a = 0, p = command->argv; *p; a++, p++) {
2173 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
2175 free_strings(command->argv);
2176 command->argv = NULL;
2178 /* not "else if": on syntax error, we may have both! */
2179 if (command->group) {
2180 debug_printf_clean("%s begin group (grp_type:%d)\n", indenter(indent), command->grp_type);
2181 free_pipe_list(command->group, indent+3);
2182 debug_printf_clean("%s end group\n", indenter(indent));
2183 command->group = NULL;
2186 free(command->group_as_string);
2187 command->group_as_string = NULL;
2189 for (r = command->redirects; r; r = rnext) {
2190 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->rd_type].descrip);
2192 /* guard against the case >$FOO, where foo is unset or blank */
2193 if (r->rd_filename) {
2194 debug_printf_clean(" %s\n", r->rd_filename);
2195 free(r->rd_filename);
2196 r->rd_filename = NULL;
2199 debug_printf_clean("&%d\n", r->dup);
2204 command->redirects = NULL;
2206 free(pi->cmds); /* children are an array, they get freed all at once */
2214 static void free_pipe_list(struct pipe *head, int indent)
2216 struct pipe *pi, *next;
2218 for (pi = head; pi; pi = next) {
2220 debug_printf_clean("%s pipe reserved word %d\n", indenter(indent), pi->res_word);
2222 free_pipe(pi, indent);
2223 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
2225 /*pi->next = NULL;*/
2232 typedef struct nommu_save_t {
2238 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
2239 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
2240 #define pseudo_exec(nommu_save, command, argv_expanded) \
2241 pseudo_exec(command, argv_expanded)
2244 /* Called after [v]fork() in run_pipe, or from builtin_exec.
2246 * XXX no exit() here. If you don't exec, use _exit instead.
2247 * The at_exit handlers apparently confuse the calling process,
2248 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
2249 static void pseudo_exec_argv(nommu_save_t *nommu_save,
2250 char **argv, int assignment_cnt,
2251 char **argv_expanded) NORETURN;
2252 static void pseudo_exec_argv(nommu_save_t *nommu_save,
2253 char **argv, int assignment_cnt,
2254 char **argv_expanded)
2258 /* Case when we are here: ... | var=val | ... */
2259 if (!argv[assignment_cnt])
2260 _exit(EXIT_SUCCESS);
2262 new_env = expand_assignments(argv, assignment_cnt);
2264 putenv_all(new_env);
2265 free(new_env); /* optional */
2267 nommu_save->new_env = new_env;
2268 nommu_save->old_env = putenv_all_and_save_old(new_env);
2270 if (argv_expanded) {
2271 argv = argv_expanded;
2273 argv = expand_strvec_to_strvec(argv + assignment_cnt);
2275 nommu_save->argv = argv;
2279 /* On NOMMU, we must never block!
2280 * Example: { sleep 99999 | read line } & echo Ok
2281 * read builtin will block on read syscall, leaving parent blocked
2282 * in vfork. Therefore we can't do this:
2285 /* Check if the command matches any of the builtins.
2286 * Depending on context, this might be redundant. But it's
2287 * easier to waste a few CPU cycles than it is to figure out
2288 * if this is one of those cases.
2292 const struct built_in_command *x;
2293 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2294 if (strcmp(argv[0], x->cmd) == 0) {
2295 debug_printf_exec("running builtin '%s'\n",
2297 rcode = x->function(argv);
2305 #if ENABLE_FEATURE_SH_STANDALONE
2306 /* Check if the command matches any busybox applets */
2307 if (strchr(argv[0], '/') == NULL) {
2308 int a = find_applet_by_name(argv[0]);
2310 #if BB_MMU /* see above why on NOMMU it is not allowed */
2311 if (APPLET_IS_NOEXEC(a)) {
2312 debug_printf_exec("running applet '%s'\n", argv[0]);
2313 run_applet_no_and_exit(a, argv);
2316 /* Re-exec ourselves */
2317 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
2318 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2319 execv(bb_busybox_exec_path, argv);
2320 /* If they called chroot or otherwise made the binary no longer
2321 * executable, fall through */
2326 debug_printf_exec("execing '%s'\n", argv[0]);
2327 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2328 execvp(argv[0], argv);
2329 bb_perror_msg("can't exec '%s'", argv[0]);
2330 _exit(EXIT_FAILURE);
2334 static void reset_traps_to_defaults(void)
2342 for (sig = 0; sig < NSIG; sig++) {
2346 G.traps[sig] = NULL;
2347 /* There is no signal for 0 (EXIT) */
2350 /* there was a trap handler, we are removing it
2351 * (if sig has non-DFL handling,
2352 * we don't need to do anything) */
2353 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
2355 sigdelset(&G.blocked_set, sig);
2359 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
2361 #define clean_up_after_re_execute() ((void)0)
2365 static void re_execute_shell(const char *s) NORETURN;
2366 static void re_execute_shell(const char *s)
2368 char param_buf[sizeof("-$%x:%x:%x:%x") + sizeof(unsigned) * 4];
2369 struct variable *cur;
2370 char **argv, **pp, **pp2;
2373 sprintf(param_buf, "-$%x:%x:%x" USE_HUSH_LOOPS(":%x")
2374 , (unsigned) G.root_pid
2375 , (unsigned) G.last_bg_pid
2376 , (unsigned) G.last_exitcode
2377 USE_HUSH_LOOPS(, G.depth_of_loop)
2379 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...>
2380 * 3:-c 4:<cmd> <argN...> 5:NULL
2382 cnt = 5 + G.global_argc;
2383 for (cur = G.top_var; cur; cur = cur->next) {
2384 if (!cur->flg_export || cur->flg_read_only)
2387 G.argv_from_re_execing = pp = xzalloc(sizeof(argv[0]) * cnt);
2388 *pp++ = (char *) G.argv0_for_re_execing;
2390 for (cur = G.top_var; cur; cur = cur->next) {
2391 if (cur->varstr == hush_version_str)
2393 if (cur->flg_read_only) {
2394 *pp++ = (char *) "-R";
2395 *pp++ = cur->varstr;
2396 } else if (!cur->flg_export) {
2397 *pp++ = (char *) "-V";
2398 *pp++ = cur->varstr;
2401 //TODO: pass functions
2402 /* We can pass activated traps here. Say, -Tnn:trap_string
2404 * However, POSIX says that subshells reset signals with traps
2406 * I tested bash-3.2 and it not only does that with true subshells
2407 * of the form ( list ), but with any forked children shells.
2408 * I set trap "echo W" WINCH; and then tried:
2410 * { echo 1; sleep 20; echo 2; } &
2411 * while true; do echo 1; sleep 20; echo 2; break; done &
2412 * true | { echo 1; sleep 20; echo 2; } | cat
2414 * In all these cases sending SIGWINCH to the child shell
2415 * did not run the trap. If I add trap "echo V" WINCH;
2416 * _inside_ group (just before echo 1), it works.
2418 * I conclude it means we don't need to pass active traps here.
2419 * exec syscall below resets them to SIG_DFL for us.
2421 *pp++ = (char *) "-c";
2423 pp2 = G.global_argv;
2426 /* *pp = NULL; - is already there */
2428 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
2429 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2430 execv(bb_busybox_exec_path, G.argv_from_re_execing);
2431 /* Fallback. Useful for init=/bin/hush usage etc */
2432 if (G.argv0_for_re_execing[0] == '/')
2433 execv(G.argv0_for_re_execing, G.argv_from_re_execing);
2434 xfunc_error_retval = 127;
2435 bb_error_msg_and_die("can't re-execute the shell");
2438 static void clean_up_after_re_execute(void)
2440 char **pp = G.argv_from_re_execing;
2442 /* Must match re_execute_shell's allocations (if any) */
2444 G.argv_from_re_execing = NULL;
2449 static int run_list(struct pipe *pi);
2451 /* Called after [v]fork() in run_pipe
2453 static void pseudo_exec(nommu_save_t *nommu_save,
2454 struct command *command,
2455 char **argv_expanded) NORETURN;
2456 static void pseudo_exec(nommu_save_t *nommu_save,
2457 struct command *command,
2458 char **argv_expanded)
2460 if (command->argv) {
2461 pseudo_exec_argv(nommu_save, command->argv,
2462 command->assignment_cnt, argv_expanded);
2465 if (command->group) {
2466 /* Cases when we are here:
2469 * ... | ( list ) | ...
2470 * ... | { list } | ...
2474 debug_printf_exec("pseudo_exec: run_list\n");
2475 reset_traps_to_defaults();
2476 rcode = run_list(command->group);
2477 /* OK to leak memory by not calling free_pipe_list,
2478 * since this process is about to exit */
2481 re_execute_shell(command->group_as_string);
2485 /* Case when we are here: ... | >file */
2486 debug_printf_exec("pseudo_exec'ed null command\n");
2487 _exit(EXIT_SUCCESS);
2491 static const char *get_cmdtext(struct pipe *pi)
2497 /* This is subtle. ->cmdtext is created only on first backgrounding.
2498 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
2499 * On subsequent bg argv is trashed, but we won't use it */
2502 argv = pi->cmds[0].argv;
2503 if (!argv || !argv[0]) {
2504 pi->cmdtext = xzalloc(1);
2509 do len += strlen(*argv) + 1; while (*++argv);
2510 pi->cmdtext = p = xmalloc(len);
2511 argv = pi->cmds[0].argv;
2513 len = strlen(*argv);
2514 memcpy(p, *argv, len);
2522 static void insert_bg_job(struct pipe *pi)
2524 struct pipe *thejob;
2527 /* Linear search for the ID of the job to use */
2529 for (thejob = G.job_list; thejob; thejob = thejob->next)
2530 if (thejob->jobid >= pi->jobid)
2531 pi->jobid = thejob->jobid + 1;
2533 /* Add thejob to the list of running jobs */
2535 thejob = G.job_list = xmalloc(sizeof(*thejob));
2537 for (thejob = G.job_list; thejob->next; thejob = thejob->next)
2539 thejob->next = xmalloc(sizeof(*thejob));
2540 thejob = thejob->next;
2543 /* Physically copy the struct job */
2544 memcpy(thejob, pi, sizeof(struct pipe));
2545 thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
2546 /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
2547 for (i = 0; i < pi->num_cmds; i++) {
2548 // TODO: do we really need to have so many fields which are just dead weight
2549 // at execution stage?
2550 thejob->cmds[i].pid = pi->cmds[i].pid;
2551 /* all other fields are not used and stay zero */
2553 thejob->next = NULL;
2554 thejob->cmdtext = xstrdup(get_cmdtext(pi));
2556 /* We don't wait for background thejobs to return -- append it
2557 to the list of backgrounded thejobs and leave it alone */
2558 if (G_interactive_fd)
2559 printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
2560 G.last_bg_pid = thejob->cmds[0].pid;
2561 G.last_jobid = thejob->jobid;
2564 static void remove_bg_job(struct pipe *pi)
2566 struct pipe *prev_pipe;
2568 if (pi == G.job_list) {
2569 G.job_list = pi->next;
2571 prev_pipe = G.job_list;
2572 while (prev_pipe->next != pi)
2573 prev_pipe = prev_pipe->next;
2574 prev_pipe->next = pi->next;
2577 G.last_jobid = G.job_list->jobid;
2582 /* Remove a backgrounded job */
2583 static void delete_finished_bg_job(struct pipe *pi)
2586 pi->stopped_cmds = 0;
2592 /* Check to see if any processes have exited -- if they
2593 * have, figure out why and see if a job has completed */
2594 static int checkjobs(struct pipe* fg_pipe)
2604 debug_printf_jobs("checkjobs %p\n", fg_pipe);
2607 // if (G.handled_SIGCHLD == G.count_SIGCHLD)
2608 // /* avoid doing syscall, nothing there anyway */
2611 attributes = WUNTRACED;
2612 if (fg_pipe == NULL)
2613 attributes |= WNOHANG;
2615 /* Do we do this right?
2616 * bash-3.00# sleep 20 | false
2618 * [3]+ Stopped sleep 20 | false
2619 * bash-3.00# echo $?
2620 * 1 <========== bg pipe is not fully done, but exitcode is already known!
2623 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
2624 //are stopped. Testcase: "cat | cat" in a script (not on command line)
2625 // + killall -STOP cat
2632 // i = G.count_SIGCHLD;
2633 childpid = waitpid(-1, &status, attributes);
2634 if (childpid <= 0) {
2635 if (childpid && errno != ECHILD)
2636 bb_perror_msg("waitpid");
2637 // else /* Until next SIGCHLD, waitpid's are useless */
2638 // G.handled_SIGCHLD = i;
2641 dead = WIFEXITED(status) || WIFSIGNALED(status);
2644 if (WIFSTOPPED(status))
2645 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
2646 childpid, WSTOPSIG(status), WEXITSTATUS(status));
2647 if (WIFSIGNALED(status))
2648 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
2649 childpid, WTERMSIG(status), WEXITSTATUS(status));
2650 if (WIFEXITED(status))
2651 debug_printf_jobs("pid %d exited, exitcode %d\n",
2652 childpid, WEXITSTATUS(status));
2654 /* Were we asked to wait for fg pipe? */
2656 for (i = 0; i < fg_pipe->num_cmds; i++) {
2657 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
2658 if (fg_pipe->cmds[i].pid != childpid)
2660 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
2662 fg_pipe->cmds[i].pid = 0;
2663 fg_pipe->alive_cmds--;
2664 if (i == fg_pipe->num_cmds - 1) {
2665 /* last process gives overall exitstatus */
2666 rcode = WEXITSTATUS(status);
2667 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
2670 fg_pipe->cmds[i].is_stopped = 1;
2671 fg_pipe->stopped_cmds++;
2673 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
2674 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
2675 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
2676 /* All processes in fg pipe have exited/stopped */
2678 if (fg_pipe->alive_cmds)
2679 insert_bg_job(fg_pipe);
2683 /* There are still running processes in the fg pipe */
2684 goto wait_more; /* do waitpid again */
2686 /* it wasnt fg_pipe, look for process in bg pipes */
2690 /* We asked to wait for bg or orphaned children */
2691 /* No need to remember exitcode in this case */
2692 for (pi = G.job_list; pi; pi = pi->next) {
2693 for (i = 0; i < pi->num_cmds; i++) {
2694 if (pi->cmds[i].pid == childpid)
2695 goto found_pi_and_prognum;
2698 /* Happens when shell is used as init process (init=/bin/sh) */
2699 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
2700 continue; /* do waitpid again */
2702 found_pi_and_prognum:
2705 pi->cmds[i].pid = 0;
2707 if (!pi->alive_cmds) {
2708 if (G_interactive_fd)
2709 printf(JOB_STATUS_FORMAT, pi->jobid,
2710 "Done", pi->cmdtext);
2711 delete_finished_bg_job(pi);
2715 pi->cmds[i].is_stopped = 1;
2719 } /* while (waitpid succeeds)... */
2725 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
2728 int rcode = checkjobs(fg_pipe);
2729 /* Job finished, move the shell to the foreground */
2730 p = getpgid(0); /* pgid of our process */
2731 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
2732 tcsetpgrp(G_interactive_fd, p);
2737 /* Start all the jobs, but don't wait for anything to finish.
2740 * Return code is normally -1, when the caller has to wait for children
2741 * to finish to determine the exit status of the pipe. If the pipe
2742 * is a simple builtin command, however, the action is done by the
2743 * time run_pipe returns, and the exit code is provided as the
2746 * Returns -1 only if started some children. IOW: we have to
2747 * mask out retvals of builtins etc with 0xff!
2749 * The only case when we do not need to [v]fork is when the pipe
2750 * is single, non-backgrounded, non-subshell command. Examples:
2751 * cmd ; ... { list } ; ...
2752 * cmd && ... { list } && ...
2753 * cmd || ... { list } || ...
2754 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
2755 * or (if SH_STANDALONE) an applet, and we can run the { list }
2756 * with run_list(). If it isn't one of these, we fork and exec cmd.
2758 * Cases when we must fork:
2759 * non-single: cmd | cmd
2760 * backgrounded: cmd & { list } &
2761 * subshell: ( list ) [&]
2763 static int run_pipe(struct pipe *pi)
2765 static const char *const null_ptr = NULL;
2768 int pipefds[2]; /* pipefds[0] is for reading */
2769 struct command *command;
2770 char **argv_expanded;
2773 /* it is not always needed, but we aim to smaller code */
2774 int squirrel[] = { -1, -1, -1 };
2777 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
2779 USE_HUSH_JOB(pi->pgrp = -1;)
2780 pi->stopped_cmds = 0;
2781 command = &(pi->cmds[0]);
2782 argv_expanded = NULL;
2784 if (pi->num_cmds != 1
2785 || pi->followup == PIPE_BG
2786 || command->grp_type == GRP_SUBSHELL
2793 debug_printf_exec(": group:%p argv:'%s'\n",
2794 command->group, command->argv ? command->argv[0] : "NONE");
2796 if (command->group) {
2797 #if ENABLE_HUSH_FUNCTIONS
2798 if (command->grp_type == GRP_FUNCTION) {
2799 /* func () { list } */
2800 bb_error_msg("here we ought to remember function definition, and go on");
2801 return EXIT_SUCCESS;
2805 debug_printf("non-subshell group\n");
2806 setup_redirects(command, squirrel);
2807 debug_printf_exec(": run_list\n");
2808 rcode = run_list(command->group) & 0xff;
2809 restore_redirects(squirrel);
2810 debug_printf_exec("run_pipe return %d\n", rcode);
2811 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2815 argv = command->argv ? command->argv : (char **) &null_ptr;
2817 const struct built_in_command *x;
2818 char **new_env = NULL;
2819 char **old_env = NULL;
2821 if (argv[command->assignment_cnt] == NULL) {
2822 /* Assignments, but no command */
2823 /* Ensure redirects take effect. Try "a=t >file" */
2824 setup_redirects(command, squirrel);
2825 restore_redirects(squirrel);
2826 /* Set shell variables */
2828 p = expand_string_to_string(*argv);
2829 debug_printf_exec("set shell var:'%s'->'%s'\n",
2831 set_local_var(p, 0, 0);
2834 /* Do we need to flag set_local_var() errors?
2835 * "assignment to readonly var" and "putenv error"
2837 return EXIT_SUCCESS;
2840 /* Expand the rest into (possibly) many strings each */
2841 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
2843 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2844 if (strcmp(argv_expanded[0], x->cmd) != 0)
2846 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
2847 debug_printf("exec with redirects only\n");
2848 setup_redirects(command, NULL);
2849 rcode = EXIT_SUCCESS;
2850 goto clean_up_and_ret1;
2852 debug_printf("builtin inline %s\n", argv_expanded[0]);
2853 /* XXX setup_redirects acts on file descriptors, not FILEs.
2854 * This is perfect for work that comes after exec().
2855 * Is it really safe for inline use? Experimentally,
2856 * things seem to work with glibc. */
2857 setup_redirects(command, squirrel);
2858 new_env = expand_assignments(argv, command->assignment_cnt);
2859 old_env = putenv_all_and_save_old(new_env);
2860 debug_printf_exec(": builtin '%s' '%s'...\n",
2861 x->cmd, argv_expanded[1]);
2862 rcode = x->function(argv_expanded) & 0xff;
2863 #if ENABLE_FEATURE_SH_STANDALONE
2866 restore_redirects(squirrel);
2867 free_strings_and_unsetenv(new_env, 1);
2868 putenv_all(old_env);
2869 free(old_env); /* not free_strings()! */
2871 free(argv_expanded);
2872 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2873 debug_printf_exec("run_pipe return %d\n", rcode);
2876 #if ENABLE_FEATURE_SH_STANDALONE
2877 i = find_applet_by_name(argv_expanded[0]);
2878 if (i >= 0 && APPLET_IS_NOFORK(i)) {
2879 setup_redirects(command, squirrel);
2880 save_nofork_data(&G.nofork_save);
2881 new_env = expand_assignments(argv, command->assignment_cnt);
2882 old_env = putenv_all_and_save_old(new_env);
2883 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
2884 argv_expanded[0], argv_expanded[1]);
2885 rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
2886 goto clean_up_and_ret;
2889 /* It is neither builtin nor applet. We must fork. */
2893 /* NB: argv_expanded may already be created, and that
2894 * might include `cmd` runs! Do not rerun it! We *must*
2895 * use argv_expanded if it's non-NULL */
2897 /* Going to fork a child per each pipe member */
2901 for (i = 0; i < pi->num_cmds; i++) {
2903 volatile nommu_save_t nommu_save;
2904 nommu_save.new_env = NULL;
2905 nommu_save.old_env = NULL;
2906 nommu_save.argv = NULL;
2908 command = &(pi->cmds[i]);
2909 if (command->argv) {
2910 debug_printf_exec(": pipe member '%s' '%s'...\n",
2911 command->argv[0], command->argv[1]);
2913 debug_printf_exec(": pipe member with no argv\n");
2916 /* pipes are inserted between pairs of commands */
2919 if ((i + 1) < pi->num_cmds)
2922 command->pid = BB_MMU ? fork() : vfork();
2923 if (!command->pid) { /* child */
2925 die_sleep = 0; /* do not restore tty pgrp on xfunc death */
2927 /* Every child adds itself to new process group
2928 * with pgid == pid_of_first_child_in_pipe */
2929 if (G.run_list_level == 1 && G_interactive_fd) {
2932 if (pgrp < 0) /* true for 1st process only */
2934 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
2935 /* We do it in *every* child, not just first,
2937 tcsetpgrp(G_interactive_fd, pgrp);
2941 xmove_fd(nextin, 0);
2942 xmove_fd(pipefds[1], 1); /* write end */
2944 close(pipefds[0]); /* read end */
2945 /* Like bash, explicit redirects override pipes,
2946 * and the pipe fd is available for dup'ing. */
2947 setup_redirects(command, NULL);
2949 /* Restore default handlers just prior to exec */
2950 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
2952 /* Stores to nommu_save list of env vars putenv'ed
2953 * (NOMMU, on MMU we don't need that) */
2954 /* cast away volatility... */
2955 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
2956 /* pseudo_exec() does not return */
2959 /* parent or error */
2961 die_sleep = -1; /* restore tty pgrp on xfunc death */
2964 /* Clean up after vforked child */
2965 clean_up_after_re_execute();
2966 free(nommu_save.argv);
2967 free_strings_and_unsetenv(nommu_save.new_env, 1);
2968 putenv_all(nommu_save.old_env);
2970 free(argv_expanded);
2971 argv_expanded = NULL;
2972 if (command->pid < 0) { /* [v]fork failed */
2973 /* Clearly indicate, was it fork or vfork */
2974 bb_perror_msg(BB_MMU ? "fork" : "vfork");
2978 /* Second and next children need to know pid of first one */
2980 pi->pgrp = command->pid;
2986 if ((i + 1) < pi->num_cmds)
2987 close(pipefds[1]); /* write end */
2988 /* Pass read (output) pipe end to next iteration */
2989 nextin = pipefds[0];
2992 if (!pi->alive_cmds) {
2993 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
2997 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
3001 #ifndef debug_print_tree
3002 static void debug_print_tree(struct pipe *pi, int lvl)
3004 static const char *const PIPE[] = {
3010 static const char *RES[] = {
3011 [RES_NONE ] = "NONE" ,
3014 [RES_THEN ] = "THEN" ,
3015 [RES_ELIF ] = "ELIF" ,
3016 [RES_ELSE ] = "ELSE" ,
3019 #if ENABLE_HUSH_LOOPS
3020 [RES_FOR ] = "FOR" ,
3021 [RES_WHILE] = "WHILE",
3022 [RES_UNTIL] = "UNTIL",
3024 [RES_DONE ] = "DONE" ,
3026 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3029 #if ENABLE_HUSH_CASE
3030 [RES_CASE ] = "CASE" ,
3031 [RES_MATCH] = "MATCH",
3032 [RES_CASEI] = "CASEI",
3033 [RES_ESAC ] = "ESAC" ,
3035 [RES_XXXX ] = "XXXX" ,
3036 [RES_SNTX ] = "SNTX" ,
3038 static const char *const GRPTYPE[] = {
3041 #if ENABLE_HUSH_FUNCTIONS
3050 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3051 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3053 while (prn < pi->num_cmds) {
3054 struct command *command = &pi->cmds[prn];
3055 char **argv = command->argv;
3057 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
3059 command->assignment_cnt);
3060 if (command->group) {
3061 fprintf(stderr, " group %s: (argv=%p)\n",
3062 GRPTYPE[command->grp_type],
3064 debug_print_tree(command->group, lvl+1);
3068 if (argv) while (*argv) {
3069 fprintf(stderr, " '%s'", *argv);
3072 fprintf(stderr, "\n");
3081 /* NB: called by pseudo_exec, and therefore must not modify any
3082 * global data until exec/_exit (we can be a child after vfork!) */
3083 static int run_list(struct pipe *pi)
3085 #if ENABLE_HUSH_CASE
3086 char *case_word = NULL;
3088 #if ENABLE_HUSH_LOOPS
3089 struct pipe *loop_top = NULL;
3090 char *for_varname = NULL;
3091 char **for_lcur = NULL;
3092 char **for_list = NULL;
3094 smallint last_followup;
3096 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
3097 smalluint cond_code = 0;
3099 enum { cond_code = 0 };
3102 smallint rword; /* enum reserved_style */
3103 smallint last_rword; /* ditto */
3106 debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
3108 #if ENABLE_HUSH_LOOPS
3109 /* Check syntax for "for" */
3110 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
3111 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
3113 /* current word is FOR or IN (BOLD in comments below) */
3114 if (cpipe->next == NULL) {
3115 syntax("malformed for");
3116 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
3119 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
3120 if (cpipe->next->res_word == RES_DO)
3122 /* next word is not "do". It must be "in" then ("FOR v in ...") */
3123 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
3124 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
3126 syntax("malformed for");
3127 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
3133 /* Past this point, all code paths should jump to ret: label
3134 * in order to return, no direct "return" statements please.
3135 * This helps to ensure that no memory is leaked. */
3137 ////TODO: ctrl-Z handling needs re-thinking and re-testing
3140 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
3141 * We are saving state before entering outermost list ("while...done")
3142 * so that ctrl-Z will correctly background _entire_ outermost list,
3143 * not just a part of it (like "sleep 1 | exit 2") */
3144 if (++G.run_list_level == 1 && G_interactive_fd) {
3145 if (sigsetjmp(G.toplevel_jb, 1)) {
3146 /* ctrl-Z forked and we are parent; or ctrl-C.
3147 * Sighandler has longjmped us here */
3148 signal(SIGINT, SIG_IGN);
3149 signal(SIGTSTP, SIG_IGN);
3150 /* Restore level (we can be coming from deep inside
3152 G.run_list_level = 1;
3153 #if ENABLE_FEATURE_SH_STANDALONE
3154 if (G.nofork_save.saved) { /* if save area is valid */
3155 debug_printf_jobs("exiting nofork early\n");
3156 restore_nofork_data(&G.nofork_save);
3159 //// if (G.ctrl_z_flag) {
3160 //// /* ctrl-Z has forked and stored pid of the child in pi->pid.
3161 //// * Remember this child as background job */
3162 //// insert_bg_job(pi);
3164 /* ctrl-C. We just stop doing whatever we were doing */
3167 USE_HUSH_LOOPS(loop_top = NULL;)
3168 USE_HUSH_LOOPS(G.depth_of_loop = 0;)
3172 //// /* ctrl-Z handler will store pid etc in pi */
3173 //// G.toplevel_list = pi;
3174 //// G.ctrl_z_flag = 0;
3175 ////#if ENABLE_FEATURE_SH_STANDALONE
3176 //// G.nofork_save.saved = 0; /* in case we will run a nofork later */
3178 //// signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
3179 //// signal(SIGINT, handler_ctrl_c);
3185 last_rword = RES_XXXX;
3187 last_followup = PIPE_SEQ;
3188 rcode = G.last_exitcode;
3190 /* Go through list of pipes, (maybe) executing them. */
3191 for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
3195 IF_HAS_KEYWORDS(rword = pi->res_word;)
3196 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
3197 rword, cond_code, last_rword);
3198 #if ENABLE_HUSH_LOOPS
3199 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
3200 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
3202 /* start of a loop: remember where loop starts */
3207 /* Still in the same "if...", "then..." or "do..." branch? */
3208 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
3209 if ((rcode == 0 && last_followup == PIPE_OR)
3210 || (rcode != 0 && last_followup == PIPE_AND)
3212 /* It is "<true> || CMD" or "<false> && CMD"
3213 * and we should not execute CMD */
3214 debug_printf_exec("skipped cmd because of || or &&\n");
3215 last_followup = pi->followup;
3219 last_followup = pi->followup;
3220 IF_HAS_KEYWORDS(last_rword = rword;)
3223 if (rword == RES_THEN) {
3224 /* if false; then ... fi has exitcode 0! */
3225 G.last_exitcode = rcode = EXIT_SUCCESS;
3226 /* "if <false> THEN cmd": skip cmd */
3230 if (rword == RES_ELSE || rword == RES_ELIF) {
3231 /* "if <true> then ... ELSE/ELIF cmd":
3232 * skip cmd and all following ones */
3237 #if ENABLE_HUSH_LOOPS
3238 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
3240 /* first loop through for */
3242 static const char encoded_dollar_at[] ALIGN1 = {
3243 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
3244 }; /* encoded representation of "$@" */
3245 static const char *const encoded_dollar_at_argv[] = {
3246 encoded_dollar_at, NULL
3247 }; /* argv list with one element: "$@" */
3250 vals = (char**)encoded_dollar_at_argv;
3251 if (pi->next->res_word == RES_IN) {
3252 /* if no variable values after "in" we skip "for" */
3253 if (!pi->next->cmds[0].argv) {
3254 G.last_exitcode = rcode = EXIT_SUCCESS;
3255 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
3258 vals = pi->next->cmds[0].argv;
3259 } /* else: "for var; do..." -> assume "$@" list */
3260 /* create list of variable values */
3261 debug_print_strings("for_list made from", vals);
3262 for_list = expand_strvec_to_strvec(vals);
3263 for_lcur = for_list;
3264 debug_print_strings("for_list", for_list);
3265 for_varname = pi->cmds[0].argv[0];
3266 pi->cmds[0].argv[0] = NULL;
3268 free(pi->cmds[0].argv[0]);
3270 /* "for" loop is over, clean up */
3274 pi->cmds[0].argv[0] = for_varname;
3277 /* Insert next value from for_lcur */
3278 //TODO: does it need escaping?
3279 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
3280 pi->cmds[0].assignment_cnt = 1;
3282 if (rword == RES_IN) {
3283 continue; /* "for v IN list;..." - "in" has no cmds anyway */
3285 if (rword == RES_DONE) {
3286 continue; /* "done" has no cmds too */
3289 #if ENABLE_HUSH_CASE
3290 if (rword == RES_CASE) {
3291 case_word = expand_strvec_to_string(pi->cmds->argv);
3294 if (rword == RES_MATCH) {
3297 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
3299 /* all prev words didn't match, does this one match? */
3300 argv = pi->cmds->argv;
3302 char *pattern = expand_string_to_string(*argv);
3303 /* TODO: which FNM_xxx flags to use? */
3304 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
3306 if (cond_code == 0) { /* match! we will execute this branch */
3307 free(case_word); /* make future "word)" stop */
3315 if (rword == RES_CASEI) { /* inside of a case branch */
3317 continue; /* not matched yet, skip this pipe */
3320 /* Just pressing <enter> in shell should check for jobs.
3321 * OTOH, in non-interactive shell this is useless
3322 * and only leads to extra job checks */
3323 if (pi->num_cmds == 0) {
3324 if (G_interactive_fd)
3325 goto check_jobs_and_continue;
3329 /* After analyzing all keywords and conditions, we decided
3330 * to execute this pipe. NB: have to do checkjobs(NULL)
3331 * after run_pipe to collect any background children,
3332 * even if list execution is to be stopped. */
3333 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
3336 #if ENABLE_HUSH_LOOPS
3337 G.flag_break_continue = 0;
3339 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
3341 /* We only ran a builtin: rcode is already known
3342 * and we don't need to wait for anything. */
3343 G.last_exitcode = rcode;
3344 debug_printf_exec(": builtin exitcode %d\n", rcode);
3345 check_and_run_traps(0);
3346 #if ENABLE_HUSH_LOOPS
3347 /* Was it "break" or "continue"? */
3348 if (G.flag_break_continue) {
3349 smallint fbc = G.flag_break_continue;
3350 /* We might fall into outer *loop*,
3351 * don't want to break it too */
3353 G.depth_break_continue--;
3354 if (G.depth_break_continue == 0)
3355 G.flag_break_continue = 0;
3356 /* else: e.g. "continue 2" should *break* once, *then* continue */
3357 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
3358 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
3359 goto check_jobs_and_break;
3360 /* "continue": simulate end of loop */
3365 } else if (pi->followup == PIPE_BG) {
3366 /* What does bash do with attempts to background builtins? */
3367 /* even bash 3.2 doesn't do that well with nested bg:
3368 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
3369 * I'm NOT treating inner &'s as jobs */
3370 check_and_run_traps(0);
3372 if (G.run_list_level == 1)
3375 G.last_exitcode = rcode = EXIT_SUCCESS;
3376 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
3379 if (G.run_list_level == 1 && G_interactive_fd) {
3380 /* Waits for completion, then fg's main shell */
3381 rcode = checkjobs_and_fg_shell(pi);
3382 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
3383 check_and_run_traps(0);
3386 { /* This one just waits for completion */
3387 rcode = checkjobs(pi);
3388 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
3389 check_and_run_traps(0);
3391 G.last_exitcode = rcode;
3395 /* Analyze how result affects subsequent commands */
3397 if (rword == RES_IF || rword == RES_ELIF)
3400 #if ENABLE_HUSH_LOOPS
3401 /* Beware of "while false; true; do ..."! */
3402 if (pi->next && pi->next->res_word == RES_DO) {
3403 if (rword == RES_WHILE) {
3405 /* "while false; do...done" - exitcode 0 */
3406 G.last_exitcode = rcode = EXIT_SUCCESS;
3407 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
3408 goto check_jobs_and_break;
3411 if (rword == RES_UNTIL) {
3413 debug_printf_exec(": until expr is true: breaking\n");
3414 check_jobs_and_break:
3422 check_jobs_and_continue:
3427 //// if (G.ctrl_z_flag) {
3428 //// /* ctrl-Z forked somewhere in the past, we are the child,
3429 //// * and now we completed running the list. Exit. */
3435 //// if (!G.run_list_level && G_interactive_fd) {
3436 //// signal(SIGTSTP, SIG_IGN);
3437 //// signal(SIGINT, SIG_IGN);
3440 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
3441 #if ENABLE_HUSH_LOOPS
3446 #if ENABLE_HUSH_CASE
3452 /* Select which version we will use */
3453 static int run_and_free_list(struct pipe *pi)
3456 debug_printf_exec("run_and_free_list entered\n");
3458 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
3459 rcode = run_list(pi);
3461 /* free_pipe_list has the side effect of clearing memory.
3462 * In the long run that function can be merged with run_list,
3463 * but doing that now would hobble the debugging effort. */
3464 free_pipe_list(pi, /* indent: */ 0);
3465 debug_printf_exec("run_and_free_list return %d\n", rcode);
3470 static struct pipe *new_pipe(void)
3473 pi = xzalloc(sizeof(struct pipe));
3474 /*pi->followup = 0; - deliberately invalid value */
3475 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3479 /* Command (member of a pipe) is complete. The only possible error here
3480 * is out of memory, in which case xmalloc exits. */
3481 static int done_command(struct parse_context *ctx)
3483 /* The command is really already in the pipe structure, so
3484 * advance the pipe counter and make a new, null command. */
3485 struct pipe *pi = ctx->pipe;
3486 struct command *command = ctx->command;
3489 if (command->group == NULL
3490 && command->argv == NULL
3491 && command->redirects == NULL
3493 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3494 memset(command, 0, sizeof(*command)); /* paranoia */
3495 return pi->num_cmds;
3498 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3499 //debug_print_tree(ctx->list_head, 20);
3501 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3504 /* Only real trickiness here is that the uncommitted
3505 * command structure is not counted in pi->num_cmds. */
3506 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3507 command = &pi->cmds[pi->num_cmds];
3508 memset(command, 0, sizeof(*command));
3510 ctx->command = command;
3511 /* but ctx->pipe and ctx->list_head remain unchanged */
3513 return pi->num_cmds; /* used only for 0/nonzero check */
3516 static void done_pipe(struct parse_context *ctx, pipe_style type)
3520 debug_printf_parse("done_pipe entered, followup %d\n", type);
3521 /* Close previous command */
3522 not_null = done_command(ctx);
3523 ctx->pipe->followup = type;
3525 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3526 ctx->ctx_inverted = 0;
3527 ctx->pipe->res_word = ctx->ctx_res_w;
3530 /* Without this check, even just <enter> on command line generates
3531 * tree of three NOPs (!). Which is harmless but annoying.
3532 * IOW: it is safe to do it unconditionally.
3533 * RES_NONE case is for "for a in; do ..." (empty IN set)
3534 * and other cases to work. */
3537 || ctx->ctx_res_w == RES_FI
3538 || ctx->ctx_res_w == RES_DONE
3539 || ctx->ctx_res_w == RES_FOR
3540 || ctx->ctx_res_w == RES_IN
3541 || ctx->ctx_res_w == RES_ESAC
3545 debug_printf_parse("done_pipe: adding new pipe: "
3546 "not_null:%d ctx->ctx_res_w:%d\n",
3547 not_null, ctx->ctx_res_w);
3549 ctx->pipe->next = new_p;
3551 /* RES_THEN, RES_DO etc are "sticky" -
3552 * they remain set for commands inside if/while.
3553 * This is used to control execution.
3554 * RES_FOR and RES_IN are NOT sticky (needed to support
3555 * cases where variable or value happens to match a keyword):
3557 #if ENABLE_HUSH_LOOPS
3558 if (ctx->ctx_res_w == RES_FOR
3559 || ctx->ctx_res_w == RES_IN)
3560 ctx->ctx_res_w = RES_NONE;
3562 #if ENABLE_HUSH_CASE
3563 if (ctx->ctx_res_w == RES_MATCH)
3564 ctx->ctx_res_w = RES_CASEI;
3566 ctx->command = NULL; /* trick done_command below */
3567 /* Create the memory for command, roughly:
3568 * ctx->pipe->cmds = new struct command;
3569 * ctx->command = &ctx->pipe->cmds[0];
3572 //debug_print_tree(ctx->list_head, 10);
3574 debug_printf_parse("done_pipe return\n");
3577 static void initialize_context(struct parse_context *ctx)
3579 memset(ctx, 0, sizeof(*ctx));
3580 ctx->pipe = ctx->list_head = new_pipe();
3581 /* Create the memory for command, roughly:
3582 * ctx->pipe->cmds = new struct command;
3583 * ctx->command = &ctx->pipe->cmds[0];
3588 /* If a reserved word is found and processed, parse context is modified
3589 * and 1 is returned.
3592 struct reserved_combo {
3595 unsigned char assignment_flag;
3599 FLAG_END = (1 << RES_NONE ),
3601 FLAG_IF = (1 << RES_IF ),
3602 FLAG_THEN = (1 << RES_THEN ),
3603 FLAG_ELIF = (1 << RES_ELIF ),
3604 FLAG_ELSE = (1 << RES_ELSE ),
3605 FLAG_FI = (1 << RES_FI ),
3607 #if ENABLE_HUSH_LOOPS
3608 FLAG_FOR = (1 << RES_FOR ),
3609 FLAG_WHILE = (1 << RES_WHILE),
3610 FLAG_UNTIL = (1 << RES_UNTIL),
3611 FLAG_DO = (1 << RES_DO ),
3612 FLAG_DONE = (1 << RES_DONE ),
3613 FLAG_IN = (1 << RES_IN ),
3615 #if ENABLE_HUSH_CASE
3616 FLAG_MATCH = (1 << RES_MATCH),
3617 FLAG_ESAC = (1 << RES_ESAC ),
3619 FLAG_START = (1 << RES_XXXX ),
3622 static const struct reserved_combo* match_reserved_word(o_string *word)
3624 /* Mostly a list of accepted follow-up reserved words.
3625 * FLAG_END means we are done with the sequence, and are ready
3626 * to turn the compound list into a command.
3627 * FLAG_START means the word must start a new compound list.
3629 static const struct reserved_combo reserved_list[] = {
3631 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3632 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
3633 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3634 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
3635 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
3636 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3638 #if ENABLE_HUSH_LOOPS
3639 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3640 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3641 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3642 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3643 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
3644 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3646 #if ENABLE_HUSH_CASE
3647 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3648 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3651 const struct reserved_combo *r;
3653 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3654 if (strcmp(word->data, r->literal) == 0)
3659 static int reserved_word(o_string *word, struct parse_context *ctx)
3661 #if ENABLE_HUSH_CASE
3662 static const struct reserved_combo reserved_match = {
3663 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3666 const struct reserved_combo *r;
3668 r = match_reserved_word(word);
3672 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3673 #if ENABLE_HUSH_CASE
3674 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
3675 /* "case word IN ..." - IN part starts first match part */
3676 r = &reserved_match;
3679 if (r->flag == 0) { /* '!' */
3680 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3681 syntax("! ! command");
3682 IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
3684 ctx->ctx_inverted = 1;
3687 if (r->flag & FLAG_START) {
3688 struct parse_context *old;
3689 old = xmalloc(sizeof(*old));
3690 debug_printf_parse("push stack %p\n", old);
3691 *old = *ctx; /* physical copy */
3692 initialize_context(ctx);
3694 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3696 ctx->ctx_res_w = RES_SNTX;
3699 ctx->ctx_res_w = r->res;
3700 ctx->old_flag = r->flag;
3701 if (ctx->old_flag & FLAG_END) {
3702 struct parse_context *old;
3703 done_pipe(ctx, PIPE_SEQ);
3704 debug_printf_parse("pop stack %p\n", ctx->stack);
3706 old->command->group = ctx->list_head;
3707 old->command->grp_type = GRP_NORMAL;
3709 o_addstr(&old->as_string, ctx->as_string.data);
3710 o_free_unsafe(&ctx->as_string);
3711 old->command->group_as_string = xstrdup(old->as_string.data);
3712 debug_printf_parse("pop, remembering as:'%s'\n",
3713 old->command->group_as_string);
3715 *ctx = *old; /* physical copy */
3718 word->o_assignment = r->assignment_flag;
3723 /* Word is complete, look at it and update parsing context.
3724 * Normal return is 0. Syntax errors return 1.
3725 * Note: on return, word is reset, but not o_free'd!
3727 static int done_word(o_string *word, struct parse_context *ctx)
3729 struct command *command = ctx->command;
3731 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3732 if (word->length == 0 && word->nonnull == 0) {
3733 debug_printf_parse("done_word return 0: true null, ignored\n");
3736 /* If this word wasn't an assignment, next ones definitely
3737 * can't be assignments. Even if they look like ones. */
3738 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3739 && word->o_assignment != WORD_IS_KEYWORD
3741 word->o_assignment = NOT_ASSIGNMENT;
3743 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3744 command->assignment_cnt++;
3745 word->o_assignment = MAYBE_ASSIGNMENT;
3748 if (ctx->pending_redirect) {
3749 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3750 * only if run as "bash", not "sh" */
3751 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3753 * ...the word that follows the redirection operator
3754 * shall be subjected to tilde expansion, parameter expansion,
3755 * command substitution, arithmetic expansion, and quote
3756 * removal. Pathname expansion shall not be performed
3757 * on the word by a non-interactive shell; an interactive
3758 * shell may perform it, but shall do so only when
3759 * the expansion would result in one word."
3761 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3762 word->o_assignment = NOT_ASSIGNMENT;
3763 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3765 /* "{ echo foo; } echo bar" - bad */
3766 /* NB: bash allows e.g.:
3767 * if true; then { echo foo; } fi
3768 * while if false; then false; fi do break; done
3770 * while if false; then false; fi; do; break; done
3772 if (command->group) {
3774 debug_printf_parse("done_word return 1: syntax error, "
3775 "groups and arglists don't mix\n");
3779 #if ENABLE_HUSH_CASE
3780 if (ctx->ctx_dsemicolon
3781 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3783 /* already done when ctx_dsemicolon was set to 1: */
3784 /* ctx->ctx_res_w = RES_MATCH; */
3785 ctx->ctx_dsemicolon = 0;
3788 if (!command->argv /* if it's the first word... */
3789 #if ENABLE_HUSH_LOOPS
3790 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3791 && ctx->ctx_res_w != RES_IN
3794 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
3795 if (reserved_word(word, ctx)) {
3797 debug_printf_parse("done_word return %d\n",
3798 (ctx->ctx_res_w == RES_SNTX));
3799 return (ctx->ctx_res_w == RES_SNTX);
3803 if (word->nonnull /* word had "xx" or 'xx' at least as part of it. */
3804 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3805 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3806 /* (otherwise it's known to be not empty and is already safe) */
3808 /* exclude "$@" - it can expand to no word despite "" */
3809 char *p = word->data;
3810 while (p[0] == SPECIAL_VAR_SYMBOL
3811 && (p[1] & 0x7f) == '@'
3812 && p[2] == SPECIAL_VAR_SYMBOL
3816 if (p == word->data || p[0] != '\0') {
3817 /* saw no "$@", or not only "$@" but some
3818 * real text is there too */
3819 /* insert "empty variable" reference, this makes
3820 * e.g. "", $empty"" etc to not disappear */
3821 o_addchr(word, SPECIAL_VAR_SYMBOL);
3822 o_addchr(word, SPECIAL_VAR_SYMBOL);
3825 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3826 debug_print_strings("word appended to argv", command->argv);
3830 ctx->pending_redirect = NULL;
3832 #if ENABLE_HUSH_LOOPS
3833 /* Force FOR to have just one word (variable name) */
3834 /* NB: basically, this makes hush see "for v in ..." syntax as if
3835 * as it is "for v; in ...". FOR and IN become two pipe structs
3837 if (ctx->ctx_res_w == RES_FOR) {
3838 //TODO: check that command->argv[0] is a valid variable name!
3839 done_pipe(ctx, PIPE_SEQ);
3842 #if ENABLE_HUSH_CASE
3843 /* Force CASE to have just one word */
3844 if (ctx->ctx_res_w == RES_CASE) {
3845 done_pipe(ctx, PIPE_SEQ);
3848 debug_printf_parse("done_word return 0\n");
3853 /* Peek ahead in the input to find out if we have a "&n" construct,
3854 * as in "2>&1", that represents duplicating a file descriptor.
3855 * Return: -3 if >&- "close fd" construct is seen,
3856 * -2 (syntax error), -1 if no & was seen, or the number found.
3859 #define redirect_dup_num(as_string, input) \
3860 redirect_dup_num(input)
3862 static int redirect_dup_num(o_string *as_string, struct in_str *input)
3870 ch = i_getch(input); /* get the & */
3872 o_addchr(as_string, ch);
3876 ch = i_getch(input);
3878 o_addchr(as_string, ch);
3880 return -3; /* "-" represents "close me" */
3884 while (ch != EOF && isdigit(ch)) {
3885 d = d*10 + (ch-'0');
3887 ch = i_getch(input);
3889 o_addchr(as_string, ch);
3895 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3897 bb_error_msg("ambiguous redirect");
3901 /* Return code is 0 normally, 1 if a syntax error is detected
3903 static int parse_redirect(struct parse_context *ctx,
3906 struct in_str *input)
3908 struct command *command = ctx->command;
3909 struct redir_struct *redir;
3910 struct redir_struct **redirp;
3914 if (style != REDIRECT_HEREDOC) {
3915 /* Check for a '2>&1' type redirect */
3916 dup_num = redirect_dup_num(&ctx->as_string, input);
3918 return 1; /* syntax error */
3920 //TODO: else { check for <<-word }
3922 if (style == REDIRECT_OVERWRITE && dup_num == -1) {
3923 int ch = i_peek(input);
3925 /* >|FILE redirect ("clobbering" >).
3926 * Since we do not support "set -o noclobber" yet,
3927 * >| and > are the same for now. Just eat |.
3929 ch = i_getch(input);
3931 o_addchr(&ctx->as_string, ch);
3936 /* Create a new redir_struct and append it to the linked list */
3937 redirp = &command->redirects;
3938 while ((redir = *redirp) != NULL) {
3939 redirp = &(redir->next);
3941 *redirp = redir = xzalloc(sizeof(*redir));
3942 /* redir->next = NULL; */
3943 /* redir->rd_filename = NULL; */
3944 redir->rd_type = style;
3945 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
3947 debug_printf_parse("redirect type %d %s\n", redir->fd, redir_table[style].descrip);
3949 redir->dup = dup_num;
3950 if (dup_num != -1) {
3951 /* Erik had a check here that the file descriptor in question
3952 * is legit; I postpone that to "run time"
3953 * A "-" representation of "close me" shows up as a -3 here */
3954 debug_printf_parse("duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
3956 /* Set ctx->pending_redirect, so we know what to do at the
3957 * end of the next parsed word. */
3958 ctx->pending_redirect = redir;
3963 /* If a redirect is immediately preceded by a number, that number is
3964 * supposed to tell which file descriptor to redirect. This routine
3965 * looks for such preceding numbers. In an ideal world this routine
3966 * needs to handle all the following classes of redirects...
3967 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3968 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3969 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3970 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3972 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3974 * ... If n is quoted, the number shall not be recognized as part of
3975 * the redirection expression. For example:
3977 * writes the character 2 into file a"
3978 * I am not sure we do it right (and not sure we care)
3980 * A -1 return means no valid number was found,
3981 * the caller should use the appropriate default for this redirection.
3983 static int redirect_opt_num(o_string *o)
3987 if (o->data == NULL)
3989 num = bb_strtou(o->data, NULL, 10);
3990 if (errno || num < 0)
3996 //TODO: add NOMMU as_string fill
3997 static char *fetch_till_str(struct in_str *input, const char *word)
3999 o_string heredoc = NULL_O_STRING;
4004 ch = i_getch(input);
4006 o_free_unsafe(&heredoc);
4010 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4011 heredoc.data[past_EOL] = '\0';
4012 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4013 return heredoc.data;
4015 past_EOL = heredoc.length + 1;
4017 o_addchr(&heredoc, ch);
4021 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4023 struct pipe *pi = ctx->list_head;
4027 struct command *cmd = pi->cmds;
4029 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4031 cmd->argv ? cmd->argv[0] : "NONE");
4032 for (i = 0; i < pi->num_cmds; i++) {
4033 struct redir_struct *redirect = cmd->redirects;
4035 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4036 i, cmd->argv ? cmd->argv[0] : "NONE");
4038 if (redirect->rd_type == REDIRECT_HEREDOC) {
4041 if (heredoc_cnt <= 0)
4042 return 1; /* error */
4043 redirect->rd_type = REDIRECT_HEREDOC2;
4044 p = fetch_till_str(input, redirect->rd_filename);
4046 return 1; /* unexpected EOF */
4047 free(redirect->rd_filename);
4048 redirect->rd_filename = p;
4051 redirect = redirect->next;
4057 /* Should be 0. If it isn't, it's a parse error */
4063 #define parse_stream(pstring, input, end_trigger) \
4064 parse_stream(input, end_trigger)
4066 static struct pipe *parse_stream(char **pstring,
4067 struct in_str *input,
4069 static void parse_and_run_string(const char *s);
4071 #if ENABLE_HUSH_TICK
4072 static FILE *generate_stream_from_string(const char *s)
4075 int pid, channel[2];
4078 pid = BB_MMU ? fork() : vfork();
4080 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
4082 if (pid == 0) { /* child */
4084 die_sleep = 0; /* do not restore tty pgrp on xfunc death */
4086 /* Process substitution is not considered to be usual
4087 * 'command execution'.
4088 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
4095 close(channel[0]); /* NB: close _first_, then move fd! */
4096 xmove_fd(channel[1], 1);
4097 /* Prevent it from trying to handle ctrl-z etc */
4098 USE_HUSH_JOB(G.run_list_level = 1;)
4100 reset_traps_to_defaults();
4101 parse_and_run_string(s);
4102 _exit(G.last_exitcode);
4104 /* We re-execute after vfork on NOMMU. This makes this script safe:
4105 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
4106 * huge=`cat BIG` # was blocking here forever
4109 re_execute_shell(s);
4115 die_sleep = -1; /* restore tty pgrp on xfunc death */
4117 clean_up_after_re_execute();
4119 pf = fdopen(channel[0], "r");
4123 /* Return code is exit status of the process that is run. */
4124 static int process_command_subs(o_string *dest, const char *s)
4127 struct in_str pipe_str;
4130 pf = generate_stream_from_string(s);
4133 close_on_exec_on(fileno(pf));
4135 /* Now send results of command back into original context */
4136 setup_file_in_str(&pipe_str, pf);
4138 while ((ch = i_getch(&pipe_str)) != EOF) {
4144 o_addchr(dest, '\n');
4147 o_addQchr(dest, ch);
4150 debug_printf("done reading from pipe, pclose()ing\n");
4151 /* Note: we got EOF, and we just close the read end of the pipe.
4152 * We do not wait for the `cmd` child to terminate. bash and ash do.
4154 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
4155 * `false`; echo $? - bash outputs "1"
4158 debug_printf("closed FILE from child. return 0\n");
4163 static int parse_group(o_string *dest, struct parse_context *ctx,
4164 struct in_str *input, int ch)
4166 /* dest contains characters seen prior to ( or {.
4167 * Typically it's empty, but for function defs,
4168 * it contains function name (without '()'). */
4169 struct pipe *pipe_list;
4171 struct command *command = ctx->command;
4173 debug_printf_parse("parse_group entered\n");
4174 #if ENABLE_HUSH_FUNCTIONS
4175 if (ch == 'F') { /* function definition? */
4176 bb_error_msg("aha '%s' is a function, parsing it...", dest->data);
4177 //command->fname = dest->data;
4178 command->grp_type = GRP_FUNCTION;
4179 //TODO: review every o_reset() location... do they handle all o_string fields correctly?
4180 memset(dest, 0, sizeof(*dest));
4183 if (command->argv /* word [word](... */
4184 || dest->length /* word(... */
4185 || dest->nonnull /* ""(... */
4188 debug_printf_parse("parse_group return 1: "
4189 "syntax error, groups and arglists don't mix\n");
4195 command->grp_type = GRP_SUBSHELL;
4199 char *as_string = NULL;
4201 pipe_list = parse_stream(&as_string, input, endch);
4204 o_addstr(&ctx->as_string, as_string);
4206 /* empty ()/{} or parse error? */
4207 if (!pipe_list || pipe_list == ERR_PTR) {
4212 debug_printf_parse("parse_group return 1: "
4213 "parse_stream returned %p\n", pipe_list);
4216 command->group = pipe_list;
4218 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4219 command->group_as_string = as_string;
4220 debug_printf_parse("end of group, remembering as:'%s'\n",
4221 command->group_as_string);
4224 debug_printf_parse("parse_group return 0\n");
4226 /* command remains "open", available for possible redirects */
4229 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
4230 /* Subroutines for copying $(...) and `...` things */
4231 static void add_till_backquote(o_string *dest, struct in_str *input);
4233 static void add_till_single_quote(o_string *dest, struct in_str *input)
4236 int ch = i_getch(input);
4244 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
4245 static void add_till_double_quote(o_string *dest, struct in_str *input)
4248 int ch = i_getch(input);
4251 if (ch == '\\') { /* \x. Copy both chars. */
4253 ch = i_getch(input);
4259 add_till_backquote(dest, input);
4263 //if (ch == '$') ...
4266 /* Process `cmd` - copy contents until "`" is seen. Complicated by
4268 * "Within the backquoted style of command substitution, backslash
4269 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4270 * The search for the matching backquote shall be satisfied by the first
4271 * backquote found without a preceding backslash; during this search,
4272 * if a non-escaped backquote is encountered within a shell comment,
4273 * a here-document, an embedded command substitution of the $(command)
4274 * form, or a quoted string, undefined results occur. A single-quoted
4275 * or double-quoted string that begins, but does not end, within the
4276 * "`...`" sequence produces undefined results."
4278 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4280 static void add_till_backquote(o_string *dest, struct in_str *input)
4283 int ch = i_getch(input);
4286 if (ch == '\\') { /* \x. Copy both chars unless it is \` */
4287 int ch2 = i_getch(input);
4288 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
4297 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
4298 * quoting and nested ()s.
4299 * "With the $(command) style of command substitution, all characters
4300 * following the open parenthesis to the matching closing parenthesis
4301 * constitute the command. Any valid shell script can be used for command,
4302 * except a script consisting solely of redirections which produces
4303 * unspecified results."
4305 * echo $(echo '(TEST)' BEST) (TEST) BEST
4306 * echo $(echo 'TEST)' BEST) TEST) BEST
4307 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
4309 static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
4313 int ch = i_getch(input);
4322 if (i_peek(input) == ')') {
4330 add_till_single_quote(dest, input);
4335 add_till_double_quote(dest, input);
4339 if (ch == '\\') { /* \x. Copy verbatim. Important for \(, \) */
4340 ch = i_getch(input);
4348 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
4350 /* Return code: 0 for OK, 1 for syntax error */
4352 #define handle_dollar(as_string, dest, input) \
4353 handle_dollar(dest, input)
4355 static int handle_dollar(o_string *as_string,
4357 struct in_str *input)
4360 int ch = i_peek(input); /* first character after the $ */
4361 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
4363 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
4365 ch = i_getch(input);
4367 if (as_string) o_addchr(as_string, ch);
4370 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4372 debug_printf_parse(": '%c'\n", ch);
4373 o_addchr(dest, ch | quote_mask);
4376 if (!isalnum(ch) && ch != '_')
4378 ch = i_getch(input);
4380 if (as_string) o_addchr(as_string, ch);
4383 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4384 } else if (isdigit(ch)) {
4386 ch = i_getch(input);
4388 if (as_string) o_addchr(as_string, ch);
4390 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4391 debug_printf_parse(": '%c'\n", ch);
4392 o_addchr(dest, ch | quote_mask);
4393 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4394 } else switch (ch) {
4396 case '!': /* last bg pid */
4397 case '?': /* last exit code */
4398 case '#': /* number of args */
4399 case '*': /* args */
4400 case '@': /* args */
4401 goto make_one_char_var;
4403 bool first_char, all_digits;
4405 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4406 ch = i_getch(input);
4408 if (as_string) o_addchr(as_string, ch);
4410 /* XXX maybe someone will try to escape the '}' */
4415 ch = i_getch(input);
4417 if (as_string) o_addchr(as_string, ch);
4424 /* ${#var}: length of var contents */
4426 else if (isdigit(ch)) {
4433 && ( (all_digits && !isdigit(ch))
4434 || (!all_digits && !isalnum(ch) && ch != '_')
4437 /* handle parameter expansions
4438 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4443 case ':': /* null modifier */
4444 if (expansion == 0) {
4445 debug_printf_parse(": null modifier\n");
4450 case '#': /* remove prefix */
4451 case '%': /* remove suffix */
4452 if (expansion == 0) {
4453 debug_printf_parse(": remove suffix/prefix\n");
4458 case '-': /* default value */
4459 case '=': /* assign default */
4460 case '+': /* alternative */
4461 case '?': /* error indicate */
4462 debug_printf_parse(": parameter expansion\n");
4467 syntax("unterminated ${name}");
4468 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
4473 debug_printf_parse(": '%c'\n", ch);
4474 o_addchr(dest, ch | quote_mask);
4478 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4481 #if (ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK)
4486 ch = i_getch(input);
4488 if (as_string) o_addchr(as_string, ch);
4490 # if ENABLE_SH_MATH_SUPPORT
4491 if (i_peek(input) == '(') {
4492 ch = i_getch(input);
4494 if (as_string) o_addchr(as_string, ch);
4496 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4497 o_addchr(dest, /*quote_mask |*/ '+');
4501 add_till_closing_paren(dest, input, true);
4504 o_addstr(as_string, dest->data + pos);
4505 o_addchr(as_string, ')');
4506 o_addchr(as_string, ')');
4509 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4513 # if ENABLE_HUSH_TICK
4514 //int pos = dest->length;
4515 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4516 o_addchr(dest, quote_mask | '`');
4520 add_till_closing_paren(dest, input, false);
4523 o_addstr(as_string, dest->data + pos);
4524 o_addchr(as_string, '`');
4527 //debug_printf_subst("SUBST RES2 '%s'\n", dest->data + pos);
4528 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4534 ch = i_getch(input);
4536 if (as_string) o_addchr(as_string, ch);
4539 if (isalnum(ch)) { /* it's $_name or $_123 */
4545 /* $_ Shell or shell script name; or last cmd name */
4546 /* $- Option flags set by set builtin or shell options (-i etc) */
4548 o_addQchr(dest, '$');
4550 debug_printf_parse("handle_dollar return 0\n");
4555 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
4556 parse_stream_dquoted(dest, input, dquote_end)
4558 static int parse_stream_dquoted(o_string *as_string,
4560 struct in_str *input,
4567 ch = i_getch(input);
4569 if (as_string && ch != EOF) o_addchr(as_string, ch);
4571 if (ch == dquote_end) { /* may be only '"' or EOF */
4573 if (dest->o_assignment == NOT_ASSIGNMENT)
4574 dest->o_escape ^= 1;
4575 debug_printf_parse("parse_stream_dquoted return 0\n");
4579 syntax("unterminated \"");
4580 debug_printf_parse("parse_stream_dquoted return 1: unterminated \"\n");
4585 next = i_peek(input);
4587 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4588 ch, ch, dest->o_escape);
4592 debug_printf_parse("parse_stream_dquoted return 1: \\<eof>\n");
4596 * "The backslash retains its special meaning [in "..."]
4597 * only when followed by one of the following characters:
4598 * $, `, ", \, or <newline>. A double quote may be quoted
4599 * within double quotes by preceding it with a backslash.
4600 * If enabled, history expansion will be performed unless
4601 * an ! appearing in double quotes is escaped using
4602 * a backslash. The backslash preceding the ! is not removed."
4604 if (strchr("$`\"\\", next) != NULL) {
4605 o_addqchr(dest, i_getch(input));
4607 o_addqchr(dest, '\\');
4612 if (handle_dollar(as_string, dest, input) != 0) {
4613 debug_printf_parse("parse_stream_dquoted return 1: "
4614 "handle_dollar returned non-0\n");
4619 #if ENABLE_HUSH_TICK
4621 //int pos = dest->length;
4622 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4623 o_addchr(dest, 0x80 | '`');
4624 add_till_backquote(dest, input);
4625 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4626 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4630 o_addQchr(dest, ch);
4632 && (dest->o_assignment == MAYBE_ASSIGNMENT
4633 || dest->o_assignment == WORD_IS_KEYWORD)
4634 && is_assignment(dest->data)
4636 dest->o_assignment = DEFINITELY_ASSIGNMENT;
4642 * Scan input until EOF or end_trigger char.
4643 * Return a list of pipes to execute, or NULL on EOF
4644 * or if end_trigger character is met.
4645 * On syntax error, exit is shell is not interactive,
4646 * reset parsing machinery and start parsing anew,
4647 * or return ERR_PTR.
4649 static struct pipe *parse_stream(char **pstring,
4650 struct in_str *input,
4653 struct parse_context ctx;
4654 o_string dest = NULL_O_STRING;
4658 /* Double-quote state is handled in the state variable is_in_dquote.
4659 * A single-quote triggers a bypass of the main loop until its mate is
4660 * found. When recursing, quote state is passed in via dest->o_escape.
4662 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4663 end_trigger ? : 'X');
4665 G.ifs = get_local_var_value("IFS");
4670 #if ENABLE_HUSH_INTERACTIVE
4671 input->promptmode = 0; /* PS1 */
4673 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
4674 initialize_context(&ctx);
4679 const char *is_special;
4683 redir_type redir_style;
4686 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
4689 /* We reached closing '"' */
4692 ch = i_getch(input);
4693 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4694 ch, ch, dest.o_escape);
4699 syntax("unterminated here document");
4702 if (done_word(&dest, &ctx)) {
4706 done_pipe(&ctx, PIPE_SEQ);
4708 /* If we got nothing... */
4709 // TODO: test script consisting of just "&"
4710 if (pi->num_cmds == 0
4711 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4713 free_pipe_list(pi, 0);
4716 debug_printf_parse("parse_stream return %p\n", pi);
4718 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4720 *pstring = ctx.as_string.data;
4722 o_free_unsafe(&ctx.as_string);
4727 o_addchr(&ctx.as_string, ch);
4729 is_ifs = strchr(G.ifs, ch);
4730 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
4731 "\\$\"" USE_HUSH_TICK("`") /* always special */
4734 if (!is_special && !is_ifs) { /* ordinary char */
4735 o_addQchr(&dest, ch);
4736 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4737 || dest.o_assignment == WORD_IS_KEYWORD)
4739 && is_assignment(dest.data)
4741 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4747 if (done_word(&dest, &ctx)) {
4751 #if ENABLE_HUSH_CASE
4752 /* "case ... in <newline> word) ..." -
4753 * newlines are ignored (but ';' wouldn't be) */
4754 if (ctx.command->argv == NULL
4755 && ctx.ctx_res_w == RES_MATCH
4760 /* Treat newline as a command separator. */
4761 done_pipe(&ctx, PIPE_SEQ);
4762 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4764 if (fetch_heredocs(heredoc_cnt, &ctx, input))
4768 dest.o_assignment = MAYBE_ASSIGNMENT;
4770 /* note: if (is_ifs) continue;
4771 * will still trigger for us */
4774 if (end_trigger && end_trigger == ch
4775 && (heredoc_cnt == 0 || end_trigger != ';')
4777 //TODO: disallow "{ cmd }" without semicolon
4779 /* This is technically valid:
4780 * { cat <<HERE; }; echo Ok
4785 * but we don't support this.
4786 * We require heredoc to be in enclosing {}/(),
4789 syntax("unterminated here document");
4792 if (done_word(&dest, &ctx)) {
4795 done_pipe(&ctx, PIPE_SEQ);
4796 dest.o_assignment = MAYBE_ASSIGNMENT;
4797 /* Do we sit outside of any if's, loops or case's? */
4799 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4801 debug_printf_parse("parse_stream return %p: "
4802 "end_trigger char found\n",
4806 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4808 *pstring = ctx.as_string.data;
4810 o_free_unsafe(&ctx.as_string);
4812 return ctx.list_head;
4818 if (dest.o_assignment == MAYBE_ASSIGNMENT) {
4819 /* ch is a special char and thus this word
4820 * cannot be an assignment */
4821 dest.o_assignment = NOT_ASSIGNMENT;
4826 next = i_peek(input);
4831 if (dest.length == 0) {
4834 if (ch == EOF || ch == '\n')
4837 /* note: we do not add it to &ctx.as_string */
4840 //TODO: go back one char?
4841 o_addchr(&ctx.as_string, '\n');
4844 o_addQchr(&dest, ch);
4852 o_addchr(&dest, '\\');
4853 ch = i_getch(input);
4854 o_addchr(&dest, ch);
4856 o_addchr(&ctx.as_string, ch);
4860 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
4861 debug_printf_parse("parse_stream parse error: "
4862 "handle_dollar returned non-0\n");
4869 ch = i_getch(input);
4871 syntax("unterminated '");
4875 o_addchr(&ctx.as_string, ch);
4879 if (dest.o_assignment == NOT_ASSIGNMENT)
4880 o_addqchr(&dest, ch);
4882 o_addchr(&dest, ch);
4887 is_in_dquote ^= 1; /* invert */
4888 if (dest.o_assignment == NOT_ASSIGNMENT)
4891 #if ENABLE_HUSH_TICK
4893 //int pos = dest.length;
4894 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4895 o_addchr(&dest, '`');
4896 add_till_backquote(&dest, input);
4897 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4898 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4903 redir_fd = redirect_opt_num(&dest);
4904 if (done_word(&dest, &ctx)) {
4907 redir_style = REDIRECT_OVERWRITE;
4909 redir_style = REDIRECT_APPEND;
4910 ch = i_getch(input);
4912 o_addchr(&ctx.as_string, ch);
4916 else if (next == '(') {
4917 syntax(">(process) not supported");
4921 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4925 redir_fd = redirect_opt_num(&dest);
4926 if (done_word(&dest, &ctx)) {
4929 redir_style = REDIRECT_INPUT;
4931 redir_style = REDIRECT_HEREDOC;
4933 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4934 ch = i_getch(input);
4936 o_addchr(&ctx.as_string, ch);
4938 } else if (next == '>') {
4939 redir_style = REDIRECT_IO;
4940 ch = i_getch(input);
4942 o_addchr(&ctx.as_string, ch);
4946 else if (next == '(') {
4947 syntax("<(process) not supported");
4951 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4955 #if ENABLE_HUSH_CASE
4958 if (done_word(&dest, &ctx)) {
4961 done_pipe(&ctx, PIPE_SEQ);
4962 #if ENABLE_HUSH_CASE
4963 /* Eat multiple semicolons, detect
4964 * whether it means something special */
4969 ch = i_getch(input);
4971 o_addchr(&ctx.as_string, ch);
4973 if (ctx.ctx_res_w == RES_CASEI) {
4974 ctx.ctx_dsemicolon = 1;
4975 ctx.ctx_res_w = RES_MATCH;
4981 /* We just finished a cmd. New one may start
4982 * with an assignment */
4983 dest.o_assignment = MAYBE_ASSIGNMENT;
4986 if (done_word(&dest, &ctx)) {
4990 ch = i_getch(input);
4992 o_addchr(&ctx.as_string, ch);
4994 done_pipe(&ctx, PIPE_AND);
4996 done_pipe(&ctx, PIPE_BG);
5000 if (done_word(&dest, &ctx)) {
5003 #if ENABLE_HUSH_CASE
5004 if (ctx.ctx_res_w == RES_MATCH)
5005 break; /* we are in case's "word | word)" */
5007 if (next == '|') { /* || */
5008 ch = i_getch(input);
5010 o_addchr(&ctx.as_string, ch);
5012 done_pipe(&ctx, PIPE_OR);
5014 /* we could pick up a file descriptor choice here
5015 * with redirect_opt_num(), but bash doesn't do it.
5016 * "echo foo 2| cat" yields "foo 2". */
5021 #if ENABLE_HUSH_CASE
5022 /* "case... in [(]word)..." - skip '(' */
5023 if (ctx.ctx_res_w == RES_MATCH
5024 && ctx.command->argv == NULL /* not (word|(... */
5025 && dest.length == 0 /* not word(... */
5026 && dest.nonnull == 0 /* not ""(... */
5031 #if ENABLE_HUSH_FUNCTIONS
5032 if (dest.length != 0 /* not just () but word() */
5033 && dest.nonnull == 0 /* not a"b"c() */
5034 && ctx.command->argv == NULL /* it's the first word */
5035 //TODO: "func ( ) {...}" - note spaces - is valid format too in bash
5036 && i_peek(input) == ')'
5037 && !match_reserved_word(&dest)
5039 bb_error_msg("seems like a function definition");
5041 //if !BB_MMU o_addchr(&ctx.as_string...
5043 //TODO: do it properly.
5044 ch = i_getch(input);
5045 } while (ch == ' ' || ch == '\n');
5047 syntax("was expecting {");
5050 ch = 'F'; /* magic value */
5054 if (parse_group(&dest, &ctx, input, ch) != 0) {
5059 #if ENABLE_HUSH_CASE
5060 if (ctx.ctx_res_w == RES_MATCH)
5064 /* proper use of this character is caught by end_trigger:
5065 * if we see {, we call parse_group(..., end_trigger='}')
5066 * and it will match } earlier (not here). */
5067 syntax("unexpected } or )");
5071 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
5077 struct parse_context *pctx;
5078 IF_HAS_KEYWORDS(struct parse_context *p2;)
5080 /* Clean up allocated tree.
5081 * Samples for finding leaks on syntax error recovery path.
5082 * Run them from interactive shell, watch pmap `pidof hush`.
5083 * while if false; then false; fi do break; done
5085 * while if false; then false; fi; do break; fi
5086 * Samples to catch leaks at execution:
5087 * while if (true | {true;}); then echo ok; fi; do break; done
5088 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
5092 /* Update pipe/command counts,
5093 * otherwise freeing may miss some */
5094 done_pipe(pctx, PIPE_SEQ);
5095 debug_printf_clean("freeing list %p from ctx %p\n",
5096 pctx->list_head, pctx);
5097 debug_print_tree(pctx->list_head, 0);
5098 free_pipe_list(pctx->list_head, 0);
5099 debug_printf_clean("freed list %p\n", pctx->list_head);
5101 o_free_unsafe(&pctx->as_string);
5103 IF_HAS_KEYWORDS(p2 = pctx->stack;)
5107 IF_HAS_KEYWORDS(pctx = p2;)
5108 } while (HAS_KEYWORDS && pctx);
5109 /* Free text, clear all dest fields */
5111 /* If we are not in top-level parse, we return,
5112 * our caller will propagate error.
5114 if (end_trigger != ';') {
5121 /* Discard cached input, force prompt */
5123 USE_HUSH_INTERACTIVE(input->promptme = 1;)
5128 /* Executing from string: eval, sh -c '...'
5129 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5130 * end_trigger controls how often we stop parsing
5131 * NUL: parse all, execute, return
5132 * ';': parse till ';' or newline, execute, repeat till EOF
5134 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5137 struct pipe *pipe_list;
5139 pipe_list = parse_stream(NULL, inp, end_trigger);
5140 if (!pipe_list) /* EOF */
5142 debug_print_tree(pipe_list, 0);
5143 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5144 run_and_free_list(pipe_list);
5148 static void parse_and_run_string(const char *s)
5150 struct in_str input;
5151 setup_string_in_str(&input, s);
5152 parse_and_run_stream(&input, '\0');
5155 static void parse_and_run_file(FILE *f)
5157 struct in_str input;
5158 setup_file_in_str(&input, f);
5159 parse_and_run_stream(&input, ';');
5162 /* Called a few times only (or even once if "sh -c") */
5163 static void block_signals(int second_time)
5168 mask = (1 << SIGQUIT);
5169 if (G_interactive_fd) {
5173 //TODO | (1 << SIGHUP)
5175 | (1 << SIGTTIN) | (1 << SIGTTOU) | (1 << SIGTSTP)
5180 G.non_DFL_mask = mask;
5183 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
5187 sigaddset(&G.blocked_set, sig);
5191 sigdelset(&G.blocked_set, SIGCHLD);
5193 sigprocmask(SIG_SETMASK, &G.blocked_set,
5194 second_time ? NULL : &G.inherited_set);
5195 /* POSIX allows shell to re-enable SIGCHLD
5196 * even if it was SIG_IGN on entry */
5197 // G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
5199 signal(SIGCHLD, SIG_DFL); // SIGCHLD_handler);
5204 static void maybe_set_to_sigexit(int sig)
5206 void (*handler)(int);
5207 /* non_DFL_mask'ed signals are, well, masked,
5208 * no need to set handler for them.
5210 if (!((G.non_DFL_mask >> sig) & 1)) {
5211 handler = signal(sig, sigexit);
5212 if (handler == SIG_IGN) /* oops... restore back to IGN! */
5213 signal(sig, handler);
5216 /* Set handlers to restore tty pgrp and exit */
5217 static void set_fatal_handlers(void)
5219 /* We _must_ restore tty pgrp on fatal signals */
5221 maybe_set_to_sigexit(SIGILL );
5222 maybe_set_to_sigexit(SIGFPE );
5223 maybe_set_to_sigexit(SIGBUS );
5224 maybe_set_to_sigexit(SIGSEGV);
5225 maybe_set_to_sigexit(SIGTRAP);
5226 } /* else: hush is perfect. what SEGV? */
5227 maybe_set_to_sigexit(SIGABRT);
5228 /* bash 3.2 seems to handle these just like 'fatal' ones */
5229 maybe_set_to_sigexit(SIGPIPE);
5230 maybe_set_to_sigexit(SIGALRM);
5231 //TODO: disable and move down when proper SIGHUP handling is added
5232 maybe_set_to_sigexit(SIGHUP );
5233 /* if we are interactive, [SIGHUP,] SIGTERM and SIGINT are masked.
5234 * if we aren't interactive... but in this case
5235 * we never want to restore pgrp on exit, and this fn is not called */
5236 /*maybe_set_to_sigexit(SIGTERM);*/
5237 /*maybe_set_to_sigexit(SIGINT );*/
5241 static int set_mode(const char cstate, const char mode)
5243 int state = (cstate == '-' ? 1 : 0);
5245 case 'n': G.fake_mode = state; break;
5246 case 'x': /*G.debug_mode = state;*/ break;
5247 default: return EXIT_FAILURE;
5249 return EXIT_SUCCESS;
5252 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
5253 int hush_main(int argc, char **argv)
5255 static const struct variable const_shell_ver = {
5257 .varstr = (char*)hush_version_str,
5258 .max_len = 1, /* 0 can provoke free(name) */
5262 int signal_mask_is_inited = 0;
5265 struct variable *cur_var;
5268 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
5269 G.last_exitcode = EXIT_SUCCESS;
5271 G.argv0_for_re_execing = argv[0];
5273 /* Deal with HUSH_VERSION */
5274 G.shell_ver = const_shell_ver; /* copying struct here */
5275 G.top_var = &G.shell_ver;
5276 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
5277 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
5278 /* Initialize our shell local variables with the values
5279 * currently living in the environment */
5280 cur_var = G.top_var;
5283 char *value = strchr(*e, '=');
5284 if (value) { /* paranoia */
5285 cur_var->next = xzalloc(sizeof(*cur_var));
5286 cur_var = cur_var->next;
5287 cur_var->varstr = *e;
5288 cur_var->max_len = strlen(*e);
5289 cur_var->flg_export = 1;
5293 debug_printf_env("putenv '%s'\n", hush_version_str);
5294 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
5295 #if ENABLE_FEATURE_EDITING
5296 G.line_input_state = new_line_input_t(FOR_SHELL);
5298 G.global_argc = argc;
5299 G.global_argv = argv;
5300 /* Initialize some more globals to non-zero values */
5302 #if ENABLE_HUSH_INTERACTIVE
5303 if (ENABLE_FEATURE_EDITING)
5304 cmdedit_set_initial_prompt();
5308 /* Shell is non-interactive at first. We need to call
5309 * block_signals(0) if we are going to execute "sh <script>",
5310 * "sh -c <cmds>" or login shell's /etc/profile and friends.
5311 * If we later decide that we are interactive, we run block_signals(0)
5312 * (or re-run block_signals(1) if we ran block_signals(0) before)
5313 * in order to intercept (more) signals.
5317 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
5319 opt = getopt(argc, argv, "c:xins"
5329 G.root_pid = getpid();
5330 G.global_argv = argv + optind;
5331 if (!argv[optind]) {
5332 /* -c 'script' (no params): prevent empty $0 */
5333 *--G.global_argv = argv[0];
5335 } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
5336 G.global_argc = argc - optind;
5337 block_signals(0); /* 0: called 1st time */
5338 parse_and_run_string(optarg);
5341 /* Well, we cannot just declare interactiveness,
5342 * we have to have some stuff (ctty, etc) */
5343 /* G_interactive_fd++; */
5346 /* "-s" means "read from stdin", but this is how we always
5347 * operate, so simply do nothing here. */
5351 G.root_pid = bb_strtou(optarg, &optarg, 16);
5353 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
5355 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
5356 # if ENABLE_HUSH_LOOPS
5358 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
5363 set_local_var(xstrdup(optarg), 0, opt == 'R');
5368 if (!set_mode('-', opt))
5372 fprintf(stderr, "Usage: sh [FILE]...\n"
5373 " or: sh -c command [args]...\n\n");
5379 } /* option parsing loop */
5382 G.root_pid = getpid();
5384 /* If we are login shell... */
5385 if (argv[0] && argv[0][0] == '-') {
5387 /* XXX what should argv be while sourcing /etc/profile? */
5388 debug_printf("sourcing /etc/profile\n");
5389 input = fopen_for_read("/etc/profile");
5390 if (input != NULL) {
5391 close_on_exec_on(fileno(input));
5392 block_signals(0); /* 0: called 1st time */
5393 signal_mask_is_inited = 1;
5394 parse_and_run_file(input);
5397 /* bash: after sourcing /etc/profile,
5398 * tries to source (in the given order):
5399 * ~/.bash_profile, ~/.bash_login, ~/.profile,
5400 * stopping of first found. --noprofile turns this off.
5401 * bash also sources ~/.bash_logout on exit.
5402 * If called as sh, skips .bash_XXX files.
5409 * "bash <script>" (which is never interactive (unless -i?))
5410 * sources $BASH_ENV here (without scanning $PATH).
5411 * If called as sh, does the same but with $ENV.
5413 debug_printf("running script '%s'\n", argv[optind]);
5414 G.global_argv = argv + optind;
5415 G.global_argc = argc - optind;
5416 input = xfopen_for_read(argv[optind]);
5417 close_on_exec_on(fileno(input));
5418 if (!signal_mask_is_inited)
5419 block_signals(0); /* 0: called 1st time */
5420 parse_and_run_file(input);
5421 #if ENABLE_FEATURE_CLEAN_UP
5427 /* Up to here, shell was non-interactive. Now it may become one.
5428 * NB: don't forget to (re)run block_signals(0/1) as needed.
5431 /* A shell is interactive if the '-i' flag was given, or if all of
5432 * the following conditions are met:
5434 * no arguments remaining or the -s flag given
5435 * standard input is a terminal
5436 * standard output is a terminal
5437 * Refer to Posix.2, the description of the 'sh' utility.
5440 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
5441 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
5442 debug_printf("saved_tty_pgrp:%d\n", G.saved_tty_pgrp);
5443 //TODO: "interactive" and "have job control" are two different things.
5444 //If tcgetpgrp fails here, "have job control" is false, but "interactive"
5445 //should stay on! Currently, we mix these into one.
5446 if (G.saved_tty_pgrp >= 0) {
5447 /* try to dup stdin to high fd#, >= 255 */
5448 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
5449 if (G_interactive_fd < 0) {
5450 /* try to dup to any fd */
5451 G_interactive_fd = dup(STDIN_FILENO);
5452 if (G_interactive_fd < 0)
5454 G_interactive_fd = 0;
5456 // TODO: track & disallow any attempts of user
5457 // to (inadvertently) close/redirect it
5460 debug_printf("interactive_fd:%d\n", G_interactive_fd);
5461 if (G_interactive_fd) {
5464 /* We are indeed interactive shell, and we will perform
5465 * job control. Setting up for that. */
5467 close_on_exec_on(G_interactive_fd);
5468 /* If we were run as 'hush &', sleep until we are
5469 * in the foreground (tty pgrp == our pgrp).
5470 * If we get started under a job aware app (like bash),
5471 * make sure we are now in charge so we don't fight over
5472 * who gets the foreground */
5474 shell_pgrp = getpgrp();
5475 G.saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
5476 if (G.saved_tty_pgrp == shell_pgrp)
5478 /* send TTIN to ourself (should stop us) */
5479 kill(- shell_pgrp, SIGTTIN);
5481 /* Block some signals */
5482 block_signals(signal_mask_is_inited);
5483 /* Set other signals to restore saved_tty_pgrp */
5484 set_fatal_handlers();
5485 /* Put ourselves in our own process group */
5486 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
5487 /* Grab control of the terminal */
5488 tcsetpgrp(G_interactive_fd, getpid());
5489 /* -1 is special - makes xfuncs longjmp, not exit
5490 * (we reset die_sleep = 0 whereever we [v]fork) */
5492 if (setjmp(die_jmp)) {
5493 /* xfunc has failed! die die die */
5494 hush_exit(xfunc_error_retval);
5496 } else if (!signal_mask_is_inited) {
5497 block_signals(0); /* 0: called 1st time */
5498 } /* else: block_signals(0) was done before */
5499 #elif ENABLE_HUSH_INTERACTIVE
5500 /* No job control compiled in, only prompt/line editing */
5501 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
5502 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
5503 if (G_interactive_fd < 0) {
5504 /* try to dup to any fd */
5505 G_interactive_fd = dup(STDIN_FILENO);
5506 if (G_interactive_fd < 0)
5508 G_interactive_fd = 0;
5511 if (G_interactive_fd) {
5512 close_on_exec_on(G_interactive_fd);
5513 block_signals(signal_mask_is_inited);
5514 } else if (!signal_mask_is_inited) {
5518 /* We have interactiveness code disabled */
5519 if (!signal_mask_is_inited) {
5524 * if interactive but not a login shell, sources ~/.bashrc
5525 * (--norc turns this off, --rcfile <file> overrides)
5528 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
5529 printf("\n\n%s hush - the humble shell\n", bb_banner);
5530 printf("Enter 'help' for a list of built-in commands.\n\n");
5533 parse_and_run_file(stdin);
5536 #if ENABLE_FEATURE_CLEAN_UP
5537 if (G.cwd != bb_msg_unknown)
5539 cur_var = G.top_var->next;
5541 struct variable *tmp = cur_var;
5542 if (!cur_var->max_len)
5543 free(cur_var->varstr);
5544 cur_var = cur_var->next;
5548 hush_exit(G.last_exitcode);
5553 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
5554 int lash_main(int argc, char **argv)
5556 //bb_error_msg("lash is deprecated, please use hush instead");
5557 return hush_main(argc, argv);
5565 static int builtin_trap(char **argv)
5572 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
5576 /* No args: print all trapped. This isn't 100% correct as we
5577 * should be escaping the cmd so that it can be pasted back in
5579 for (i = 0; i < NSIG; ++i)
5581 printf("trap -- '%s' %s\n", G.traps[i], get_signame(i));
5582 return EXIT_SUCCESS;
5587 /* If first arg is decimal: reset all specified signals */
5588 sig = bb_strtou(*argv, NULL, 10);
5594 sig = get_signum(*argv++);
5595 if (sig < 0 || sig >= NSIG) {
5597 /* Mimic bash message exactly */
5598 bb_perror_msg("trap: %s: invalid signal specification", argv[i]);
5603 G.traps[sig] = xstrdup(new_cmd);
5605 debug_printf("trap: setting SIG%s (%i) to '%s'",
5606 get_signame(sig), sig, G.traps[sig]);
5608 /* There is no signal for 0 (EXIT) */
5613 sigaddset(&G.blocked_set, sig);
5615 /* There was a trap handler, we are removing it
5616 * (if sig has non-DFL handling,
5617 * we don't need to do anything) */
5618 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
5620 sigdelset(&G.blocked_set, sig);
5622 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5627 /* First arg is "-": reset all specified to default */
5628 /* First arg is "": ignore all specified */
5629 /* Everything else: execute first arg upon signal */
5631 bb_error_msg("trap: invalid arguments");
5632 return EXIT_FAILURE;
5634 if (NOT_LONE_DASH(*argv))
5640 static int builtin_true(char **argv UNUSED_PARAM)
5645 static int builtin_test(char **argv)
5652 return test_main(argc, argv - argc);
5655 static int builtin_echo(char **argv)
5662 return echo_main(argc, argv - argc);
5665 static int builtin_eval(char **argv)
5667 int rcode = EXIT_SUCCESS;
5670 char *str = expand_strvec_to_string(argv);
5672 * eval "echo Hi; done" ("done" is syntax error):
5673 * "echo Hi" will not execute too.
5675 parse_and_run_string(str);
5677 rcode = G.last_exitcode;
5682 static int builtin_cd(char **argv)
5684 const char *newdir = argv[1];
5685 if (newdir == NULL) {
5686 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
5687 * bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
5689 newdir = getenv("HOME") ? : "/";
5691 if (chdir(newdir)) {
5692 /* Mimic bash message exactly */
5693 bb_perror_msg("cd: %s", newdir);
5694 return EXIT_FAILURE;
5697 return EXIT_SUCCESS;
5700 static int builtin_exec(char **argv)
5702 if (*++argv == NULL)
5703 return EXIT_SUCCESS; /* bash does this */
5708 // FIXME: if exec fails, bash does NOT exit! We do...
5709 pseudo_exec_argv(&dummy, argv, 0, NULL);
5714 static int builtin_exit(char **argv)
5716 debug_printf_exec("%s()\n", __func__);
5717 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
5718 //puts("exit"); /* bash does it */
5719 // TODO: warn if we have background jobs: "There are stopped jobs"
5720 // On second consecutive 'exit', exit anyway.
5721 if (*++argv == NULL)
5722 hush_exit(G.last_exitcode);
5723 /* mimic bash: exit 123abc == exit 255 + error msg */
5724 xfunc_error_retval = 255;
5725 /* bash: exit -2 == exit 254, no error msg */
5726 hush_exit(xatoi(*argv) & 0xff);
5729 static int builtin_export(char **argv)
5731 if (*++argv == NULL) {
5733 // ash emits: export VAR='VAL'
5734 // bash: declare -x VAR="VAL"
5735 // (both also escape as needed (quotes, $, etc))
5740 return EXIT_SUCCESS;
5747 value = strchr(name, '=');
5749 /* They are exporting something without a =VALUE */
5750 struct variable *var;
5752 var = get_local_var(name);
5754 var->flg_export = 1;
5755 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
5756 putenv(var->varstr);
5758 /* bash does not return an error when trying to export
5759 * an undefined variable. Do likewise. */
5762 set_local_var(xstrdup(name), 1, 0);
5765 return EXIT_SUCCESS;
5769 /* built-in 'fg' and 'bg' handler */
5770 static int builtin_fg_bg(char **argv)
5775 if (!G_interactive_fd)
5776 return EXIT_FAILURE;
5777 /* If they gave us no args, assume they want the last backgrounded task */
5779 for (pi = G.job_list; pi; pi = pi->next) {
5780 if (pi->jobid == G.last_jobid) {
5784 bb_error_msg("%s: no current job", argv[0]);
5785 return EXIT_FAILURE;
5787 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
5788 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
5789 return EXIT_FAILURE;
5791 for (pi = G.job_list; pi; pi = pi->next) {
5792 if (pi->jobid == jobnum) {
5796 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
5797 return EXIT_FAILURE;
5799 // TODO: bash prints a string representation
5800 // of job being foregrounded (like "sleep 1 | cat")
5801 if (argv[0][0] == 'f') {
5802 /* Put the job into the foreground. */
5803 tcsetpgrp(G_interactive_fd, pi->pgrp);
5806 /* Restart the processes in the job */
5807 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
5808 for (i = 0; i < pi->num_cmds; i++) {
5809 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
5810 pi->cmds[i].is_stopped = 0;
5812 pi->stopped_cmds = 0;
5814 i = kill(- pi->pgrp, SIGCONT);
5816 if (errno == ESRCH) {
5817 delete_finished_bg_job(pi);
5818 return EXIT_SUCCESS;
5820 bb_perror_msg("kill (SIGCONT)");
5823 if (argv[0][0] == 'f') {
5825 return checkjobs_and_fg_shell(pi);
5827 return EXIT_SUCCESS;
5831 #if ENABLE_HUSH_HELP
5832 static int builtin_help(char **argv UNUSED_PARAM)
5834 const struct built_in_command *x;
5837 "Built-in commands:\n"
5838 "------------------\n");
5839 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
5840 printf("%s\t%s\n", x->cmd, x->descr);
5843 return EXIT_SUCCESS;
5848 static int builtin_jobs(char **argv UNUSED_PARAM)
5851 const char *status_string;
5853 for (job = G.job_list; job; job = job->next) {
5854 if (job->alive_cmds == job->stopped_cmds)
5855 status_string = "Stopped";
5857 status_string = "Running";
5859 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
5861 return EXIT_SUCCESS;
5865 static int builtin_pwd(char **argv UNUSED_PARAM)
5868 return EXIT_SUCCESS;
5871 static int builtin_read(char **argv)
5874 const char *name = argv[1] ? argv[1] : "REPLY";
5875 //TODO: check that argv[1] is a valid variable name
5877 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
5878 return set_local_var(string, 0, 0);
5881 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
5882 * built-in 'set' handler
5884 * set [-abCefhmnuvx] [-o option] [argument...]
5885 * set [+abCefhmnuvx] [+o option] [argument...]
5886 * set -- [argument...]
5889 * Implementations shall support the options in both their hyphen and
5890 * plus-sign forms. These options can also be specified as options to sh.
5892 * Write out all variables and their values: set
5893 * Set $1, $2, and $3 and set "$#" to 3: set c a b
5894 * Turn on the -x and -v options: set -xv
5895 * Unset all positional parameters: set --
5896 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
5897 * Set the positional parameters to the expansion of x, even if x expands
5898 * with a leading '-' or '+': set -- $x
5900 * So far, we only support "set -- [argument...]" and some of the short names.
5902 static int builtin_set(char **argv)
5905 char **pp, **g_argv;
5906 char *arg = *++argv;
5910 for (e = G.top_var; e; e = e->next)
5912 return EXIT_SUCCESS;
5916 if (!strcmp(arg, "--")) {
5921 if (arg[0] == '+' || arg[0] == '-') {
5922 for (n = 1; arg[n]; ++n)
5923 if (set_mode(arg[0], arg[n]))
5929 } while ((arg = *++argv) != NULL);
5930 /* Now argv[0] is 1st argument */
5932 /* Only reset global_argv if we didn't process anything */
5934 return EXIT_SUCCESS;
5937 /* NB: G.global_argv[0] ($0) is never freed/changed */
5938 g_argv = G.global_argv;
5939 if (G.global_args_malloced) {
5945 G.global_args_malloced = 1;
5946 pp = xzalloc(sizeof(pp[0]) * 2);
5947 pp[0] = g_argv[0]; /* retain $0 */
5950 /* This realloc's G.global_argv */
5951 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
5958 return EXIT_SUCCESS;
5960 /* Nothing known, so abort */
5962 bb_error_msg("set: %s: invalid option", arg);
5963 return EXIT_FAILURE;
5966 static int builtin_shift(char **argv)
5972 if (n >= 0 && n < G.global_argc) {
5973 if (G.global_args_malloced) {
5976 free(G.global_argv[m++]);
5979 memmove(&G.global_argv[1], &G.global_argv[n+1],
5980 G.global_argc * sizeof(G.global_argv[0]));
5981 return EXIT_SUCCESS;
5983 return EXIT_FAILURE;
5986 static int builtin_source(char **argv)
5990 if (*++argv == NULL)
5991 return EXIT_FAILURE;
5993 /* XXX search through $PATH is missing */
5994 input = fopen_or_warn(*argv, "r");
5996 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
5997 return EXIT_FAILURE;
5999 close_on_exec_on(fileno(input));
6001 /* Now run the file */
6003 /* XXX argv and argc are broken; need to save old G.global_argv
6004 * (pointer only is OK!) on this stack frame,
6005 * set G.global_argv=argv+1, recurse, and restore. */
6006 parse_and_run_file(input);
6008 return G.last_exitcode;
6011 static int builtin_umask(char **argv)
6014 const char *arg = argv[1];
6016 //TODO: umask may take chmod-like symbolic masks
6017 new_umask = bb_strtou(arg, NULL, 8);
6019 //Message? bash examples:
6020 //bash: umask: 'q': invalid symbolic mode operator
6021 //bash: umask: 999: octal number out of range
6022 return EXIT_FAILURE;
6025 new_umask = umask(0);
6026 printf("%.3o\n", (unsigned) new_umask);
6027 /* fall through and restore new_umask which we set to 0 */
6030 return EXIT_SUCCESS;
6033 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
6034 static int builtin_unset(char **argv)
6040 return EXIT_SUCCESS;
6043 if (argv[0][0] == '-') {
6044 switch (argv[0][1]) {
6050 bb_error_msg("unset: %s: invalid option", *argv);
6051 return EXIT_FAILURE;
6053 //TODO: disallow "unset -vf ..." too
6060 if (unset_local_var(*argv)) {
6061 /* unset <nonexistent_var> doesn't fail.
6062 * Error is when one tries to unset RO var.
6063 * Message was printed by unset_local_var. */
6067 #if ENABLE_HUSH_FUNCTIONS
6069 unset_local_func(*argv);
6077 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
6078 static int builtin_wait(char **argv)
6080 int ret = EXIT_SUCCESS;
6083 if (*++argv == NULL) {
6084 /* Don't care about wait results */
6085 /* Note 1: must wait until there are no more children */
6086 /* Note 2: must be interruptible */
6088 * $ sleep 3 & sleep 6 & wait
6093 * $ sleep 3 & sleep 6 & wait
6097 * ^C <-- after ~4 sec from keyboard
6100 sigaddset(&G.blocked_set, SIGCHLD);
6101 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6104 if (errno == ECHILD)
6106 /* Wait for SIGCHLD or any other signal of interest */
6107 /* sigtimedwait with infinite timeout: */
6108 sig = sigwaitinfo(&G.blocked_set, NULL);
6110 sig = check_and_run_traps(sig);
6111 if (sig && sig != SIGCHLD) { /* see note 2 */
6117 sigdelset(&G.blocked_set, SIGCHLD);
6118 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6122 /* This is probably buggy wrt interruptible-ness */
6124 pid_t pid = bb_strtou(*argv, NULL, 10);
6126 /* mimic bash message */
6127 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
6128 return EXIT_FAILURE;
6130 if (waitpid(pid, &status, 0) == pid) {
6131 if (WIFSIGNALED(status))
6132 ret = 128 + WTERMSIG(status);
6133 else if (WIFEXITED(status))
6134 ret = WEXITSTATUS(status);
6138 bb_perror_msg("wait %s", *argv);
6147 #if ENABLE_HUSH_LOOPS
6148 static int builtin_break(char **argv)
6150 if (G.depth_of_loop == 0) {
6151 bb_error_msg("%s: only meaningful in a loop", argv[0]);
6152 return EXIT_SUCCESS; /* bash compat */
6154 G.flag_break_continue++; /* BC_BREAK = 1 */
6155 G.depth_break_continue = 1;
6157 G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
6158 if (errno || !G.depth_break_continue || argv[2]) {
6159 bb_error_msg("%s: bad arguments", argv[0]);
6160 G.flag_break_continue = BC_BREAK;
6161 G.depth_break_continue = UINT_MAX;
6164 if (G.depth_of_loop < G.depth_break_continue)
6165 G.depth_break_continue = G.depth_of_loop;
6166 return EXIT_SUCCESS;
6169 static int builtin_continue(char **argv)
6171 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
6172 return builtin_break(argv);