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
46 * Bash stuff (maybe optionally enable?):
47 * &> and >& redirection of stdout+stderr
49 * reserved words: [[ ]] function select
50 * substrings ${var:1:5}
53 * grep for "TODO" and fix (some of them are easy)
54 * change { and } from special chars to reserved words
55 * builtins: return, ulimit
56 * follow IFS rules more precisely, including update semantics
57 * figure out what to do with backslash-newline
58 * continuation lines, both explicit and implicit - done?
60 * ^Z handling (and explain it in comments for mere humans)
61 * separate job control from interactiveness
62 * (testcase: booting with init=/bin/hush does not show prompt (2009-04))
65 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
68 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
69 //TODO: pull in some .h and find out whether we have SINGLE_APPLET_MAIN?
70 //#include "applet_tables.h" doesn't work
72 /* #include <dmalloc.h> */
79 #ifdef WANT_TO_TEST_NOMMU
84 # define USE_FOR_NOMMU(...) __VA_ARGS__
85 # define USE_FOR_MMU(...)
88 #if defined SINGLE_APPLET_MAIN
89 /* STANDALONE does not make sense, and won't compile */
90 #undef CONFIG_FEATURE_SH_STANDALONE
91 #undef ENABLE_FEATURE_SH_STANDALONE
92 #undef USE_FEATURE_SH_STANDALONE
93 #define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
94 #define ENABLE_FEATURE_SH_STANDALONE 0
95 #define USE_FEATURE_SH_STANDALONE(...)
96 #define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
99 #if !ENABLE_HUSH_INTERACTIVE
100 #undef ENABLE_FEATURE_EDITING
101 #define ENABLE_FEATURE_EDITING 0
102 #undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
103 #define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
106 /* Do we support ANY keywords? */
107 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
108 #define HAS_KEYWORDS 1
109 #define IF_HAS_KEYWORDS(...) __VA_ARGS__
110 #define IF_HAS_NO_KEYWORDS(...)
112 #define HAS_KEYWORDS 0
113 #define IF_HAS_KEYWORDS(...)
114 #define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
117 /* Keep unconditionally on for now */
120 #define ENABLE_HUSH_FUNCTIONS 0
123 /* If you comment out one of these below, it will be #defined later
124 * to perform debug printfs to stderr: */
125 #define debug_printf(...) do {} while (0)
126 /* Finer-grained debug switches */
127 #define debug_printf_parse(...) do {} while (0)
128 #define debug_print_tree(a, b) do {} while (0)
129 #define debug_printf_exec(...) do {} while (0)
130 #define debug_printf_env(...) do {} while (0)
131 #define debug_printf_jobs(...) do {} while (0)
132 #define debug_printf_expand(...) do {} while (0)
133 #define debug_printf_glob(...) do {} while (0)
134 #define debug_printf_list(...) do {} while (0)
135 #define debug_printf_subst(...) do {} while (0)
136 #define debug_printf_clean(...) do {} while (0)
139 #define debug_printf(...) fprintf(stderr, __VA_ARGS__)
142 #ifndef debug_printf_parse
143 #define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
146 #ifndef debug_printf_exec
147 #define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
150 #ifndef debug_printf_env
151 #define debug_printf_env(...) fprintf(stderr, __VA_ARGS__)
154 #ifndef debug_printf_jobs
155 #define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
161 #ifndef debug_printf_expand
162 #define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
163 #define DEBUG_EXPAND 1
165 #define DEBUG_EXPAND 0
168 #ifndef debug_printf_glob
169 #define debug_printf_glob(...) fprintf(stderr, __VA_ARGS__)
175 #ifndef debug_printf_list
176 #define debug_printf_list(...) fprintf(stderr, __VA_ARGS__)
179 #ifndef debug_printf_subst
180 #define debug_printf_subst(...) fprintf(stderr, __VA_ARGS__)
183 #ifndef debug_printf_clean
184 /* broken, of course, but OK for testing */
185 static const char *indenter(int i)
187 static const char blanks[] ALIGN1 =
189 return &blanks[sizeof(blanks) - i - 1];
191 #define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
192 #define DEBUG_CLEAN 1
194 #define DEBUG_CLEAN 0
198 static void debug_print_strings(const char *prefix, char **vv)
200 fprintf(stderr, "%s:\n", prefix);
202 fprintf(stderr, " '%s'\n", *vv++);
205 #define debug_print_strings(prefix, vv) ((void)0)
209 * Leak hunting. Use hush_leaktool.sh for post-processing.
211 #ifdef FOR_HUSH_LEAKTOOL
212 static void *xxmalloc(int lineno, size_t size)
214 void *ptr = xmalloc((size + 0xff) & ~0xff);
215 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
218 static void *xxrealloc(int lineno, void *ptr, size_t size)
220 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
221 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
224 static char *xxstrdup(int lineno, const char *str)
226 char *ptr = xstrdup(str);
227 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
230 static void xxfree(void *ptr)
232 fdprintf(2, "free %p\n", ptr);
235 #define xmalloc(s) xxmalloc(__LINE__, s)
236 #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
237 #define xstrdup(s) xxstrdup(__LINE__, s)
238 #define free(p) xxfree(p)
242 #define ERR_PTR ((void*)(long)1)
244 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
246 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
248 #define SPECIAL_VAR_SYMBOL 3
250 typedef enum redir_type {
251 REDIRECT_INVALID = 0,
253 REDIRECT_OVERWRITE = 2,
255 REDIRECT_HEREDOC = 4,
257 REDIRECT_HEREDOC2 = 6, /* REDIRECT_HEREDOC after heredoc load */
260 /* The descrip member of this structure is only used to make
261 * debugging output pretty */
262 static const struct {
264 signed char default_fd;
268 { O_RDONLY, 0, "<" },
269 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
270 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
271 { O_RDONLY, 0, "<<" },
272 { O_CREAT|O_RDWR, 1, "<>" },
273 /* Should not be needed. Bogus default_fd helps in debugging */
274 /* { O_RDONLY, 77, "<<" }, */
277 typedef enum reserved_style {
286 #if ENABLE_HUSH_LOOPS
293 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
298 /* two pseudo-keywords support contrived "case" syntax: */
299 RES_MATCH , /* "word)" */
300 RES_CASEI , /* "this command is inside CASE" */
307 typedef struct o_string {
309 int length; /* position where data is appended */
311 /* Protect newly added chars against globbing
312 * (by prepending \ to *, ?, [, \) */
316 smallint has_empty_slot;
317 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
320 MAYBE_ASSIGNMENT = 0,
321 DEFINITELY_ASSIGNMENT = 1,
323 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
325 /* Used for initialization: o_string foo = NULL_O_STRING; */
326 #define NULL_O_STRING { NULL }
328 /* I can almost use ordinary FILE*. Is open_memstream() universally
329 * available? Where is it documented? */
330 typedef struct in_str {
332 /* eof_flag=1: last char in ->p is really an EOF */
333 char eof_flag; /* meaningless if ->p == NULL */
335 #if ENABLE_HUSH_INTERACTIVE
337 smallint promptmode; /* 0: PS1, 1: PS2 */
340 int (*get) (struct in_str *);
341 int (*peek) (struct in_str *);
343 #define i_getch(input) ((input)->get(input))
344 #define i_peek(input) ((input)->peek(input))
346 struct redir_struct {
347 struct redir_struct *next;
348 char *rd_filename; /* filename */
349 int fd; /* file descriptor being redirected */
350 int dup; /* -1, or file descriptor being duplicated */
351 smallint /*enum redir_type*/ rd_type;
355 pid_t pid; /* 0 if exited */
356 int assignment_cnt; /* how many argv[i] are assignments? */
357 smallint is_stopped; /* is the command currently running? */
358 smallint grp_type; /* GRP_xxx */
359 struct pipe *group; /* if non-NULL, this "command" is { list },
360 * ( list ), or a compound statement */
362 char *group_as_string;
364 char **argv; /* command name and arguments */
365 struct redir_struct *redirects; /* I/O redirections */
367 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
368 * and on execution these are substituted with their values.
369 * Substitution can make _several_ words out of one argv[n]!
370 * Example: argv[0]=='.^C*^C.' here: echo .$*.
371 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
374 #define GRP_SUBSHELL 1
375 #if ENABLE_HUSH_FUNCTIONS
376 #define GRP_FUNCTION 2
381 int num_cmds; /* total number of commands in job */
382 int alive_cmds; /* number of commands running (not exited) */
383 int stopped_cmds; /* number of commands alive, but stopped */
385 int jobid; /* job number */
386 pid_t pgrp; /* process group ID for the job */
387 char *cmdtext; /* name of job */
389 struct command *cmds; /* array of commands in pipe */
390 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
391 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
392 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
394 typedef enum pipe_style {
401 /* This holds pointers to the various results of parsing */
402 struct parse_context {
403 /* linked list of pipes */
404 struct pipe *list_head;
405 /* last pipe (being constructed right now) */
407 /* last command in pipe (being constructed right now) */
408 struct command *command;
409 /* last redirect in command->redirects list */
410 struct redir_struct *pending_redirect;
416 smallint ctx_inverted; /* "! cmd | cmd" */
418 smallint ctx_dsemicolon; /* ";;" seen */
420 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
422 /* group we are enclosed in:
423 * example: "if pipe1; pipe2; then pipe3; fi"
424 * when we see "if" or "then", we malloc and copy current context,
425 * and make ->stack point to it. then we parse pipeN.
426 * when closing "then" / fi" / whatever is found,
427 * we move list_head into ->stack->command->group,
428 * copy ->stack into current context, and delete ->stack.
429 * (parsing of { list } and ( list ) doesn't use this method)
431 struct parse_context *stack;
435 /* On program start, environ points to initial environment.
436 * putenv adds new pointers into it, unsetenv removes them.
437 * Neither of these (de)allocates the strings.
438 * setenv allocates new strings in malloc space and does putenv,
439 * and thus setenv is unusable (leaky) for shell's purposes */
440 #define setenv(...) setenv_is_leaky_dont_use()
442 struct variable *next;
443 char *varstr; /* points to "name=" portion */
444 int max_len; /* if > 0, name is part of initial env; else name is malloced */
445 smallint flg_export; /* putenv should be done on this var */
446 smallint flg_read_only;
455 /* "Globals" within this file */
456 /* Sorted roughly by size (smaller offsets == smaller code) */
458 #if ENABLE_HUSH_INTERACTIVE
459 /* 'interactive_fd' is a fd# open to ctty, if we have one
460 * _AND_ if we decided to act interactively */
464 #define G_interactive_fd (G.interactive_fd)
466 #define G_interactive_fd 0
468 #if ENABLE_FEATURE_EDITING
469 line_input_t *line_input_state;
475 pid_t saved_tty_pgrp;
477 struct pipe *job_list;
478 struct pipe *toplevel_list;
479 //// smallint ctrl_z_flag;
481 smallint flag_SIGINT;
482 #if ENABLE_HUSH_LOOPS
483 smallint flag_break_continue;
486 /* These four support $?, $#, and $1 */
487 smalluint last_exitcode;
488 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
489 smalluint global_args_malloced;
490 /* how many non-NULL argv's we have. NB: $# + 1 */
494 char *argv0_for_re_execing;
495 char **argv_from_re_execing;
497 #if ENABLE_HUSH_LOOPS
498 unsigned depth_break_continue;
499 unsigned depth_of_loop;
503 struct variable *top_var; /* = &G.shell_ver (set in main()) */
504 struct variable shell_ver;
505 /* Signal and trap handling */
506 // unsigned count_SIGCHLD;
507 // unsigned handled_SIGCHLD;
508 /* which signals have non-DFL handler (even with no traps set)? */
509 unsigned non_DFL_mask;
510 char **traps; /* char *traps[NSIG] */
511 sigset_t blocked_set;
512 sigset_t inherited_set;
513 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
514 #if ENABLE_FEATURE_SH_STANDALONE
515 struct nofork_save_area nofork_save;
518 sigjmp_buf toplevel_jb;
521 #define G (*ptr_to_globals)
522 /* Not #defining name to G.name - this quickly gets unwieldy
523 * (too many defines). Also, I actually prefer to see when a variable
524 * is global, thus "G." prefix is a useful hint */
525 #define INIT_G() do { \
526 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
530 /* Function prototypes for builtins */
531 static int builtin_cd(char **argv);
532 static int builtin_echo(char **argv);
533 static int builtin_eval(char **argv);
534 static int builtin_exec(char **argv);
535 static int builtin_exit(char **argv);
536 static int builtin_export(char **argv);
538 static int builtin_fg_bg(char **argv);
539 static int builtin_jobs(char **argv);
542 static int builtin_help(char **argv);
544 static int builtin_pwd(char **argv);
545 static int builtin_read(char **argv);
546 static int builtin_test(char **argv);
547 static int builtin_trap(char **argv);
548 static int builtin_true(char **argv);
549 static int builtin_set(char **argv);
550 static int builtin_shift(char **argv);
551 static int builtin_source(char **argv);
552 static int builtin_umask(char **argv);
553 static int builtin_unset(char **argv);
554 static int builtin_wait(char **argv);
555 #if ENABLE_HUSH_LOOPS
556 static int builtin_break(char **argv);
557 static int builtin_continue(char **argv);
560 /* Table of built-in functions. They can be forked or not, depending on
561 * context: within pipes, they fork. As simple commands, they do not.
562 * When used in non-forking context, they can change global variables
563 * in the parent shell process. If forked, of course they cannot.
564 * For example, 'unset foo | whatever' will parse and run, but foo will
565 * still be set at the end. */
566 struct built_in_command {
568 int (*function)(char **argv);
571 #define BLTIN(cmd, func, help) { cmd, func, help }
573 #define BLTIN(cmd, func, help) { cmd, func }
577 /* For now, echo and test are unconditionally enabled.
578 * Maybe make it configurable? */
579 static const struct built_in_command bltins[] = {
580 BLTIN("." , builtin_source , "Run commands in a file"),
581 BLTIN(":" , builtin_true , "No-op"),
582 BLTIN("[" , builtin_test , "Test condition"),
584 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
586 #if ENABLE_HUSH_LOOPS
587 BLTIN("break" , builtin_break , "Exit from a loop"),
589 BLTIN("cd" , builtin_cd , "Change directory"),
590 #if ENABLE_HUSH_LOOPS
591 BLTIN("continue", builtin_continue, "Start new loop iteration"),
593 BLTIN("echo" , builtin_echo , "Write to stdout"),
594 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
595 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
596 BLTIN("exit" , builtin_exit , "Exit"),
597 BLTIN("export" , builtin_export , "Set environment variable"),
599 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
602 BLTIN("help" , builtin_help , "List shell built-in commands"),
605 BLTIN("jobs" , builtin_jobs , "List active jobs"),
607 BLTIN("pwd" , builtin_pwd , "Print current directory"),
608 BLTIN("read" , builtin_read , "Input environment variable"),
609 // BLTIN("return" , builtin_return , "Return from a function"),
610 BLTIN("set" , builtin_set , "Set/unset shell local variables"),
611 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
612 BLTIN("test" , builtin_test , "Test condition"),
613 BLTIN("trap" , builtin_trap , "Trap signals"),
614 // BLTIN("ulimit" , builtin_return , "Control resource limits"),
615 BLTIN("umask" , builtin_umask , "Set file creation mask"),
616 BLTIN("unset" , builtin_unset , "Unset environment variable"),
617 BLTIN("wait" , builtin_wait , "Wait for process"),
621 static void maybe_die(const char *notice, const char *msg)
623 /* Was using fancy stuff:
624 * (G_interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
625 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
626 void FAST_FUNC (*fp)(const char *s, ...) = bb_error_msg_and_die;
627 #if ENABLE_HUSH_INTERACTIVE
628 if (G_interactive_fd)
631 fp(msg ? "%s: %s" : notice, notice, msg);
634 #define syntax(msg) maybe_die("syntax error", msg);
636 /* Debug -- trick gcc to expand __LINE__ and convert to string */
637 #define __syntax(msg, line) maybe_die("syntax error hush.c:" # line, msg)
638 #define _syntax(msg, line) __syntax(msg, line)
639 #define syntax(msg) _syntax(msg, __LINE__)
643 static int glob_needed(const char *s)
648 if (*s == '*' || *s == '[' || *s == '?')
655 static int is_assignment(const char *s)
657 if (!s || !(isalpha(*s) || *s == '_'))
660 while (isalnum(*s) || *s == '_')
665 /* Replace each \x with x in place, return ptr past NUL. */
666 static char *unbackslash(char *src)
672 if ((*dst++ = *src++) == '\0')
678 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
699 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
700 v[count1 + count2] = NULL;
703 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
707 static char **add_string_to_strings(char **strings, char *add)
712 return add_strings_to_strings(strings, v, /*dup:*/ 0);
715 static void putenv_all(char **strings)
720 debug_printf_env("putenv '%s'\n", *strings);
725 static char **putenv_all_and_save_old(char **strings)
735 eq = strchr(*strings, '=');
738 v = getenv(*strings);
741 /* v points to VAL in VAR=VAL, go back to VAR */
742 v -= (eq - *strings) + 1;
743 old = add_string_to_strings(old, v);
752 static void free_strings_and_unsetenv(char **strings, int unset)
762 debug_printf_env("unsetenv '%s'\n", *v);
770 static void free_strings(char **strings)
772 free_strings_and_unsetenv(strings, 0);
776 /* Basic theory of signal handling in shell
777 * ========================================
778 * This does not describe what hush does, rather, it is current understanding
779 * what it _should_ do. If it doesn't, it's a bug.
780 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
782 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
783 * is finished or backgrounded. It is the same in interactive and
784 * non-interactive shells, and is the same regardless of whether
785 * a user trap handler is installed or a shell special one is in effect.
786 * ^C or ^Z from keyboard seem to execute "at once" because it usually
787 * backgrounds (i.e. stops) or kills all members of currently running
790 * Wait builtin in interruptible by signals for which user trap is set
791 * or by SIGINT in interactive shell.
793 * Trap handlers will execute even within trap handlers. (right?)
795 * User trap handlers are forgotten when subshell ("(cmd)") is entered. [TODO]
797 * If job control is off, backgrounded commands ("cmd &")
798 * have SIGINT, SIGQUIT set to SIG_IGN.
800 * Commands run in command substitution ("`cmd`")
801 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
803 * Ordinary commands have signals set to SIG_IGN/DFL set as inherited
804 * by the shell from its parent.
806 * Siganls which differ from SIG_DFL action
807 * (note: child (i.e., [v]forked) shell is not an interactive shell):
810 * SIGTERM (interactive): ignore
811 * SIGHUP (interactive):
812 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
813 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
814 * (note that ^Z is handled not by trapping SIGTSTP, but by seeing
815 * that all pipe members are stopped) (right?)
816 * SIGINT (interactive): wait for last pipe, ignore the rest
817 * of the command line, show prompt. NB: ^C does not send SIGINT
818 * to interactive shell while shell is waiting for a pipe,
819 * since shell is bg'ed (is not in foreground process group).
820 * (check/expand this)
821 * Example 1: this waits 5 sec, but does not execute ls:
822 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
823 * Example 2: this does not wait and does not execute ls:
824 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
825 * Example 3: this does not wait 5 sec, but executes ls:
826 * "sleep 5; ls -l" + press ^C
828 * (What happens to signals which are IGN on shell start?)
829 * (What happens with signal mask on shell start?)
831 * Implementation in hush
832 * ======================
833 * We use in-kernel pending signal mask to determine which signals were sent.
834 * We block all signals which we don't want to take action immediately,
835 * i.e. we block all signals which need to have special handling as described
836 * above, and all signals which have traps set.
837 * After each pipe execution, we extract any pending signals via sigtimedwait()
840 * unsigned non_DFL_mask: a mask of such "special" signals
841 * sigset_t blocked_set: current blocked signal set
844 * clear bit in blocked_set unless it is also in non_DFL_mask
845 * "trap 'cmd' SIGxxx":
846 * set bit in blocked_set (even if 'cmd' is '')
847 * after [v]fork, if we plan to be a shell:
848 * nothing for {} child shell (say, "true | { true; true; } | true")
849 * unset all traps if () shell. [TODO]
850 * after [v]fork, if we plan to exec:
851 * POSIX says pending signal mask is cleared in child - no need to clear it.
852 * Restore blocked signal set to one inherited by shell just prior to exec.
854 * Note: as a result, we do not use signal handlers much. The only uses
855 * are to count SIGCHLDs [disabled - bug somewhere, + bloat]
856 * and to restore tty pgrp on signal-induced exit.
859 //static void SIGCHLD_handler(int sig UNUSED_PARAM)
861 // G.count_SIGCHLD++;
864 static int check_and_run_traps(int sig)
866 static const struct timespec zero_timespec = { 0, 0 };
867 smalluint save_rcode;
873 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
878 if (G.traps && G.traps[sig]) {
879 if (G.traps[sig][0]) {
880 /* We have user-defined handler */
881 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
882 save_rcode = G.last_exitcode;
885 G.last_exitcode = save_rcode;
886 } /* else: "" trap, ignoring signal */
889 /* not a trap: special action */
892 // G.count_SIGCHLD++;
901 default: /* ignored: */
902 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
910 /* Restores tty foreground process group, and exits.
911 * May be called as signal handler for fatal signal
912 * (will faithfully resend signal to itself, producing correct exit state)
913 * or called directly with -EXITCODE.
914 * We also call it if xfunc is exiting. */
915 static void sigexit(int sig) NORETURN;
916 static void sigexit(int sig)
918 /* Disable all signals: job control, SIGPIPE, etc. */
919 sigprocmask_allsigs(SIG_BLOCK);
921 /* Careful: we can end up here after [v]fork. Do not restore
922 * tty pgrp then, only top-level shell process does that */
923 if (G_interactive_fd && getpid() == G.root_pid)
924 tcsetpgrp(G_interactive_fd, G.saved_tty_pgrp);
926 /* Not a signal, just exit */
930 kill_myself_with_sig(sig); /* does not return */
934 /* Restores tty foreground process group, and exits. */
935 static void hush_exit(int exitcode) NORETURN;
936 static void hush_exit(int exitcode)
938 if (G.traps && G.traps[0] && G.traps[0][0]) {
939 char *argv[] = { NULL, xstrdup(G.traps[0]), NULL };
940 //TODO: do we need to prevent recursion?
946 fflush(NULL); /* flush all streams */
947 sigexit(- (exitcode & 0xff));
954 static const char *set_cwd(void)
956 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
957 * we must not try to free(bb_msg_unknown) */
958 if (G.cwd == bb_msg_unknown)
960 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
962 G.cwd = bb_msg_unknown;
967 /* Get/check local shell variables */
968 static struct variable *get_local_var(const char *name)
970 struct variable *cur;
976 for (cur = G.top_var; cur; cur = cur->next) {
977 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
983 static const char *get_local_var_value(const char *src)
985 struct variable *var = get_local_var(src);
987 return strchr(var->varstr, '=') + 1;
991 /* str holds "NAME=VAL" and is expected to be malloced.
992 * We take ownership of it.
996 * -1: if NAME is set, leave export status alone
997 * if NAME is not set, do not export
998 * flg_read_only is set only when we handle -R var=val
1001 #define set_local_var(str, flg_export, flg_read_only) \
1002 set_local_var(str, flg_export)
1004 static int set_local_var(char *str, int flg_export, int flg_read_only)
1006 struct variable *cur;
1010 value = strchr(str, '=');
1011 if (!value) { /* not expected to ever happen? */
1016 name_len = value - str + 1; /* including '=' */
1017 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
1019 if (strncmp(cur->varstr, str, name_len) != 0) {
1021 /* Bail out. Note that now cur points
1022 * to last var in linked list */
1028 /* We found an existing var with this name */
1030 if (cur->flg_read_only) {
1034 bb_error_msg("%s: readonly variable", str);
1038 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1039 unsetenv(str); /* just in case */
1041 if (strcmp(cur->varstr, str) == 0) {
1046 if (cur->max_len >= strlen(str)) {
1047 /* This one is from startup env, reuse space */
1048 strcpy(cur->varstr, str);
1051 /* max_len == 0 signifies "malloced" var, which we can
1052 * (and has to) free */
1056 goto set_str_and_exp;
1059 /* Not found - create next variable struct */
1060 cur->next = xzalloc(sizeof(*cur));
1066 cur->flg_read_only = flg_read_only;
1069 if (flg_export == 1)
1070 cur->flg_export = 1;
1071 if (cur->flg_export) {
1072 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1073 return putenv(cur->varstr);
1078 static int unset_local_var(const char *name)
1080 struct variable *cur;
1081 struct variable *prev = prev; /* for gcc */
1085 return EXIT_SUCCESS;
1086 name_len = strlen(name);
1089 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1090 if (cur->flg_read_only) {
1091 bb_error_msg("%s: readonly variable", name);
1092 return EXIT_FAILURE;
1094 /* prev is ok to use here because 1st variable, HUSH_VERSION,
1095 * is ro, and we cannot reach this code on the 1st pass */
1096 prev->next = cur->next;
1097 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1098 bb_unsetenv(cur->varstr);
1102 return EXIT_SUCCESS;
1107 return EXIT_SUCCESS;
1110 #if ENABLE_SH_MATH_SUPPORT
1111 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1112 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1113 static char *endofname(const char *name)
1121 if (!is_in_name(*p))
1127 static void arith_set_local_var(const char *name, const char *val, int flags)
1129 /* arith code doesnt malloc space, so do it for it */
1130 char *var = xasprintf("%s=%s", name, val);
1131 set_local_var(var, flags, 0);
1139 static int static_get(struct in_str *i)
1148 static int static_peek(struct in_str *i)
1153 #if ENABLE_HUSH_INTERACTIVE
1155 static void cmdedit_set_initial_prompt(void)
1157 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1158 G.PS1 = getenv("PS1");
1165 static const char* setup_prompt_string(int promptmode)
1167 const char *prompt_str;
1168 debug_printf("setup_prompt_string %d ", promptmode);
1169 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1170 /* Set up the prompt */
1171 if (promptmode == 0) { /* PS1 */
1173 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1178 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1179 debug_printf("result '%s'\n", prompt_str);
1183 static void get_user_input(struct in_str *i)
1186 const char *prompt_str;
1188 prompt_str = setup_prompt_string(i->promptmode);
1189 #if ENABLE_FEATURE_EDITING
1190 /* Enable command line editing only while a command line
1191 * is actually being read */
1194 /* buglet: SIGINT will not make new prompt to appear _at once_,
1195 * only after <Enter>. (^C will work) */
1196 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1197 /* catch *SIGINT* etc (^C is handled by read_line_input) */
1198 check_and_run_traps(0);
1199 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
1200 i->eof_flag = (r < 0);
1201 if (i->eof_flag) { /* EOF/error detected */
1202 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1203 G.user_input_buf[1] = '\0';
1208 fputs(prompt_str, stdout);
1210 G.user_input_buf[0] = r = fgetc(i->file);
1211 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1212 //do we need check_and_run_traps(0)? (maybe only if stdin)
1213 } while (G.flag_SIGINT);
1214 i->eof_flag = (r == EOF);
1216 i->p = G.user_input_buf;
1219 #endif /* INTERACTIVE */
1221 /* This is the magic location that prints prompts
1222 * and gets data back from the user */
1223 static int file_get(struct in_str *i)
1227 /* If there is data waiting, eat it up */
1228 if (i->p && *i->p) {
1229 #if ENABLE_HUSH_INTERACTIVE
1233 if (i->eof_flag && !*i->p)
1235 /* note: ch is never NUL */
1237 /* need to double check i->file because we might be doing something
1238 * more complicated by now, like sourcing or substituting. */
1239 #if ENABLE_HUSH_INTERACTIVE
1240 if (G_interactive_fd && i->promptme && i->file == stdin) {
1243 } while (!*i->p); /* need non-empty line */
1244 i->promptmode = 1; /* PS2 */
1249 do ch = fgetc(i->file); while (ch == '\0');
1251 debug_printf("file_get: got '%c' %d\n", ch, ch);
1252 #if ENABLE_HUSH_INTERACTIVE
1259 /* All callers guarantee this routine will never
1260 * be used right after a newline, so prompting is not needed.
1262 static int file_peek(struct in_str *i)
1265 if (i->p && *i->p) {
1266 if (i->eof_flag && !i->p[1])
1269 /* note: ch is never NUL */
1271 do ch = fgetc(i->file); while (ch == '\0');
1272 i->eof_flag = (ch == EOF);
1273 i->peek_buf[0] = ch;
1274 i->peek_buf[1] = '\0';
1276 debug_printf("file_peek: got '%c' %d\n", ch, ch);
1280 static void setup_file_in_str(struct in_str *i, FILE *f)
1282 i->peek = file_peek;
1284 #if ENABLE_HUSH_INTERACTIVE
1286 i->promptmode = 0; /* PS1 */
1292 static void setup_string_in_str(struct in_str *i, const char *s)
1294 i->peek = static_peek;
1295 i->get = static_get;
1296 #if ENABLE_HUSH_INTERACTIVE
1298 i->promptmode = 0; /* PS1 */
1308 #define B_CHUNK (32 * sizeof(char*))
1310 static void o_reset(o_string *o)
1318 static void o_free(o_string *o)
1321 memset(o, 0, sizeof(*o));
1324 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1329 static void o_grow_by(o_string *o, int len)
1331 if (o->length + len > o->maxlen) {
1332 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1333 o->data = xrealloc(o->data, 1 + o->maxlen);
1337 static void o_addchr(o_string *o, int ch)
1339 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1341 o->data[o->length] = ch;
1343 o->data[o->length] = '\0';
1346 static void o_addblock(o_string *o, const char *str, int len)
1349 memcpy(&o->data[o->length], str, len);
1351 o->data[o->length] = '\0';
1355 static void o_addstr(o_string *o, const char *str)
1357 o_addblock(o, str, strlen(str));
1361 static void o_addstr_with_NUL(o_string *o, const char *str)
1363 o_addblock(o, str, strlen(str) + 1);
1366 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
1371 && (*str != '*' && *str != '?' && *str != '[')
1379 /* My analysis of quoting semantics tells me that state information
1380 * is associated with a destination, not a source.
1382 static void o_addqchr(o_string *o, int ch)
1385 char *found = strchr("*?[\\", ch);
1390 o->data[o->length] = '\\';
1393 o->data[o->length] = ch;
1395 o->data[o->length] = '\0';
1398 static void o_addQchr(o_string *o, int ch)
1401 if (o->o_escape && strchr("*?[\\", ch)) {
1403 o->data[o->length] = '\\';
1407 o->data[o->length] = ch;
1409 o->data[o->length] = '\0';
1412 static void o_addQstr(o_string *o, const char *str, int len)
1415 o_addblock(o, str, len);
1421 int ordinary_cnt = strcspn(str, "*?[\\");
1422 if (ordinary_cnt > len) /* paranoia */
1424 o_addblock(o, str, ordinary_cnt);
1425 if (ordinary_cnt == len)
1427 str += ordinary_cnt;
1428 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
1432 if (ch) { /* it is necessarily one of "*?[\\" */
1434 o->data[o->length] = '\\';
1438 o->data[o->length] = ch;
1440 o->data[o->length] = '\0';
1444 /* A special kind of o_string for $VAR and `cmd` expansion.
1445 * It contains char* list[] at the beginning, which is grown in 16 element
1446 * increments. Actual string data starts at the next multiple of 16 * (char*).
1447 * list[i] contains an INDEX (int!) into this string data.
1448 * It means that if list[] needs to grow, data needs to be moved higher up
1449 * but list[i]'s need not be modified.
1450 * NB: remembering how many list[i]'s you have there is crucial.
1451 * o_finalize_list() operation post-processes this structure - calculates
1452 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1454 #if DEBUG_EXPAND || DEBUG_GLOB
1455 static void debug_print_list(const char *prefix, o_string *o, int n)
1457 char **list = (char**)o->data;
1458 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1460 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1461 prefix, list, n, string_start, o->length, o->maxlen);
1463 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1464 o->data + (int)list[i] + string_start,
1465 o->data + (int)list[i] + string_start);
1469 const char *p = o->data + (int)list[n - 1] + string_start;
1470 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
1474 #define debug_print_list(prefix, o, n) ((void)0)
1477 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1478 * in list[n] so that it points past last stored byte so far.
1479 * It returns n+1. */
1480 static int o_save_ptr_helper(o_string *o, int n)
1482 char **list = (char**)o->data;
1486 if (!o->has_empty_slot) {
1487 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1488 string_len = o->length - string_start;
1489 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1490 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
1491 /* list[n] points to string_start, make space for 16 more pointers */
1492 o->maxlen += 0x10 * sizeof(list[0]);
1493 o->data = xrealloc(o->data, o->maxlen + 1);
1494 list = (char**)o->data;
1495 memmove(list + n + 0x10, list + n, string_len);
1496 o->length += 0x10 * sizeof(list[0]);
1498 debug_printf_list("list[%d]=%d string_start=%d\n",
1499 n, string_len, string_start);
1502 /* We have empty slot at list[n], reuse without growth */
1503 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1504 string_len = o->length - string_start;
1505 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1506 n, string_len, string_start);
1507 o->has_empty_slot = 0;
1509 list[n] = (char*)(ptrdiff_t)string_len;
1513 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
1514 static int o_get_last_ptr(o_string *o, int n)
1516 char **list = (char**)o->data;
1517 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1519 return ((int)(ptrdiff_t)list[n-1]) + string_start;
1522 /* o_glob performs globbing on last list[], saving each result
1523 * as a new list[]. */
1524 static int o_glob(o_string *o, int n)
1530 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
1532 return o_save_ptr_helper(o, n);
1533 pattern = o->data + o_get_last_ptr(o, n);
1534 debug_printf_glob("glob pattern '%s'\n", pattern);
1535 if (!glob_needed(pattern)) {
1537 o->length = unbackslash(pattern) - o->data;
1538 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
1539 return o_save_ptr_helper(o, n);
1542 memset(&globdata, 0, sizeof(globdata));
1543 gr = glob(pattern, 0, NULL, &globdata);
1544 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1545 if (gr == GLOB_NOSPACE)
1546 bb_error_msg_and_die("out of memory during glob");
1547 if (gr == GLOB_NOMATCH) {
1548 globfree(&globdata);
1551 if (gr != 0) { /* GLOB_ABORTED ? */
1552 //TODO: testcase for bad glob pattern behavior
1553 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1555 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1556 char **argv = globdata.gl_pathv;
1557 o->length = pattern - o->data; /* "forget" pattern */
1559 o_addstr_with_NUL(o, *argv);
1560 n = o_save_ptr_helper(o, n);
1566 globfree(&globdata);
1568 debug_print_list("o_glob returning", o, n);
1572 /* If o->o_glob == 1, glob the string so far remembered.
1573 * Otherwise, just finish current list[] and start new */
1574 static int o_save_ptr(o_string *o, int n)
1576 if (o->o_glob) { /* if globbing is requested */
1577 /* If o->has_empty_slot, list[n] was already globbed
1578 * (if it was requested back then when it was filled)
1579 * so don't do that again! */
1580 if (!o->has_empty_slot)
1581 return o_glob(o, n); /* o_save_ptr_helper is inside */
1583 return o_save_ptr_helper(o, n);
1586 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
1587 static char **o_finalize_list(o_string *o, int n)
1592 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1594 debug_print_list("finalized", o, n);
1595 debug_printf_expand("finalized n:%d\n", n);
1596 list = (char**)o->data;
1597 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1601 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
1607 /* Expansion can recurse */
1608 #if ENABLE_HUSH_TICK
1609 static int process_command_subs(o_string *dest, const char *s);
1611 static char *expand_string_to_string(const char *str);
1613 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
1614 parse_stream_dquoted(dest, input, dquote_end)
1616 static int parse_stream_dquoted(o_string *as_string,
1618 struct in_str *input,
1621 /* expand_strvec_to_strvec() takes a list of strings, expands
1622 * all variable references within and returns a pointer to
1623 * a list of expanded strings, possibly with larger number
1624 * of strings. (Think VAR="a b"; echo $VAR).
1625 * This new list is allocated as a single malloc block.
1626 * NULL-terminated list of char* pointers is at the beginning of it,
1627 * followed by strings themself.
1628 * Caller can deallocate entire list by single free(list). */
1630 /* Store given string, finalizing the word and starting new one whenever
1631 * we encounter IFS char(s). This is used for expanding variable values.
1632 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
1633 static int expand_on_ifs(o_string *output, int n, const char *str)
1636 int word_len = strcspn(str, G.ifs);
1638 if (output->o_escape || !output->o_glob)
1639 o_addQstr(output, str, word_len);
1640 else /* protect backslashes against globbing up :) */
1641 o_addblock_duplicate_backslash(output, str, word_len);
1644 if (!*str) /* EOL - do not finalize word */
1646 o_addchr(output, '\0');
1647 debug_print_list("expand_on_ifs", output, n);
1648 n = o_save_ptr(output, n);
1649 str += strspn(str, G.ifs); /* skip ifs chars */
1651 debug_print_list("expand_on_ifs[1]", output, n);
1655 /* Expand all variable references in given string, adding words to list[]
1656 * at n, n+1,... positions. Return updated n (so that list[n] is next one
1657 * to be filled). This routine is extremely tricky: has to deal with
1658 * variables/parameters with whitespace, $* and $@, and constructs like
1659 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
1660 static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
1662 /* or_mask is either 0 (normal case) or 0x80
1663 * (expansion of right-hand side of assignment == 1-element expand.
1664 * It will also do no globbing, and thus we must not backslash-quote!) */
1666 char first_ch, ored_ch;
1674 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
1675 debug_print_list("expand_vars_to_list", output, n);
1676 n = o_save_ptr(output, n);
1677 debug_print_list("expand_vars_to_list[0]", output, n);
1679 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
1680 #if ENABLE_HUSH_TICK
1681 o_string subst_result = NULL_O_STRING;
1683 #if ENABLE_SH_MATH_SUPPORT
1684 char arith_buf[sizeof(arith_t)*3 + 2];
1686 o_addblock(output, arg, p - arg);
1687 debug_print_list("expand_vars_to_list[1]", output, n);
1689 p = strchr(p, SPECIAL_VAR_SYMBOL);
1691 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
1692 /* "$@" is special. Even if quoted, it can still
1693 * expand to nothing (not even an empty string) */
1694 if ((first_ch & 0x7f) != '@')
1695 ored_ch |= first_ch;
1698 switch (first_ch & 0x7f) {
1699 /* Highest bit in first_ch indicates that var is double-quoted */
1701 val = utoa(G.root_pid);
1703 case '!': /* bg pid */
1704 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
1706 case '?': /* exitcode */
1707 val = utoa(G.last_exitcode);
1709 case '#': /* argc */
1710 if (arg[1] != SPECIAL_VAR_SYMBOL)
1711 /* actually, it's a ${#var} */
1713 val = utoa(G.global_argc ? G.global_argc-1 : 0);
1718 if (!G.global_argv[i])
1720 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
1721 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
1722 smallint sv = output->o_escape;
1723 /* unquoted var's contents should be globbed, so don't escape */
1724 output->o_escape = 0;
1725 while (G.global_argv[i]) {
1726 n = expand_on_ifs(output, n, G.global_argv[i]);
1727 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
1728 if (G.global_argv[i++][0] && G.global_argv[i]) {
1729 /* this argv[] is not empty and not last:
1730 * put terminating NUL, start new word */
1731 o_addchr(output, '\0');
1732 debug_print_list("expand_vars_to_list[2]", output, n);
1733 n = o_save_ptr(output, n);
1734 debug_print_list("expand_vars_to_list[3]", output, n);
1737 output->o_escape = sv;
1739 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
1740 * and in this case should treat it like '$*' - see 'else...' below */
1741 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
1743 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1744 if (++i >= G.global_argc)
1746 o_addchr(output, '\0');
1747 debug_print_list("expand_vars_to_list[4]", output, n);
1748 n = o_save_ptr(output, n);
1750 } else { /* quoted $*: add as one word */
1752 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1753 if (!G.global_argv[++i])
1756 o_addchr(output, G.ifs[0]);
1760 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
1761 /* "Empty variable", used to make "" etc to not disappear */
1765 #if ENABLE_HUSH_TICK
1766 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
1769 //TODO: can we just stuff it into "output" directly?
1770 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
1771 process_command_subs(&subst_result, arg);
1772 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
1773 val = subst_result.data;
1776 #if ENABLE_SH_MATH_SUPPORT
1777 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
1778 arith_eval_hooks_t hooks;
1783 arg++; /* skip '+' */
1784 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
1785 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
1787 /* Optional: skip expansion if expr is simple ("a + 3", "i++" etc) */
1789 if (strchr(arg, '$') != NULL
1790 #if ENABLE_HUSH_TICK
1791 || strchr(arg, '`') != NULL
1794 /* We need to expand. Example:
1795 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
1797 struct in_str input;
1798 o_string dest = NULL_O_STRING;
1800 setup_string_in_str(&input, arg);
1801 parse_stream_dquoted(NULL, &dest, &input, EOF);
1802 //bb_error_msg("'%s' -> '%s'", arg, dest.data);
1803 exp_str = expand_string_to_string(dest.data);
1804 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
1805 o_free_unsafe(&dest);
1807 hooks.lookupvar = get_local_var_value;
1808 hooks.setvar = arith_set_local_var;
1809 hooks.endofname = endofname;
1810 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
1815 case -3: maybe_die("arith", "exponent less than 0"); break;
1816 case -2: maybe_die("arith", "divide by zero"); break;
1817 case -5: maybe_die("arith", "expression recursion loop detected"); break;
1818 default: maybe_die("arith", "syntax error"); break;
1821 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
1822 sprintf(arith_buf, arith_t_fmt, res);
1827 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
1829 bool exp_len = false;
1830 bool exp_null = false;
1832 char exp_save = exp_save; /* for compiler */
1833 char exp_op = exp_op; /* for compiler */
1834 char *exp_word = exp_word; /* for compiler */
1838 arg[0] = first_ch & 0x7f;
1840 /* prepare for expansions */
1841 if (var[0] == '#') {
1842 /* handle length expansion ${#var} */
1846 /* maybe handle parameter expansion */
1847 exp_off = strcspn(var, ":-=+?%#");
1851 exp_save = var[exp_off];
1852 exp_null = exp_save == ':';
1853 exp_word = var + exp_off;
1854 if (exp_null) ++exp_word;
1855 exp_op = *exp_word++;
1856 var[exp_off] = '\0';
1860 /* lookup the variable in question */
1861 if (isdigit(var[0])) {
1862 /* handle_dollar() should have vetted var for us */
1864 if (i < G.global_argc)
1865 val = G.global_argv[i];
1866 /* else val remains NULL: $N with too big N */
1868 val = get_local_var_value(var);
1870 /* handle any expansions */
1872 debug_printf_expand("expand: length of '%s' = ", val);
1873 val = utoa(val ? strlen(val) : 0);
1874 debug_printf_expand("%s\n", val);
1875 } else if (exp_off) {
1876 if (exp_op == '%' || exp_op == '#') {
1877 /* we need to do a pattern match */
1880 scan_t scan = pick_scan(exp_op, *exp_word, &zero);
1881 if (exp_op == *exp_word) /* ## or %% */
1883 val = dyn_val = xstrdup(val);
1884 loc = scan(dyn_val, exp_word, zero);
1890 /* we need to do an expansion */
1891 int exp_test = (!val || (exp_null && !val[0]));
1893 exp_test = !exp_test;
1894 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
1895 exp_null ? "true" : "false", exp_test);
1898 maybe_die(var, *exp_word ? exp_word : "parameter null or not set");
1902 if (exp_op == '=') {
1903 if (isdigit(var[0]) || var[0] == '#') {
1904 maybe_die(var, "special vars cannot assign in this way");
1907 char *new_var = xmalloc(strlen(var) + strlen(val) + 2);
1908 sprintf(new_var, "%s=%s", var, val);
1909 set_local_var(new_var, -1, 0);
1915 var[exp_off] = exp_save;
1919 #if ENABLE_HUSH_TICK
1922 if (!(first_ch & 0x80)) { /* unquoted $VAR */
1923 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
1925 /* unquoted var's contents should be globbed, so don't escape */
1926 smallint sv = output->o_escape;
1927 output->o_escape = 0;
1928 n = expand_on_ifs(output, n, val);
1930 output->o_escape = sv;
1932 } else { /* quoted $VAR, val will be appended below */
1933 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
1936 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
1938 o_addQstr(output, val, strlen(val));
1942 /* Do the check to avoid writing to a const string */
1943 if (*p != SPECIAL_VAR_SYMBOL)
1944 *p = SPECIAL_VAR_SYMBOL;
1946 #if ENABLE_HUSH_TICK
1947 o_free(&subst_result);
1950 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
1953 debug_print_list("expand_vars_to_list[a]", output, n);
1954 /* this part is literal, and it was already pre-quoted
1955 * if needed (much earlier), do not use o_addQstr here! */
1956 o_addstr_with_NUL(output, arg);
1957 debug_print_list("expand_vars_to_list[b]", output, n);
1958 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
1959 && !(ored_ch & 0x80) /* and all vars were not quoted. */
1962 /* allow to reuse list[n] later without re-growth */
1963 output->has_empty_slot = 1;
1965 o_addchr(output, '\0');
1970 static char **expand_variables(char **argv, int or_mask)
1975 o_string output = NULL_O_STRING;
1977 if (or_mask & 0x100) {
1978 output.o_escape = 1; /* protect against globbing for "$var" */
1979 /* (unquoted $var will temporarily switch it off) */
1986 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
1989 debug_print_list("expand_variables", &output, n);
1991 /* output.data (malloced in one block) gets returned in "list" */
1992 list = o_finalize_list(&output, n);
1993 debug_print_strings("expand_variables[1]", list);
1997 static char **expand_strvec_to_strvec(char **argv)
1999 return expand_variables(argv, 0x100);
2002 /* Used for expansion of right hand of assignments */
2003 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2005 static char *expand_string_to_string(const char *str)
2007 char *argv[2], **list;
2009 argv[0] = (char*)str;
2011 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2013 if (!list[0] || list[1])
2014 bb_error_msg_and_die("BUG in varexp2");
2015 /* actually, just move string 2*sizeof(char*) bytes back */
2016 overlapping_strcpy((char*)list, list[0]);
2017 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2021 /* Used for "eval" builtin */
2022 static char* expand_strvec_to_string(char **argv)
2026 list = expand_variables(argv, 0x80);
2027 /* Convert all NULs to spaces */
2032 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2033 bb_error_msg_and_die("BUG in varexp3");
2034 list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
2038 overlapping_strcpy((char*)list, list[0]);
2039 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2043 static char **expand_assignments(char **argv, int count)
2047 /* Expand assignments into one string each */
2048 for (i = 0; i < count; i++) {
2049 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2055 //TODO: fix big string case!
2056 static void setup_heredoc(int fd, const char *heredoc)
2058 struct fd_pair pair;
2064 bb_perror_msg_and_die("vfork");
2065 if (pid == 0) { /* child */
2068 xwrite_str(pair.wr, heredoc);
2074 xmove_fd(pair.rd, fd);
2077 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
2078 * and stderr if they are redirected. */
2079 static int setup_redirects(struct command *prog, int squirrel[])
2081 //TODO: no callers ever check return value - ?!
2083 struct redir_struct *redir;
2085 for (redir = prog->redirects; redir; redir = redir->next) {
2086 if (redir->rd_type == REDIRECT_HEREDOC2) {
2087 if (squirrel && redir->fd < 3) {
2088 squirrel[redir->fd] = dup(redir->fd);
2090 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
2092 debug_printf_parse("set heredoc '%s'\n",
2093 redir->rd_filename);
2094 setup_heredoc(redir->fd, redir->rd_filename);
2098 if (redir->dup == -1) {
2100 if (redir->rd_filename == NULL) {
2101 /* Something went wrong in the parse.
2102 * Pretend it didn't happen */
2105 mode = redir_table[redir->rd_type].mode;
2106 //TODO: check redir for names like '\\'
2107 p = expand_string_to_string(redir->rd_filename);
2108 openfd = open_or_warn(p, mode);
2111 /* this could get lost if stderr has been redirected, but
2112 * bash and ash both lose it as well (though zsh doesn't!) */
2113 //what the above comment tries to say?
2117 openfd = redir->dup;
2120 if (openfd != redir->fd) {
2121 if (squirrel && redir->fd < 3) {
2122 squirrel[redir->fd] = dup(redir->fd);
2125 /* "-" means "close me" and we use -3 for that */
2128 dup2(openfd, redir->fd);
2129 if (redir->dup == -1)
2137 static void restore_redirects(int squirrel[])
2140 for (i = 0; i < 3; i++) {
2143 /* We simply die on error */
2151 #define free_pipe_list(head, indent) free_pipe_list(head)
2152 #define free_pipe(pi, indent) free_pipe(pi)
2154 static void free_pipe_list(struct pipe *head, int indent);
2156 /* Return code is the exit status of the pipe */
2157 static void free_pipe(struct pipe *pi, int indent)
2160 struct command *command;
2161 struct redir_struct *r, *rnext;
2164 if (pi->stopped_cmds > 0) /* why? */
2166 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2167 for (i = 0; i < pi->num_cmds; i++) {
2168 command = &pi->cmds[i];
2169 debug_printf_clean("%s command %d:\n", indenter(indent), i);
2170 if (command->argv) {
2171 for (a = 0, p = command->argv; *p; a++, p++) {
2172 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
2174 free_strings(command->argv);
2175 command->argv = NULL;
2177 /* not "else if": on syntax error, we may have both! */
2178 if (command->group) {
2179 debug_printf_clean("%s begin group (grp_type:%d)\n", indenter(indent), command->grp_type);
2180 free_pipe_list(command->group, indent+3);
2181 debug_printf_clean("%s end group\n", indenter(indent));
2182 command->group = NULL;
2185 free(command->group_as_string);
2186 command->group_as_string = NULL;
2188 for (r = command->redirects; r; r = rnext) {
2189 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->rd_type].descrip);
2191 /* guard against the case >$FOO, where foo is unset or blank */
2192 if (r->rd_filename) {
2193 debug_printf_clean(" %s\n", r->rd_filename);
2194 free(r->rd_filename);
2195 r->rd_filename = NULL;
2198 debug_printf_clean("&%d\n", r->dup);
2203 command->redirects = NULL;
2205 free(pi->cmds); /* children are an array, they get freed all at once */
2213 static void free_pipe_list(struct pipe *head, int indent)
2215 struct pipe *pi, *next;
2217 for (pi = head; pi; pi = next) {
2219 debug_printf_clean("%s pipe reserved word %d\n", indenter(indent), pi->res_word);
2221 free_pipe(pi, indent);
2222 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
2224 /*pi->next = NULL;*/
2231 typedef struct nommu_save_t {
2237 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
2238 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
2239 #define pseudo_exec(nommu_save, command, argv_expanded) \
2240 pseudo_exec(command, argv_expanded)
2243 /* Called after [v]fork() in run_pipe, or from builtin_exec.
2245 * XXX no exit() here. If you don't exec, use _exit instead.
2246 * The at_exit handlers apparently confuse the calling process,
2247 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
2248 static void pseudo_exec_argv(nommu_save_t *nommu_save,
2249 char **argv, int assignment_cnt,
2250 char **argv_expanded) NORETURN;
2251 static void pseudo_exec_argv(nommu_save_t *nommu_save,
2252 char **argv, int assignment_cnt,
2253 char **argv_expanded)
2257 /* Case when we are here: ... | var=val | ... */
2258 if (!argv[assignment_cnt])
2259 _exit(EXIT_SUCCESS);
2261 new_env = expand_assignments(argv, assignment_cnt);
2263 putenv_all(new_env);
2264 free(new_env); /* optional */
2266 nommu_save->new_env = new_env;
2267 nommu_save->old_env = putenv_all_and_save_old(new_env);
2269 if (argv_expanded) {
2270 argv = argv_expanded;
2272 argv = expand_strvec_to_strvec(argv + assignment_cnt);
2274 nommu_save->argv = argv;
2278 /* On NOMMU, we must never block!
2279 * Example: { sleep 99999 | read line } & echo Ok
2280 * read builtin will block on read syscall, leaving parent blocked
2281 * in vfork. Therefore we can't do this:
2284 /* Check if the command matches any of the builtins.
2285 * Depending on context, this might be redundant. But it's
2286 * easier to waste a few CPU cycles than it is to figure out
2287 * if this is one of those cases.
2291 const struct built_in_command *x;
2292 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2293 if (strcmp(argv[0], x->cmd) == 0) {
2294 debug_printf_exec("running builtin '%s'\n",
2296 rcode = x->function(argv);
2304 #if ENABLE_FEATURE_SH_STANDALONE
2305 /* Check if the command matches any busybox applets */
2306 if (strchr(argv[0], '/') == NULL) {
2307 int a = find_applet_by_name(argv[0]);
2309 #if BB_MMU /* see above why on NOMMU it is not allowed */
2310 if (APPLET_IS_NOEXEC(a)) {
2311 debug_printf_exec("running applet '%s'\n", argv[0]);
2312 run_applet_no_and_exit(a, argv);
2315 /* Re-exec ourselves */
2316 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
2317 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2318 execv(bb_busybox_exec_path, argv);
2319 /* If they called chroot or otherwise made the binary no longer
2320 * executable, fall through */
2325 debug_printf_exec("execing '%s'\n", argv[0]);
2326 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2327 execvp(argv[0], argv);
2328 bb_perror_msg("can't exec '%s'", argv[0]);
2329 _exit(EXIT_FAILURE);
2333 static void reset_traps_to_defaults(void)
2341 for (sig = 0; sig < NSIG; sig++) {
2345 G.traps[sig] = NULL;
2346 /* There is no signal for 0 (EXIT) */
2349 /* there was a trap handler, we are removing it
2350 * (if sig has non-DFL handling,
2351 * we don't need to do anything) */
2352 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
2354 sigdelset(&G.blocked_set, sig);
2358 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
2360 #define clean_up_after_re_execute() ((void)0)
2364 static void re_execute_shell(const char *s) NORETURN;
2365 static void re_execute_shell(const char *s)
2367 char param_buf[sizeof("-$%x:%x:%x:%x") + sizeof(unsigned) * 4];
2368 struct variable *cur;
2369 char **argv, **pp, **pp2;
2372 sprintf(param_buf, "-$%x:%x:%x" USE_HUSH_LOOPS(":%x")
2373 , (unsigned) G.root_pid
2374 , (unsigned) G.last_bg_pid
2375 , (unsigned) G.last_exitcode
2376 USE_HUSH_LOOPS(, G.depth_of_loop)
2378 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...>
2379 * 3:-c 4:<cmd> <argN...> 5:NULL
2381 cnt = 5 + G.global_argc;
2382 for (cur = G.top_var; cur; cur = cur->next) {
2383 if (!cur->flg_export || cur->flg_read_only)
2386 G.argv_from_re_execing = pp = xzalloc(sizeof(argv[0]) * cnt);
2387 *pp++ = (char *) G.argv0_for_re_execing;
2389 for (cur = G.top_var; cur; cur = cur->next) {
2390 if (cur->varstr == hush_version_str)
2392 if (cur->flg_read_only) {
2393 *pp++ = (char *) "-R";
2394 *pp++ = cur->varstr;
2395 } else if (!cur->flg_export) {
2396 *pp++ = (char *) "-V";
2397 *pp++ = cur->varstr;
2400 //TODO: pass functions
2401 /* We can pass activated traps here. Say, -Tnn:trap_string
2403 * However, POSIX says that subshells reset signals with traps
2405 * I tested bash-3.2 and it not only does that with true subshells
2406 * of the form ( list ), but with any forked children shells.
2407 * I set trap "echo W" WINCH; and then tried:
2409 * { echo 1; sleep 20; echo 2; } &
2410 * while true; do echo 1; sleep 20; echo 2; break; done &
2411 * true | { echo 1; sleep 20; echo 2; } | cat
2413 * In all these cases sending SIGWINCH to the child shell
2414 * did not run the trap. If I add trap "echo V" WINCH;
2415 * _inside_ group (just before echo 1), it works.
2417 * I conclude it means we don't need to pass active traps here.
2418 * exec syscall below resets them to SIG_DFL for us.
2420 *pp++ = (char *) "-c";
2422 pp2 = G.global_argv;
2425 /* *pp = NULL; - is already there */
2427 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
2428 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2429 execv(bb_busybox_exec_path, G.argv_from_re_execing);
2430 /* Fallback. Useful for init=/bin/hush usage etc */
2431 if (G.argv0_for_re_execing[0] == '/')
2432 execv(G.argv0_for_re_execing, G.argv_from_re_execing);
2433 xfunc_error_retval = 127;
2434 bb_error_msg_and_die("can't re-execute the shell");
2437 static void clean_up_after_re_execute(void)
2439 char **pp = G.argv_from_re_execing;
2441 /* Must match re_execute_shell's allocations (if any) */
2443 G.argv_from_re_execing = NULL;
2448 static int run_list(struct pipe *pi);
2450 /* Called after [v]fork() in run_pipe
2452 static void pseudo_exec(nommu_save_t *nommu_save,
2453 struct command *command,
2454 char **argv_expanded) NORETURN;
2455 static void pseudo_exec(nommu_save_t *nommu_save,
2456 struct command *command,
2457 char **argv_expanded)
2459 if (command->argv) {
2460 pseudo_exec_argv(nommu_save, command->argv,
2461 command->assignment_cnt, argv_expanded);
2464 if (command->group) {
2465 /* Cases when we are here:
2468 * ... | ( list ) | ...
2469 * ... | { list } | ...
2473 debug_printf_exec("pseudo_exec: run_list\n");
2474 reset_traps_to_defaults();
2475 rcode = run_list(command->group);
2476 /* OK to leak memory by not calling free_pipe_list,
2477 * since this process is about to exit */
2480 re_execute_shell(command->group_as_string);
2484 /* Case when we are here: ... | >file */
2485 debug_printf_exec("pseudo_exec'ed null command\n");
2486 _exit(EXIT_SUCCESS);
2490 static const char *get_cmdtext(struct pipe *pi)
2496 /* This is subtle. ->cmdtext is created only on first backgrounding.
2497 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
2498 * On subsequent bg argv is trashed, but we won't use it */
2501 argv = pi->cmds[0].argv;
2502 if (!argv || !argv[0]) {
2503 pi->cmdtext = xzalloc(1);
2508 do len += strlen(*argv) + 1; while (*++argv);
2509 pi->cmdtext = p = xmalloc(len);
2510 argv = pi->cmds[0].argv;
2512 len = strlen(*argv);
2513 memcpy(p, *argv, len);
2521 static void insert_bg_job(struct pipe *pi)
2523 struct pipe *thejob;
2526 /* Linear search for the ID of the job to use */
2528 for (thejob = G.job_list; thejob; thejob = thejob->next)
2529 if (thejob->jobid >= pi->jobid)
2530 pi->jobid = thejob->jobid + 1;
2532 /* Add thejob to the list of running jobs */
2534 thejob = G.job_list = xmalloc(sizeof(*thejob));
2536 for (thejob = G.job_list; thejob->next; thejob = thejob->next)
2538 thejob->next = xmalloc(sizeof(*thejob));
2539 thejob = thejob->next;
2542 /* Physically copy the struct job */
2543 memcpy(thejob, pi, sizeof(struct pipe));
2544 thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
2545 /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
2546 for (i = 0; i < pi->num_cmds; i++) {
2547 // TODO: do we really need to have so many fields which are just dead weight
2548 // at execution stage?
2549 thejob->cmds[i].pid = pi->cmds[i].pid;
2550 /* all other fields are not used and stay zero */
2552 thejob->next = NULL;
2553 thejob->cmdtext = xstrdup(get_cmdtext(pi));
2555 /* We don't wait for background thejobs to return -- append it
2556 to the list of backgrounded thejobs and leave it alone */
2557 if (G_interactive_fd)
2558 printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
2559 G.last_bg_pid = thejob->cmds[0].pid;
2560 G.last_jobid = thejob->jobid;
2563 static void remove_bg_job(struct pipe *pi)
2565 struct pipe *prev_pipe;
2567 if (pi == G.job_list) {
2568 G.job_list = pi->next;
2570 prev_pipe = G.job_list;
2571 while (prev_pipe->next != pi)
2572 prev_pipe = prev_pipe->next;
2573 prev_pipe->next = pi->next;
2576 G.last_jobid = G.job_list->jobid;
2581 /* Remove a backgrounded job */
2582 static void delete_finished_bg_job(struct pipe *pi)
2585 pi->stopped_cmds = 0;
2591 /* Check to see if any processes have exited -- if they
2592 * have, figure out why and see if a job has completed */
2593 static int checkjobs(struct pipe* fg_pipe)
2603 debug_printf_jobs("checkjobs %p\n", fg_pipe);
2606 // if (G.handled_SIGCHLD == G.count_SIGCHLD)
2607 // /* avoid doing syscall, nothing there anyway */
2610 attributes = WUNTRACED;
2611 if (fg_pipe == NULL)
2612 attributes |= WNOHANG;
2614 /* Do we do this right?
2615 * bash-3.00# sleep 20 | false
2617 * [3]+ Stopped sleep 20 | false
2618 * bash-3.00# echo $?
2619 * 1 <========== bg pipe is not fully done, but exitcode is already known!
2622 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
2623 //are stopped. Testcase: "cat | cat" in a script (not on command line)
2624 // + killall -STOP cat
2631 // i = G.count_SIGCHLD;
2632 childpid = waitpid(-1, &status, attributes);
2633 if (childpid <= 0) {
2634 if (childpid && errno != ECHILD)
2635 bb_perror_msg("waitpid");
2636 // else /* Until next SIGCHLD, waitpid's are useless */
2637 // G.handled_SIGCHLD = i;
2640 dead = WIFEXITED(status) || WIFSIGNALED(status);
2643 if (WIFSTOPPED(status))
2644 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
2645 childpid, WSTOPSIG(status), WEXITSTATUS(status));
2646 if (WIFSIGNALED(status))
2647 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
2648 childpid, WTERMSIG(status), WEXITSTATUS(status));
2649 if (WIFEXITED(status))
2650 debug_printf_jobs("pid %d exited, exitcode %d\n",
2651 childpid, WEXITSTATUS(status));
2653 /* Were we asked to wait for fg pipe? */
2655 for (i = 0; i < fg_pipe->num_cmds; i++) {
2656 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
2657 if (fg_pipe->cmds[i].pid != childpid)
2659 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
2661 fg_pipe->cmds[i].pid = 0;
2662 fg_pipe->alive_cmds--;
2663 if (i == fg_pipe->num_cmds - 1) {
2664 /* last process gives overall exitstatus */
2665 rcode = WEXITSTATUS(status);
2666 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
2669 fg_pipe->cmds[i].is_stopped = 1;
2670 fg_pipe->stopped_cmds++;
2672 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
2673 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
2674 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
2675 /* All processes in fg pipe have exited/stopped */
2677 if (fg_pipe->alive_cmds)
2678 insert_bg_job(fg_pipe);
2682 /* There are still running processes in the fg pipe */
2683 goto wait_more; /* do waitpid again */
2685 /* it wasnt fg_pipe, look for process in bg pipes */
2689 /* We asked to wait for bg or orphaned children */
2690 /* No need to remember exitcode in this case */
2691 for (pi = G.job_list; pi; pi = pi->next) {
2692 for (i = 0; i < pi->num_cmds; i++) {
2693 if (pi->cmds[i].pid == childpid)
2694 goto found_pi_and_prognum;
2697 /* Happens when shell is used as init process (init=/bin/sh) */
2698 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
2699 continue; /* do waitpid again */
2701 found_pi_and_prognum:
2704 pi->cmds[i].pid = 0;
2706 if (!pi->alive_cmds) {
2707 if (G_interactive_fd)
2708 printf(JOB_STATUS_FORMAT, pi->jobid,
2709 "Done", pi->cmdtext);
2710 delete_finished_bg_job(pi);
2714 pi->cmds[i].is_stopped = 1;
2718 } /* while (waitpid succeeds)... */
2724 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
2727 int rcode = checkjobs(fg_pipe);
2728 /* Job finished, move the shell to the foreground */
2729 p = getpgid(0); /* pgid of our process */
2730 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
2731 tcsetpgrp(G_interactive_fd, p);
2736 /* Start all the jobs, but don't wait for anything to finish.
2739 * Return code is normally -1, when the caller has to wait for children
2740 * to finish to determine the exit status of the pipe. If the pipe
2741 * is a simple builtin command, however, the action is done by the
2742 * time run_pipe returns, and the exit code is provided as the
2745 * Returns -1 only if started some children. IOW: we have to
2746 * mask out retvals of builtins etc with 0xff!
2748 * The only case when we do not need to [v]fork is when the pipe
2749 * is single, non-backgrounded, non-subshell command. Examples:
2750 * cmd ; ... { list } ; ...
2751 * cmd && ... { list } && ...
2752 * cmd || ... { list } || ...
2753 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
2754 * or (if SH_STANDALONE) an applet, and we can run the { list }
2755 * with run_list(). If it isn't one of these, we fork and exec cmd.
2757 * Cases when we must fork:
2758 * non-single: cmd | cmd
2759 * backgrounded: cmd & { list } &
2760 * subshell: ( list ) [&]
2762 static int run_pipe(struct pipe *pi)
2764 static const char *const null_ptr = NULL;
2767 int pipefds[2]; /* pipefds[0] is for reading */
2768 struct command *command;
2769 char **argv_expanded;
2772 /* it is not always needed, but we aim to smaller code */
2773 int squirrel[] = { -1, -1, -1 };
2776 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
2778 USE_HUSH_JOB(pi->pgrp = -1;)
2779 pi->stopped_cmds = 0;
2780 command = &(pi->cmds[0]);
2781 argv_expanded = NULL;
2783 if (pi->num_cmds != 1
2784 || pi->followup == PIPE_BG
2785 || command->grp_type == GRP_SUBSHELL
2792 debug_printf_exec(": group:%p argv:'%s'\n",
2793 command->group, command->argv ? command->argv[0] : "NONE");
2795 if (command->group) {
2796 #if ENABLE_HUSH_FUNCTIONS
2797 if (command->grp_type == GRP_FUNCTION) {
2798 /* func () { list } */
2799 bb_error_msg("here we ought to remember function definition, and go on");
2800 return EXIT_SUCCESS;
2804 debug_printf("non-subshell group\n");
2805 setup_redirects(command, squirrel);
2806 debug_printf_exec(": run_list\n");
2807 rcode = run_list(command->group) & 0xff;
2808 restore_redirects(squirrel);
2809 debug_printf_exec("run_pipe return %d\n", rcode);
2810 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2814 argv = command->argv ? command->argv : (char **) &null_ptr;
2816 const struct built_in_command *x;
2817 char **new_env = NULL;
2818 char **old_env = NULL;
2820 if (argv[command->assignment_cnt] == NULL) {
2821 /* Assignments, but no command */
2822 /* Ensure redirects take effect. Try "a=t >file" */
2823 setup_redirects(command, squirrel);
2824 restore_redirects(squirrel);
2825 /* Set shell variables */
2827 p = expand_string_to_string(*argv);
2828 debug_printf_exec("set shell var:'%s'->'%s'\n",
2830 set_local_var(p, 0, 0);
2833 /* Do we need to flag set_local_var() errors?
2834 * "assignment to readonly var" and "putenv error"
2836 return EXIT_SUCCESS;
2839 /* Expand the rest into (possibly) many strings each */
2840 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
2842 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2843 if (strcmp(argv_expanded[0], x->cmd) != 0)
2845 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
2846 debug_printf("exec with redirects only\n");
2847 setup_redirects(command, NULL);
2848 rcode = EXIT_SUCCESS;
2849 goto clean_up_and_ret1;
2851 debug_printf("builtin inline %s\n", argv_expanded[0]);
2852 /* XXX setup_redirects acts on file descriptors, not FILEs.
2853 * This is perfect for work that comes after exec().
2854 * Is it really safe for inline use? Experimentally,
2855 * things seem to work with glibc. */
2856 setup_redirects(command, squirrel);
2857 new_env = expand_assignments(argv, command->assignment_cnt);
2858 old_env = putenv_all_and_save_old(new_env);
2859 debug_printf_exec(": builtin '%s' '%s'...\n",
2860 x->cmd, argv_expanded[1]);
2861 rcode = x->function(argv_expanded) & 0xff;
2862 #if ENABLE_FEATURE_SH_STANDALONE
2865 restore_redirects(squirrel);
2866 free_strings_and_unsetenv(new_env, 1);
2867 putenv_all(old_env);
2868 free(old_env); /* not free_strings()! */
2870 free(argv_expanded);
2871 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2872 debug_printf_exec("run_pipe return %d\n", rcode);
2875 #if ENABLE_FEATURE_SH_STANDALONE
2876 i = find_applet_by_name(argv_expanded[0]);
2877 if (i >= 0 && APPLET_IS_NOFORK(i)) {
2878 setup_redirects(command, squirrel);
2879 save_nofork_data(&G.nofork_save);
2880 new_env = expand_assignments(argv, command->assignment_cnt);
2881 old_env = putenv_all_and_save_old(new_env);
2882 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
2883 argv_expanded[0], argv_expanded[1]);
2884 rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
2885 goto clean_up_and_ret;
2888 /* It is neither builtin nor applet. We must fork. */
2892 /* NB: argv_expanded may already be created, and that
2893 * might include `cmd` runs! Do not rerun it! We *must*
2894 * use argv_expanded if it's non-NULL */
2896 /* Going to fork a child per each pipe member */
2900 for (i = 0; i < pi->num_cmds; i++) {
2902 volatile nommu_save_t nommu_save;
2903 nommu_save.new_env = NULL;
2904 nommu_save.old_env = NULL;
2905 nommu_save.argv = NULL;
2907 command = &(pi->cmds[i]);
2908 if (command->argv) {
2909 debug_printf_exec(": pipe member '%s' '%s'...\n",
2910 command->argv[0], command->argv[1]);
2912 debug_printf_exec(": pipe member with no argv\n");
2915 /* pipes are inserted between pairs of commands */
2918 if ((i + 1) < pi->num_cmds)
2921 command->pid = BB_MMU ? fork() : vfork();
2922 if (!command->pid) { /* child */
2924 die_sleep = 0; /* do not restore tty pgrp on xfunc death */
2926 /* Every child adds itself to new process group
2927 * with pgid == pid_of_first_child_in_pipe */
2928 if (G.run_list_level == 1 && G_interactive_fd) {
2931 if (pgrp < 0) /* true for 1st process only */
2933 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
2934 /* We do it in *every* child, not just first,
2936 tcsetpgrp(G_interactive_fd, pgrp);
2940 xmove_fd(nextin, 0);
2941 xmove_fd(pipefds[1], 1); /* write end */
2943 close(pipefds[0]); /* read end */
2944 /* Like bash, explicit redirects override pipes,
2945 * and the pipe fd is available for dup'ing. */
2946 setup_redirects(command, NULL);
2948 /* Restore default handlers just prior to exec */
2949 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
2951 /* Stores to nommu_save list of env vars putenv'ed
2952 * (NOMMU, on MMU we don't need that) */
2953 /* cast away volatility... */
2954 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
2955 /* pseudo_exec() does not return */
2958 /* parent or error */
2960 die_sleep = -1; /* restore tty pgrp on xfunc death */
2963 /* Clean up after vforked child */
2964 clean_up_after_re_execute();
2965 free(nommu_save.argv);
2966 free_strings_and_unsetenv(nommu_save.new_env, 1);
2967 putenv_all(nommu_save.old_env);
2969 free(argv_expanded);
2970 argv_expanded = NULL;
2971 if (command->pid < 0) { /* [v]fork failed */
2972 /* Clearly indicate, was it fork or vfork */
2973 bb_perror_msg(BB_MMU ? "fork" : "vfork");
2977 /* Second and next children need to know pid of first one */
2979 pi->pgrp = command->pid;
2985 if ((i + 1) < pi->num_cmds)
2986 close(pipefds[1]); /* write end */
2987 /* Pass read (output) pipe end to next iteration */
2988 nextin = pipefds[0];
2991 if (!pi->alive_cmds) {
2992 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
2996 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
3000 #ifndef debug_print_tree
3001 static void debug_print_tree(struct pipe *pi, int lvl)
3003 static const char *const PIPE[] = {
3009 static const char *RES[] = {
3010 [RES_NONE ] = "NONE" ,
3013 [RES_THEN ] = "THEN" ,
3014 [RES_ELIF ] = "ELIF" ,
3015 [RES_ELSE ] = "ELSE" ,
3018 #if ENABLE_HUSH_LOOPS
3019 [RES_FOR ] = "FOR" ,
3020 [RES_WHILE] = "WHILE",
3021 [RES_UNTIL] = "UNTIL",
3023 [RES_DONE ] = "DONE" ,
3025 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
3028 #if ENABLE_HUSH_CASE
3029 [RES_CASE ] = "CASE" ,
3030 [RES_MATCH] = "MATCH",
3031 [RES_CASEI] = "CASEI",
3032 [RES_ESAC ] = "ESAC" ,
3034 [RES_XXXX ] = "XXXX" ,
3035 [RES_SNTX ] = "SNTX" ,
3037 static const char *const GRPTYPE[] = {
3040 #if ENABLE_HUSH_FUNCTIONS
3049 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3050 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
3052 while (prn < pi->num_cmds) {
3053 struct command *command = &pi->cmds[prn];
3054 char **argv = command->argv;
3056 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
3058 command->assignment_cnt);
3059 if (command->group) {
3060 fprintf(stderr, " group %s: (argv=%p)\n",
3061 GRPTYPE[command->grp_type],
3063 debug_print_tree(command->group, lvl+1);
3067 if (argv) while (*argv) {
3068 fprintf(stderr, " '%s'", *argv);
3071 fprintf(stderr, "\n");
3080 /* NB: called by pseudo_exec, and therefore must not modify any
3081 * global data until exec/_exit (we can be a child after vfork!) */
3082 static int run_list(struct pipe *pi)
3084 #if ENABLE_HUSH_CASE
3085 char *case_word = NULL;
3087 #if ENABLE_HUSH_LOOPS
3088 struct pipe *loop_top = NULL;
3089 char *for_varname = NULL;
3090 char **for_lcur = NULL;
3091 char **for_list = NULL;
3093 smallint last_followup;
3095 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
3096 smalluint cond_code = 0;
3098 enum { cond_code = 0 };
3101 smallint rword; /* enum reserved_style */
3102 smallint last_rword; /* ditto */
3105 debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
3107 #if ENABLE_HUSH_LOOPS
3108 /* Check syntax for "for" */
3109 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
3110 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
3112 /* current word is FOR or IN (BOLD in comments below) */
3113 if (cpipe->next == NULL) {
3114 syntax("malformed for");
3115 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
3118 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
3119 if (cpipe->next->res_word == RES_DO)
3121 /* next word is not "do". It must be "in" then ("FOR v in ...") */
3122 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
3123 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
3125 syntax("malformed for");
3126 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
3132 /* Past this point, all code paths should jump to ret: label
3133 * in order to return, no direct "return" statements please.
3134 * This helps to ensure that no memory is leaked. */
3136 ////TODO: ctrl-Z handling needs re-thinking and re-testing
3139 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
3140 * We are saving state before entering outermost list ("while...done")
3141 * so that ctrl-Z will correctly background _entire_ outermost list,
3142 * not just a part of it (like "sleep 1 | exit 2") */
3143 if (++G.run_list_level == 1 && G_interactive_fd) {
3144 if (sigsetjmp(G.toplevel_jb, 1)) {
3145 /* ctrl-Z forked and we are parent; or ctrl-C.
3146 * Sighandler has longjmped us here */
3147 signal(SIGINT, SIG_IGN);
3148 signal(SIGTSTP, SIG_IGN);
3149 /* Restore level (we can be coming from deep inside
3151 G.run_list_level = 1;
3152 #if ENABLE_FEATURE_SH_STANDALONE
3153 if (G.nofork_save.saved) { /* if save area is valid */
3154 debug_printf_jobs("exiting nofork early\n");
3155 restore_nofork_data(&G.nofork_save);
3158 //// if (G.ctrl_z_flag) {
3159 //// /* ctrl-Z has forked and stored pid of the child in pi->pid.
3160 //// * Remember this child as background job */
3161 //// insert_bg_job(pi);
3163 /* ctrl-C. We just stop doing whatever we were doing */
3166 USE_HUSH_LOOPS(loop_top = NULL;)
3167 USE_HUSH_LOOPS(G.depth_of_loop = 0;)
3171 //// /* ctrl-Z handler will store pid etc in pi */
3172 //// G.toplevel_list = pi;
3173 //// G.ctrl_z_flag = 0;
3174 ////#if ENABLE_FEATURE_SH_STANDALONE
3175 //// G.nofork_save.saved = 0; /* in case we will run a nofork later */
3177 //// signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
3178 //// signal(SIGINT, handler_ctrl_c);
3184 last_rword = RES_XXXX;
3186 last_followup = PIPE_SEQ;
3187 rcode = G.last_exitcode;
3189 /* Go through list of pipes, (maybe) executing them. */
3190 for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
3194 IF_HAS_KEYWORDS(rword = pi->res_word;)
3195 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
3196 rword, cond_code, last_rword);
3197 #if ENABLE_HUSH_LOOPS
3198 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
3199 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
3201 /* start of a loop: remember where loop starts */
3206 /* Still in the same "if...", "then..." or "do..." branch? */
3207 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
3208 if ((rcode == 0 && last_followup == PIPE_OR)
3209 || (rcode != 0 && last_followup == PIPE_AND)
3211 /* It is "<true> || CMD" or "<false> && CMD"
3212 * and we should not execute CMD */
3213 debug_printf_exec("skipped cmd because of || or &&\n");
3214 last_followup = pi->followup;
3218 last_followup = pi->followup;
3219 IF_HAS_KEYWORDS(last_rword = rword;)
3222 if (rword == RES_THEN) {
3223 /* if false; then ... fi has exitcode 0! */
3224 G.last_exitcode = rcode = EXIT_SUCCESS;
3225 /* "if <false> THEN cmd": skip cmd */
3229 if (rword == RES_ELSE || rword == RES_ELIF) {
3230 /* "if <true> then ... ELSE/ELIF cmd":
3231 * skip cmd and all following ones */
3236 #if ENABLE_HUSH_LOOPS
3237 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
3239 /* first loop through for */
3241 static const char encoded_dollar_at[] ALIGN1 = {
3242 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
3243 }; /* encoded representation of "$@" */
3244 static const char *const encoded_dollar_at_argv[] = {
3245 encoded_dollar_at, NULL
3246 }; /* argv list with one element: "$@" */
3249 vals = (char**)encoded_dollar_at_argv;
3250 if (pi->next->res_word == RES_IN) {
3251 /* if no variable values after "in" we skip "for" */
3252 if (!pi->next->cmds[0].argv) {
3253 G.last_exitcode = rcode = EXIT_SUCCESS;
3254 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
3257 vals = pi->next->cmds[0].argv;
3258 } /* else: "for var; do..." -> assume "$@" list */
3259 /* create list of variable values */
3260 debug_print_strings("for_list made from", vals);
3261 for_list = expand_strvec_to_strvec(vals);
3262 for_lcur = for_list;
3263 debug_print_strings("for_list", for_list);
3264 for_varname = pi->cmds[0].argv[0];
3265 pi->cmds[0].argv[0] = NULL;
3267 free(pi->cmds[0].argv[0]);
3269 /* "for" loop is over, clean up */
3273 pi->cmds[0].argv[0] = for_varname;
3276 /* Insert next value from for_lcur */
3277 //TODO: does it need escaping?
3278 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
3279 pi->cmds[0].assignment_cnt = 1;
3281 if (rword == RES_IN) {
3282 continue; /* "for v IN list;..." - "in" has no cmds anyway */
3284 if (rword == RES_DONE) {
3285 continue; /* "done" has no cmds too */
3288 #if ENABLE_HUSH_CASE
3289 if (rword == RES_CASE) {
3290 case_word = expand_strvec_to_string(pi->cmds->argv);
3293 if (rword == RES_MATCH) {
3296 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
3298 /* all prev words didn't match, does this one match? */
3299 argv = pi->cmds->argv;
3301 char *pattern = expand_string_to_string(*argv);
3302 /* TODO: which FNM_xxx flags to use? */
3303 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
3305 if (cond_code == 0) { /* match! we will execute this branch */
3306 free(case_word); /* make future "word)" stop */
3314 if (rword == RES_CASEI) { /* inside of a case branch */
3316 continue; /* not matched yet, skip this pipe */
3319 /* Just pressing <enter> in shell should check for jobs.
3320 * OTOH, in non-interactive shell this is useless
3321 * and only leads to extra job checks */
3322 if (pi->num_cmds == 0) {
3323 if (G_interactive_fd)
3324 goto check_jobs_and_continue;
3328 /* After analyzing all keywords and conditions, we decided
3329 * to execute this pipe. NB: have to do checkjobs(NULL)
3330 * after run_pipe to collect any background children,
3331 * even if list execution is to be stopped. */
3332 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
3335 #if ENABLE_HUSH_LOOPS
3336 G.flag_break_continue = 0;
3338 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
3340 /* We only ran a builtin: rcode is already known
3341 * and we don't need to wait for anything. */
3342 G.last_exitcode = rcode;
3343 debug_printf_exec(": builtin exitcode %d\n", rcode);
3344 check_and_run_traps(0);
3345 #if ENABLE_HUSH_LOOPS
3346 /* Was it "break" or "continue"? */
3347 if (G.flag_break_continue) {
3348 smallint fbc = G.flag_break_continue;
3349 /* We might fall into outer *loop*,
3350 * don't want to break it too */
3352 G.depth_break_continue--;
3353 if (G.depth_break_continue == 0)
3354 G.flag_break_continue = 0;
3355 /* else: e.g. "continue 2" should *break* once, *then* continue */
3356 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
3357 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
3358 goto check_jobs_and_break;
3359 /* "continue": simulate end of loop */
3364 } else if (pi->followup == PIPE_BG) {
3365 /* What does bash do with attempts to background builtins? */
3366 /* even bash 3.2 doesn't do that well with nested bg:
3367 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
3368 * I'm NOT treating inner &'s as jobs */
3369 check_and_run_traps(0);
3371 if (G.run_list_level == 1)
3374 G.last_exitcode = rcode = EXIT_SUCCESS;
3375 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
3378 if (G.run_list_level == 1 && G_interactive_fd) {
3379 /* Waits for completion, then fg's main shell */
3380 rcode = checkjobs_and_fg_shell(pi);
3381 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
3382 check_and_run_traps(0);
3385 { /* This one just waits for completion */
3386 rcode = checkjobs(pi);
3387 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
3388 check_and_run_traps(0);
3390 G.last_exitcode = rcode;
3394 /* Analyze how result affects subsequent commands */
3396 if (rword == RES_IF || rword == RES_ELIF)
3399 #if ENABLE_HUSH_LOOPS
3400 /* Beware of "while false; true; do ..."! */
3401 if (pi->next && pi->next->res_word == RES_DO) {
3402 if (rword == RES_WHILE) {
3404 /* "while false; do...done" - exitcode 0 */
3405 G.last_exitcode = rcode = EXIT_SUCCESS;
3406 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
3407 goto check_jobs_and_break;
3410 if (rword == RES_UNTIL) {
3412 debug_printf_exec(": until expr is true: breaking\n");
3413 check_jobs_and_break:
3421 check_jobs_and_continue:
3426 //// if (G.ctrl_z_flag) {
3427 //// /* ctrl-Z forked somewhere in the past, we are the child,
3428 //// * and now we completed running the list. Exit. */
3434 //// if (!G.run_list_level && G_interactive_fd) {
3435 //// signal(SIGTSTP, SIG_IGN);
3436 //// signal(SIGINT, SIG_IGN);
3439 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
3440 #if ENABLE_HUSH_LOOPS
3445 #if ENABLE_HUSH_CASE
3451 /* Select which version we will use */
3452 static int run_and_free_list(struct pipe *pi)
3455 debug_printf_exec("run_and_free_list entered\n");
3457 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
3458 rcode = run_list(pi);
3460 /* free_pipe_list has the side effect of clearing memory.
3461 * In the long run that function can be merged with run_list,
3462 * but doing that now would hobble the debugging effort. */
3463 free_pipe_list(pi, /* indent: */ 0);
3464 debug_printf_exec("run_and_free_list return %d\n", rcode);
3469 static struct pipe *new_pipe(void)
3472 pi = xzalloc(sizeof(struct pipe));
3473 /*pi->followup = 0; - deliberately invalid value */
3474 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3478 /* Command (member of a pipe) is complete. The only possible error here
3479 * is out of memory, in which case xmalloc exits. */
3480 static int done_command(struct parse_context *ctx)
3482 /* The command is really already in the pipe structure, so
3483 * advance the pipe counter and make a new, null command. */
3484 struct pipe *pi = ctx->pipe;
3485 struct command *command = ctx->command;
3488 if (command->group == NULL
3489 && command->argv == NULL
3490 && command->redirects == NULL
3492 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3493 memset(command, 0, sizeof(*command)); /* paranoia */
3494 return pi->num_cmds;
3497 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3498 //debug_print_tree(ctx->list_head, 20);
3500 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3503 /* Only real trickiness here is that the uncommitted
3504 * command structure is not counted in pi->num_cmds. */
3505 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3506 command = &pi->cmds[pi->num_cmds];
3507 memset(command, 0, sizeof(*command));
3509 ctx->command = command;
3510 /* but ctx->pipe and ctx->list_head remain unchanged */
3512 return pi->num_cmds; /* used only for 0/nonzero check */
3515 static void done_pipe(struct parse_context *ctx, pipe_style type)
3519 debug_printf_parse("done_pipe entered, followup %d\n", type);
3520 /* Close previous command */
3521 not_null = done_command(ctx);
3522 ctx->pipe->followup = type;
3524 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3525 ctx->ctx_inverted = 0;
3526 ctx->pipe->res_word = ctx->ctx_res_w;
3529 /* Without this check, even just <enter> on command line generates
3530 * tree of three NOPs (!). Which is harmless but annoying.
3531 * IOW: it is safe to do it unconditionally.
3532 * RES_NONE case is for "for a in; do ..." (empty IN set)
3533 * and other cases to work. */
3536 || ctx->ctx_res_w == RES_FI
3537 || ctx->ctx_res_w == RES_DONE
3538 || ctx->ctx_res_w == RES_FOR
3539 || ctx->ctx_res_w == RES_IN
3540 || ctx->ctx_res_w == RES_ESAC
3544 debug_printf_parse("done_pipe: adding new pipe: "
3545 "not_null:%d ctx->ctx_res_w:%d\n",
3546 not_null, ctx->ctx_res_w);
3548 ctx->pipe->next = new_p;
3550 /* RES_THEN, RES_DO etc are "sticky" -
3551 * they remain set for commands inside if/while.
3552 * This is used to control execution.
3553 * RES_FOR and RES_IN are NOT sticky (needed to support
3554 * cases where variable or value happens to match a keyword):
3556 #if ENABLE_HUSH_LOOPS
3557 if (ctx->ctx_res_w == RES_FOR
3558 || ctx->ctx_res_w == RES_IN)
3559 ctx->ctx_res_w = RES_NONE;
3561 #if ENABLE_HUSH_CASE
3562 if (ctx->ctx_res_w == RES_MATCH)
3563 ctx->ctx_res_w = RES_CASEI;
3565 ctx->command = NULL; /* trick done_command below */
3566 /* Create the memory for command, roughly:
3567 * ctx->pipe->cmds = new struct command;
3568 * ctx->command = &ctx->pipe->cmds[0];
3571 //debug_print_tree(ctx->list_head, 10);
3573 debug_printf_parse("done_pipe return\n");
3576 static void initialize_context(struct parse_context *ctx)
3578 memset(ctx, 0, sizeof(*ctx));
3579 ctx->pipe = ctx->list_head = new_pipe();
3580 /* Create the memory for command, roughly:
3581 * ctx->pipe->cmds = new struct command;
3582 * ctx->command = &ctx->pipe->cmds[0];
3587 /* If a reserved word is found and processed, parse context is modified
3588 * and 1 is returned.
3591 struct reserved_combo {
3594 unsigned char assignment_flag;
3598 FLAG_END = (1 << RES_NONE ),
3600 FLAG_IF = (1 << RES_IF ),
3601 FLAG_THEN = (1 << RES_THEN ),
3602 FLAG_ELIF = (1 << RES_ELIF ),
3603 FLAG_ELSE = (1 << RES_ELSE ),
3604 FLAG_FI = (1 << RES_FI ),
3606 #if ENABLE_HUSH_LOOPS
3607 FLAG_FOR = (1 << RES_FOR ),
3608 FLAG_WHILE = (1 << RES_WHILE),
3609 FLAG_UNTIL = (1 << RES_UNTIL),
3610 FLAG_DO = (1 << RES_DO ),
3611 FLAG_DONE = (1 << RES_DONE ),
3612 FLAG_IN = (1 << RES_IN ),
3614 #if ENABLE_HUSH_CASE
3615 FLAG_MATCH = (1 << RES_MATCH),
3616 FLAG_ESAC = (1 << RES_ESAC ),
3618 FLAG_START = (1 << RES_XXXX ),
3621 static const struct reserved_combo* match_reserved_word(o_string *word)
3623 /* Mostly a list of accepted follow-up reserved words.
3624 * FLAG_END means we are done with the sequence, and are ready
3625 * to turn the compound list into a command.
3626 * FLAG_START means the word must start a new compound list.
3628 static const struct reserved_combo reserved_list[] = {
3630 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3631 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
3632 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3633 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
3634 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
3635 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3637 #if ENABLE_HUSH_LOOPS
3638 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3639 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3640 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3641 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3642 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
3643 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3645 #if ENABLE_HUSH_CASE
3646 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3647 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3650 const struct reserved_combo *r;
3652 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3653 if (strcmp(word->data, r->literal) == 0)
3658 static int reserved_word(o_string *word, struct parse_context *ctx)
3660 #if ENABLE_HUSH_CASE
3661 static const struct reserved_combo reserved_match = {
3662 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3665 const struct reserved_combo *r;
3667 r = match_reserved_word(word);
3671 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3672 #if ENABLE_HUSH_CASE
3673 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
3674 /* "case word IN ..." - IN part starts first match part */
3675 r = &reserved_match;
3678 if (r->flag == 0) { /* '!' */
3679 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3680 syntax("! ! command");
3681 IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
3683 ctx->ctx_inverted = 1;
3686 if (r->flag & FLAG_START) {
3687 struct parse_context *old;
3688 old = xmalloc(sizeof(*old));
3689 debug_printf_parse("push stack %p\n", old);
3690 *old = *ctx; /* physical copy */
3691 initialize_context(ctx);
3693 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3695 ctx->ctx_res_w = RES_SNTX;
3698 ctx->ctx_res_w = r->res;
3699 ctx->old_flag = r->flag;
3700 if (ctx->old_flag & FLAG_END) {
3701 struct parse_context *old;
3702 done_pipe(ctx, PIPE_SEQ);
3703 debug_printf_parse("pop stack %p\n", ctx->stack);
3705 old->command->group = ctx->list_head;
3706 old->command->grp_type = GRP_NORMAL;
3708 o_addstr(&old->as_string, ctx->as_string.data);
3709 o_free_unsafe(&ctx->as_string);
3710 old->command->group_as_string = xstrdup(old->as_string.data);
3711 debug_printf_parse("pop, remembering as:'%s'\n",
3712 old->command->group_as_string);
3714 *ctx = *old; /* physical copy */
3717 word->o_assignment = r->assignment_flag;
3722 /* Word is complete, look at it and update parsing context.
3723 * Normal return is 0. Syntax errors return 1.
3724 * Note: on return, word is reset, but not o_free'd!
3726 static int done_word(o_string *word, struct parse_context *ctx)
3728 struct command *command = ctx->command;
3730 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3731 if (word->length == 0 && word->nonnull == 0) {
3732 debug_printf_parse("done_word return 0: true null, ignored\n");
3735 /* If this word wasn't an assignment, next ones definitely
3736 * can't be assignments. Even if they look like ones. */
3737 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3738 && word->o_assignment != WORD_IS_KEYWORD
3740 word->o_assignment = NOT_ASSIGNMENT;
3742 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3743 command->assignment_cnt++;
3744 word->o_assignment = MAYBE_ASSIGNMENT;
3747 if (ctx->pending_redirect) {
3748 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3749 * only if run as "bash", not "sh" */
3750 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3752 * ...the word that follows the redirection operator
3753 * shall be subjected to tilde expansion, parameter expansion,
3754 * command substitution, arithmetic expansion, and quote
3755 * removal. Pathname expansion shall not be performed
3756 * on the word by a non-interactive shell; an interactive
3757 * shell may perform it, but shall do so only when
3758 * the expansion would result in one word."
3760 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3761 word->o_assignment = NOT_ASSIGNMENT;
3762 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3764 /* "{ echo foo; } echo bar" - bad */
3765 /* NB: bash allows e.g.:
3766 * if true; then { echo foo; } fi
3767 * while if false; then false; fi do break; done
3769 * while if false; then false; fi; do; break; done
3771 if (command->group) {
3773 debug_printf_parse("done_word return 1: syntax error, "
3774 "groups and arglists don't mix\n");
3778 #if ENABLE_HUSH_CASE
3779 if (ctx->ctx_dsemicolon
3780 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3782 /* already done when ctx_dsemicolon was set to 1: */
3783 /* ctx->ctx_res_w = RES_MATCH; */
3784 ctx->ctx_dsemicolon = 0;
3787 if (!command->argv /* if it's the first word... */
3788 #if ENABLE_HUSH_LOOPS
3789 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3790 && ctx->ctx_res_w != RES_IN
3793 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
3794 if (reserved_word(word, ctx)) {
3796 debug_printf_parse("done_word return %d\n",
3797 (ctx->ctx_res_w == RES_SNTX));
3798 return (ctx->ctx_res_w == RES_SNTX);
3802 if (word->nonnull /* word had "xx" or 'xx' at least as part of it. */
3803 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3804 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3805 /* (otherwise it's known to be not empty and is already safe) */
3807 /* exclude "$@" - it can expand to no word despite "" */
3808 char *p = word->data;
3809 while (p[0] == SPECIAL_VAR_SYMBOL
3810 && (p[1] & 0x7f) == '@'
3811 && p[2] == SPECIAL_VAR_SYMBOL
3815 if (p == word->data || p[0] != '\0') {
3816 /* saw no "$@", or not only "$@" but some
3817 * real text is there too */
3818 /* insert "empty variable" reference, this makes
3819 * e.g. "", $empty"" etc to not disappear */
3820 o_addchr(word, SPECIAL_VAR_SYMBOL);
3821 o_addchr(word, SPECIAL_VAR_SYMBOL);
3824 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3825 debug_print_strings("word appended to argv", command->argv);
3829 ctx->pending_redirect = NULL;
3831 #if ENABLE_HUSH_LOOPS
3832 /* Force FOR to have just one word (variable name) */
3833 /* NB: basically, this makes hush see "for v in ..." syntax as if
3834 * as it is "for v; in ...". FOR and IN become two pipe structs
3836 if (ctx->ctx_res_w == RES_FOR) {
3837 //TODO: check that command->argv[0] is a valid variable name!
3838 done_pipe(ctx, PIPE_SEQ);
3841 #if ENABLE_HUSH_CASE
3842 /* Force CASE to have just one word */
3843 if (ctx->ctx_res_w == RES_CASE) {
3844 done_pipe(ctx, PIPE_SEQ);
3847 debug_printf_parse("done_word return 0\n");
3852 /* Peek ahead in the input to find out if we have a "&n" construct,
3853 * as in "2>&1", that represents duplicating a file descriptor.
3854 * Return: -3 if >&- "close fd" construct is seen,
3855 * -2 (syntax error), -1 if no & was seen, or the number found.
3858 #define redirect_dup_num(as_string, input) \
3859 redirect_dup_num(input)
3861 static int redirect_dup_num(o_string *as_string, struct in_str *input)
3869 ch = i_getch(input); /* get the & */
3871 o_addchr(as_string, ch);
3875 ch = i_getch(input);
3877 o_addchr(as_string, ch);
3879 return -3; /* "-" represents "close me" */
3883 while (ch != EOF && isdigit(ch)) {
3884 d = d*10 + (ch-'0');
3886 ch = i_getch(input);
3888 o_addchr(as_string, ch);
3894 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3896 bb_error_msg("ambiguous redirect");
3900 /* Return code is 0 normally, 1 if a syntax error is detected
3902 static int parse_redirect(struct parse_context *ctx,
3905 struct in_str *input)
3907 struct command *command = ctx->command;
3908 struct redir_struct *redir;
3909 struct redir_struct **redirp;
3913 if (style != REDIRECT_HEREDOC) {
3914 /* Check for a '2>&1' type redirect */
3915 dup_num = redirect_dup_num(&ctx->as_string, input);
3917 return 1; /* syntax error */
3919 //TODO: else { check for <<-word }
3921 if (style == REDIRECT_OVERWRITE && dup_num == -1) {
3922 int ch = i_peek(input);
3924 /* >|FILE redirect ("clobbering" >).
3925 * Since we do not support "set -o noclobber" yet,
3926 * >| and > are the same for now. Just eat |.
3928 ch = i_getch(input);
3930 o_addchr(&ctx->as_string, ch);
3935 /* Create a new redir_struct and append it to the linked list */
3936 redirp = &command->redirects;
3937 while ((redir = *redirp) != NULL) {
3938 redirp = &(redir->next);
3940 *redirp = redir = xzalloc(sizeof(*redir));
3941 /* redir->next = NULL; */
3942 /* redir->rd_filename = NULL; */
3943 redir->rd_type = style;
3944 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
3946 debug_printf_parse("redirect type %d %s\n", redir->fd, redir_table[style].descrip);
3948 redir->dup = dup_num;
3949 if (dup_num != -1) {
3950 /* Erik had a check here that the file descriptor in question
3951 * is legit; I postpone that to "run time"
3952 * A "-" representation of "close me" shows up as a -3 here */
3953 debug_printf_parse("duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
3955 /* Set ctx->pending_redirect, so we know what to do at the
3956 * end of the next parsed word. */
3957 ctx->pending_redirect = redir;
3962 /* If a redirect is immediately preceded by a number, that number is
3963 * supposed to tell which file descriptor to redirect. This routine
3964 * looks for such preceding numbers. In an ideal world this routine
3965 * needs to handle all the following classes of redirects...
3966 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3967 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3968 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3969 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3971 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3973 * ... If n is quoted, the number shall not be recognized as part of
3974 * the redirection expression. For example:
3976 * writes the character 2 into file a"
3977 * I am not sure we do it right (and not sure we care)
3979 * A -1 return means no valid number was found,
3980 * the caller should use the appropriate default for this redirection.
3982 static int redirect_opt_num(o_string *o)
3986 if (o->data == NULL)
3988 num = bb_strtou(o->data, NULL, 10);
3989 if (errno || num < 0)
3995 //TODO: add NOMMU as_string fill
3996 static char *fetch_till_str(struct in_str *input, const char *word)
3998 o_string heredoc = NULL_O_STRING;
4003 ch = i_getch(input);
4005 o_free_unsafe(&heredoc);
4009 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4010 heredoc.data[past_EOL] = '\0';
4011 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4012 return heredoc.data;
4014 past_EOL = heredoc.length + 1;
4016 o_addchr(&heredoc, ch);
4020 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4022 struct pipe *pi = ctx->list_head;
4026 struct command *cmd = pi->cmds;
4028 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4030 cmd->argv ? cmd->argv[0] : "NONE");
4031 for (i = 0; i < pi->num_cmds; i++) {
4032 struct redir_struct *redirect = cmd->redirects;
4034 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4035 i, cmd->argv ? cmd->argv[0] : "NONE");
4037 if (redirect->rd_type == REDIRECT_HEREDOC) {
4040 if (heredoc_cnt <= 0)
4041 return 1; /* error */
4042 redirect->rd_type = REDIRECT_HEREDOC2;
4043 p = fetch_till_str(input, redirect->rd_filename);
4045 return 1; /* unexpected EOF */
4046 free(redirect->rd_filename);
4047 redirect->rd_filename = p;
4050 redirect = redirect->next;
4056 /* Should be 0. If it isn't, it's a parse error */
4062 #define parse_stream(pstring, input, end_trigger) \
4063 parse_stream(input, end_trigger)
4065 static struct pipe *parse_stream(char **pstring,
4066 struct in_str *input,
4068 static void parse_and_run_string(const char *s);
4070 #if ENABLE_HUSH_TICK
4071 static FILE *generate_stream_from_string(const char *s)
4074 int pid, channel[2];
4077 pid = BB_MMU ? fork() : vfork();
4079 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
4081 if (pid == 0) { /* child */
4083 die_sleep = 0; /* do not restore tty pgrp on xfunc death */
4085 /* Process substitution is not considered to be usual
4086 * 'command execution'.
4087 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
4094 close(channel[0]); /* NB: close _first_, then move fd! */
4095 xmove_fd(channel[1], 1);
4096 /* Prevent it from trying to handle ctrl-z etc */
4097 USE_HUSH_JOB(G.run_list_level = 1;)
4099 reset_traps_to_defaults();
4100 parse_and_run_string(s);
4101 _exit(G.last_exitcode);
4103 /* We re-execute after vfork on NOMMU. This makes this script safe:
4104 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
4105 * huge=`cat BIG` # was blocking here forever
4108 re_execute_shell(s);
4114 die_sleep = -1; /* restore tty pgrp on xfunc death */
4116 clean_up_after_re_execute();
4118 pf = fdopen(channel[0], "r");
4122 /* Return code is exit status of the process that is run. */
4123 static int process_command_subs(o_string *dest, const char *s)
4126 struct in_str pipe_str;
4129 pf = generate_stream_from_string(s);
4132 close_on_exec_on(fileno(pf));
4134 /* Now send results of command back into original context */
4135 setup_file_in_str(&pipe_str, pf);
4137 while ((ch = i_getch(&pipe_str)) != EOF) {
4143 o_addchr(dest, '\n');
4146 o_addQchr(dest, ch);
4149 debug_printf("done reading from pipe, pclose()ing\n");
4150 /* Note: we got EOF, and we just close the read end of the pipe.
4151 * We do not wait for the `cmd` child to terminate. bash and ash do.
4153 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
4154 * `false`; echo $? - bash outputs "1"
4157 debug_printf("closed FILE from child. return 0\n");
4162 static int parse_group(o_string *dest, struct parse_context *ctx,
4163 struct in_str *input, int ch)
4165 /* dest contains characters seen prior to ( or {.
4166 * Typically it's empty, but for function defs,
4167 * it contains function name (without '()'). */
4168 struct pipe *pipe_list;
4170 struct command *command = ctx->command;
4172 debug_printf_parse("parse_group entered\n");
4173 #if ENABLE_HUSH_FUNCTIONS
4174 if (ch == 'F') { /* function definition? */
4175 bb_error_msg("aha '%s' is a function, parsing it...", dest->data);
4176 //command->fname = dest->data;
4177 command->grp_type = GRP_FUNCTION;
4178 //TODO: review every o_reset() location... do they handle all o_string fields correctly?
4179 memset(dest, 0, sizeof(*dest));
4182 if (command->argv /* word [word](... */
4183 || dest->length /* word(... */
4184 || dest->nonnull /* ""(... */
4187 debug_printf_parse("parse_group return 1: "
4188 "syntax error, groups and arglists don't mix\n");
4194 command->grp_type = GRP_SUBSHELL;
4198 char *as_string = NULL;
4200 pipe_list = parse_stream(&as_string, input, endch);
4203 o_addstr(&ctx->as_string, as_string);
4205 /* empty ()/{} or parse error? */
4206 if (!pipe_list || pipe_list == ERR_PTR) {
4211 debug_printf_parse("parse_group return 1: "
4212 "parse_stream returned %p\n", pipe_list);
4215 command->group = pipe_list;
4217 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4218 command->group_as_string = as_string;
4219 debug_printf_parse("end of group, remembering as:'%s'\n",
4220 command->group_as_string);
4223 debug_printf_parse("parse_group return 0\n");
4225 /* command remains "open", available for possible redirects */
4228 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
4229 /* Subroutines for copying $(...) and `...` things */
4230 static void add_till_backquote(o_string *dest, struct in_str *input);
4232 static void add_till_single_quote(o_string *dest, struct in_str *input)
4235 int ch = i_getch(input);
4243 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
4244 static void add_till_double_quote(o_string *dest, struct in_str *input)
4247 int ch = i_getch(input);
4250 if (ch == '\\') { /* \x. Copy both chars. */
4252 ch = i_getch(input);
4258 add_till_backquote(dest, input);
4262 //if (ch == '$') ...
4265 /* Process `cmd` - copy contents until "`" is seen. Complicated by
4267 * "Within the backquoted style of command substitution, backslash
4268 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4269 * The search for the matching backquote shall be satisfied by the first
4270 * backquote found without a preceding backslash; during this search,
4271 * if a non-escaped backquote is encountered within a shell comment,
4272 * a here-document, an embedded command substitution of the $(command)
4273 * form, or a quoted string, undefined results occur. A single-quoted
4274 * or double-quoted string that begins, but does not end, within the
4275 * "`...`" sequence produces undefined results."
4277 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4279 static void add_till_backquote(o_string *dest, struct in_str *input)
4282 int ch = i_getch(input);
4285 if (ch == '\\') { /* \x. Copy both chars unless it is \` */
4286 int ch2 = i_getch(input);
4287 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
4296 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
4297 * quoting and nested ()s.
4298 * "With the $(command) style of command substitution, all characters
4299 * following the open parenthesis to the matching closing parenthesis
4300 * constitute the command. Any valid shell script can be used for command,
4301 * except a script consisting solely of redirections which produces
4302 * unspecified results."
4304 * echo $(echo '(TEST)' BEST) (TEST) BEST
4305 * echo $(echo 'TEST)' BEST) TEST) BEST
4306 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
4308 static void add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
4312 int ch = i_getch(input);
4321 if (i_peek(input) == ')') {
4329 add_till_single_quote(dest, input);
4334 add_till_double_quote(dest, input);
4338 if (ch == '\\') { /* \x. Copy verbatim. Important for \(, \) */
4339 ch = i_getch(input);
4347 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
4349 /* Return code: 0 for OK, 1 for syntax error */
4351 #define handle_dollar(as_string, dest, input) \
4352 handle_dollar(dest, input)
4354 static int handle_dollar(o_string *as_string,
4356 struct in_str *input)
4359 int ch = i_peek(input); /* first character after the $ */
4360 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
4362 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
4364 ch = i_getch(input);
4366 if (as_string) o_addchr(as_string, ch);
4369 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4371 debug_printf_parse(": '%c'\n", ch);
4372 o_addchr(dest, ch | quote_mask);
4375 if (!isalnum(ch) && ch != '_')
4377 ch = i_getch(input);
4379 if (as_string) o_addchr(as_string, ch);
4382 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4383 } else if (isdigit(ch)) {
4385 ch = i_getch(input);
4387 if (as_string) o_addchr(as_string, ch);
4389 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4390 debug_printf_parse(": '%c'\n", ch);
4391 o_addchr(dest, ch | quote_mask);
4392 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4393 } else switch (ch) {
4395 case '!': /* last bg pid */
4396 case '?': /* last exit code */
4397 case '#': /* number of args */
4398 case '*': /* args */
4399 case '@': /* args */
4400 goto make_one_char_var;
4402 bool first_char, all_digits;
4404 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4405 ch = i_getch(input);
4407 if (as_string) o_addchr(as_string, ch);
4409 /* XXX maybe someone will try to escape the '}' */
4414 ch = i_getch(input);
4416 if (as_string) o_addchr(as_string, ch);
4423 /* ${#var}: length of var contents */
4425 else if (isdigit(ch)) {
4432 && ( (all_digits && !isdigit(ch))
4433 || (!all_digits && !isalnum(ch) && ch != '_')
4436 /* handle parameter expansions
4437 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4442 case ':': /* null modifier */
4443 if (expansion == 0) {
4444 debug_printf_parse(": null modifier\n");
4449 case '#': /* remove prefix */
4450 case '%': /* remove suffix */
4451 if (expansion == 0) {
4452 debug_printf_parse(": remove suffix/prefix\n");
4457 case '-': /* default value */
4458 case '=': /* assign default */
4459 case '+': /* alternative */
4460 case '?': /* error indicate */
4461 debug_printf_parse(": parameter expansion\n");
4466 syntax("unterminated ${name}");
4467 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
4472 debug_printf_parse(": '%c'\n", ch);
4473 o_addchr(dest, ch | quote_mask);
4477 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4480 #if (ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK)
4485 ch = i_getch(input);
4487 if (as_string) o_addchr(as_string, ch);
4489 # if ENABLE_SH_MATH_SUPPORT
4490 if (i_peek(input) == '(') {
4491 ch = i_getch(input);
4493 if (as_string) o_addchr(as_string, ch);
4495 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4496 o_addchr(dest, /*quote_mask |*/ '+');
4500 add_till_closing_paren(dest, input, true);
4503 o_addstr(as_string, dest->data + pos);
4504 o_addchr(as_string, ')');
4505 o_addchr(as_string, ')');
4508 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4512 # if ENABLE_HUSH_TICK
4513 //int pos = dest->length;
4514 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4515 o_addchr(dest, quote_mask | '`');
4519 add_till_closing_paren(dest, input, false);
4522 o_addstr(as_string, dest->data + pos);
4523 o_addchr(as_string, '`');
4526 //debug_printf_subst("SUBST RES2 '%s'\n", dest->data + pos);
4527 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4533 ch = i_getch(input);
4535 if (as_string) o_addchr(as_string, ch);
4538 if (isalnum(ch)) { /* it's $_name or $_123 */
4544 /* $_ Shell or shell script name; or last cmd name */
4545 /* $- Option flags set by set builtin or shell options (-i etc) */
4547 o_addQchr(dest, '$');
4549 debug_printf_parse("handle_dollar return 0\n");
4554 #define parse_stream_dquoted(as_string, dest, input, dquote_end) \
4555 parse_stream_dquoted(dest, input, dquote_end)
4557 static int parse_stream_dquoted(o_string *as_string,
4559 struct in_str *input,
4566 ch = i_getch(input);
4568 if (as_string && ch != EOF) o_addchr(as_string, ch);
4570 if (ch == dquote_end) { /* may be only '"' or EOF */
4572 if (dest->o_assignment == NOT_ASSIGNMENT)
4573 dest->o_escape ^= 1;
4574 debug_printf_parse("parse_stream_dquoted return 0\n");
4578 syntax("unterminated \"");
4579 debug_printf_parse("parse_stream_dquoted return 1: unterminated \"\n");
4584 next = i_peek(input);
4586 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4587 ch, ch, dest->o_escape);
4591 debug_printf_parse("parse_stream_dquoted return 1: \\<eof>\n");
4595 * "The backslash retains its special meaning [in "..."]
4596 * only when followed by one of the following characters:
4597 * $, `, ", \, or <newline>. A double quote may be quoted
4598 * within double quotes by preceding it with a backslash.
4599 * If enabled, history expansion will be performed unless
4600 * an ! appearing in double quotes is escaped using
4601 * a backslash. The backslash preceding the ! is not removed."
4603 if (strchr("$`\"\\", next) != NULL) {
4604 o_addqchr(dest, i_getch(input));
4606 o_addqchr(dest, '\\');
4611 if (handle_dollar(as_string, dest, input) != 0) {
4612 debug_printf_parse("parse_stream_dquoted return 1: "
4613 "handle_dollar returned non-0\n");
4618 #if ENABLE_HUSH_TICK
4620 //int pos = dest->length;
4621 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4622 o_addchr(dest, 0x80 | '`');
4623 add_till_backquote(dest, input);
4624 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4625 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4629 o_addQchr(dest, ch);
4631 && (dest->o_assignment == MAYBE_ASSIGNMENT
4632 || dest->o_assignment == WORD_IS_KEYWORD)
4633 && is_assignment(dest->data)
4635 dest->o_assignment = DEFINITELY_ASSIGNMENT;
4641 * Scan input until EOF or end_trigger char.
4642 * Return a list of pipes to execute, or NULL on EOF
4643 * or if end_trigger character is met.
4644 * On syntax error, exit is shell is not interactive,
4645 * reset parsing machinery and start parsing anew,
4646 * or return ERR_PTR.
4648 static struct pipe *parse_stream(char **pstring,
4649 struct in_str *input,
4652 struct parse_context ctx;
4653 o_string dest = NULL_O_STRING;
4657 /* Double-quote state is handled in the state variable is_in_dquote.
4658 * A single-quote triggers a bypass of the main loop until its mate is
4659 * found. When recursing, quote state is passed in via dest->o_escape.
4661 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4662 end_trigger ? : 'X');
4664 G.ifs = get_local_var_value("IFS");
4669 #if ENABLE_HUSH_INTERACTIVE
4670 input->promptmode = 0; /* PS1 */
4672 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
4673 initialize_context(&ctx);
4678 const char *is_special;
4682 redir_type redir_style;
4685 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
4688 /* We reached closing '"' */
4691 ch = i_getch(input);
4692 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4693 ch, ch, dest.o_escape);
4698 syntax("unterminated here document");
4701 if (done_word(&dest, &ctx)) {
4705 done_pipe(&ctx, PIPE_SEQ);
4707 /* If we got nothing... */
4708 // TODO: test script consisting of just "&"
4709 if (pi->num_cmds == 0
4710 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4712 free_pipe_list(pi, 0);
4715 debug_printf_parse("parse_stream return %p\n", pi);
4717 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4719 *pstring = ctx.as_string.data;
4721 o_free_unsafe(&ctx.as_string);
4726 o_addchr(&ctx.as_string, ch);
4728 is_ifs = strchr(G.ifs, ch);
4729 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
4730 "\\$\"" USE_HUSH_TICK("`") /* always special */
4733 if (!is_special && !is_ifs) { /* ordinary char */
4734 o_addQchr(&dest, ch);
4735 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4736 || dest.o_assignment == WORD_IS_KEYWORD)
4738 && is_assignment(dest.data)
4740 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4746 if (done_word(&dest, &ctx)) {
4750 #if ENABLE_HUSH_CASE
4751 /* "case ... in <newline> word) ..." -
4752 * newlines are ignored (but ';' wouldn't be) */
4753 if (ctx.command->argv == NULL
4754 && ctx.ctx_res_w == RES_MATCH
4759 /* Treat newline as a command separator. */
4760 done_pipe(&ctx, PIPE_SEQ);
4761 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4763 if (fetch_heredocs(heredoc_cnt, &ctx, input))
4767 dest.o_assignment = MAYBE_ASSIGNMENT;
4769 /* note: if (is_ifs) continue;
4770 * will still trigger for us */
4773 if (end_trigger && end_trigger == ch
4774 && (heredoc_cnt == 0 || end_trigger != ';')
4776 //TODO: disallow "{ cmd }" without semicolon
4778 /* This is technically valid:
4779 * { cat <<HERE; }; echo Ok
4784 * but we don't support this.
4785 * We require heredoc to be in enclosing {}/(),
4788 syntax("unterminated here document");
4791 if (done_word(&dest, &ctx)) {
4794 done_pipe(&ctx, PIPE_SEQ);
4795 dest.o_assignment = MAYBE_ASSIGNMENT;
4796 /* Do we sit outside of any if's, loops or case's? */
4798 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4800 debug_printf_parse("parse_stream return %p: "
4801 "end_trigger char found\n",
4805 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4807 *pstring = ctx.as_string.data;
4809 o_free_unsafe(&ctx.as_string);
4811 return ctx.list_head;
4817 if (dest.o_assignment == MAYBE_ASSIGNMENT) {
4818 /* ch is a special char and thus this word
4819 * cannot be an assignment */
4820 dest.o_assignment = NOT_ASSIGNMENT;
4825 next = i_peek(input);
4830 if (dest.length == 0) {
4833 if (ch == EOF || ch == '\n')
4836 /* note: we do not add it to &ctx.as_string */
4839 //TODO: go back one char?
4840 o_addchr(&ctx.as_string, '\n');
4843 o_addQchr(&dest, ch);
4851 o_addchr(&dest, '\\');
4852 ch = i_getch(input);
4853 o_addchr(&dest, ch);
4855 o_addchr(&ctx.as_string, ch);
4859 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
4860 debug_printf_parse("parse_stream parse error: "
4861 "handle_dollar returned non-0\n");
4868 ch = i_getch(input);
4870 syntax("unterminated '");
4874 o_addchr(&ctx.as_string, ch);
4878 if (dest.o_assignment == NOT_ASSIGNMENT)
4879 o_addqchr(&dest, ch);
4881 o_addchr(&dest, ch);
4886 is_in_dquote ^= 1; /* invert */
4887 if (dest.o_assignment == NOT_ASSIGNMENT)
4890 #if ENABLE_HUSH_TICK
4892 //int pos = dest.length;
4893 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4894 o_addchr(&dest, '`');
4895 add_till_backquote(&dest, input);
4896 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4897 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4902 redir_fd = redirect_opt_num(&dest);
4903 if (done_word(&dest, &ctx)) {
4906 redir_style = REDIRECT_OVERWRITE;
4908 redir_style = REDIRECT_APPEND;
4909 ch = i_getch(input);
4911 o_addchr(&ctx.as_string, ch);
4915 else if (next == '(') {
4916 syntax(">(process) not supported");
4920 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4924 redir_fd = redirect_opt_num(&dest);
4925 if (done_word(&dest, &ctx)) {
4928 redir_style = REDIRECT_INPUT;
4930 redir_style = REDIRECT_HEREDOC;
4932 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4933 ch = i_getch(input);
4935 o_addchr(&ctx.as_string, ch);
4937 } else if (next == '>') {
4938 redir_style = REDIRECT_IO;
4939 ch = i_getch(input);
4941 o_addchr(&ctx.as_string, ch);
4945 else if (next == '(') {
4946 syntax("<(process) not supported");
4950 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4954 #if ENABLE_HUSH_CASE
4957 if (done_word(&dest, &ctx)) {
4960 done_pipe(&ctx, PIPE_SEQ);
4961 #if ENABLE_HUSH_CASE
4962 /* Eat multiple semicolons, detect
4963 * whether it means something special */
4968 ch = i_getch(input);
4970 o_addchr(&ctx.as_string, ch);
4972 if (ctx.ctx_res_w == RES_CASEI) {
4973 ctx.ctx_dsemicolon = 1;
4974 ctx.ctx_res_w = RES_MATCH;
4980 /* We just finished a cmd. New one may start
4981 * with an assignment */
4982 dest.o_assignment = MAYBE_ASSIGNMENT;
4985 if (done_word(&dest, &ctx)) {
4989 ch = i_getch(input);
4991 o_addchr(&ctx.as_string, ch);
4993 done_pipe(&ctx, PIPE_AND);
4995 done_pipe(&ctx, PIPE_BG);
4999 if (done_word(&dest, &ctx)) {
5002 #if ENABLE_HUSH_CASE
5003 if (ctx.ctx_res_w == RES_MATCH)
5004 break; /* we are in case's "word | word)" */
5006 if (next == '|') { /* || */
5007 ch = i_getch(input);
5009 o_addchr(&ctx.as_string, ch);
5011 done_pipe(&ctx, PIPE_OR);
5013 /* we could pick up a file descriptor choice here
5014 * with redirect_opt_num(), but bash doesn't do it.
5015 * "echo foo 2| cat" yields "foo 2". */
5020 #if ENABLE_HUSH_CASE
5021 /* "case... in [(]word)..." - skip '(' */
5022 if (ctx.ctx_res_w == RES_MATCH
5023 && ctx.command->argv == NULL /* not (word|(... */
5024 && dest.length == 0 /* not word(... */
5025 && dest.nonnull == 0 /* not ""(... */
5030 #if ENABLE_HUSH_FUNCTIONS
5031 if (dest.length != 0 /* not just () but word() */
5032 && dest.nonnull == 0 /* not a"b"c() */
5033 && ctx.command->argv == NULL /* it's the first word */
5034 //TODO: "func ( ) {...}" - note spaces - is valid format too in bash
5035 && i_peek(input) == ')'
5036 && !match_reserved_word(&dest)
5038 bb_error_msg("seems like a function definition");
5040 //if !BB_MMU o_addchr(&ctx.as_string...
5042 //TODO: do it properly.
5043 ch = i_getch(input);
5044 } while (ch == ' ' || ch == '\n');
5046 syntax("was expecting {");
5049 ch = 'F'; /* magic value */
5053 if (parse_group(&dest, &ctx, input, ch) != 0) {
5058 #if ENABLE_HUSH_CASE
5059 if (ctx.ctx_res_w == RES_MATCH)
5063 /* proper use of this character is caught by end_trigger:
5064 * if we see {, we call parse_group(..., end_trigger='}')
5065 * and it will match } earlier (not here). */
5066 syntax("unexpected } or )");
5070 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
5076 struct parse_context *pctx;
5077 IF_HAS_KEYWORDS(struct parse_context *p2;)
5079 /* Clean up allocated tree.
5080 * Samples for finding leaks on syntax error recovery path.
5081 * Run them from interactive shell, watch pmap `pidof hush`.
5082 * while if false; then false; fi do break; done
5084 * while if false; then false; fi; do break; fi
5085 * Samples to catch leaks at execution:
5086 * while if (true | {true;}); then echo ok; fi; do break; done
5087 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
5091 /* Update pipe/command counts,
5092 * otherwise freeing may miss some */
5093 done_pipe(pctx, PIPE_SEQ);
5094 debug_printf_clean("freeing list %p from ctx %p\n",
5095 pctx->list_head, pctx);
5096 debug_print_tree(pctx->list_head, 0);
5097 free_pipe_list(pctx->list_head, 0);
5098 debug_printf_clean("freed list %p\n", pctx->list_head);
5100 o_free_unsafe(&pctx->as_string);
5102 IF_HAS_KEYWORDS(p2 = pctx->stack;)
5106 IF_HAS_KEYWORDS(pctx = p2;)
5107 } while (HAS_KEYWORDS && pctx);
5108 /* Free text, clear all dest fields */
5110 /* If we are not in top-level parse, we return,
5111 * our caller will propagate error.
5113 if (end_trigger != ';') {
5120 /* Discard cached input, force prompt */
5122 USE_HUSH_INTERACTIVE(input->promptme = 1;)
5127 /* Executing from string: eval, sh -c '...'
5128 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5129 * end_trigger controls how often we stop parsing
5130 * NUL: parse all, execute, return
5131 * ';': parse till ';' or newline, execute, repeat till EOF
5133 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5136 struct pipe *pipe_list;
5138 pipe_list = parse_stream(NULL, inp, end_trigger);
5139 if (!pipe_list) /* EOF */
5141 debug_print_tree(pipe_list, 0);
5142 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5143 run_and_free_list(pipe_list);
5147 static void parse_and_run_string(const char *s)
5149 struct in_str input;
5150 setup_string_in_str(&input, s);
5151 parse_and_run_stream(&input, '\0');
5154 static void parse_and_run_file(FILE *f)
5156 struct in_str input;
5157 setup_file_in_str(&input, f);
5158 parse_and_run_stream(&input, ';');
5161 /* Called a few times only (or even once if "sh -c") */
5162 static void block_signals(int second_time)
5167 mask = (1 << SIGQUIT);
5168 if (G_interactive_fd) {
5172 //TODO | (1 << SIGHUP)
5174 | (1 << SIGTTIN) | (1 << SIGTTOU) | (1 << SIGTSTP)
5179 G.non_DFL_mask = mask;
5182 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
5186 sigaddset(&G.blocked_set, sig);
5190 sigdelset(&G.blocked_set, SIGCHLD);
5192 sigprocmask(SIG_SETMASK, &G.blocked_set,
5193 second_time ? NULL : &G.inherited_set);
5194 /* POSIX allows shell to re-enable SIGCHLD
5195 * even if it was SIG_IGN on entry */
5196 // G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
5198 signal(SIGCHLD, SIG_DFL); // SIGCHLD_handler);
5203 static void maybe_set_to_sigexit(int sig)
5205 void (*handler)(int);
5206 /* non_DFL_mask'ed signals are, well, masked,
5207 * no need to set handler for them.
5209 if (!((G.non_DFL_mask >> sig) & 1)) {
5210 handler = signal(sig, sigexit);
5211 if (handler == SIG_IGN) /* oops... restore back to IGN! */
5212 signal(sig, handler);
5215 /* Set handlers to restore tty pgrp and exit */
5216 static void set_fatal_handlers(void)
5218 /* We _must_ restore tty pgrp on fatal signals */
5220 maybe_set_to_sigexit(SIGILL );
5221 maybe_set_to_sigexit(SIGFPE );
5222 maybe_set_to_sigexit(SIGBUS );
5223 maybe_set_to_sigexit(SIGSEGV);
5224 maybe_set_to_sigexit(SIGTRAP);
5225 } /* else: hush is perfect. what SEGV? */
5226 maybe_set_to_sigexit(SIGABRT);
5227 /* bash 3.2 seems to handle these just like 'fatal' ones */
5228 maybe_set_to_sigexit(SIGPIPE);
5229 maybe_set_to_sigexit(SIGALRM);
5230 //TODO: disable and move down when proper SIGHUP handling is added
5231 maybe_set_to_sigexit(SIGHUP );
5232 /* if we are interactive, [SIGHUP,] SIGTERM and SIGINT are masked.
5233 * if we aren't interactive... but in this case
5234 * we never want to restore pgrp on exit, and this fn is not called */
5235 /*maybe_set_to_sigexit(SIGTERM);*/
5236 /*maybe_set_to_sigexit(SIGINT );*/
5240 static int set_mode(const char cstate, const char mode)
5242 int state = (cstate == '-' ? 1 : 0);
5244 case 'n': G.fake_mode = state; break;
5245 case 'x': /*G.debug_mode = state;*/ break;
5246 default: return EXIT_FAILURE;
5248 return EXIT_SUCCESS;
5251 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
5252 int hush_main(int argc, char **argv)
5254 static const struct variable const_shell_ver = {
5256 .varstr = (char*)hush_version_str,
5257 .max_len = 1, /* 0 can provoke free(name) */
5261 int signal_mask_is_inited = 0;
5264 struct variable *cur_var;
5267 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
5268 G.last_exitcode = EXIT_SUCCESS;
5270 G.argv0_for_re_execing = argv[0];
5272 /* Deal with HUSH_VERSION */
5273 G.shell_ver = const_shell_ver; /* copying struct here */
5274 G.top_var = &G.shell_ver;
5275 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
5276 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
5277 /* Initialize our shell local variables with the values
5278 * currently living in the environment */
5279 cur_var = G.top_var;
5282 char *value = strchr(*e, '=');
5283 if (value) { /* paranoia */
5284 cur_var->next = xzalloc(sizeof(*cur_var));
5285 cur_var = cur_var->next;
5286 cur_var->varstr = *e;
5287 cur_var->max_len = strlen(*e);
5288 cur_var->flg_export = 1;
5292 debug_printf_env("putenv '%s'\n", hush_version_str);
5293 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
5294 #if ENABLE_FEATURE_EDITING
5295 G.line_input_state = new_line_input_t(FOR_SHELL);
5297 G.global_argc = argc;
5298 G.global_argv = argv;
5299 /* Initialize some more globals to non-zero values */
5301 #if ENABLE_HUSH_INTERACTIVE
5302 if (ENABLE_FEATURE_EDITING)
5303 cmdedit_set_initial_prompt();
5307 /* Shell is non-interactive at first. We need to call
5308 * block_signals(0) if we are going to execute "sh <script>",
5309 * "sh -c <cmds>" or login shell's /etc/profile and friends.
5310 * If we later decide that we are interactive, we run block_signals(0)
5311 * (or re-run block_signals(1) if we ran block_signals(0) before)
5312 * in order to intercept (more) signals.
5316 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
5318 opt = getopt(argc, argv, "c:xins"
5328 G.root_pid = getpid();
5329 G.global_argv = argv + optind;
5330 if (!argv[optind]) {
5331 /* -c 'script' (no params): prevent empty $0 */
5332 *--G.global_argv = argv[0];
5334 } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
5335 G.global_argc = argc - optind;
5336 block_signals(0); /* 0: called 1st time */
5337 parse_and_run_string(optarg);
5340 /* Well, we cannot just declare interactiveness,
5341 * we have to have some stuff (ctty, etc) */
5342 /* G_interactive_fd++; */
5345 /* "-s" means "read from stdin", but this is how we always
5346 * operate, so simply do nothing here. */
5350 G.root_pid = bb_strtou(optarg, &optarg, 16);
5352 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
5354 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
5355 # if ENABLE_HUSH_LOOPS
5357 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
5362 set_local_var(xstrdup(optarg), 0, opt == 'R');
5367 if (!set_mode('-', opt))
5371 fprintf(stderr, "Usage: sh [FILE]...\n"
5372 " or: sh -c command [args]...\n\n");
5378 } /* option parsing loop */
5381 G.root_pid = getpid();
5383 /* If we are login shell... */
5384 if (argv[0] && argv[0][0] == '-') {
5386 /* XXX what should argv be while sourcing /etc/profile? */
5387 debug_printf("sourcing /etc/profile\n");
5388 input = fopen_for_read("/etc/profile");
5389 if (input != NULL) {
5390 close_on_exec_on(fileno(input));
5391 block_signals(0); /* 0: called 1st time */
5392 signal_mask_is_inited = 1;
5393 parse_and_run_file(input);
5396 /* bash: after sourcing /etc/profile,
5397 * tries to source (in the given order):
5398 * ~/.bash_profile, ~/.bash_login, ~/.profile,
5399 * stopping of first found. --noprofile turns this off.
5400 * bash also sources ~/.bash_logout on exit.
5401 * If called as sh, skips .bash_XXX files.
5408 * "bash <script>" (which is never interactive (unless -i?))
5409 * sources $BASH_ENV here (without scanning $PATH).
5410 * If called as sh, does the same but with $ENV.
5412 debug_printf("running script '%s'\n", argv[optind]);
5413 G.global_argv = argv + optind;
5414 G.global_argc = argc - optind;
5415 input = xfopen_for_read(argv[optind]);
5416 close_on_exec_on(fileno(input));
5417 if (!signal_mask_is_inited)
5418 block_signals(0); /* 0: called 1st time */
5419 parse_and_run_file(input);
5420 #if ENABLE_FEATURE_CLEAN_UP
5426 /* Up to here, shell was non-interactive. Now it may become one.
5427 * NB: don't forget to (re)run block_signals(0/1) as needed.
5430 /* A shell is interactive if the '-i' flag was given, or if all of
5431 * the following conditions are met:
5433 * no arguments remaining or the -s flag given
5434 * standard input is a terminal
5435 * standard output is a terminal
5436 * Refer to Posix.2, the description of the 'sh' utility.
5439 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
5440 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
5441 debug_printf("saved_tty_pgrp:%d\n", G.saved_tty_pgrp);
5442 //TODO: "interactive" and "have job control" are two different things.
5443 //If tcgetpgrp fails here, "have job control" is false, but "interactive"
5444 //should stay on! Currently, we mix these into one.
5445 if (G.saved_tty_pgrp >= 0) {
5446 /* try to dup stdin to high fd#, >= 255 */
5447 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
5448 if (G_interactive_fd < 0) {
5449 /* try to dup to any fd */
5450 G_interactive_fd = dup(STDIN_FILENO);
5451 if (G_interactive_fd < 0)
5453 G_interactive_fd = 0;
5455 // TODO: track & disallow any attempts of user
5456 // to (inadvertently) close/redirect it
5459 debug_printf("interactive_fd:%d\n", G_interactive_fd);
5460 if (G_interactive_fd) {
5463 /* We are indeed interactive shell, and we will perform
5464 * job control. Setting up for that. */
5466 close_on_exec_on(G_interactive_fd);
5467 /* If we were run as 'hush &', sleep until we are
5468 * in the foreground (tty pgrp == our pgrp).
5469 * If we get started under a job aware app (like bash),
5470 * make sure we are now in charge so we don't fight over
5471 * who gets the foreground */
5473 shell_pgrp = getpgrp();
5474 G.saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
5475 if (G.saved_tty_pgrp == shell_pgrp)
5477 /* send TTIN to ourself (should stop us) */
5478 kill(- shell_pgrp, SIGTTIN);
5480 /* Block some signals */
5481 block_signals(signal_mask_is_inited);
5482 /* Set other signals to restore saved_tty_pgrp */
5483 set_fatal_handlers();
5484 /* Put ourselves in our own process group */
5485 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
5486 /* Grab control of the terminal */
5487 tcsetpgrp(G_interactive_fd, getpid());
5488 /* -1 is special - makes xfuncs longjmp, not exit
5489 * (we reset die_sleep = 0 whereever we [v]fork) */
5491 if (setjmp(die_jmp)) {
5492 /* xfunc has failed! die die die */
5493 hush_exit(xfunc_error_retval);
5495 } else if (!signal_mask_is_inited) {
5496 block_signals(0); /* 0: called 1st time */
5497 } /* else: block_signals(0) was done before */
5498 #elif ENABLE_HUSH_INTERACTIVE
5499 /* No job control compiled in, only prompt/line editing */
5500 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
5501 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
5502 if (G_interactive_fd < 0) {
5503 /* try to dup to any fd */
5504 G_interactive_fd = dup(STDIN_FILENO);
5505 if (G_interactive_fd < 0)
5507 G_interactive_fd = 0;
5510 if (G_interactive_fd) {
5511 close_on_exec_on(G_interactive_fd);
5512 block_signals(signal_mask_is_inited);
5513 } else if (!signal_mask_is_inited) {
5517 /* We have interactiveness code disabled */
5518 if (!signal_mask_is_inited) {
5523 * if interactive but not a login shell, sources ~/.bashrc
5524 * (--norc turns this off, --rcfile <file> overrides)
5527 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
5528 printf("\n\n%s hush - the humble shell\n", bb_banner);
5529 printf("Enter 'help' for a list of built-in commands.\n\n");
5532 parse_and_run_file(stdin);
5535 #if ENABLE_FEATURE_CLEAN_UP
5536 if (G.cwd != bb_msg_unknown)
5538 cur_var = G.top_var->next;
5540 struct variable *tmp = cur_var;
5541 if (!cur_var->max_len)
5542 free(cur_var->varstr);
5543 cur_var = cur_var->next;
5547 hush_exit(G.last_exitcode);
5552 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
5553 int lash_main(int argc, char **argv)
5555 //bb_error_msg("lash is deprecated, please use hush instead");
5556 return hush_main(argc, argv);
5564 static int builtin_trap(char **argv)
5571 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
5575 /* No args: print all trapped. This isn't 100% correct as we
5576 * should be escaping the cmd so that it can be pasted back in
5578 for (i = 0; i < NSIG; ++i)
5580 printf("trap -- '%s' %s\n", G.traps[i], get_signame(i));
5581 return EXIT_SUCCESS;
5586 /* If first arg is decimal: reset all specified signals */
5587 sig = bb_strtou(*argv, NULL, 10);
5593 sig = get_signum(*argv++);
5594 if (sig < 0 || sig >= NSIG) {
5596 /* Mimic bash message exactly */
5597 bb_perror_msg("trap: %s: invalid signal specification", argv[i]);
5602 G.traps[sig] = xstrdup(new_cmd);
5604 debug_printf("trap: setting SIG%s (%i) to '%s'",
5605 get_signame(sig), sig, G.traps[sig]);
5607 /* There is no signal for 0 (EXIT) */
5612 sigaddset(&G.blocked_set, sig);
5614 /* There was a trap handler, we are removing it
5615 * (if sig has non-DFL handling,
5616 * we don't need to do anything) */
5617 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
5619 sigdelset(&G.blocked_set, sig);
5621 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
5626 /* First arg is "-": reset all specified to default */
5627 /* First arg is "": ignore all specified */
5628 /* Everything else: execute first arg upon signal */
5630 bb_error_msg("trap: invalid arguments");
5631 return EXIT_FAILURE;
5633 if (NOT_LONE_DASH(*argv))
5639 static int builtin_true(char **argv UNUSED_PARAM)
5644 static int builtin_test(char **argv)
5651 return test_main(argc, argv - argc);
5654 static int builtin_echo(char **argv)
5661 return echo_main(argc, argv - argc);
5664 static int builtin_eval(char **argv)
5666 int rcode = EXIT_SUCCESS;
5669 char *str = expand_strvec_to_string(argv);
5671 * eval "echo Hi; done" ("done" is syntax error):
5672 * "echo Hi" will not execute too.
5674 parse_and_run_string(str);
5676 rcode = G.last_exitcode;
5681 static int builtin_cd(char **argv)
5683 const char *newdir = argv[1];
5684 if (newdir == NULL) {
5685 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
5686 * bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
5688 newdir = getenv("HOME") ? : "/";
5690 if (chdir(newdir)) {
5691 /* Mimic bash message exactly */
5692 bb_perror_msg("cd: %s", newdir);
5693 return EXIT_FAILURE;
5696 return EXIT_SUCCESS;
5699 static int builtin_exec(char **argv)
5701 if (*++argv == NULL)
5702 return EXIT_SUCCESS; /* bash does this */
5707 // FIXME: if exec fails, bash does NOT exit! We do...
5708 pseudo_exec_argv(&dummy, argv, 0, NULL);
5713 static int builtin_exit(char **argv)
5715 debug_printf_exec("%s()\n", __func__);
5716 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
5717 //puts("exit"); /* bash does it */
5718 // TODO: warn if we have background jobs: "There are stopped jobs"
5719 // On second consecutive 'exit', exit anyway.
5720 if (*++argv == NULL)
5721 hush_exit(G.last_exitcode);
5722 /* mimic bash: exit 123abc == exit 255 + error msg */
5723 xfunc_error_retval = 255;
5724 /* bash: exit -2 == exit 254, no error msg */
5725 hush_exit(xatoi(*argv) & 0xff);
5728 static int builtin_export(char **argv)
5730 if (*++argv == NULL) {
5732 // ash emits: export VAR='VAL'
5733 // bash: declare -x VAR="VAL"
5734 // (both also escape as needed (quotes, $, etc))
5739 return EXIT_SUCCESS;
5746 value = strchr(name, '=');
5748 /* They are exporting something without a =VALUE */
5749 struct variable *var;
5751 var = get_local_var(name);
5753 var->flg_export = 1;
5754 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
5755 putenv(var->varstr);
5757 /* bash does not return an error when trying to export
5758 * an undefined variable. Do likewise. */
5761 set_local_var(xstrdup(name), 1, 0);
5764 return EXIT_SUCCESS;
5768 /* built-in 'fg' and 'bg' handler */
5769 static int builtin_fg_bg(char **argv)
5774 if (!G_interactive_fd)
5775 return EXIT_FAILURE;
5776 /* If they gave us no args, assume they want the last backgrounded task */
5778 for (pi = G.job_list; pi; pi = pi->next) {
5779 if (pi->jobid == G.last_jobid) {
5783 bb_error_msg("%s: no current job", argv[0]);
5784 return EXIT_FAILURE;
5786 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
5787 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
5788 return EXIT_FAILURE;
5790 for (pi = G.job_list; pi; pi = pi->next) {
5791 if (pi->jobid == jobnum) {
5795 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
5796 return EXIT_FAILURE;
5798 // TODO: bash prints a string representation
5799 // of job being foregrounded (like "sleep 1 | cat")
5800 if (argv[0][0] == 'f') {
5801 /* Put the job into the foreground. */
5802 tcsetpgrp(G_interactive_fd, pi->pgrp);
5805 /* Restart the processes in the job */
5806 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
5807 for (i = 0; i < pi->num_cmds; i++) {
5808 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
5809 pi->cmds[i].is_stopped = 0;
5811 pi->stopped_cmds = 0;
5813 i = kill(- pi->pgrp, SIGCONT);
5815 if (errno == ESRCH) {
5816 delete_finished_bg_job(pi);
5817 return EXIT_SUCCESS;
5819 bb_perror_msg("kill (SIGCONT)");
5822 if (argv[0][0] == 'f') {
5824 return checkjobs_and_fg_shell(pi);
5826 return EXIT_SUCCESS;
5830 #if ENABLE_HUSH_HELP
5831 static int builtin_help(char **argv UNUSED_PARAM)
5833 const struct built_in_command *x;
5836 "Built-in commands:\n"
5837 "------------------\n");
5838 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
5839 printf("%s\t%s\n", x->cmd, x->descr);
5842 return EXIT_SUCCESS;
5847 static int builtin_jobs(char **argv UNUSED_PARAM)
5850 const char *status_string;
5852 for (job = G.job_list; job; job = job->next) {
5853 if (job->alive_cmds == job->stopped_cmds)
5854 status_string = "Stopped";
5856 status_string = "Running";
5858 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
5860 return EXIT_SUCCESS;
5864 static int builtin_pwd(char **argv UNUSED_PARAM)
5867 return EXIT_SUCCESS;
5870 static int builtin_read(char **argv)
5873 const char *name = argv[1] ? argv[1] : "REPLY";
5874 //TODO: check that argv[1] is a valid variable name
5876 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
5877 return set_local_var(string, 0, 0);
5880 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
5881 * built-in 'set' handler
5883 * set [-abCefhmnuvx] [-o option] [argument...]
5884 * set [+abCefhmnuvx] [+o option] [argument...]
5885 * set -- [argument...]
5888 * Implementations shall support the options in both their hyphen and
5889 * plus-sign forms. These options can also be specified as options to sh.
5891 * Write out all variables and their values: set
5892 * Set $1, $2, and $3 and set "$#" to 3: set c a b
5893 * Turn on the -x and -v options: set -xv
5894 * Unset all positional parameters: set --
5895 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
5896 * Set the positional parameters to the expansion of x, even if x expands
5897 * with a leading '-' or '+': set -- $x
5899 * So far, we only support "set -- [argument...]" and some of the short names.
5901 static int builtin_set(char **argv)
5904 char **pp, **g_argv;
5905 char *arg = *++argv;
5909 for (e = G.top_var; e; e = e->next)
5911 return EXIT_SUCCESS;
5915 if (!strcmp(arg, "--")) {
5920 if (arg[0] == '+' || arg[0] == '-') {
5921 for (n = 1; arg[n]; ++n)
5922 if (set_mode(arg[0], arg[n]))
5928 } while ((arg = *++argv) != NULL);
5929 /* Now argv[0] is 1st argument */
5931 /* Only reset global_argv if we didn't process anything */
5933 return EXIT_SUCCESS;
5936 /* NB: G.global_argv[0] ($0) is never freed/changed */
5937 g_argv = G.global_argv;
5938 if (G.global_args_malloced) {
5944 G.global_args_malloced = 1;
5945 pp = xzalloc(sizeof(pp[0]) * 2);
5946 pp[0] = g_argv[0]; /* retain $0 */
5949 /* This realloc's G.global_argv */
5950 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
5957 return EXIT_SUCCESS;
5959 /* Nothing known, so abort */
5961 bb_error_msg("set: %s: invalid option", arg);
5962 return EXIT_FAILURE;
5965 static int builtin_shift(char **argv)
5971 if (n >= 0 && n < G.global_argc) {
5972 if (G.global_args_malloced) {
5975 free(G.global_argv[m++]);
5978 memmove(&G.global_argv[1], &G.global_argv[n+1],
5979 G.global_argc * sizeof(G.global_argv[0]));
5980 return EXIT_SUCCESS;
5982 return EXIT_FAILURE;
5985 static int builtin_source(char **argv)
5989 if (*++argv == NULL)
5990 return EXIT_FAILURE;
5992 /* XXX search through $PATH is missing */
5993 input = fopen_or_warn(*argv, "r");
5995 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
5996 return EXIT_FAILURE;
5998 close_on_exec_on(fileno(input));
6000 /* Now run the file */
6002 /* XXX argv and argc are broken; need to save old G.global_argv
6003 * (pointer only is OK!) on this stack frame,
6004 * set G.global_argv=argv+1, recurse, and restore. */
6005 parse_and_run_file(input);
6007 return G.last_exitcode;
6010 static int builtin_umask(char **argv)
6013 const char *arg = argv[1];
6015 //TODO: umask may take chmod-like symbolic masks
6016 new_umask = bb_strtou(arg, NULL, 8);
6018 //Message? bash examples:
6019 //bash: umask: 'q': invalid symbolic mode operator
6020 //bash: umask: 999: octal number out of range
6021 return EXIT_FAILURE;
6024 new_umask = umask(0);
6025 printf("%.3o\n", (unsigned) new_umask);
6026 /* fall through and restore new_umask which we set to 0 */
6029 return EXIT_SUCCESS;
6032 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
6033 static int builtin_unset(char **argv)
6039 return EXIT_SUCCESS;
6042 if (argv[0][0] == '-') {
6043 switch (argv[0][1]) {
6049 bb_error_msg("unset: %s: invalid option", *argv);
6050 return EXIT_FAILURE;
6052 //TODO: disallow "unset -vf ..." too
6059 if (unset_local_var(*argv)) {
6060 /* unset <nonexistent_var> doesn't fail.
6061 * Error is when one tries to unset RO var.
6062 * Message was printed by unset_local_var. */
6066 #if ENABLE_HUSH_FUNCTIONS
6068 unset_local_func(*argv);
6076 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
6077 static int builtin_wait(char **argv)
6079 int ret = EXIT_SUCCESS;
6082 if (*++argv == NULL) {
6083 /* Don't care about wait results */
6084 /* Note 1: must wait until there are no more children */
6085 /* Note 2: must be interruptible */
6087 * $ sleep 3 & sleep 6 & wait
6092 * $ sleep 3 & sleep 6 & wait
6096 * ^C <-- after ~4 sec from keyboard
6099 sigaddset(&G.blocked_set, SIGCHLD);
6100 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6103 if (errno == ECHILD)
6105 /* Wait for SIGCHLD or any other signal of interest */
6106 /* sigtimedwait with infinite timeout: */
6107 sig = sigwaitinfo(&G.blocked_set, NULL);
6109 sig = check_and_run_traps(sig);
6110 if (sig && sig != SIGCHLD) { /* see note 2 */
6116 sigdelset(&G.blocked_set, SIGCHLD);
6117 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6121 /* This is probably buggy wrt interruptible-ness */
6123 pid_t pid = bb_strtou(*argv, NULL, 10);
6125 /* mimic bash message */
6126 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
6127 return EXIT_FAILURE;
6129 if (waitpid(pid, &status, 0) == pid) {
6130 if (WIFSIGNALED(status))
6131 ret = 128 + WTERMSIG(status);
6132 else if (WIFEXITED(status))
6133 ret = WEXITSTATUS(status);
6137 bb_perror_msg("wait %s", *argv);
6146 #if ENABLE_HUSH_LOOPS
6147 static int builtin_break(char **argv)
6149 if (G.depth_of_loop == 0) {
6150 bb_error_msg("%s: only meaningful in a loop", argv[0]);
6151 return EXIT_SUCCESS; /* bash compat */
6153 G.flag_break_continue++; /* BC_BREAK = 1 */
6154 G.depth_break_continue = 1;
6156 G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
6157 if (errno || !G.depth_break_continue || argv[2]) {
6158 bb_error_msg("%s: bad arguments", argv[0]);
6159 G.flag_break_continue = BC_BREAK;
6160 G.depth_break_continue = UINT_MAX;
6163 if (G.depth_of_loop < G.depth_break_continue)
6164 G.depth_break_continue = G.depth_of_loop;
6165 return EXIT_SUCCESS;
6168 static int builtin_continue(char **argv)
6170 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
6171 return builtin_break(argv);