1 /* vi: set sw=4 ts=4: */
3 * A prototype Bourne shell grammar parser.
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
11 * The parser routines proper are all original material, first
12 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
13 * execution engine, the builtins, and much of the underlying
14 * support has been adapted from busybox-0.49pre's lash, which is
15 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
16 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
17 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
18 * Troan, which they placed in the public domain. I don't know
19 * how much of the Johnson/Troan code has survived the repeated
23 * o_addchr() derived from similar w_addchar function in glibc-2.2.
24 * setup_redirect(), redirect_opt_num(), and big chunks of main()
25 * and many builtins derived from contributions by Erik Andersen.
26 * Miscellaneous bugfixes from Matt Kraai.
28 * There are two big (and related) architecture differences between
29 * this parser and the lash parser. One is that this version is
30 * actually designed from the ground up to understand nearly all
31 * of the Bourne grammar. The second, consequential change is that
32 * the parser and input reader have been turned inside out. Now,
33 * the parser is in control, and asks for input as needed. The old
34 * way had the input reader in control, and it asked for parsing to
35 * take place as needed. The new way makes it much easier to properly
36 * handle the recursion implicit in the various substitutions, especially
37 * across continuation lines.
39 * POSIX syntax not implemented:
41 * Arithmetic Expansion
42 * <(list) and >(list) Process Substitution
43 * Here Documents ( << word )
46 * fancy forms of Parameter Expansion: ${var:-val}
48 * Bash stuff maybe optional enable:
49 * &> and >& redirection of stdout+stderr
51 * reserved words: [[ ]] function select
54 * job handling woefully incomplete and buggy (improved --vda)
56 * port selected bugfixes from post-0.49 busybox lash - done?
57 * change { and } from special chars to reserved words
58 * builtins: return, trap, ulimit
59 * test magic exec with redirection only
60 * follow IFS rules more precisely, including update semantics
61 * figure out what to do with backslash-newline
62 * propagate syntax errors, die on resource errors?
63 * continuation lines, both explicit and implicit - done?
64 * maybe change charmap[] to use 2-bit entries
66 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
69 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
70 //TODO: pull in some .h and find out whether we have SINGLE_APPLET_MAIN?
71 //#include "applet_tables.h" doesn't work
73 /* #include <dmalloc.h> */
78 #define HUSH_VER_STR "0.92"
80 #if defined SINGLE_APPLET_MAIN
81 /* STANDALONE does not make sense, and won't compile */
82 #undef CONFIG_FEATURE_SH_STANDALONE
83 #undef ENABLE_FEATURE_SH_STANDALONE
84 #undef USE_FEATURE_SH_STANDALONE
85 #define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
86 #define ENABLE_FEATURE_SH_STANDALONE 0
87 #define USE_FEATURE_SH_STANDALONE(...)
88 #define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
91 #if !BB_MMU && ENABLE_HUSH_TICK
92 //#undef ENABLE_HUSH_TICK
93 //#define ENABLE_HUSH_TICK 0
94 #warning On NOMMU, hush command substitution is dangerous.
95 #warning Dont use it for commands which produce lots of output.
96 #warning For more info see shell/hush.c, generate_stream_from_list().
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
196 static void debug_print_strings(const char *prefix, char **vv)
198 fprintf(stderr, "%s:\n", prefix);
200 fprintf(stderr, " '%s'\n", *vv++);
203 #define debug_print_strings(prefix, vv) ((void)0)
207 * Leak hunting. Use hush_leaktool.sh for post-processing.
209 #ifdef FOR_HUSH_LEAKTOOL
210 /* suppress "warning: no previous prototype..." */
211 void *xxmalloc(int lineno, size_t size);
212 void *xxrealloc(int lineno, void *ptr, size_t size);
213 char *xxstrdup(int lineno, const char *str);
214 void xxfree(void *ptr);
215 void *xxmalloc(int lineno, size_t size)
217 void *ptr = xmalloc((size + 0xff) & ~0xff);
218 fprintf(stderr, "line %d: malloc %p\n", lineno, ptr);
221 void *xxrealloc(int lineno, void *ptr, size_t size)
223 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
224 fprintf(stderr, "line %d: realloc %p\n", lineno, ptr);
227 char *xxstrdup(int lineno, const char *str)
229 char *ptr = xstrdup(str);
230 fprintf(stderr, "line %d: strdup %p\n", lineno, ptr);
233 void xxfree(void *ptr)
235 fprintf(stderr, "free %p\n", ptr);
238 #define xmalloc(s) xxmalloc(__LINE__, s)
239 #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
240 #define xstrdup(s) xxstrdup(__LINE__, s)
241 #define free(p) xxfree(p)
245 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="HUSH_VER_STR;
247 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
249 #define SPECIAL_VAR_SYMBOL 3
250 #define PARSEFLAG_EXIT_FROM_LOOP 1
252 typedef enum redir_type {
254 REDIRECT_OVERWRITE = 2,
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, -1, "<<" },
275 typedef enum pipe_style {
282 typedef enum reserved_style {
291 #if ENABLE_HUSH_LOOPS
298 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
303 /* two pseudo-keywords support contrived "case" syntax: */
304 RES_MATCH , /* "word)" */
305 RES_CASEI , /* "this command is inside CASE" */
312 struct redir_struct {
313 struct redir_struct *next;
314 char *rd_filename; /* filename */
315 int fd; /* file descriptor being redirected */
316 int dup; /* -1, or file descriptor being duplicated */
317 smallint /*enum redir_type*/ rd_type;
321 pid_t pid; /* 0 if exited */
322 int assignment_cnt; /* how many argv[i] are assignments? */
323 smallint is_stopped; /* is the command currently running? */
324 smallint grp_type; /* GRP_xxx */
325 struct pipe *group; /* if non-NULL, this "prog" is {} group,
326 * subshell, or a compound statement */
327 char **argv; /* command name and arguments */
328 struct redir_struct *redirects; /* I/O redirections */
330 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
331 * and on execution these are substituted with their values.
332 * Substitution can make _several_ words out of one argv[n]!
333 * Example: argv[0]=='.^C*^C.' here: echo .$*.
334 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
337 #define GRP_SUBSHELL 1
338 #if ENABLE_HUSH_FUNCTIONS
339 #define GRP_FUNCTION 2
344 int num_cmds; /* total number of commands in job */
345 int alive_cmds; /* number of commands running (not exited) */
346 int stopped_cmds; /* number of commands alive, but stopped */
348 int jobid; /* job number */
349 pid_t pgrp; /* process group ID for the job */
350 char *cmdtext; /* name of job */
352 struct command *cmds; /* array of commands in pipe */
353 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
354 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
355 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
358 /* This holds pointers to the various results of parsing */
359 struct parse_context {
360 struct command *command;
361 struct pipe *list_head;
363 struct redir_struct *pending_redirect;
366 smallint ctx_inverted; /* "! cmd | cmd" */
368 smallint ctx_dsemicolon; /* ";;" seen */
370 int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */
371 struct parse_context *stack;
375 /* On program start, environ points to initial environment.
376 * putenv adds new pointers into it, unsetenv removes them.
377 * Neither of these (de)allocates the strings.
378 * setenv allocates new strings in malloc space and does putenv,
379 * and thus setenv is unusable (leaky) for shell's purposes */
380 #define setenv(...) setenv_is_leaky_dont_use()
382 struct variable *next;
383 char *varstr; /* points to "name=" portion */
384 int max_len; /* if > 0, name is part of initial env; else name is malloced */
385 smallint flg_export; /* putenv should be done on this var */
386 smallint flg_read_only;
389 typedef struct o_string {
391 int length; /* position where data is appended */
393 /* Misnomer! it's not "quoting", it's "protection against globbing"!
394 * (by prepending \ to *, ?, [ and to \ too) */
398 smallint has_empty_slot;
399 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
402 MAYBE_ASSIGNMENT = 0,
403 DEFINITELY_ASSIGNMENT = 1,
405 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
407 /* Used for initialization: o_string foo = NULL_O_STRING; */
408 #define NULL_O_STRING { NULL }
410 /* I can almost use ordinary FILE*. Is open_memstream() universally
411 * available? Where is it documented? */
412 typedef struct in_str {
414 /* eof_flag=1: last char in ->p is really an EOF */
415 char eof_flag; /* meaningless if ->p == NULL */
417 #if ENABLE_HUSH_INTERACTIVE
419 smallint promptmode; /* 0: PS1, 1: PS2 */
422 int (*get) (struct in_str *);
423 int (*peek) (struct in_str *);
425 #define i_getch(input) ((input)->get(input))
426 #define i_peek(input) ((input)->peek(input))
430 CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
431 CHAR_IFS = 2, /* treated as ordinary if quoted */
432 CHAR_SPECIAL = 3, /* example: $ */
441 /* "Globals" within this file */
442 /* Sorted roughly by size (smaller offsets == smaller code) */
444 #if ENABLE_HUSH_INTERACTIVE
445 /* 'interactive_fd' is a fd# open to ctty, if we have one
446 * _AND_ if we decided to act interactively */
451 #if ENABLE_FEATURE_EDITING
452 line_input_t *line_input_state;
458 pid_t saved_tty_pgrp;
460 struct pipe *job_list;
461 struct pipe *toplevel_list;
462 smallint ctrl_z_flag;
464 #if ENABLE_HUSH_LOOPS
465 smallint flag_break_continue;
468 /* these three support $?, $#, and $1 */
469 smalluint last_return_code;
470 /* is global_argv and global_argv[1..n] malloced? (note: not [0]) */
471 smalluint global_args_malloced;
472 /* how many non-NULL argv's we have. NB: $# + 1 */
475 #if ENABLE_HUSH_LOOPS
476 unsigned depth_break_continue;
477 unsigned depth_of_loop;
481 struct variable *top_var; /* = &G.shell_ver (set in main()) */
482 struct variable shell_ver;
483 #if ENABLE_FEATURE_SH_STANDALONE
484 struct nofork_save_area nofork_save;
487 sigjmp_buf toplevel_jb;
489 unsigned char charmap[256];
490 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
493 #define G (*ptr_to_globals)
494 /* Not #defining name to G.name - this quickly gets unwieldy
495 * (too many defines). Also, I actually prefer to see when a variable
496 * is global, thus "G." prefix is a useful hint */
497 #define INIT_G() do { \
498 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
502 /* Function prototypes for builtins */
503 static int builtin_cd(char **argv);
504 static int builtin_echo(char **argv);
505 static int builtin_eval(char **argv);
506 static int builtin_exec(char **argv);
507 static int builtin_exit(char **argv);
508 static int builtin_export(char **argv);
510 static int builtin_fg_bg(char **argv);
511 static int builtin_jobs(char **argv);
514 static int builtin_help(char **argv);
516 static int builtin_pwd(char **argv);
517 static int builtin_read(char **argv);
518 static int builtin_test(char **argv);
519 static int builtin_true(char **argv);
520 static int builtin_set(char **argv);
521 static int builtin_set_mode(const char, const char);
522 static int builtin_shift(char **argv);
523 static int builtin_source(char **argv);
524 static int builtin_umask(char **argv);
525 static int builtin_unset(char **argv);
526 #if ENABLE_HUSH_LOOPS
527 static int builtin_break(char **argv);
528 static int builtin_continue(char **argv);
530 //static int builtin_not_written(char **argv);
532 /* Table of built-in functions. They can be forked or not, depending on
533 * context: within pipes, they fork. As simple commands, they do not.
534 * When used in non-forking context, they can change global variables
535 * in the parent shell process. If forked, of course they cannot.
536 * For example, 'unset foo | whatever' will parse and run, but foo will
537 * still be set at the end. */
538 struct built_in_command {
540 int (*function)(char **argv);
543 #define BLTIN(cmd, func, help) { cmd, func, help }
545 #define BLTIN(cmd, func, help) { cmd, func }
549 /* For now, echo and test are unconditionally enabled.
550 * Maybe make it configurable? */
551 static const struct built_in_command bltins[] = {
552 BLTIN("." , builtin_source, "Run commands in a file"),
553 BLTIN(":" , builtin_true, "No-op"),
554 BLTIN("[" , builtin_test, "Test condition"),
556 BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"),
558 #if ENABLE_HUSH_LOOPS
559 BLTIN("break" , builtin_break, "Exit from a loop"),
561 BLTIN("cd" , builtin_cd, "Change directory"),
562 #if ENABLE_HUSH_LOOPS
563 BLTIN("continue", builtin_continue, "Start new loop iteration"),
565 BLTIN("echo" , builtin_echo, "Write to stdout"),
566 BLTIN("eval" , builtin_eval, "Construct and run shell command"),
567 BLTIN("exec" , builtin_exec, "Execute command, don't return to shell"),
568 BLTIN("exit" , builtin_exit, "Exit"),
569 BLTIN("export", builtin_export, "Set environment variable"),
571 BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"),
572 BLTIN("jobs" , builtin_jobs, "List active jobs"),
574 BLTIN("pwd" , builtin_pwd, "Print current directory"),
575 BLTIN("read" , builtin_read, "Input environment variable"),
576 // BLTIN("return", builtin_not_written, "Return from a function"),
577 BLTIN("set" , builtin_set, "Set/unset shell local variables"),
578 BLTIN("shift" , builtin_shift, "Shift positional parameters"),
579 // BLTIN("trap" , builtin_not_written, "Trap signals"),
580 BLTIN("test" , builtin_test, "Test condition"),
581 // BLTIN("ulimit", builtin_not_written, "Control resource limits"),
582 BLTIN("umask" , builtin_umask, "Set file creation mask"),
583 BLTIN("unset" , builtin_unset, "Unset environment variable"),
585 BLTIN("help" , builtin_help, "List shell built-in commands"),
592 static void syntax(const char *msg)
594 #if ENABLE_HUSH_INTERACTIVE
595 /* Was using fancy stuff:
596 * (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
597 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
598 void FAST_FUNC (*fp)(const char *s, ...);
599 fp = (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die);
600 fp(msg ? "%s: %s" : "syntax error", "syntax error", msg);
602 bb_error_msg_and_die(msg ? "%s: %s" : "syntax error", "syntax error", msg);
607 static void syntax_lineno(int line)
609 #if ENABLE_HUSH_INTERACTIVE
610 void FAST_FUNC (*fp)(const char *s, ...);
611 fp = (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die);
612 fp("syntax error hush.c:%d", line);
614 bb_error_msg_and_die("syntax error hush.c:%d", line);
617 #define syntax(str) syntax_lineno(__LINE__)
620 static int glob_needed(const char *s)
625 if (*s == '*' || *s == '[' || *s == '?')
632 static int is_assignment(const char *s)
634 if (!s || !(isalpha(*s) || *s == '_'))
637 while (isalnum(*s) || *s == '_')
642 /* Replace each \x with x in place, return ptr past NUL. */
643 static char *unbackslash(char *src)
649 if ((*dst++ = *src++) == '\0')
655 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
676 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
677 v[count1 + count2] = NULL;
680 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
684 static char **add_string_to_strings(char **strings, char *add)
689 return add_strings_to_strings(strings, v, /*dup:*/ 0);
692 static void putenv_all(char **strings)
697 debug_printf_env("putenv '%s'\n", *strings);
702 static char **putenv_all_and_save_old(char **strings)
712 eq = strchr(*strings, '=');
715 v = getenv(*strings);
718 /* v points to VAL in VAR=VAL, go back to VAR */
719 v -= (eq - *strings) + 1;
720 old = add_string_to_strings(old, v);
729 static void free_strings_and_unsetenv(char **strings, int unset)
739 debug_printf_env("unsetenv '%s'\n", *v);
747 static void free_strings(char **strings)
749 free_strings_and_unsetenv(strings, 0);
753 /* Signals are grouped, we handle them in batches */
754 static void set_misc_sighandler(void (*handler)(int))
765 static void set_fatal_sighandler(void (*handler)(int))
774 /* bash 3.2 seems to handle these just like 'fatal' ones */
780 static void set_jobctrl_sighandler(void (*handler)(int))
788 /* SIGCHLD is special and handled separately */
790 static void set_every_sighandler(void (*handler)(int))
792 set_fatal_sighandler(handler);
793 set_jobctrl_sighandler(handler);
794 set_misc_sighandler(handler);
795 signal(SIGCHLD, handler);
798 static void handler_ctrl_c(int sig UNUSED_PARAM)
800 debug_printf_jobs("got sig %d\n", sig);
801 // as usual we can have all kinds of nasty problems with leaked malloc data here
802 siglongjmp(G.toplevel_jb, 1);
805 static void handler_ctrl_z(int sig UNUSED_PARAM)
809 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
812 fputs("Sorry, backgrounding (CTRL+Z) of foreground scripts not supported on nommu\n", stderr);
817 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
820 if (!pid) { /* child */
822 die_sleep = 0; /* let nofork's xfuncs die */
824 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
825 set_every_sighandler(SIG_DFL);
826 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
827 debug_printf_jobs("returning in child\n");
828 /* return to nofork, it will eventually exit now,
829 * not return back to shell */
833 /* finish filling up pipe info */
834 G.toplevel_list->pgrp = pid; /* child is in its own pgrp */
835 G.toplevel_list->cmds[0].pid = pid;
836 /* parent needs to longjmp out of running nofork.
837 * we will "return" exitcode 0, with child put in background */
838 // as usual we can have all kinds of nasty problems with leaked malloc data here
839 debug_printf_jobs("siglongjmp in parent\n");
840 siglongjmp(G.toplevel_jb, 1);
843 /* Restores tty foreground process group, and exits.
844 * May be called as signal handler for fatal signal
845 * (will faithfully resend signal to itself, producing correct exit state)
846 * or called directly with -EXITCODE.
847 * We also call it if xfunc is exiting. */
848 static void sigexit(int sig) NORETURN;
849 static void sigexit(int sig)
851 /* Disable all signals: job control, SIGPIPE, etc. */
852 sigprocmask_allsigs(SIG_BLOCK);
854 #if ENABLE_HUSH_INTERACTIVE
855 if (G.interactive_fd)
856 tcsetpgrp(G.interactive_fd, G.saved_tty_pgrp);
859 /* Not a signal, just exit */
863 kill_myself_with_sig(sig); /* does not return */
866 /* Restores tty foreground process group, and exits. */
867 static void hush_exit(int exitcode) NORETURN;
868 static void hush_exit(int exitcode)
870 fflush(NULL); /* flush all streams */
871 sigexit(- (exitcode & 0xff));
876 #define set_fatal_sighandler(handler) ((void)0)
877 #define set_jobctrl_sighandler(handler) ((void)0)
878 #define hush_exit(e) exit(e)
883 static const char *set_cwd(void)
885 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
886 * we must not try to free(bb_msg_unknown) */
887 if (G.cwd == bb_msg_unknown)
889 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
891 G.cwd = bb_msg_unknown;
896 /* Get/check local shell variables */
897 static struct variable *get_local_var(const char *name)
899 struct variable *cur;
905 for (cur = G.top_var; cur; cur = cur->next) {
906 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
912 /* Basically useful version until someone wants to get fancier,
913 * see the bash man page under "Parameter Expansion" */
914 static const char *lookup_param(const char *src)
916 struct variable *var = get_local_var(src);
918 return strchr(var->varstr, '=') + 1;
922 /* str holds "NAME=VAL" and is expected to be malloced.
923 * We take ownership of it. */
924 static int set_local_var(char *str, int flg_export)
926 struct variable *cur;
930 value = strchr(str, '=');
931 if (!value) { /* not expected to ever happen? */
936 name_len = value - str + 1; /* including '=' */
937 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
939 if (strncmp(cur->varstr, str, name_len) != 0) {
941 /* Bail out. Note that now cur points
942 * to last var in linked list */
948 /* We found an existing var with this name */
950 if (cur->flg_read_only) {
951 bb_error_msg("%s: readonly variable", str);
955 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
956 unsetenv(str); /* just in case */
958 if (strcmp(cur->varstr, str) == 0) {
963 if (cur->max_len >= strlen(str)) {
964 /* This one is from startup env, reuse space */
965 strcpy(cur->varstr, str);
968 /* max_len == 0 signifies "malloced" var, which we can
969 * (and has to) free */
973 goto set_str_and_exp;
976 /* Not found - create next variable struct */
977 cur->next = xzalloc(sizeof(*cur));
985 if (cur->flg_export) {
986 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
987 return putenv(cur->varstr);
992 static void unset_local_var(const char *name)
994 struct variable *cur;
995 struct variable *prev = prev; /* for gcc */
1000 name_len = strlen(name);
1003 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1004 if (cur->flg_read_only) {
1005 bb_error_msg("%s: readonly variable", name);
1008 /* prev is ok to use here because 1st variable, HUSH_VERSION,
1009 * is ro, and we cannot reach this code on the 1st pass */
1010 prev->next = cur->next;
1011 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1012 bb_unsetenv(cur->varstr);
1027 static int static_get(struct in_str *i)
1030 if (ch == '\0') return EOF;
1034 static int static_peek(struct in_str *i)
1039 #if ENABLE_HUSH_INTERACTIVE
1041 static void cmdedit_set_initial_prompt(void)
1043 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1044 G.PS1 = getenv("PS1");
1051 static const char* setup_prompt_string(int promptmode)
1053 const char *prompt_str;
1054 debug_printf("setup_prompt_string %d ", promptmode);
1055 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1056 /* Set up the prompt */
1057 if (promptmode == 0) { /* PS1 */
1059 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1064 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1065 debug_printf("result '%s'\n", prompt_str);
1069 static void get_user_input(struct in_str *i)
1072 const char *prompt_str;
1074 prompt_str = setup_prompt_string(i->promptmode);
1075 #if ENABLE_FEATURE_EDITING
1076 /* Enable command line editing only while a command line
1077 * is actually being read */
1079 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1080 } while (r == 0); /* repeat if Ctrl-C */
1081 i->eof_flag = (r < 0);
1082 if (i->eof_flag) { /* EOF/error detected */
1083 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1084 G.user_input_buf[1] = '\0';
1087 fputs(prompt_str, stdout);
1089 G.user_input_buf[0] = r = fgetc(i->file);
1090 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1091 i->eof_flag = (r == EOF);
1093 i->p = G.user_input_buf;
1096 #endif /* INTERACTIVE */
1098 /* This is the magic location that prints prompts
1099 * and gets data back from the user */
1100 static int file_get(struct in_str *i)
1104 /* If there is data waiting, eat it up */
1105 if (i->p && *i->p) {
1106 #if ENABLE_HUSH_INTERACTIVE
1110 if (i->eof_flag && !*i->p)
1113 /* need to double check i->file because we might be doing something
1114 * more complicated by now, like sourcing or substituting. */
1115 #if ENABLE_HUSH_INTERACTIVE
1116 if (G.interactive_fd && i->promptme && i->file == stdin) {
1119 } while (!*i->p); /* need non-empty line */
1120 i->promptmode = 1; /* PS2 */
1125 ch = fgetc(i->file);
1127 debug_printf("file_get: got a '%c' %d\n", ch, ch);
1128 #if ENABLE_HUSH_INTERACTIVE
1135 /* All the callers guarantee this routine will never be
1136 * used right after a newline, so prompting is not needed.
1138 static int file_peek(struct in_str *i)
1141 if (i->p && *i->p) {
1142 if (i->eof_flag && !i->p[1])
1146 ch = fgetc(i->file);
1147 i->eof_flag = (ch == EOF);
1148 i->peek_buf[0] = ch;
1149 i->peek_buf[1] = '\0';
1151 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
1155 static void setup_file_in_str(struct in_str *i, FILE *f)
1157 i->peek = file_peek;
1159 #if ENABLE_HUSH_INTERACTIVE
1161 i->promptmode = 0; /* PS1 */
1167 static void setup_string_in_str(struct in_str *i, const char *s)
1169 i->peek = static_peek;
1170 i->get = static_get;
1171 #if ENABLE_HUSH_INTERACTIVE
1173 i->promptmode = 0; /* PS1 */
1183 #define B_CHUNK (32 * sizeof(char*))
1185 static void o_reset(o_string *o)
1193 static void o_free(o_string *o)
1196 memset(o, 0, sizeof(*o));
1199 static void o_grow_by(o_string *o, int len)
1201 if (o->length + len > o->maxlen) {
1202 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1203 o->data = xrealloc(o->data, 1 + o->maxlen);
1207 static void o_addchr(o_string *o, int ch)
1209 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1211 o->data[o->length] = ch;
1213 o->data[o->length] = '\0';
1216 static void o_addstr(o_string *o, const char *str, int len)
1219 memcpy(&o->data[o->length], str, len);
1221 o->data[o->length] = '\0';
1224 static void o_addstr_duplicate_backslash(o_string *o, const char *str, int len)
1229 && (*str != '*' && *str != '?' && *str != '[')
1237 /* My analysis of quoting semantics tells me that state information
1238 * is associated with a destination, not a source.
1240 static void o_addqchr(o_string *o, int ch)
1243 char *found = strchr("*?[\\", ch);
1248 o->data[o->length] = '\\';
1251 o->data[o->length] = ch;
1253 o->data[o->length] = '\0';
1256 static void o_addQchr(o_string *o, int ch)
1259 if (o->o_quote && strchr("*?[\\", ch)) {
1261 o->data[o->length] = '\\';
1265 o->data[o->length] = ch;
1267 o->data[o->length] = '\0';
1270 static void o_addQstr(o_string *o, const char *str, int len)
1273 o_addstr(o, str, len);
1279 int ordinary_cnt = strcspn(str, "*?[\\");
1280 if (ordinary_cnt > len) /* paranoia */
1282 o_addstr(o, str, ordinary_cnt);
1283 if (ordinary_cnt == len)
1285 str += ordinary_cnt;
1286 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
1290 if (ch) { /* it is necessarily one of "*?[\\" */
1292 o->data[o->length] = '\\';
1296 o->data[o->length] = ch;
1298 o->data[o->length] = '\0';
1302 /* A special kind of o_string for $VAR and `cmd` expansion.
1303 * It contains char* list[] at the beginning, which is grown in 16 element
1304 * increments. Actual string data starts at the next multiple of 16 * (char*).
1305 * list[i] contains an INDEX (int!) into this string data.
1306 * It means that if list[] needs to grow, data needs to be moved higher up
1307 * but list[i]'s need not be modified.
1308 * NB: remembering how many list[i]'s you have there is crucial.
1309 * o_finalize_list() operation post-processes this structure - calculates
1310 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1312 #if DEBUG_EXPAND || DEBUG_GLOB
1313 static void debug_print_list(const char *prefix, o_string *o, int n)
1315 char **list = (char**)o->data;
1316 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1318 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1319 prefix, list, n, string_start, o->length, o->maxlen);
1321 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1322 o->data + (int)list[i] + string_start,
1323 o->data + (int)list[i] + string_start);
1327 const char *p = o->data + (int)list[n - 1] + string_start;
1328 fprintf(stderr, " total_sz:%ld\n", (p + strlen(p) + 1) - o->data);
1332 #define debug_print_list(prefix, o, n) ((void)0)
1335 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1336 * in list[n] so that it points past last stored byte so far.
1337 * It returns n+1. */
1338 static int o_save_ptr_helper(o_string *o, int n)
1340 char **list = (char**)o->data;
1344 if (!o->has_empty_slot) {
1345 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1346 string_len = o->length - string_start;
1347 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1348 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
1349 /* list[n] points to string_start, make space for 16 more pointers */
1350 o->maxlen += 0x10 * sizeof(list[0]);
1351 o->data = xrealloc(o->data, o->maxlen + 1);
1352 list = (char**)o->data;
1353 memmove(list + n + 0x10, list + n, string_len);
1354 o->length += 0x10 * sizeof(list[0]);
1356 debug_printf_list("list[%d]=%d string_start=%d\n", n, string_len, string_start);
1358 /* We have empty slot at list[n], reuse without growth */
1359 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1360 string_len = o->length - string_start;
1361 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n", n, string_len, string_start);
1362 o->has_empty_slot = 0;
1364 list[n] = (char*)(ptrdiff_t)string_len;
1368 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
1369 static int o_get_last_ptr(o_string *o, int n)
1371 char **list = (char**)o->data;
1372 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1374 return ((int)(ptrdiff_t)list[n-1]) + string_start;
1377 /* o_glob performs globbing on last list[], saving each result
1378 * as a new list[]. */
1379 static int o_glob(o_string *o, int n)
1385 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
1387 return o_save_ptr_helper(o, n);
1388 pattern = o->data + o_get_last_ptr(o, n);
1389 debug_printf_glob("glob pattern '%s'\n", pattern);
1390 if (!glob_needed(pattern)) {
1392 o->length = unbackslash(pattern) - o->data;
1393 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
1394 return o_save_ptr_helper(o, n);
1397 memset(&globdata, 0, sizeof(globdata));
1398 gr = glob(pattern, 0, NULL, &globdata);
1399 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1400 if (gr == GLOB_NOSPACE)
1401 bb_error_msg_and_die("out of memory during glob");
1402 if (gr == GLOB_NOMATCH) {
1403 globfree(&globdata);
1406 if (gr != 0) { /* GLOB_ABORTED ? */
1407 //TODO: testcase for bad glob pattern behavior
1408 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1410 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1411 char **argv = globdata.gl_pathv;
1412 o->length = pattern - o->data; /* "forget" pattern */
1414 o_addstr(o, *argv, strlen(*argv) + 1);
1415 n = o_save_ptr_helper(o, n);
1421 globfree(&globdata);
1423 debug_print_list("o_glob returning", o, n);
1427 /* If o->o_glob == 1, glob the string so far remembered.
1428 * Otherwise, just finish current list[] and start new */
1429 static int o_save_ptr(o_string *o, int n)
1431 if (o->o_glob) { /* if globbing is requested */
1432 /* If o->has_empty_slot, list[n] was already globbed
1433 * (if it was requested back then when it was filled)
1434 * so don't do that again! */
1435 if (!o->has_empty_slot)
1436 return o_glob(o, n); /* o_save_ptr_helper is inside */
1438 return o_save_ptr_helper(o, n);
1441 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
1442 static char **o_finalize_list(o_string *o, int n)
1447 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1449 debug_print_list("finalized", o, n);
1450 debug_printf_expand("finalized n:%d\n", n);
1451 list = (char**)o->data;
1452 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1456 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
1462 /* expand_strvec_to_strvec() takes a list of strings, expands
1463 * all variable references within and returns a pointer to
1464 * a list of expanded strings, possibly with larger number
1465 * of strings. (Think VAR="a b"; echo $VAR).
1466 * This new list is allocated as a single malloc block.
1467 * NULL-terminated list of char* pointers is at the beginning of it,
1468 * followed by strings themself.
1469 * Caller can deallocate entire list by single free(list). */
1471 /* Store given string, finalizing the word and starting new one whenever
1472 * we encounter IFS char(s). This is used for expanding variable values.
1473 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
1474 static int expand_on_ifs(o_string *output, int n, const char *str)
1477 int word_len = strcspn(str, G.ifs);
1479 if (output->o_quote || !output->o_glob)
1480 o_addQstr(output, str, word_len);
1481 else /* protect backslashes against globbing up :) */
1482 o_addstr_duplicate_backslash(output, str, word_len);
1485 if (!*str) /* EOL - do not finalize word */
1487 o_addchr(output, '\0');
1488 debug_print_list("expand_on_ifs", output, n);
1489 n = o_save_ptr(output, n);
1490 str += strspn(str, G.ifs); /* skip ifs chars */
1492 debug_print_list("expand_on_ifs[1]", output, n);
1496 #if ENABLE_HUSH_TICK
1497 static int process_command_subs(o_string *dest,
1498 struct in_str *input, const char *subst_end);
1501 /* Expand all variable references in given string, adding words to list[]
1502 * at n, n+1,... positions. Return updated n (so that list[n] is next one
1503 * to be filled). This routine is extremely tricky: has to deal with
1504 * variables/parameters with whitespace, $* and $@, and constructs like
1505 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
1506 static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
1508 /* or_mask is either 0 (normal case) or 0x80
1509 * (expansion of right-hand side of assignment == 1-element expand.
1510 * It will also do no globbing, and thus we must not backslash-quote!) */
1512 char first_ch, ored_ch;
1519 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
1520 debug_print_list("expand_vars_to_list", output, n);
1521 n = o_save_ptr(output, n);
1522 debug_print_list("expand_vars_to_list[0]", output, n);
1524 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
1525 #if ENABLE_HUSH_TICK
1526 o_string subst_result = NULL_O_STRING;
1528 o_addstr(output, arg, p - arg);
1529 debug_print_list("expand_vars_to_list[1]", output, n);
1531 p = strchr(p, SPECIAL_VAR_SYMBOL);
1533 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
1534 /* "$@" is special. Even if quoted, it can still
1535 * expand to nothing (not even an empty string) */
1536 if ((first_ch & 0x7f) != '@')
1537 ored_ch |= first_ch;
1539 switch (first_ch & 0x7f) {
1540 /* Highest bit in first_ch indicates that var is double-quoted */
1542 val = utoa(G.root_pid);
1544 case '!': /* bg pid */
1545 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
1547 case '?': /* exitcode */
1548 val = utoa(G.last_return_code);
1550 case '#': /* argc */
1551 val = utoa(G.global_argc ? G.global_argc-1 : 0);
1556 if (!G.global_argv[i])
1558 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
1559 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
1560 smallint sv = output->o_quote;
1561 /* unquoted var's contents should be globbed, so don't quote */
1562 output->o_quote = 0;
1563 while (G.global_argv[i]) {
1564 n = expand_on_ifs(output, n, G.global_argv[i]);
1565 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
1566 if (G.global_argv[i++][0] && G.global_argv[i]) {
1567 /* this argv[] is not empty and not last:
1568 * put terminating NUL, start new word */
1569 o_addchr(output, '\0');
1570 debug_print_list("expand_vars_to_list[2]", output, n);
1571 n = o_save_ptr(output, n);
1572 debug_print_list("expand_vars_to_list[3]", output, n);
1575 output->o_quote = sv;
1577 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
1578 * and in this case should treat it like '$*' - see 'else...' below */
1579 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
1581 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1582 if (++i >= G.global_argc)
1584 o_addchr(output, '\0');
1585 debug_print_list("expand_vars_to_list[4]", output, n);
1586 n = o_save_ptr(output, n);
1588 } else { /* quoted $*: add as one word */
1590 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1591 if (!G.global_argv[++i])
1594 o_addchr(output, G.ifs[0]);
1598 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
1599 /* "Empty variable", used to make "" etc to not disappear */
1603 #if ENABLE_HUSH_TICK
1604 case '`': { /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
1605 struct in_str input;
1608 //TODO: can we just stuff it into "output" directly?
1609 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
1610 setup_string_in_str(&input, arg);
1611 process_command_subs(&subst_result, &input, NULL);
1612 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
1613 val = subst_result.data;
1617 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
1619 arg[0] = first_ch & 0x7f;
1620 if (isdigit(arg[0])) {
1622 if (i < G.global_argc)
1623 val = G.global_argv[i];
1624 /* else val remains NULL: $N with too big N */
1626 val = lookup_param(arg);
1628 #if ENABLE_HUSH_TICK
1631 *p = SPECIAL_VAR_SYMBOL;
1632 if (!(first_ch & 0x80)) { /* unquoted $VAR */
1633 debug_printf_expand("unquoted '%s', output->o_quote:%d\n", val, output->o_quote);
1635 /* unquoted var's contents should be globbed, so don't quote */
1636 smallint sv = output->o_quote;
1637 output->o_quote = 0;
1638 n = expand_on_ifs(output, n, val);
1640 output->o_quote = sv;
1642 } else { /* quoted $VAR, val will be appended below */
1643 debug_printf_expand("quoted '%s', output->o_quote:%d\n", val, output->o_quote);
1647 o_addQstr(output, val, strlen(val));
1650 #if ENABLE_HUSH_TICK
1651 o_free(&subst_result);
1654 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
1657 debug_print_list("expand_vars_to_list[a]", output, n);
1658 /* this part is literal, and it was already pre-quoted
1659 * if needed (much earlier), do not use o_addQstr here! */
1660 o_addstr(output, arg, strlen(arg) + 1);
1661 debug_print_list("expand_vars_to_list[b]", output, n);
1662 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
1663 && !(ored_ch & 0x80) /* and all vars were not quoted. */
1666 /* allow to reuse list[n] later without re-growth */
1667 output->has_empty_slot = 1;
1669 o_addchr(output, '\0');
1674 static char **expand_variables(char **argv, int or_mask)
1679 o_string output = NULL_O_STRING;
1681 if (or_mask & 0x100) {
1682 output.o_quote = 1; /* protect against globbing for "$var" */
1683 /* (unquoted $var will temporarily switch it off) */
1690 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
1693 debug_print_list("expand_variables", &output, n);
1695 /* output.data (malloced in one block) gets returned in "list" */
1696 list = o_finalize_list(&output, n);
1697 debug_print_strings("expand_variables[1]", list);
1701 static char **expand_strvec_to_strvec(char **argv)
1703 return expand_variables(argv, 0x100);
1706 /* Used for expansion of right hand of assignments */
1707 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
1709 static char *expand_string_to_string(const char *str)
1711 char *argv[2], **list;
1713 argv[0] = (char*)str;
1715 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
1717 if (!list[0] || list[1])
1718 bb_error_msg_and_die("BUG in varexp2");
1719 /* actually, just move string 2*sizeof(char*) bytes back */
1720 overlapping_strcpy((char*)list, list[0]);
1721 debug_printf_expand("string_to_string='%s'\n", (char*)list);
1725 /* Used for "eval" builtin */
1726 static char* expand_strvec_to_string(char **argv)
1730 list = expand_variables(argv, 0x80);
1731 /* Convert all NULs to spaces */
1736 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
1737 bb_error_msg_and_die("BUG in varexp3");
1738 list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
1742 overlapping_strcpy((char*)list, list[0]);
1743 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
1747 static char **expand_assignments(char **argv, int count)
1751 /* Expand assignments into one string each */
1752 for (i = 0; i < count; i++) {
1753 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
1759 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
1760 * and stderr if they are redirected. */
1761 static int setup_redirects(struct command *prog, int squirrel[])
1764 struct redir_struct *redir;
1766 for (redir = prog->redirects; redir; redir = redir->next) {
1767 if (redir->dup == -1 && redir->rd_filename == NULL) {
1768 /* something went wrong in the parse. Pretend it didn't happen */
1771 if (redir->dup == -1) {
1773 mode = redir_table[redir->rd_type].mode;
1774 //TODO: check redir for names like '\\'
1775 p = expand_string_to_string(redir->rd_filename);
1776 openfd = open_or_warn(p, mode);
1779 /* this could get lost if stderr has been redirected, but
1780 bash and ash both lose it as well (though zsh doesn't!) */
1784 openfd = redir->dup;
1787 if (openfd != redir->fd) {
1788 if (squirrel && redir->fd < 3) {
1789 squirrel[redir->fd] = dup(redir->fd);
1792 //close(openfd); // close(-3) ??!
1794 dup2(openfd, redir->fd);
1795 if (redir->dup == -1)
1803 static void restore_redirects(int squirrel[])
1806 for (i = 0; i < 3; i++) {
1809 /* We simply die on error */
1816 #if !defined(DEBUG_CLEAN)
1817 #define free_pipe_list(head, indent) free_pipe_list(head)
1818 #define free_pipe(pi, indent) free_pipe(pi)
1820 static int free_pipe_list(struct pipe *head, int indent);
1822 /* return code is the exit status of the pipe */
1823 static int free_pipe(struct pipe *pi, int indent)
1826 struct command *command;
1827 struct redir_struct *r, *rnext;
1828 int a, i, ret_code = 0;
1830 if (pi->stopped_cmds > 0)
1832 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
1833 for (i = 0; i < pi->num_cmds; i++) {
1834 command = &pi->cmds[i];
1835 debug_printf_clean("%s command %d:\n", indenter(indent), i);
1836 if (command->argv) {
1837 for (a = 0, p = command->argv; *p; a++, p++) {
1838 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
1840 free_strings(command->argv);
1841 command->argv = NULL;
1842 } else if (command->group) {
1843 debug_printf_clean("%s begin group (grp_type:%d)\n", indenter(indent), command->grp_type);
1844 ret_code = free_pipe_list(command->group, indent+3);
1845 debug_printf_clean("%s end group\n", indenter(indent));
1847 debug_printf_clean("%s (nil)\n", indenter(indent));
1849 for (r = command->redirects; r; r = rnext) {
1850 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->rd_type].descrip);
1852 /* guard against the case >$FOO, where foo is unset or blank */
1853 if (r->rd_filename) {
1854 debug_printf_clean(" %s\n", r->rd_filename);
1855 free(r->rd_filename);
1856 r->rd_filename = NULL;
1859 debug_printf_clean("&%d\n", r->dup);
1864 command->redirects = NULL;
1866 free(pi->cmds); /* children are an array, they get freed all at once */
1875 static int free_pipe_list(struct pipe *head, int indent)
1877 int rcode = 0; /* if list has no members */
1878 struct pipe *pi, *next;
1880 for (pi = head; pi; pi = next) {
1882 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
1884 rcode = free_pipe(pi, indent);
1885 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
1887 /*pi->next = NULL;*/
1895 typedef struct nommu_save_t {
1901 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
1902 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
1903 #define pseudo_exec(nommu_save, command, argv_expanded) \
1904 pseudo_exec(command, argv_expanded)
1907 /* Called after [v]fork() in run_pipe(), or from builtin_exec().
1909 * XXX no exit() here. If you don't exec, use _exit instead.
1910 * The at_exit handlers apparently confuse the calling process,
1911 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
1912 static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded) NORETURN;
1913 static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded)
1917 const struct built_in_command *x;
1919 /* If a variable is assigned in a forest, and nobody listens,
1920 * was it ever really set?
1922 if (!argv[assignment_cnt])
1923 _exit(EXIT_SUCCESS);
1925 new_env = expand_assignments(argv, assignment_cnt);
1927 putenv_all(new_env);
1928 free(new_env); /* optional */
1930 nommu_save->new_env = new_env;
1931 nommu_save->old_env = putenv_all_and_save_old(new_env);
1933 if (argv_expanded) {
1934 argv = argv_expanded;
1936 argv = expand_strvec_to_strvec(argv);
1938 nommu_save->argv = argv;
1943 * Check if the command matches any of the builtins.
1944 * Depending on context, this might be redundant. But it's
1945 * easier to waste a few CPU cycles than it is to figure out
1946 * if this is one of those cases.
1948 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
1949 if (strcmp(argv[0], x->cmd) == 0) {
1950 debug_printf_exec("running builtin '%s'\n", argv[0]);
1951 rcode = x->function(argv);
1957 /* Check if the command matches any busybox applets */
1958 #if ENABLE_FEATURE_SH_STANDALONE
1959 if (strchr(argv[0], '/') == NULL) {
1960 int a = find_applet_by_name(argv[0]);
1962 if (APPLET_IS_NOEXEC(a)) {
1963 debug_printf_exec("running applet '%s'\n", argv[0]);
1964 // is it ok that run_applet_no_and_exit() does exit(), not _exit()?
1965 run_applet_no_and_exit(a, argv);
1967 /* re-exec ourselves with the new arguments */
1968 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
1969 execvp(bb_busybox_exec_path, argv);
1970 /* If they called chroot or otherwise made the binary no longer
1971 * executable, fall through */
1976 debug_printf_exec("execing '%s'\n", argv[0]);
1977 execvp(argv[0], argv);
1978 bb_perror_msg("can't exec '%s'", argv[0]);
1979 _exit(EXIT_FAILURE);
1982 static int run_list(struct pipe *pi);
1984 /* Called after [v]fork() in run_pipe()
1986 static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded) NORETURN;
1987 static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded)
1990 pseudo_exec_argv(nommu_save, command->argv, command->assignment_cnt, argv_expanded);
1992 if (command->group) {
1994 bb_error_msg_and_die("nested lists are not supported on NOMMU");
1997 debug_printf_exec("pseudo_exec: run_list\n");
1998 rcode = run_list(command->group);
1999 /* OK to leak memory by not calling free_pipe_list,
2000 * since this process is about to exit */
2005 /* Can happen. See what bash does with ">foo" by itself. */
2006 debug_printf("trying to pseudo_exec null command\n");
2007 _exit(EXIT_SUCCESS);
2011 static const char *get_cmdtext(struct pipe *pi)
2017 /* This is subtle. ->cmdtext is created only on first backgrounding.
2018 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
2019 * On subsequent bg argv is trashed, but we won't use it */
2022 argv = pi->cmds[0].argv;
2023 if (!argv || !argv[0]) {
2024 pi->cmdtext = xzalloc(1);
2029 do len += strlen(*argv) + 1; while (*++argv);
2030 pi->cmdtext = p = xmalloc(len);
2031 argv = pi->cmds[0].argv;
2033 len = strlen(*argv);
2034 memcpy(p, *argv, len);
2042 static void insert_bg_job(struct pipe *pi)
2044 struct pipe *thejob;
2047 /* Linear search for the ID of the job to use */
2049 for (thejob = G.job_list; thejob; thejob = thejob->next)
2050 if (thejob->jobid >= pi->jobid)
2051 pi->jobid = thejob->jobid + 1;
2053 /* Add thejob to the list of running jobs */
2055 thejob = G.job_list = xmalloc(sizeof(*thejob));
2057 for (thejob = G.job_list; thejob->next; thejob = thejob->next)
2059 thejob->next = xmalloc(sizeof(*thejob));
2060 thejob = thejob->next;
2063 /* Physically copy the struct job */
2064 memcpy(thejob, pi, sizeof(struct pipe));
2065 thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
2066 /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
2067 for (i = 0; i < pi->num_cmds; i++) {
2068 // TODO: do we really need to have so many fields which are just dead weight
2069 // at execution stage?
2070 thejob->cmds[i].pid = pi->cmds[i].pid;
2071 /* all other fields are not used and stay zero */
2073 thejob->next = NULL;
2074 thejob->cmdtext = xstrdup(get_cmdtext(pi));
2076 /* We don't wait for background thejobs to return -- append it
2077 to the list of backgrounded thejobs and leave it alone */
2078 printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
2079 G.last_bg_pid = thejob->cmds[0].pid;
2080 G.last_jobid = thejob->jobid;
2083 static void remove_bg_job(struct pipe *pi)
2085 struct pipe *prev_pipe;
2087 if (pi == G.job_list) {
2088 G.job_list = pi->next;
2090 prev_pipe = G.job_list;
2091 while (prev_pipe->next != pi)
2092 prev_pipe = prev_pipe->next;
2093 prev_pipe->next = pi->next;
2096 G.last_jobid = G.job_list->jobid;
2101 /* Remove a backgrounded job */
2102 static void delete_finished_bg_job(struct pipe *pi)
2105 pi->stopped_cmds = 0;
2111 /* Check to see if any processes have exited -- if they
2112 * have, figure out why and see if a job has completed */
2113 static int checkjobs(struct pipe* fg_pipe)
2123 attributes = WUNTRACED;
2124 if (fg_pipe == NULL)
2125 attributes |= WNOHANG;
2127 /* Do we do this right?
2128 * bash-3.00# sleep 20 | false
2130 * [3]+ Stopped sleep 20 | false
2131 * bash-3.00# echo $?
2132 * 1 <========== bg pipe is not fully done, but exitcode is already known!
2135 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
2136 //are stopped. Testcase: "cat | cat" in a script (not on command line)
2137 // + killall -STOP cat
2140 // TODO: safe_waitpid?
2141 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
2143 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
2145 if (WIFSTOPPED(status))
2146 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
2147 childpid, WSTOPSIG(status), WEXITSTATUS(status));
2148 if (WIFSIGNALED(status))
2149 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
2150 childpid, WTERMSIG(status), WEXITSTATUS(status));
2151 if (WIFEXITED(status))
2152 debug_printf_jobs("pid %d exited, exitcode %d\n",
2153 childpid, WEXITSTATUS(status));
2155 /* Were we asked to wait for fg pipe? */
2157 for (i = 0; i < fg_pipe->num_cmds; i++) {
2158 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
2159 if (fg_pipe->cmds[i].pid != childpid)
2161 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
2163 fg_pipe->cmds[i].pid = 0;
2164 fg_pipe->alive_cmds--;
2165 if (i == fg_pipe->num_cmds - 1) {
2166 /* last process gives overall exitstatus */
2167 rcode = WEXITSTATUS(status);
2168 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
2171 fg_pipe->cmds[i].is_stopped = 1;
2172 fg_pipe->stopped_cmds++;
2174 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
2175 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
2176 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
2177 /* All processes in fg pipe have exited/stopped */
2179 if (fg_pipe->alive_cmds)
2180 insert_bg_job(fg_pipe);
2184 /* There are still running processes in the fg pipe */
2185 goto wait_more; /* do waitpid again */
2187 /* it wasnt fg_pipe, look for process in bg pipes */
2191 /* We asked to wait for bg or orphaned children */
2192 /* No need to remember exitcode in this case */
2193 for (pi = G.job_list; pi; pi = pi->next) {
2194 for (i = 0; i < pi->num_cmds; i++) {
2195 if (pi->cmds[i].pid == childpid)
2196 goto found_pi_and_prognum;
2199 /* Happens when shell is used as init process (init=/bin/sh) */
2200 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
2201 continue; /* do waitpid again */
2203 found_pi_and_prognum:
2206 pi->cmds[i].pid = 0;
2208 if (!pi->alive_cmds) {
2209 printf(JOB_STATUS_FORMAT, pi->jobid,
2210 "Done", pi->cmdtext);
2211 delete_finished_bg_job(pi);
2215 pi->cmds[i].is_stopped = 1;
2219 } /* while (waitpid succeeds)... */
2221 /* wait found no children or failed */
2223 if (childpid && errno != ECHILD)
2224 bb_perror_msg("waitpid");
2229 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
2232 int rcode = checkjobs(fg_pipe);
2233 /* Job finished, move the shell to the foreground */
2234 p = getpgid(0); /* pgid of our process */
2235 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
2236 tcsetpgrp(G.interactive_fd, p);
2241 /* run_pipe() starts all the jobs, but doesn't wait for anything
2242 * to finish. See checkjobs().
2244 * return code is normally -1, when the caller has to wait for children
2245 * to finish to determine the exit status of the pipe. If the pipe
2246 * is a simple builtin command, however, the action is done by the
2247 * time run_pipe returns, and the exit code is provided as the
2250 * The input of the pipe is always stdin, the output is always
2251 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
2252 * because it tries to avoid running the command substitution in
2253 * subshell, when that is in fact necessary. The subshell process
2254 * now has its stdout directed to the input of the appropriate pipe,
2255 * so this routine is noticeably simpler.
2257 * Returns -1 only if started some children. IOW: we have to
2258 * mask out retvals of builtins etc with 0xff!
2260 static int run_pipe(struct pipe *pi)
2264 int pipefds[2]; /* pipefds[0] is for reading */
2265 struct command *command;
2266 char **argv_expanded;
2268 const struct built_in_command *x;
2270 /* it is not always needed, but we aim to smaller code */
2271 int squirrel[] = { -1, -1, -1 };
2273 const int single_and_fg = (pi->num_cmds == 1 && pi->followup != PIPE_BG);
2275 debug_printf_exec("run_pipe start: single_and_fg=%d\n", single_and_fg);
2281 pi->stopped_cmds = 0;
2283 /* Check if this is a simple builtin (not part of a pipe).
2284 * Builtins within pipes have to fork anyway, and are handled in
2285 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
2287 command = &(pi->cmds[0]);
2289 #if ENABLE_HUSH_FUNCTIONS
2290 if (single_and_fg && command->group && command->grp_type == GRP_FUNCTION) {
2291 /* We "execute" function definition */
2292 bb_error_msg("here we ought to remember function definition, and go on");
2293 return EXIT_SUCCESS;
2297 if (single_and_fg && command->group && command->grp_type == GRP_NORMAL) {
2298 debug_printf("non-subshell grouping\n");
2299 setup_redirects(command, squirrel);
2300 debug_printf_exec(": run_list\n");
2301 rcode = run_list(command->group) & 0xff;
2302 restore_redirects(squirrel);
2303 debug_printf_exec("run_pipe return %d\n", rcode);
2304 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2308 argv = command->argv;
2309 argv_expanded = NULL;
2311 if (single_and_fg && argv != NULL) {
2312 char **new_env = NULL;
2313 char **old_env = NULL;
2315 i = command->assignment_cnt;
2316 if (i != 0 && argv[i] == NULL) {
2317 /* assignments, but no command: set local environment */
2318 for (i = 0; argv[i] != NULL; i++) {
2319 debug_printf("local environment set: %s\n", argv[i]);
2320 p = expand_string_to_string(argv[i]);
2321 set_local_var(p, 0);
2323 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
2326 /* Expand the rest into (possibly) many strings each */
2327 argv_expanded = expand_strvec_to_strvec(argv + i);
2329 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2330 if (strcmp(argv_expanded[0], x->cmd) != 0)
2332 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
2333 debug_printf("exec with redirects only\n");
2334 setup_redirects(command, NULL);
2335 rcode = EXIT_SUCCESS;
2336 goto clean_up_and_ret1;
2338 debug_printf("builtin inline %s\n", argv_expanded[0]);
2339 /* XXX setup_redirects acts on file descriptors, not FILEs.
2340 * This is perfect for work that comes after exec().
2341 * Is it really safe for inline use? Experimentally,
2342 * things seem to work with glibc. */
2343 setup_redirects(command, squirrel);
2344 new_env = expand_assignments(argv, command->assignment_cnt);
2345 old_env = putenv_all_and_save_old(new_env);
2346 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv_expanded[1]);
2347 rcode = x->function(argv_expanded) & 0xff;
2348 #if ENABLE_FEATURE_SH_STANDALONE
2351 restore_redirects(squirrel);
2352 free_strings_and_unsetenv(new_env, 1);
2353 putenv_all(old_env);
2354 free(old_env); /* not free_strings()! */
2356 free(argv_expanded);
2357 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2358 debug_printf_exec("run_pipe return %d\n", rcode);
2361 #if ENABLE_FEATURE_SH_STANDALONE
2362 i = find_applet_by_name(argv_expanded[0]);
2363 if (i >= 0 && APPLET_IS_NOFORK(i)) {
2364 setup_redirects(command, squirrel);
2365 save_nofork_data(&G.nofork_save);
2366 new_env = expand_assignments(argv, command->assignment_cnt);
2367 old_env = putenv_all_and_save_old(new_env);
2368 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
2369 rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
2370 goto clean_up_and_ret;
2375 /* NB: argv_expanded may already be created, and that
2376 * might include `cmd` runs! Do not rerun it! We *must*
2377 * use argv_expanded if it's non-NULL */
2379 /* Disable job control signals for shell (parent) and
2380 * for initial child code after fork */
2381 set_jobctrl_sighandler(SIG_IGN);
2383 /* Going to fork a child per each pipe member */
2387 for (i = 0; i < pi->num_cmds; i++) {
2389 volatile nommu_save_t nommu_save;
2390 nommu_save.new_env = NULL;
2391 nommu_save.old_env = NULL;
2392 nommu_save.argv = NULL;
2394 command = &(pi->cmds[i]);
2395 if (command->argv) {
2396 debug_printf_exec(": pipe member '%s' '%s'...\n", command->argv[0], command->argv[1]);
2398 debug_printf_exec(": pipe member with no argv\n");
2400 /* pipes are inserted between pairs of commands */
2403 if ((i + 1) < pi->num_cmds)
2406 command->pid = BB_MMU ? fork() : vfork();
2407 if (!command->pid) { /* child */
2408 if (ENABLE_HUSH_JOB)
2409 die_sleep = 0; /* let nofork's xfuncs die */
2411 /* Every child adds itself to new process group
2412 * with pgid == pid_of_first_child_in_pipe */
2413 if (G.run_list_level == 1 && G.interactive_fd) {
2415 /* Don't do pgrp restore anymore on fatal signals */
2416 set_fatal_sighandler(SIG_DFL);
2418 if (pgrp < 0) /* true for 1st process only */
2420 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
2421 /* We do it in *every* child, not just first,
2423 tcsetpgrp(G.interactive_fd, pgrp);
2427 xmove_fd(nextin, 0);
2428 xmove_fd(pipefds[1], 1); /* write end */
2430 close(pipefds[0]); /* read end */
2431 /* Like bash, explicit redirects override pipes,
2432 * and the pipe fd is available for dup'ing. */
2433 setup_redirects(command, NULL);
2435 /* Restore default handlers just prior to exec */
2436 set_jobctrl_sighandler(SIG_DFL);
2437 set_misc_sighandler(SIG_DFL);
2438 signal(SIGCHLD, SIG_DFL);
2439 /* Stores to nommu_save list of env vars putenv'ed
2440 * (NOMMU, on MMU we don't need that) */
2441 /* cast away volatility... */
2442 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
2443 /* pseudo_exec() does not return */
2447 /* Clean up after vforked child */
2448 free(nommu_save.argv);
2449 free_strings_and_unsetenv(nommu_save.new_env, 1);
2450 putenv_all(nommu_save.old_env);
2452 free(argv_expanded);
2453 argv_expanded = NULL;
2454 if (command->pid < 0) { /* [v]fork failed */
2455 /* Clearly indicate, was it fork or vfork */
2456 bb_perror_msg(BB_MMU ? "fork" : "vfork");
2460 /* Second and next children need to know pid of first one */
2462 pi->pgrp = command->pid;
2468 if ((i + 1) < pi->num_cmds)
2469 close(pipefds[1]); /* write end */
2470 /* Pass read (output) pipe end to next iteration */
2471 nextin = pipefds[0];
2474 if (!pi->alive_cmds) {
2475 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
2479 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
2483 #ifndef debug_print_tree
2484 static void debug_print_tree(struct pipe *pi, int lvl)
2486 static const char *const PIPE[] = {
2492 static const char *RES[] = {
2493 [RES_NONE ] = "NONE" ,
2496 [RES_THEN ] = "THEN" ,
2497 [RES_ELIF ] = "ELIF" ,
2498 [RES_ELSE ] = "ELSE" ,
2501 #if ENABLE_HUSH_LOOPS
2502 [RES_FOR ] = "FOR" ,
2503 [RES_WHILE] = "WHILE",
2504 [RES_UNTIL] = "UNTIL",
2506 [RES_DONE ] = "DONE" ,
2508 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2511 #if ENABLE_HUSH_CASE
2512 [RES_CASE ] = "CASE" ,
2513 [RES_MATCH] = "MATCH",
2514 [RES_CASEI] = "CASEI",
2515 [RES_ESAC ] = "ESAC" ,
2517 [RES_XXXX ] = "XXXX" ,
2518 [RES_SNTX ] = "SNTX" ,
2520 static const char *const GRPTYPE[] = {
2523 #if ENABLE_HUSH_FUNCTIONS
2532 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2533 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2535 while (prn < pi->num_cmds) {
2536 struct command *command = &pi->cmds[prn];
2537 char **argv = command->argv;
2539 fprintf(stderr, "%*s prog %d assignment_cnt:%d", lvl*2, "", prn, command->assignment_cnt);
2540 if (command->group) {
2541 fprintf(stderr, " group %s: (argv=%p)\n",
2542 GRPTYPE[command->grp_type],
2544 debug_print_tree(command->group, lvl+1);
2548 if (argv) while (*argv) {
2549 fprintf(stderr, " '%s'", *argv);
2552 fprintf(stderr, "\n");
2561 /* NB: called by pseudo_exec, and therefore must not modify any
2562 * global data until exec/_exit (we can be a child after vfork!) */
2563 static int run_list(struct pipe *pi)
2565 #if ENABLE_HUSH_CASE
2566 char *case_word = NULL;
2568 #if ENABLE_HUSH_LOOPS
2569 struct pipe *loop_top = NULL;
2570 char *for_varname = NULL;
2571 char **for_lcur = NULL;
2572 char **for_list = NULL;
2574 smallint flag_skip = 1;
2575 smalluint rcode = 0; /* probably just for compiler */
2576 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
2577 smalluint cond_code = 0;
2579 enum { cond_code = 0, };
2581 /*enum reserved_style*/ smallint rword = RES_NONE;
2582 /*enum reserved_style*/ smallint skip_more_for_this_rword = RES_XXXX;
2584 debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
2586 #if ENABLE_HUSH_LOOPS
2587 /* Check syntax for "for" */
2588 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
2589 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
2591 /* current word is FOR or IN (BOLD in comments below) */
2592 if (cpipe->next == NULL) {
2593 syntax("malformed for");
2594 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
2597 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
2598 if (cpipe->next->res_word == RES_DO)
2600 /* next word is not "do". It must be "in" then ("FOR v in ...") */
2601 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
2602 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
2604 syntax("malformed for");
2605 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
2611 /* Past this point, all code paths should jump to ret: label
2612 * in order to return, no direct "return" statements please.
2613 * This helps to ensure that no memory is leaked. */
2616 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
2617 * We are saving state before entering outermost list ("while...done")
2618 * so that ctrl-Z will correctly background _entire_ outermost list,
2619 * not just a part of it (like "sleep 1 | exit 2") */
2620 if (++G.run_list_level == 1 && G.interactive_fd) {
2621 if (sigsetjmp(G.toplevel_jb, 1)) {
2622 /* ctrl-Z forked and we are parent; or ctrl-C.
2623 * Sighandler has longjmped us here */
2624 signal(SIGINT, SIG_IGN);
2625 signal(SIGTSTP, SIG_IGN);
2626 /* Restore level (we can be coming from deep inside
2628 G.run_list_level = 1;
2629 #if ENABLE_FEATURE_SH_STANDALONE
2630 if (G.nofork_save.saved) { /* if save area is valid */
2631 debug_printf_jobs("exiting nofork early\n");
2632 restore_nofork_data(&G.nofork_save);
2635 if (G.ctrl_z_flag) {
2636 /* ctrl-Z has forked and stored pid of the child in pi->pid.
2637 * Remember this child as background job */
2640 /* ctrl-C. We just stop doing whatever we were doing */
2643 USE_HUSH_LOOPS(loop_top = NULL;)
2644 USE_HUSH_LOOPS(G.depth_of_loop = 0;)
2648 /* ctrl-Z handler will store pid etc in pi */
2649 G.toplevel_list = pi;
2651 #if ENABLE_FEATURE_SH_STANDALONE
2652 G.nofork_save.saved = 0; /* in case we will run a nofork later */
2654 signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
2655 signal(SIGINT, handler_ctrl_c);
2659 /* Go through list of pipes, (maybe) executing them. */
2660 for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
2661 IF_HAS_KEYWORDS(rword = pi->res_word;)
2662 IF_HAS_NO_KEYWORDS(rword = RES_NONE;)
2663 debug_printf_exec(": rword=%d cond_code=%d skip_more=%d\n",
2664 rword, cond_code, skip_more_for_this_rword);
2665 #if ENABLE_HUSH_LOOPS
2666 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
2667 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
2669 /* start of a loop: remember where loop starts */
2674 if (rword == skip_more_for_this_rword && flag_skip) {
2675 if (pi->followup == PIPE_SEQ)
2677 /* it is "<false> && CMD" or "<true> || CMD"
2678 * and we should not execute CMD */
2682 skip_more_for_this_rword = RES_XXXX;
2685 if (rword == RES_THEN) {
2686 /* "if <false> THEN cmd": skip cmd */
2690 if (rword == RES_ELSE || rword == RES_ELIF) {
2691 /* "if <true> then ... ELSE/ELIF cmd":
2692 * skip cmd and all following ones */
2697 #if ENABLE_HUSH_LOOPS
2698 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
2700 /* first loop through for */
2702 static const char encoded_dollar_at[] ALIGN1 = {
2703 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
2704 }; /* encoded representation of "$@" */
2705 static const char *const encoded_dollar_at_argv[] = {
2706 encoded_dollar_at, NULL
2707 }; /* argv list with one element: "$@" */
2710 vals = (char**)encoded_dollar_at_argv;
2711 if (pi->next->res_word == RES_IN) {
2712 /* if no variable values after "in" we skip "for" */
2713 if (!pi->next->cmds[0].argv)
2715 vals = pi->next->cmds[0].argv;
2716 } /* else: "for var; do..." -> assume "$@" list */
2717 /* create list of variable values */
2718 debug_print_strings("for_list made from", vals);
2719 for_list = expand_strvec_to_strvec(vals);
2720 for_lcur = for_list;
2721 debug_print_strings("for_list", for_list);
2722 for_varname = pi->cmds[0].argv[0];
2723 pi->cmds[0].argv[0] = NULL;
2725 free(pi->cmds[0].argv[0]);
2727 /* "for" loop is over, clean up */
2731 pi->cmds[0].argv[0] = for_varname;
2734 /* insert next value from for_lcur */
2735 //TODO: does it need escaping?
2736 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
2737 pi->cmds[0].assignment_cnt = 1;
2739 if (rword == RES_IN) /* "for v IN list;..." - "in" has no cmds anyway */
2741 if (rword == RES_DONE) {
2742 continue; /* "done" has no cmds too */
2745 #if ENABLE_HUSH_CASE
2746 if (rword == RES_CASE) {
2747 case_word = expand_strvec_to_string(pi->cmds->argv);
2750 if (rword == RES_MATCH) {
2753 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
2755 /* all prev words didn't match, does this one match? */
2756 argv = pi->cmds->argv;
2758 char *pattern = expand_string_to_string(*argv);
2759 /* TODO: which FNM_xxx flags to use? */
2760 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
2762 if (cond_code == 0) { /* match! we will execute this branch */
2763 free(case_word); /* make future "word)" stop */
2771 if (rword == RES_CASEI) { /* inside of a case branch */
2773 continue; /* not matched yet, skip this pipe */
2776 if (pi->num_cmds == 0)
2779 /* After analyzing all keywords and conditions, we decided
2780 * to execute this pipe. NB: has to do checkjobs(NULL)
2781 * after run_pipe() to collect any background children,
2782 * even if list execution is to be stopped. */
2783 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
2786 #if ENABLE_HUSH_LOOPS
2787 G.flag_break_continue = 0;
2789 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
2791 /* we only ran a builtin: rcode is already known
2792 * and we don't need to wait for anything. */
2793 #if ENABLE_HUSH_LOOPS
2794 /* was it "break" or "continue"? */
2795 if (G.flag_break_continue) {
2796 smallint fbc = G.flag_break_continue;
2797 /* we might fall into outer *loop*,
2798 * don't want to break it too */
2800 G.depth_break_continue--;
2801 if (G.depth_break_continue == 0)
2802 G.flag_break_continue = 0;
2803 /* else: e.g. "continue 2" should *break* once, *then* continue */
2804 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
2805 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
2806 goto check_jobs_and_break;
2807 /* "continue": simulate end of loop */
2812 } else if (pi->followup == PIPE_BG) {
2813 /* what does bash do with attempts to background builtins? */
2814 /* even bash 3.2 doesn't do that well with nested bg:
2815 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
2816 * I'm NOT treating inner &'s as jobs */
2818 if (G.run_list_level == 1)
2821 rcode = 0; /* EXIT_SUCCESS */
2824 if (G.run_list_level == 1 && G.interactive_fd) {
2825 /* waits for completion, then fg's main shell */
2826 rcode = checkjobs_and_fg_shell(pi);
2827 debug_printf_exec(": checkjobs_and_fg_shell returned %d\n", rcode);
2830 { /* this one just waits for completion */
2831 rcode = checkjobs(pi);
2832 debug_printf_exec(": checkjobs returned %d\n", rcode);
2836 debug_printf_exec(": setting last_return_code=%d\n", rcode);
2837 G.last_return_code = rcode;
2839 /* Analyze how result affects subsequent commands */
2841 if (rword == RES_IF || rword == RES_ELIF)
2844 #if ENABLE_HUSH_LOOPS
2845 if (rword == RES_WHILE) {
2847 rcode = 0; /* "while false; do...done" - exitcode 0 */
2848 goto check_jobs_and_break;
2851 if (rword == RES_UNTIL) {
2853 check_jobs_and_break:
2859 if ((rcode == 0 && pi->followup == PIPE_OR)
2860 || (rcode != 0 && pi->followup == PIPE_AND)
2862 skip_more_for_this_rword = rword;
2868 if (G.ctrl_z_flag) {
2869 /* ctrl-Z forked somewhere in the past, we are the child,
2870 * and now we completed running the list. Exit. */
2875 if (!--G.run_list_level && G.interactive_fd) {
2876 signal(SIGTSTP, SIG_IGN);
2877 signal(SIGINT, SIG_IGN);
2880 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
2881 #if ENABLE_HUSH_LOOPS
2886 #if ENABLE_HUSH_CASE
2892 /* Select which version we will use */
2893 static int run_and_free_list(struct pipe *pi)
2896 debug_printf_exec("run_and_free_list entered\n");
2898 debug_printf_exec(": run_list with %d members\n", pi->num_cmds);
2899 rcode = run_list(pi);
2901 /* free_pipe_list has the side effect of clearing memory.
2902 * In the long run that function can be merged with run_list,
2903 * but doing that now would hobble the debugging effort. */
2904 free_pipe_list(pi, /* indent: */ 0);
2905 debug_printf_exec("run_and_free_list return %d\n", rcode);
2910 /* Peek ahead in the in_str to find out if we have a "&n" construct,
2911 * as in "2>&1", that represents duplicating a file descriptor.
2912 * Return either -2 (syntax error), -1 (no &), or the number found.
2914 static int redirect_dup_num(struct in_str *input)
2916 int ch, d = 0, ok = 0;
2918 if (ch != '&') return -1;
2920 i_getch(input); /* get the & */
2924 return -3; /* "-" represents "close me" */
2926 while (isdigit(ch)) {
2927 d = d*10 + (ch-'0');
2934 bb_error_msg("ambiguous redirect");
2938 /* The src parameter allows us to peek forward to a possible &n syntax
2939 * for file descriptor duplication, e.g., "2>&1".
2940 * Return code is 0 normally, 1 if a syntax error is detected in src.
2941 * Resource errors (in xmalloc) cause the process to exit */
2942 static int setup_redirect(struct parse_context *ctx, int fd, redir_type style,
2943 struct in_str *input)
2945 struct command *command = ctx->command;
2946 struct redir_struct *redir = command->redirects;
2947 struct redir_struct *last_redir = NULL;
2949 /* Create a new redir_struct and drop it onto the end of the linked list */
2952 redir = redir->next;
2954 redir = xzalloc(sizeof(struct redir_struct));
2955 /* redir->next = NULL; */
2956 /* redir->rd_filename = NULL; */
2958 last_redir->next = redir;
2960 command->redirects = redir;
2963 redir->rd_type = style;
2964 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
2966 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2968 /* Check for a '2>&1' type redirect */
2969 redir->dup = redirect_dup_num(input);
2970 if (redir->dup == -2)
2971 return 1; /* syntax error */
2972 if (redir->dup != -1) {
2973 /* Erik had a check here that the file descriptor in question
2974 * is legit; I postpone that to "run time"
2975 * A "-" representation of "close me" shows up as a -3 here */
2976 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2978 /* We do _not_ try to open the file that src points to,
2979 * since we need to return and let src be expanded first.
2980 * Set ctx->pending_redirect, so we know what to do at the
2981 * end of the next parsed word. */
2982 ctx->pending_redirect = redir;
2988 static struct pipe *new_pipe(void)
2991 pi = xzalloc(sizeof(struct pipe));
2992 /*pi->followup = 0; - deliberately invalid value */
2993 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
2997 /* Command (member of a pipe) is complete. The only possible error here
2998 * is out of memory, in which case xmalloc exits. */
2999 static int done_command(struct parse_context *ctx)
3001 /* The command is really already in the pipe structure, so
3002 * advance the pipe counter and make a new, null command. */
3003 struct pipe *pi = ctx->pipe;
3004 struct command *command = ctx->command;
3007 if (command->group == NULL
3008 && command->argv == NULL
3009 && command->redirects == NULL
3011 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3012 return pi->num_cmds;
3015 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3017 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3020 /* Only real trickiness here is that the uncommitted
3021 * command structure is not counted in pi->num_cmds. */
3022 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3023 command = &pi->cmds[pi->num_cmds];
3024 memset(command, 0, sizeof(*command));
3026 ctx->command = command;
3027 /* but ctx->pipe and ctx->list_head remain unchanged */
3029 return pi->num_cmds; /* used only for 0/nonzero check */
3032 static void done_pipe(struct parse_context *ctx, pipe_style type)
3036 debug_printf_parse("done_pipe entered, followup %d\n", type);
3037 /* Close previous command */
3038 not_null = done_command(ctx);
3039 ctx->pipe->followup = type;
3040 IF_HAS_KEYWORDS(ctx->pipe->pi_inverted = ctx->ctx_inverted;)
3041 IF_HAS_KEYWORDS(ctx->ctx_inverted = 0;)
3042 IF_HAS_KEYWORDS(ctx->pipe->res_word = ctx->ctx_res_w;)
3044 /* Without this check, even just <enter> on command line generates
3045 * tree of three NOPs (!). Which is harmless but annoying.
3046 * IOW: it is safe to do it unconditionally.
3047 * RES_NONE case is for "for a in; do ..." (empty IN set)
3048 * to work, possibly other cases too. */
3049 if (not_null IF_HAS_KEYWORDS(|| ctx->ctx_res_w != RES_NONE)) {
3051 debug_printf_parse("done_pipe: adding new pipe: "
3052 "not_null:%d ctx->ctx_res_w:%d\n",
3053 not_null, ctx->ctx_res_w);
3055 ctx->pipe->next = new_p;
3057 ctx->command = NULL; /* needed! */
3058 /* RES_THEN, RES_DO etc are "sticky" -
3059 * they remain set for commands inside if/while.
3060 * This is used to control execution.
3061 * RES_FOR and RES_IN are NOT sticky (needed to support
3062 * cases where variable or value happens to match a keyword):
3064 #if ENABLE_HUSH_LOOPS
3065 if (ctx->ctx_res_w == RES_FOR
3066 || ctx->ctx_res_w == RES_IN)
3067 ctx->ctx_res_w = RES_NONE;
3069 #if ENABLE_HUSH_CASE
3070 if (ctx->ctx_res_w == RES_MATCH)
3071 ctx->ctx_res_w = RES_CASEI;
3073 /* Create the memory for command, roughly:
3074 * ctx->pipe->cmds = new struct command;
3075 * ctx->command = &ctx->pipe->cmds[0];
3079 debug_printf_parse("done_pipe return\n");
3082 static void initialize_context(struct parse_context *ctx)
3084 memset(ctx, 0, sizeof(*ctx));
3085 ctx->pipe = ctx->list_head = new_pipe();
3086 /* Create the memory for command, roughly:
3087 * ctx->pipe->cmds = new struct command;
3088 * ctx->command = &ctx->pipe->cmds[0];
3094 /* If a reserved word is found and processed, parse context is modified
3095 * and 1 is returned.
3096 * Handles if, then, elif, else, fi, for, while, until, do, done.
3097 * case, function, and select are obnoxious, save those for later.
3100 struct reserved_combo {
3103 unsigned char assignment_flag;
3107 FLAG_END = (1 << RES_NONE ),
3109 FLAG_IF = (1 << RES_IF ),
3110 FLAG_THEN = (1 << RES_THEN ),
3111 FLAG_ELIF = (1 << RES_ELIF ),
3112 FLAG_ELSE = (1 << RES_ELSE ),
3113 FLAG_FI = (1 << RES_FI ),
3115 #if ENABLE_HUSH_LOOPS
3116 FLAG_FOR = (1 << RES_FOR ),
3117 FLAG_WHILE = (1 << RES_WHILE),
3118 FLAG_UNTIL = (1 << RES_UNTIL),
3119 FLAG_DO = (1 << RES_DO ),
3120 FLAG_DONE = (1 << RES_DONE ),
3121 FLAG_IN = (1 << RES_IN ),
3123 #if ENABLE_HUSH_CASE
3124 FLAG_MATCH = (1 << RES_MATCH),
3125 FLAG_ESAC = (1 << RES_ESAC ),
3127 FLAG_START = (1 << RES_XXXX ),
3130 static const struct reserved_combo* match_reserved_word(o_string *word)
3132 /* Mostly a list of accepted follow-up reserved words.
3133 * FLAG_END means we are done with the sequence, and are ready
3134 * to turn the compound list into a command.
3135 * FLAG_START means the word must start a new compound list.
3137 static const struct reserved_combo reserved_list[] = {
3139 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3140 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
3141 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3142 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
3143 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
3144 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3146 #if ENABLE_HUSH_LOOPS
3147 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3148 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3149 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3150 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3151 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
3152 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3154 #if ENABLE_HUSH_CASE
3155 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3156 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3159 const struct reserved_combo *r;
3161 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3162 if (strcmp(word->data, r->literal) == 0)
3167 static int reserved_word(o_string *word, struct parse_context *ctx)
3169 #if ENABLE_HUSH_CASE
3170 static const struct reserved_combo reserved_match = {
3171 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3174 const struct reserved_combo *r;
3176 r = match_reserved_word(word);
3180 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3181 #if ENABLE_HUSH_CASE
3182 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
3183 /* "case word IN ..." - IN part starts first match part */
3184 r = &reserved_match;
3187 if (r->flag == 0) { /* '!' */
3188 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3190 IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
3192 ctx->ctx_inverted = 1;
3195 if (r->flag & FLAG_START) {
3196 struct parse_context *new;
3197 debug_printf("push stack\n");
3198 new = xmalloc(sizeof(*new));
3199 *new = *ctx; /* physical copy */
3200 initialize_context(ctx);
3202 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3204 ctx->ctx_res_w = RES_SNTX;
3207 ctx->ctx_res_w = r->res;
3208 ctx->old_flag = r->flag;
3209 if (ctx->old_flag & FLAG_END) {
3210 struct parse_context *old;
3211 debug_printf("pop stack\n");
3212 done_pipe(ctx, PIPE_SEQ);
3214 old->command->group = ctx->list_head;
3215 old->command->grp_type = GRP_NORMAL;
3216 *ctx = *old; /* physical copy */
3219 word->o_assignment = r->assignment_flag;
3224 //TODO: many, many callers don't check error from done_word()
3226 /* Word is complete, look at it and update parsing context.
3227 * Normal return is 0. Syntax errors return 1. */
3228 static int done_word(o_string *word, struct parse_context *ctx)
3230 struct command *command = ctx->command;
3232 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3233 if (word->length == 0 && word->nonnull == 0) {
3234 debug_printf_parse("done_word return 0: true null, ignored\n");
3237 /* If this word wasn't an assignment, next ones definitely
3238 * can't be assignments. Even if they look like ones. */
3239 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3240 && word->o_assignment != WORD_IS_KEYWORD
3242 word->o_assignment = NOT_ASSIGNMENT;
3244 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3245 command->assignment_cnt++;
3246 word->o_assignment = MAYBE_ASSIGNMENT;
3249 if (ctx->pending_redirect) {
3250 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3251 * only if run as "bash", not "sh" */
3252 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3253 word->o_assignment = NOT_ASSIGNMENT;
3254 debug_printf("word stored in rd_filename: '%s'\n", word->data);
3256 /* "{ echo foo; } echo bar" - bad */
3257 /* NB: bash allows e.g. "if true; then { echo foo; } fi". TODO? */
3258 if (command->group) {
3260 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
3264 #if ENABLE_HUSH_CASE
3265 if (ctx->ctx_dsemicolon
3266 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3268 /* already done when ctx_dsemicolon was set to 1: */
3269 /* ctx->ctx_res_w = RES_MATCH; */
3270 ctx->ctx_dsemicolon = 0;
3274 if (!command->argv /* if it's the first word... */
3275 #if ENABLE_HUSH_LOOPS
3276 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3277 && ctx->ctx_res_w != RES_IN
3280 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
3281 if (reserved_word(word, ctx)) {
3283 debug_printf_parse("done_word return %d\n", (ctx->ctx_res_w == RES_SNTX));
3284 return (ctx->ctx_res_w == RES_SNTX);
3288 if (word->nonnull /* word had "xx" or 'xx' at least as part of it. */
3289 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3290 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3291 /* (otherwise it's known to be not empty and is already safe) */
3293 /* exclude "$@" - it can expand to no word despite "" */
3294 char *p = word->data;
3295 while (p[0] == SPECIAL_VAR_SYMBOL
3296 && (p[1] & 0x7f) == '@'
3297 && p[2] == SPECIAL_VAR_SYMBOL
3301 if (p == word->data || p[0] != '\0') {
3302 /* saw no "$@", or not only "$@" but some
3303 * real text is there too */
3304 /* insert "empty variable" reference, this makes
3305 * e.g. "", $empty"" etc to not disappear */
3306 o_addchr(word, SPECIAL_VAR_SYMBOL);
3307 o_addchr(word, SPECIAL_VAR_SYMBOL);
3310 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3311 debug_print_strings("word appended to argv", command->argv);
3315 ctx->pending_redirect = NULL;
3317 #if ENABLE_HUSH_LOOPS
3318 /* Force FOR to have just one word (variable name) */
3319 /* NB: basically, this makes hush see "for v in ..." syntax as if
3320 * as it is "for v; in ...". FOR and IN become two pipe structs
3322 if (ctx->ctx_res_w == RES_FOR) {
3323 //TODO: check that command->argv[0] is a valid variable name!
3324 done_pipe(ctx, PIPE_SEQ);
3327 #if ENABLE_HUSH_CASE
3328 /* Force CASE to have just one word */
3329 if (ctx->ctx_res_w == RES_CASE) {
3330 done_pipe(ctx, PIPE_SEQ);
3333 debug_printf_parse("done_word return 0\n");
3337 /* If a redirect is immediately preceded by a number, that number is
3338 * supposed to tell which file descriptor to redirect. This routine
3339 * looks for such preceding numbers. In an ideal world this routine
3340 * needs to handle all the following classes of redirects...
3341 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3342 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3343 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3344 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3345 * A -1 output from this program means no valid number was found, so the
3346 * caller should use the appropriate default for this redirection.
3348 static int redirect_opt_num(o_string *o)
3354 for (num = 0; num < o->length; num++) {
3355 if (!isdigit(o->data[num])) {
3359 num = atoi(o->data);
3364 static int parse_stream(o_string *dest, struct parse_context *ctx,
3365 struct in_str *input0, const char *end_trigger);
3367 #if ENABLE_HUSH_TICK
3368 static FILE *generate_stream_from_list(struct pipe *head)
3371 int pid, channel[2];
3374 /* *** NOMMU WARNING *** */
3375 /* By using vfork here, we suspend parent till child exits or execs.
3376 * If child will not do it before it fills the pipe, it can block forever
3377 * in write(STDOUT_FILENO), and parent (shell) will be also stuck.
3379 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >TESTFILE
3380 * huge=`cat TESTFILE` # will block here forever
3383 pid = BB_MMU ? fork() : vfork();
3385 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
3386 if (pid == 0) { /* child */
3387 if (ENABLE_HUSH_JOB)
3388 die_sleep = 0; /* let nofork's xfuncs die */
3389 close(channel[0]); /* NB: close _first_, then move fd! */
3390 xmove_fd(channel[1], 1);
3391 /* Prevent it from trying to handle ctrl-z etc */
3393 G.run_list_level = 1;
3395 /* Process substitution is not considered to be usual
3396 * 'command execution'.
3397 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not. */
3398 /* Not needed, we are relying on it being disabled
3399 * everywhere outside actual command execution. */
3400 /*set_jobctrl_sighandler(SIG_IGN);*/
3401 set_misc_sighandler(SIG_DFL);
3402 /* Freeing 'head' here would break NOMMU. */
3403 _exit(run_list(head));
3406 pf = fdopen(channel[0], "r");
3408 /* 'head' is freed by the caller */
3411 /* Return code is exit status of the process that is run. */
3412 static int process_command_subs(o_string *dest,
3413 struct in_str *input,
3414 const char *subst_end)
3416 int retcode, ch, eol_cnt;
3417 o_string result = NULL_O_STRING;
3418 struct parse_context inner;
3420 struct in_str pipe_str;
3422 initialize_context(&inner);
3424 /* Recursion to generate command */
3425 retcode = parse_stream(&result, &inner, input, subst_end);
3427 return retcode; /* syntax error or EOF */
3428 done_word(&result, &inner);
3429 done_pipe(&inner, PIPE_SEQ);
3432 p = generate_stream_from_list(inner.list_head);
3435 close_on_exec_on(fileno(p));
3436 setup_file_in_str(&pipe_str, p);
3438 /* Now send results of command back into original context */
3440 while ((ch = i_getch(&pipe_str)) != EOF) {
3446 o_addchr(dest, '\n');
3449 o_addQchr(dest, ch);
3452 debug_printf("done reading from pipe, pclose()ing\n");
3453 /* This is the step that wait()s for the child. Should be pretty
3454 * safe, since we just read an EOF from its stdout. We could try
3455 * to do better, by using wait(), and keeping track of background jobs
3456 * at the same time. That would be a lot of work, and contrary
3457 * to the KISS philosophy of this program. */
3458 retcode = fclose(p);
3459 free_pipe_list(inner.list_head, /* indent: */ 0);
3460 debug_printf("closed FILE from child, retcode=%d\n", retcode);
3465 static int parse_group(o_string *dest, struct parse_context *ctx,
3466 struct in_str *input, int ch)
3468 /* dest contains characters seen prior to ( or {.
3469 * Typically it's empty, but for functions defs,
3470 * it contains function name (without '()'). */
3472 const char *endch = NULL;
3473 struct parse_context sub;
3474 struct command *command = ctx->command;
3476 debug_printf_parse("parse_group entered\n");
3477 #if ENABLE_HUSH_FUNCTIONS
3478 if (ch == 'F') { /* function definition? */
3479 bb_error_msg("aha '%s' is a function, parsing it...", dest->data);
3480 //command->fname = dest->data;
3481 command->grp_type = GRP_FUNCTION;
3482 //TODO: review every o_reset() location... do they handle all o_string fields correctly?
3483 memset(dest, 0, sizeof(*dest));
3486 if (command->argv /* word [word](... */
3487 || dest->length /* word(... */
3488 || dest->nonnull /* ""(... */
3491 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3494 initialize_context(&sub);
3498 command->grp_type = GRP_SUBSHELL;
3500 rcode = parse_stream(dest, &sub, input, endch);
3502 done_word(dest, &sub); /* finish off the final word in the subcontext */
3503 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
3504 command->group = sub.list_head;
3506 debug_printf_parse("parse_group return %d\n", rcode);
3508 /* command remains "open", available for possible redirects */
3511 #if ENABLE_HUSH_TICK
3512 /* Subroutines for copying $(...) and `...` things */
3513 static void add_till_backquote(o_string *dest, struct in_str *input);
3515 static void add_till_single_quote(o_string *dest, struct in_str *input)
3518 int ch = i_getch(input);
3526 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3527 static void add_till_double_quote(o_string *dest, struct in_str *input)
3530 int ch = i_getch(input);
3533 if (ch == '\\') { /* \x. Copy both chars. */
3535 ch = i_getch(input);
3541 add_till_backquote(dest, input);
3545 //if (ch == '$') ...
3548 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3550 * "Within the backquoted style of command substitution, backslash
3551 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3552 * The search for the matching backquote shall be satisfied by the first
3553 * backquote found without a preceding backslash; during this search,
3554 * if a non-escaped backquote is encountered within a shell comment,
3555 * a here-document, an embedded command substitution of the $(command)
3556 * form, or a quoted string, undefined results occur. A single-quoted
3557 * or double-quoted string that begins, but does not end, within the
3558 * "`...`" sequence produces undefined results."
3560 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3562 static void add_till_backquote(o_string *dest, struct in_str *input)
3565 int ch = i_getch(input);
3568 if (ch == '\\') { /* \x. Copy both chars unless it is \` */
3569 int ch2 = i_getch(input);
3570 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
3579 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3580 * quoting and nested ()s.
3581 * "With the $(command) style of command substitution, all characters
3582 * following the open parenthesis to the matching closing parenthesis
3583 * constitute the command. Any valid shell script can be used for command,
3584 * except a script consisting solely of redirections which produces
3585 * unspecified results."
3587 * echo $(echo '(TEST)' BEST) (TEST) BEST
3588 * echo $(echo 'TEST)' BEST) TEST) BEST
3589 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3591 static void add_till_closing_curly_brace(o_string *dest, struct in_str *input)
3595 int ch = i_getch(input);
3605 add_till_single_quote(dest, input);
3610 add_till_double_quote(dest, input);
3614 if (ch == '\\') { /* \x. Copy verbatim. Important for \(, \) */
3615 ch = i_getch(input);
3623 #endif /* ENABLE_HUSH_TICK */
3625 /* Return code: 0 for OK, 1 for syntax error */
3626 static int handle_dollar(o_string *dest, struct in_str *input)
3628 int ch = i_peek(input); /* first character after the $ */
3629 unsigned char quote_mask = dest->o_quote ? 0x80 : 0;
3631 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
3635 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3637 debug_printf_parse(": '%c'\n", ch);
3638 o_addchr(dest, ch | quote_mask);
3641 if (!isalnum(ch) && ch != '_')
3645 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3646 } else if (isdigit(ch)) {
3649 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3650 debug_printf_parse(": '%c'\n", ch);
3651 o_addchr(dest, ch | quote_mask);
3652 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3653 } else switch (ch) {
3655 case '!': /* last bg pid */
3656 case '?': /* last exit code */
3657 case '#': /* number of args */
3658 case '*': /* args */
3659 case '@': /* args */
3660 goto make_one_char_var;
3662 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3664 /* XXX maybe someone will try to escape the '}' */
3666 ch = i_getch(input);
3669 if (!isalnum(ch) && ch != '_') {
3670 syntax("unterminated ${name}");
3671 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3674 debug_printf_parse(": '%c'\n", ch);
3675 o_addchr(dest, ch | quote_mask);
3678 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3680 #if ENABLE_HUSH_TICK
3682 //int pos = dest->length;
3684 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3685 o_addchr(dest, quote_mask | '`');
3686 add_till_closing_curly_brace(dest, input);
3687 //debug_printf_subst("SUBST RES2 '%s'\n", dest->data + pos);
3688 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3695 if (isalnum(ch)) { /* it's $_name or $_123 */
3701 /* still unhandled, but should be eventually */
3702 bb_error_msg("unhandled syntax: $%c", ch);
3706 o_addQchr(dest, '$');
3708 debug_printf_parse("handle_dollar return 0\n");
3712 /* Scan input, call done_word() whenever full IFS delimited word was seen.
3713 * Call done_pipe if '\n' was seen (and end_trigger != NULL).
3714 * Return code is 0 if end_trigger char is met,
3715 * -1 on EOF (but if end_trigger == NULL then return 0),
3716 * 1 for syntax error */
3717 static int parse_stream(o_string *dest, struct parse_context *ctx,
3718 struct in_str *input, const char *end_trigger)
3722 redir_type redir_style;
3723 int shadow_quote = dest->o_quote;
3726 /* Only double-quote state is handled in the state variable dest->o_quote.
3727 * A single-quote triggers a bypass of the main loop until its mate is
3728 * found. When recursing, quote state is passed in via dest->o_quote. */
3730 debug_printf_parse("parse_stream entered, end_trigger='%s' dest->o_assignment:%d\n", end_trigger, dest->o_assignment);
3735 ch = i_getch(input);
3739 next = i_peek(input);
3742 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
3743 ch, ch, m, dest->o_quote);
3744 if (m == CHAR_ORDINARY
3745 || (m != CHAR_SPECIAL && shadow_quote)
3748 syntax("unterminated \"");
3749 debug_printf_parse("parse_stream return 1: unterminated \"\n");
3752 o_addQchr(dest, ch);
3753 if ((dest->o_assignment == MAYBE_ASSIGNMENT
3754 || dest->o_assignment == WORD_IS_KEYWORD)
3756 && is_assignment(dest->data)
3758 dest->o_assignment = DEFINITELY_ASSIGNMENT;
3762 if (m == CHAR_IFS) {
3763 if (done_word(dest, ctx)) {
3764 debug_printf_parse("parse_stream return 1: done_word!=0\n");
3769 /* If we aren't performing a substitution, treat
3770 * a newline as a command separator.
3771 * [why we don't handle it exactly like ';'? --vda] */
3772 if (end_trigger && ch == '\n') {
3773 #if ENABLE_HUSH_CASE
3774 /* "case ... in <newline> word) ..." -
3775 * newlines are ignored (but ';' wouldn't be) */
3776 if (dest->length == 0 // && argv[0] == NULL
3777 && ctx->ctx_res_w == RES_MATCH
3782 done_pipe(ctx, PIPE_SEQ);
3783 dest->o_assignment = MAYBE_ASSIGNMENT;
3787 if (!shadow_quote && strchr(end_trigger, ch)) {
3788 /* Special case: (...word) makes last word terminate,
3789 * as if ';' is seen */
3791 done_word(dest, ctx);
3793 done_pipe(ctx, PIPE_SEQ);
3794 dest->o_assignment = MAYBE_ASSIGNMENT;
3797 IF_HAS_KEYWORDS(|| (ctx->ctx_res_w == RES_NONE && ctx->old_flag == 0))
3799 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
3807 if (dest->o_assignment == MAYBE_ASSIGNMENT) {
3808 /* ch is a special char and thus this word
3809 * cannot be an assignment: */
3810 dest->o_assignment = NOT_ASSIGNMENT;
3815 if (dest->length == 0 && !shadow_quote) {
3818 if (ch == EOF || ch == '\n')
3823 o_addQchr(dest, ch);
3829 debug_printf_parse("parse_stream return 1: \\<eof>\n");
3833 * "The backslash retains its special meaning [in "..."]
3834 * only when followed by one of the following characters:
3835 * $, `, ", \, or <newline>. A double quote may be quoted
3836 * within double quotes by preceding it with a backslash.
3837 * If enabled, history expansion will be performed unless
3838 * an ! appearing in double quotes is escaped using
3839 * a backslash. The backslash preceding the ! is not removed."
3841 if (shadow_quote) { //NOT SURE dest->o_quote) {
3842 if (strchr("$`\"\\", next) != NULL) {
3843 o_addqchr(dest, i_getch(input));
3845 o_addqchr(dest, '\\');
3848 o_addchr(dest, '\\');
3849 o_addchr(dest, i_getch(input));
3853 if (handle_dollar(dest, input) != 0) {
3854 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3861 ch = i_getch(input);
3863 syntax("unterminated '");
3864 debug_printf_parse("parse_stream return 1: unterminated '\n");
3869 if (dest->o_assignment == NOT_ASSIGNMENT)
3870 o_addqchr(dest, ch);
3877 shadow_quote ^= 1; /* invert */
3878 if (dest->o_assignment == NOT_ASSIGNMENT)
3881 #if ENABLE_HUSH_TICK
3883 //int pos = dest->length;
3884 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3885 o_addchr(dest, shadow_quote /*or dest->o_quote??*/ ? 0x80 | '`' : '`');
3886 add_till_backquote(dest, input);
3887 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3888 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
3893 redir_fd = redirect_opt_num(dest);
3894 done_word(dest, ctx);
3895 redir_style = REDIRECT_OVERWRITE;
3897 redir_style = REDIRECT_APPEND;
3901 else if (next == '(') {
3902 syntax(">(process) not supported");
3903 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
3907 setup_redirect(ctx, redir_fd, redir_style, input);
3910 redir_fd = redirect_opt_num(dest);
3911 done_word(dest, ctx);
3912 redir_style = REDIRECT_INPUT;
3914 redir_style = REDIRECT_HEREIS;
3916 } else if (next == '>') {
3917 redir_style = REDIRECT_IO;
3921 else if (next == '(') {
3922 syntax("<(process) not supported");
3923 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
3927 setup_redirect(ctx, redir_fd, redir_style, input);
3930 #if ENABLE_HUSH_CASE
3933 done_word(dest, ctx);
3934 done_pipe(ctx, PIPE_SEQ);
3935 #if ENABLE_HUSH_CASE
3936 /* Eat multiple semicolons, detect
3937 * whether it means something special */
3943 if (ctx->ctx_res_w == RES_CASEI) {
3944 ctx->ctx_dsemicolon = 1;
3945 ctx->ctx_res_w = RES_MATCH;
3951 /* We just finished a cmd. New one may start
3952 * with an assignment */
3953 dest->o_assignment = MAYBE_ASSIGNMENT;
3956 done_word(dest, ctx);
3959 done_pipe(ctx, PIPE_AND);
3961 done_pipe(ctx, PIPE_BG);
3965 done_word(dest, ctx);
3966 #if ENABLE_HUSH_CASE
3967 if (ctx->ctx_res_w == RES_MATCH)
3968 break; /* we are in case's "word | word)" */
3970 if (next == '|') { /* || */
3972 done_pipe(ctx, PIPE_OR);
3974 /* we could pick up a file descriptor choice here
3975 * with redirect_opt_num(), but bash doesn't do it.
3976 * "echo foo 2| cat" yields "foo 2". */
3981 #if ENABLE_HUSH_CASE
3982 /* "case... in [(]word)..." - skip '(' */
3983 if (ctx->ctx_res_w == RES_MATCH
3984 && ctx->command->argv == NULL /* not (word|(... */
3985 && dest->length == 0 /* not word(... */
3986 && dest->nonnull == 0 /* not ""(... */
3991 #if ENABLE_HUSH_FUNCTIONS
3992 if (dest->length != 0 /* not just () but word() */
3993 && dest->nonnull == 0 /* not a"b"c() */
3994 && ctx->command->argv == NULL /* it's the first word */
3995 //TODO: "func ( ) {...}" - note spaces - is valid format too in bash
3996 && i_peek(input) == ')'
3997 && !match_reserved_word(dest)
3999 bb_error_msg("seems like a function definition");
4002 //TODO: do it properly.
4003 ch = i_getch(input);
4004 } while (ch == ' ' || ch == '\n');
4006 syntax("was expecting {");
4007 debug_printf_parse("parse_stream return 1\n");
4010 ch = 'F'; /* magic value */
4014 if (parse_group(dest, ctx, input, ch) != 0) {
4015 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
4020 #if ENABLE_HUSH_CASE
4021 if (ctx->ctx_res_w == RES_MATCH)
4025 /* proper use of this character is caught by end_trigger:
4026 * if we see {, we call parse_group(..., end_trigger='}')
4027 * and it will match } earlier (not here). */
4028 syntax("unexpected } or )");
4029 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
4033 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4036 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
4042 static void set_in_charmap(const char *set, int code)
4045 G.charmap[(unsigned char)*set++] = code;
4048 static void update_charmap(void)
4050 G.ifs = getenv("IFS");
4053 /* Precompute a list of 'flow through' behavior so it can be treated
4054 * quickly up front. Computation is necessary because of IFS.
4055 * Special case handling of IFS == " \t\n" is not implemented.
4056 * The charmap[] array only really needs two bits each,
4057 * and on most machines that would be faster (reduced L1 cache use).
4059 memset(G.charmap, CHAR_ORDINARY, sizeof(G.charmap));
4060 #if ENABLE_HUSH_TICK
4061 set_in_charmap("\\$\"`", CHAR_SPECIAL);
4063 set_in_charmap("\\$\"", CHAR_SPECIAL);
4065 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
4066 set_in_charmap(G.ifs, CHAR_IFS); /* are ordinary if quoted */
4069 /* Most recursion does not come through here, the exception is
4070 * from builtin_source() and builtin_eval() */
4071 static int parse_and_run_stream(struct in_str *inp, int parse_flag)
4073 struct parse_context ctx;
4074 o_string temp = NULL_O_STRING;
4078 initialize_context(&ctx);
4080 #if ENABLE_HUSH_INTERACTIVE
4081 inp->promptmode = 0; /* PS1 */
4083 /* We will stop & execute after each ';' or '\n'.
4084 * Example: "sleep 9999; echo TEST" + ctrl-C:
4085 * TEST should be printed */
4086 temp.o_assignment = MAYBE_ASSIGNMENT;
4087 rcode = parse_stream(&temp, &ctx, inp, ";\n");
4089 if (rcode != 1 && ctx.old_flag != 0) {
4093 if (rcode != 1 IF_HAS_KEYWORDS(&& ctx.old_flag == 0)) {
4094 done_word(&temp, &ctx);
4095 done_pipe(&ctx, PIPE_SEQ);
4096 debug_print_tree(ctx.list_head, 0);
4097 debug_printf_exec("parse_stream_outer: run_and_free_list\n");
4098 run_and_free_list(ctx.list_head);
4100 /* We arrive here also if rcode == 1 (error in parse_stream) */
4102 if (ctx.old_flag != 0) {
4107 /*temp.nonnull = 0; - o_free does it below */
4108 /*temp.o_quote = 0; - o_free does it below */
4109 free_pipe_list(ctx.list_head, /* indent: */ 0);
4110 /* Discard all unprocessed line input, force prompt on */
4112 #if ENABLE_HUSH_INTERACTIVE
4117 /* loop on syntax errors, return on EOF: */
4118 } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP));
4122 static int parse_and_run_string(const char *s, int parse_flag)
4124 struct in_str input;
4125 setup_string_in_str(&input, s);
4126 return parse_and_run_stream(&input, parse_flag);
4129 static int parse_and_run_file(FILE *f)
4132 struct in_str input;
4133 setup_file_in_str(&input, f);
4134 rcode = parse_and_run_stream(&input, 0 /* parse_flag */);
4139 /* Make sure we have a controlling tty. If we get started under a job
4140 * aware app (like bash for example), make sure we are now in charge so
4141 * we don't fight over who gets the foreground */
4142 static void setup_job_control(void)
4146 shell_pgrp = getpgrp();
4147 close_on_exec_on(G.interactive_fd);
4149 /* If we were ran as 'hush &',
4150 * sleep until we are in the foreground. */
4151 while (tcgetpgrp(G.interactive_fd) != shell_pgrp) {
4152 /* Send TTIN to ourself (should stop us) */
4153 kill(- shell_pgrp, SIGTTIN);
4154 shell_pgrp = getpgrp();
4157 /* Ignore job-control and misc signals. */
4158 set_jobctrl_sighandler(SIG_IGN);
4159 set_misc_sighandler(SIG_IGN);
4160 //huh? signal(SIGCHLD, SIG_IGN);
4162 /* We _must_ restore tty pgrp on fatal signals */
4163 set_fatal_sighandler(sigexit);
4165 /* Put ourselves in our own process group. */
4166 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
4167 /* Grab control of the terminal. */
4168 tcsetpgrp(G.interactive_fd, getpid());
4173 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4174 int hush_main(int argc, char **argv)
4176 static const struct variable const_shell_ver = {
4178 .varstr = (char*)hush_version_str,
4179 .max_len = 1, /* 0 can provoke free(name) */
4187 struct variable *cur_var;
4191 G.root_pid = getpid();
4193 /* Deal with HUSH_VERSION */
4194 G.shell_ver = const_shell_ver; /* copying struct here */
4195 G.top_var = &G.shell_ver;
4196 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
4197 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
4198 /* Initialize our shell local variables with the values
4199 * currently living in the environment */
4200 cur_var = G.top_var;
4203 char *value = strchr(*e, '=');
4204 if (value) { /* paranoia */
4205 cur_var->next = xzalloc(sizeof(*cur_var));
4206 cur_var = cur_var->next;
4207 cur_var->varstr = *e;
4208 cur_var->max_len = strlen(*e);
4209 cur_var->flg_export = 1;
4213 debug_printf_env("putenv '%s'\n", hush_version_str);
4214 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
4216 #if ENABLE_FEATURE_EDITING
4217 G.line_input_state = new_line_input_t(FOR_SHELL);
4219 /* XXX what should these be while sourcing /etc/profile? */
4220 G.global_argc = argc;
4221 G.global_argv = argv;
4222 /* Initialize some more globals to non-zero values */
4224 #if ENABLE_HUSH_INTERACTIVE
4225 if (ENABLE_FEATURE_EDITING)
4226 cmdedit_set_initial_prompt();
4230 if (EXIT_SUCCESS) /* otherwise is already done */
4231 G.last_return_code = EXIT_SUCCESS;
4233 if (argv[0] && argv[0][0] == '-') {
4234 debug_printf("sourcing /etc/profile\n");
4235 input = fopen_for_read("/etc/profile");
4236 if (input != NULL) {
4237 close_on_exec_on(fileno(input));
4238 parse_and_run_file(input);
4244 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
4245 while ((opt = getopt(argc, argv, "c:xins")) > 0) {
4248 G.global_argv = argv + optind;
4249 if (!argv[optind]) {
4250 /* -c 'script' (no params): prevent empty $0 */
4251 *--G.global_argv = argv[0];
4253 } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
4254 G.global_argc = argc - optind;
4255 opt = parse_and_run_string(optarg, 0 /* parse_flag */);
4258 /* Well, we cannot just declare interactiveness,
4259 * we have to have some stuff (ctty, etc) */
4260 /* G.interactive_fd++; */
4263 /* "-s" means "read from stdin", but this is how we always
4264 * operate, so simply do nothing here. */
4268 if (!builtin_set_mode('-', opt))
4272 fprintf(stderr, "Usage: sh [FILE]...\n"
4273 " or: sh -c command [args]...\n\n");
4281 /* A shell is interactive if the '-i' flag was given, or if all of
4282 * the following conditions are met:
4284 * no arguments remaining or the -s flag given
4285 * standard input is a terminal
4286 * standard output is a terminal
4287 * Refer to Posix.2, the description of the 'sh' utility. */
4288 if (argv[optind] == NULL && input == stdin
4289 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4291 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
4292 debug_printf("saved_tty_pgrp=%d\n", G.saved_tty_pgrp);
4293 if (G.saved_tty_pgrp >= 0) {
4294 /* try to dup to high fd#, >= 255 */
4295 G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4296 if (G.interactive_fd < 0) {
4297 /* try to dup to any fd */
4298 G.interactive_fd = dup(STDIN_FILENO);
4299 if (G.interactive_fd < 0)
4301 G.interactive_fd = 0;
4303 // TODO: track & disallow any attempts of user
4304 // to (inadvertently) close/redirect it
4307 debug_printf("G.interactive_fd=%d\n", G.interactive_fd);
4308 if (G.interactive_fd) {
4309 fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
4310 /* Looks like they want an interactive shell */
4311 setup_job_control();
4312 /* -1 is special - makes xfuncs longjmp, not exit
4313 * (we reset die_sleep = 0 whereever we [v]fork) */
4315 if (setjmp(die_jmp)) {
4316 /* xfunc has failed! die die die */
4317 hush_exit(xfunc_error_retval);
4320 #elif ENABLE_HUSH_INTERACTIVE
4321 /* no job control compiled, only prompt/line editing */
4322 if (argv[optind] == NULL && input == stdin
4323 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4325 G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4326 if (G.interactive_fd < 0) {
4327 /* try to dup to any fd */
4328 G.interactive_fd = dup(STDIN_FILENO);
4329 if (G.interactive_fd < 0)
4331 G.interactive_fd = 0;
4333 if (G.interactive_fd) {
4334 fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
4335 set_misc_sighandler(SIG_IGN);
4340 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G.interactive_fd) {
4341 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
4342 printf("Enter 'help' for a list of built-in commands.\n\n");
4345 if (argv[optind] == NULL) {
4346 opt = parse_and_run_file(stdin);
4348 debug_printf("\nrunning script '%s'\n", argv[optind]);
4349 G.global_argv = argv + optind;
4350 G.global_argc = argc - optind;
4351 input = xfopen_for_read(argv[optind]);
4352 fcntl(fileno(input), F_SETFD, FD_CLOEXEC);
4353 opt = parse_and_run_file(input);
4358 #if ENABLE_FEATURE_CLEAN_UP
4360 if (G.cwd != bb_msg_unknown)
4362 cur_var = G.top_var->next;
4364 struct variable *tmp = cur_var;
4365 if (!cur_var->max_len)
4366 free(cur_var->varstr);
4367 cur_var = cur_var->next;
4371 hush_exit(opt ? opt : G.last_return_code);
4376 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4377 int lash_main(int argc, char **argv)
4379 //bb_error_msg("lash is deprecated, please use hush instead");
4380 return hush_main(argc, argv);
4388 static int builtin_true(char **argv UNUSED_PARAM)
4393 static int builtin_test(char **argv)
4400 return test_main(argc, argv - argc);
4403 static int builtin_echo(char **argv)
4410 return echo_main(argc, argv - argc);
4413 static int builtin_eval(char **argv)
4415 int rcode = EXIT_SUCCESS;
4418 char *str = expand_strvec_to_string(argv + 1);
4419 parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP);
4421 rcode = G.last_return_code;
4426 static int builtin_cd(char **argv)
4429 if (argv[1] == NULL) {
4430 // bash does nothing (exitcode 0) if HOME is ""; if it's unset,
4431 // bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
4432 newdir = getenv("HOME") ? : "/";
4435 if (chdir(newdir)) {
4436 printf("cd: %s: %s\n", newdir, strerror(errno));
4437 return EXIT_FAILURE;
4440 return EXIT_SUCCESS;
4443 static int builtin_exec(char **argv)
4445 if (argv[1] == NULL)
4446 return EXIT_SUCCESS; /* bash does this */
4451 // FIXME: if exec fails, bash does NOT exit! We do...
4452 pseudo_exec_argv(&dummy, argv + 1, 0, NULL);
4457 static int builtin_exit(char **argv)
4459 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
4460 //puts("exit"); /* bash does it */
4461 // TODO: warn if we have background jobs: "There are stopped jobs"
4462 // On second consecutive 'exit', exit anyway.
4463 if (argv[1] == NULL)
4464 hush_exit(G.last_return_code);
4465 /* mimic bash: exit 123abc == exit 255 + error msg */
4466 xfunc_error_retval = 255;
4467 /* bash: exit -2 == exit 254, no error msg */
4468 hush_exit(xatoi(argv[1]) & 0xff);
4471 static int builtin_export(char **argv)
4474 char *name = argv[1];
4478 // ash emits: export VAR='VAL'
4479 // bash: declare -x VAR="VAL"
4480 // (both also escape as needed (quotes, $, etc))
4485 return EXIT_SUCCESS;
4488 value = strchr(name, '=');
4490 /* They are exporting something without a =VALUE */
4491 struct variable *var;
4493 var = get_local_var(name);
4495 var->flg_export = 1;
4496 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
4497 putenv(var->varstr);
4499 /* bash does not return an error when trying to export
4500 * an undefined variable. Do likewise. */
4501 return EXIT_SUCCESS;
4504 set_local_var(xstrdup(name), 1);
4505 return EXIT_SUCCESS;
4509 /* built-in 'fg' and 'bg' handler */
4510 static int builtin_fg_bg(char **argv)
4515 if (!G.interactive_fd)
4516 return EXIT_FAILURE;
4517 /* If they gave us no args, assume they want the last backgrounded task */
4519 for (pi = G.job_list; pi; pi = pi->next) {
4520 if (pi->jobid == G.last_jobid) {
4524 bb_error_msg("%s: no current job", argv[0]);
4525 return EXIT_FAILURE;
4527 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
4528 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
4529 return EXIT_FAILURE;
4531 for (pi = G.job_list; pi; pi = pi->next) {
4532 if (pi->jobid == jobnum) {
4536 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
4537 return EXIT_FAILURE;
4539 // TODO: bash prints a string representation
4540 // of job being foregrounded (like "sleep 1 | cat")
4541 if (*argv[0] == 'f') {
4542 /* Put the job into the foreground. */
4543 tcsetpgrp(G.interactive_fd, pi->pgrp);
4546 /* Restart the processes in the job */
4547 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
4548 for (i = 0; i < pi->num_cmds; i++) {
4549 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
4550 pi->cmds[i].is_stopped = 0;
4552 pi->stopped_cmds = 0;
4554 i = kill(- pi->pgrp, SIGCONT);
4556 if (errno == ESRCH) {
4557 delete_finished_bg_job(pi);
4558 return EXIT_SUCCESS;
4560 bb_perror_msg("kill (SIGCONT)");
4564 if (*argv[0] == 'f') {
4566 return checkjobs_and_fg_shell(pi);
4568 return EXIT_SUCCESS;
4572 #if ENABLE_HUSH_HELP
4573 static int builtin_help(char **argv UNUSED_PARAM)
4575 const struct built_in_command *x;
4577 printf("\nBuilt-in commands:\n");
4578 printf("-------------------\n");
4579 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
4580 printf("%s\t%s\n", x->cmd, x->descr);
4583 return EXIT_SUCCESS;
4588 static int builtin_jobs(char **argv UNUSED_PARAM)
4591 const char *status_string;
4593 for (job = G.job_list; job; job = job->next) {
4594 if (job->alive_cmds == job->stopped_cmds)
4595 status_string = "Stopped";
4597 status_string = "Running";
4599 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
4601 return EXIT_SUCCESS;
4605 static int builtin_pwd(char **argv UNUSED_PARAM)
4608 return EXIT_SUCCESS;
4611 static int builtin_read(char **argv)
4614 const char *name = argv[1] ? argv[1] : "REPLY";
4616 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
4617 return set_local_var(string, 0);
4620 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
4621 * built-in 'set' handler
4623 * set [-abCefhmnuvx] [-o option] [argument...]
4624 * set [+abCefhmnuvx] [+o option] [argument...]
4625 * set -- [argument...]
4628 * Implementations shall support the options in both their hyphen and
4629 * plus-sign forms. These options can also be specified as options to sh.
4631 * Write out all variables and their values: set
4632 * Set $1, $2, and $3 and set "$#" to 3: set c a b
4633 * Turn on the -x and -v options: set -xv
4634 * Unset all positional parameters: set --
4635 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
4636 * Set the positional parameters to the expansion of x, even if x expands
4637 * with a leading '-' or '+': set -- $x
4639 * So far, we only support "set -- [argument...]" and some of the short names.
4641 static int builtin_set_mode(const char cstate, const char mode)
4643 int state = (cstate == '-' ? 1 : 0);
4645 case 'n': G.fake_mode = state; break;
4646 case 'x': /*G.debug_mode = state;*/ break;
4647 default: return EXIT_FAILURE;
4649 return EXIT_SUCCESS;
4651 static int builtin_set(char **argv)
4654 char **pp, **g_argv;
4655 char *arg = *++argv;
4659 for (e = G.top_var; e; e = e->next)
4661 return EXIT_SUCCESS;
4665 if (!strcmp(arg, "--")) {
4670 if (arg[0] == '+' || arg[0] == '-') {
4671 for (n = 1; arg[n]; ++n)
4672 if (builtin_set_mode(arg[0], arg[n]))
4678 } while ((arg = *++argv) != NULL);
4679 /* Now argv[0] is 1st argument */
4681 /* Only reset global_argv if we didn't process anything */
4683 return EXIT_SUCCESS;
4686 /* NB: G.global_argv[0] ($0) is never freed/changed */
4687 g_argv = G.global_argv;
4688 if (G.global_args_malloced) {
4694 G.global_args_malloced = 1;
4695 pp = xzalloc(sizeof(pp[0]) * 2);
4696 pp[0] = g_argv[0]; /* retain $0 */
4699 /* This realloc's G.global_argv */
4700 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
4707 return EXIT_SUCCESS;
4709 /* Nothing known, so abort */
4711 bb_error_msg("set: %s: invalid option", arg);
4712 return EXIT_FAILURE;
4715 static int builtin_shift(char **argv)
4721 if (n >= 0 && n < G.global_argc) {
4722 if (G.global_args_malloced) {
4725 free(G.global_argv[m++]);
4728 memmove(&G.global_argv[1], &G.global_argv[n+1],
4729 G.global_argc * sizeof(G.global_argv[0]));
4730 return EXIT_SUCCESS;
4732 return EXIT_FAILURE;
4735 static int builtin_source(char **argv)
4740 if (argv[1] == NULL)
4741 return EXIT_FAILURE;
4743 /* XXX search through $PATH is missing */
4744 input = fopen_for_read(argv[1]);
4746 bb_error_msg("can't open '%s'", argv[1]);
4747 return EXIT_FAILURE;
4749 close_on_exec_on(fileno(input));
4751 /* Now run the file */
4752 /* XXX argv and argc are broken; need to save old G.global_argv
4753 * (pointer only is OK!) on this stack frame,
4754 * set G.global_argv=argv+1, recurse, and restore. */
4755 status = parse_and_run_file(input);
4760 static int builtin_umask(char **argv)
4763 const char *arg = argv[1];
4766 new_umask = strtoul(arg, &end, 8);
4767 if (*end != '\0' || end == arg) {
4768 return EXIT_FAILURE;
4771 new_umask = umask(0);
4772 printf("%.3o\n", (unsigned) new_umask);
4775 return EXIT_SUCCESS;
4778 static int builtin_unset(char **argv)
4780 /* bash always returns true */
4781 unset_local_var(argv[1]);
4782 return EXIT_SUCCESS;
4785 #if ENABLE_HUSH_LOOPS
4786 static int builtin_break(char **argv)
4788 if (G.depth_of_loop == 0) {
4789 bb_error_msg("%s: only meaningful in a loop", argv[0]);
4790 return EXIT_SUCCESS; /* bash compat */
4792 G.flag_break_continue++; /* BC_BREAK = 1 */
4793 G.depth_break_continue = 1;
4795 G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
4796 if (errno || !G.depth_break_continue || argv[2]) {
4797 bb_error_msg("%s: bad arguments", argv[0]);
4798 G.flag_break_continue = BC_BREAK;
4799 G.depth_break_continue = UINT_MAX;
4802 if (G.depth_of_loop < G.depth_break_continue)
4803 G.depth_break_continue = G.depth_of_loop;
4804 return EXIT_SUCCESS;
4807 static int builtin_continue(char **argv)
4809 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
4810 return builtin_break(argv);