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 * Parameter Expansion for substring processing ${var#word} ${var%word}
48 * Bash stuff maybe optional enable:
49 * &> and >& redirection of stdout+stderr
51 * reserved words: [[ ]] function select
52 * substrings ${var:1:5}
55 * job handling woefully incomplete and buggy (improved --vda)
57 * port selected bugfixes from post-0.49 busybox lash - done?
58 * change { and } from special chars to reserved words
59 * builtins: return, trap, ulimit
60 * test magic exec with redirection only
61 * follow IFS rules more precisely, including update semantics
62 * figure out what to do with backslash-newline
63 * propagate syntax errors, die on resource errors?
64 * continuation lines, both explicit and implicit - done?
65 * maybe change charmap[] to use 2-bit entries
67 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
70 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
71 //TODO: pull in some .h and find out whether we have SINGLE_APPLET_MAIN?
72 //#include "applet_tables.h" doesn't work
74 /* #include <dmalloc.h> */
79 #define HUSH_VER_STR "0.92"
81 #if defined SINGLE_APPLET_MAIN
82 /* STANDALONE does not make sense, and won't compile */
83 #undef CONFIG_FEATURE_SH_STANDALONE
84 #undef ENABLE_FEATURE_SH_STANDALONE
85 #undef USE_FEATURE_SH_STANDALONE
86 #define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
87 #define ENABLE_FEATURE_SH_STANDALONE 0
88 #define USE_FEATURE_SH_STANDALONE(...)
89 #define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
92 #if !BB_MMU && ENABLE_HUSH_TICK
93 //#undef ENABLE_HUSH_TICK
94 //#define ENABLE_HUSH_TICK 0
95 #warning On NOMMU, hush command substitution is dangerous.
96 #warning Dont use it for commands which produce lots of output.
97 #warning For more info see shell/hush.c, generate_stream_from_list().
100 #if !ENABLE_HUSH_INTERACTIVE
101 #undef ENABLE_FEATURE_EDITING
102 #define ENABLE_FEATURE_EDITING 0
103 #undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
104 #define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
107 /* Do we support ANY keywords? */
108 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
109 #define HAS_KEYWORDS 1
110 #define IF_HAS_KEYWORDS(...) __VA_ARGS__
111 #define IF_HAS_NO_KEYWORDS(...)
113 #define HAS_KEYWORDS 0
114 #define IF_HAS_KEYWORDS(...)
115 #define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
118 /* Keep unconditionally on for now */
121 #define ENABLE_HUSH_FUNCTIONS 0
124 /* If you comment out one of these below, it will be #defined later
125 * to perform debug printfs to stderr: */
126 #define debug_printf(...) do {} while (0)
127 /* Finer-grained debug switches */
128 #define debug_printf_parse(...) do {} while (0)
129 #define debug_print_tree(a, b) do {} while (0)
130 #define debug_printf_exec(...) do {} while (0)
131 #define debug_printf_env(...) do {} while (0)
132 #define debug_printf_jobs(...) do {} while (0)
133 #define debug_printf_expand(...) do {} while (0)
134 #define debug_printf_glob(...) do {} while (0)
135 #define debug_printf_list(...) do {} while (0)
136 #define debug_printf_subst(...) do {} while (0)
137 #define debug_printf_clean(...) do {} while (0)
140 #define debug_printf(...) fprintf(stderr, __VA_ARGS__)
143 #ifndef debug_printf_parse
144 #define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
147 #ifndef debug_printf_exec
148 #define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
151 #ifndef debug_printf_env
152 #define debug_printf_env(...) fprintf(stderr, __VA_ARGS__)
155 #ifndef debug_printf_jobs
156 #define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
162 #ifndef debug_printf_expand
163 #define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
164 #define DEBUG_EXPAND 1
166 #define DEBUG_EXPAND 0
169 #ifndef debug_printf_glob
170 #define debug_printf_glob(...) fprintf(stderr, __VA_ARGS__)
176 #ifndef debug_printf_list
177 #define debug_printf_list(...) fprintf(stderr, __VA_ARGS__)
180 #ifndef debug_printf_subst
181 #define debug_printf_subst(...) fprintf(stderr, __VA_ARGS__)
184 #ifndef debug_printf_clean
185 /* broken, of course, but OK for testing */
186 static const char *indenter(int i)
188 static const char blanks[] ALIGN1 =
190 return &blanks[sizeof(blanks) - i - 1];
192 #define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
193 #define DEBUG_CLEAN 1
197 static void debug_print_strings(const char *prefix, char **vv)
199 fprintf(stderr, "%s:\n", prefix);
201 fprintf(stderr, " '%s'\n", *vv++);
204 #define debug_print_strings(prefix, vv) ((void)0)
208 * Leak hunting. Use hush_leaktool.sh for post-processing.
210 #ifdef FOR_HUSH_LEAKTOOL
211 /* suppress "warning: no previous prototype..." */
212 void *xxmalloc(int lineno, size_t size);
213 void *xxrealloc(int lineno, void *ptr, size_t size);
214 char *xxstrdup(int lineno, const char *str);
215 void xxfree(void *ptr);
216 void *xxmalloc(int lineno, size_t size)
218 void *ptr = xmalloc((size + 0xff) & ~0xff);
219 fprintf(stderr, "line %d: malloc %p\n", lineno, ptr);
222 void *xxrealloc(int lineno, void *ptr, size_t size)
224 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
225 fprintf(stderr, "line %d: realloc %p\n", lineno, ptr);
228 char *xxstrdup(int lineno, const char *str)
230 char *ptr = xstrdup(str);
231 fprintf(stderr, "line %d: strdup %p\n", lineno, ptr);
234 void xxfree(void *ptr)
236 fprintf(stderr, "free %p\n", ptr);
239 #define xmalloc(s) xxmalloc(__LINE__, s)
240 #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
241 #define xstrdup(s) xxstrdup(__LINE__, s)
242 #define free(p) xxfree(p)
246 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="HUSH_VER_STR;
248 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
250 #define SPECIAL_VAR_SYMBOL 3
251 #define PARSEFLAG_EXIT_FROM_LOOP 1
253 typedef enum redir_type {
255 REDIRECT_OVERWRITE = 2,
261 /* The descrip member of this structure is only used to make
262 * debugging output pretty */
263 static const struct {
265 signed char default_fd;
269 { O_RDONLY, 0, "<" },
270 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
271 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
272 { O_RDONLY, -1, "<<" },
276 typedef enum pipe_style {
283 typedef enum reserved_style {
292 #if ENABLE_HUSH_LOOPS
299 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
304 /* two pseudo-keywords support contrived "case" syntax: */
305 RES_MATCH , /* "word)" */
306 RES_CASEI , /* "this command is inside CASE" */
313 struct redir_struct {
314 struct redir_struct *next;
315 char *rd_filename; /* filename */
316 int fd; /* file descriptor being redirected */
317 int dup; /* -1, or file descriptor being duplicated */
318 smallint /*enum redir_type*/ rd_type;
322 pid_t pid; /* 0 if exited */
323 int assignment_cnt; /* how many argv[i] are assignments? */
324 smallint is_stopped; /* is the command currently running? */
325 smallint grp_type; /* GRP_xxx */
326 struct pipe *group; /* if non-NULL, this "prog" is {} group,
327 * subshell, or a compound statement */
328 char **argv; /* command name and arguments */
329 struct redir_struct *redirects; /* I/O redirections */
331 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
332 * and on execution these are substituted with their values.
333 * Substitution can make _several_ words out of one argv[n]!
334 * Example: argv[0]=='.^C*^C.' here: echo .$*.
335 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
338 #define GRP_SUBSHELL 1
339 #if ENABLE_HUSH_FUNCTIONS
340 #define GRP_FUNCTION 2
345 int num_cmds; /* total number of commands in job */
346 int alive_cmds; /* number of commands running (not exited) */
347 int stopped_cmds; /* number of commands alive, but stopped */
349 int jobid; /* job number */
350 pid_t pgrp; /* process group ID for the job */
351 char *cmdtext; /* name of job */
353 struct command *cmds; /* array of commands in pipe */
354 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
355 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
356 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
359 /* This holds pointers to the various results of parsing */
360 struct parse_context {
361 struct command *command;
362 struct pipe *list_head;
364 struct redir_struct *pending_redirect;
367 smallint ctx_inverted; /* "! cmd | cmd" */
369 smallint ctx_dsemicolon; /* ";;" seen */
371 int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */
372 struct parse_context *stack;
376 /* On program start, environ points to initial environment.
377 * putenv adds new pointers into it, unsetenv removes them.
378 * Neither of these (de)allocates the strings.
379 * setenv allocates new strings in malloc space and does putenv,
380 * and thus setenv is unusable (leaky) for shell's purposes */
381 #define setenv(...) setenv_is_leaky_dont_use()
383 struct variable *next;
384 char *varstr; /* points to "name=" portion */
385 int max_len; /* if > 0, name is part of initial env; else name is malloced */
386 smallint flg_export; /* putenv should be done on this var */
387 smallint flg_read_only;
390 typedef struct o_string {
392 int length; /* position where data is appended */
394 /* Misnomer! it's not "quoting", it's "protection against globbing"!
395 * (by prepending \ to *, ?, [ and to \ too) */
399 smallint has_empty_slot;
400 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
403 MAYBE_ASSIGNMENT = 0,
404 DEFINITELY_ASSIGNMENT = 1,
406 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
408 /* Used for initialization: o_string foo = NULL_O_STRING; */
409 #define NULL_O_STRING { NULL }
411 /* I can almost use ordinary FILE*. Is open_memstream() universally
412 * available? Where is it documented? */
413 typedef struct in_str {
415 /* eof_flag=1: last char in ->p is really an EOF */
416 char eof_flag; /* meaningless if ->p == NULL */
418 #if ENABLE_HUSH_INTERACTIVE
420 smallint promptmode; /* 0: PS1, 1: PS2 */
423 int (*get) (struct in_str *);
424 int (*peek) (struct in_str *);
426 #define i_getch(input) ((input)->get(input))
427 #define i_peek(input) ((input)->peek(input))
431 CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
432 CHAR_IFS = 2, /* treated as ordinary if quoted */
433 CHAR_SPECIAL = 3, /* example: $ */
442 /* "Globals" within this file */
443 /* Sorted roughly by size (smaller offsets == smaller code) */
445 #if ENABLE_HUSH_INTERACTIVE
446 /* 'interactive_fd' is a fd# open to ctty, if we have one
447 * _AND_ if we decided to act interactively */
452 #if ENABLE_FEATURE_EDITING
453 line_input_t *line_input_state;
459 pid_t saved_tty_pgrp;
461 struct pipe *job_list;
462 struct pipe *toplevel_list;
463 smallint ctrl_z_flag;
465 #if ENABLE_HUSH_LOOPS
466 smallint flag_break_continue;
469 /* these three support $?, $#, and $1 */
470 smalluint last_return_code;
471 /* is global_argv and global_argv[1..n] malloced? (note: not [0]) */
472 smalluint global_args_malloced;
473 /* how many non-NULL argv's we have. NB: $# + 1 */
476 #if ENABLE_HUSH_LOOPS
477 unsigned depth_break_continue;
478 unsigned depth_of_loop;
482 struct variable *top_var; /* = &G.shell_ver (set in main()) */
483 struct variable shell_ver;
484 #if ENABLE_FEATURE_SH_STANDALONE
485 struct nofork_save_area nofork_save;
488 sigjmp_buf toplevel_jb;
490 unsigned char charmap[256];
491 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
494 #define G (*ptr_to_globals)
495 /* Not #defining name to G.name - this quickly gets unwieldy
496 * (too many defines). Also, I actually prefer to see when a variable
497 * is global, thus "G." prefix is a useful hint */
498 #define INIT_G() do { \
499 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
503 /* Function prototypes for builtins */
504 static int builtin_cd(char **argv);
505 static int builtin_echo(char **argv);
506 static int builtin_eval(char **argv);
507 static int builtin_exec(char **argv);
508 static int builtin_exit(char **argv);
509 static int builtin_export(char **argv);
511 static int builtin_fg_bg(char **argv);
512 static int builtin_jobs(char **argv);
515 static int builtin_help(char **argv);
517 static int builtin_pwd(char **argv);
518 static int builtin_read(char **argv);
519 static int builtin_test(char **argv);
520 static int builtin_true(char **argv);
521 static int builtin_set(char **argv);
522 static int builtin_set_mode(const char, const char);
523 static int builtin_shift(char **argv);
524 static int builtin_source(char **argv);
525 static int builtin_umask(char **argv);
526 static int builtin_unset(char **argv);
527 #if ENABLE_HUSH_LOOPS
528 static int builtin_break(char **argv);
529 static int builtin_continue(char **argv);
531 //static int builtin_not_written(char **argv);
533 /* Table of built-in functions. They can be forked or not, depending on
534 * context: within pipes, they fork. As simple commands, they do not.
535 * When used in non-forking context, they can change global variables
536 * in the parent shell process. If forked, of course they cannot.
537 * For example, 'unset foo | whatever' will parse and run, but foo will
538 * still be set at the end. */
539 struct built_in_command {
541 int (*function)(char **argv);
544 #define BLTIN(cmd, func, help) { cmd, func, help }
546 #define BLTIN(cmd, func, help) { cmd, func }
550 /* For now, echo and test are unconditionally enabled.
551 * Maybe make it configurable? */
552 static const struct built_in_command bltins[] = {
553 BLTIN("." , builtin_source, "Run commands in a file"),
554 BLTIN(":" , builtin_true, "No-op"),
555 BLTIN("[" , builtin_test, "Test condition"),
557 BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"),
559 #if ENABLE_HUSH_LOOPS
560 BLTIN("break" , builtin_break, "Exit from a loop"),
562 BLTIN("cd" , builtin_cd, "Change directory"),
563 #if ENABLE_HUSH_LOOPS
564 BLTIN("continue", builtin_continue, "Start new loop iteration"),
566 BLTIN("echo" , builtin_echo, "Write to stdout"),
567 BLTIN("eval" , builtin_eval, "Construct and run shell command"),
568 BLTIN("exec" , builtin_exec, "Execute command, don't return to shell"),
569 BLTIN("exit" , builtin_exit, "Exit"),
570 BLTIN("export", builtin_export, "Set environment variable"),
572 BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"),
573 BLTIN("jobs" , builtin_jobs, "List active jobs"),
575 BLTIN("pwd" , builtin_pwd, "Print current directory"),
576 BLTIN("read" , builtin_read, "Input environment variable"),
577 // BLTIN("return", builtin_not_written, "Return from a function"),
578 BLTIN("set" , builtin_set, "Set/unset shell local variables"),
579 BLTIN("shift" , builtin_shift, "Shift positional parameters"),
580 // BLTIN("trap" , builtin_not_written, "Trap signals"),
581 BLTIN("test" , builtin_test, "Test condition"),
582 // BLTIN("ulimit", builtin_not_written, "Control resource limits"),
583 BLTIN("umask" , builtin_umask, "Set file creation mask"),
584 BLTIN("unset" , builtin_unset, "Unset environment variable"),
586 BLTIN("help" , builtin_help, "List shell built-in commands"),
593 static void maybe_die(const char *notice, const char *msg)
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, ...) = bb_error_msg_and_die;
599 #if ENABLE_HUSH_INTERACTIVE
600 fp = (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die);
602 fp(msg ? "%s: %s" : notice, notice, msg);
604 static void syntax(const char *msg)
606 maybe_die("syntax error", msg);
610 static void syntax_lineno(int line)
612 #if ENABLE_HUSH_INTERACTIVE
613 void FAST_FUNC (*fp)(const char *s, ...);
614 fp = (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die);
615 fp("syntax error hush.c:%d", line);
617 bb_error_msg_and_die("syntax error hush.c:%d", line);
620 #define syntax(str) syntax_lineno(__LINE__)
623 static int glob_needed(const char *s)
628 if (*s == '*' || *s == '[' || *s == '?')
635 static int is_assignment(const char *s)
637 if (!s || !(isalpha(*s) || *s == '_'))
640 while (isalnum(*s) || *s == '_')
645 /* Replace each \x with x in place, return ptr past NUL. */
646 static char *unbackslash(char *src)
652 if ((*dst++ = *src++) == '\0')
658 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
679 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
680 v[count1 + count2] = NULL;
683 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
687 static char **add_string_to_strings(char **strings, char *add)
692 return add_strings_to_strings(strings, v, /*dup:*/ 0);
695 static void putenv_all(char **strings)
700 debug_printf_env("putenv '%s'\n", *strings);
705 static char **putenv_all_and_save_old(char **strings)
715 eq = strchr(*strings, '=');
718 v = getenv(*strings);
721 /* v points to VAL in VAR=VAL, go back to VAR */
722 v -= (eq - *strings) + 1;
723 old = add_string_to_strings(old, v);
732 static void free_strings_and_unsetenv(char **strings, int unset)
742 debug_printf_env("unsetenv '%s'\n", *v);
750 static void free_strings(char **strings)
752 free_strings_and_unsetenv(strings, 0);
756 /* Signals are grouped, we handle them in batches */
757 static void set_misc_sighandler(void (*handler)(int))
768 static void set_fatal_sighandler(void (*handler)(int))
777 /* bash 3.2 seems to handle these just like 'fatal' ones */
783 static void set_jobctrl_sighandler(void (*handler)(int))
791 /* SIGCHLD is special and handled separately */
793 static void set_every_sighandler(void (*handler)(int))
795 set_fatal_sighandler(handler);
796 set_jobctrl_sighandler(handler);
797 set_misc_sighandler(handler);
798 signal(SIGCHLD, handler);
801 static void handler_ctrl_c(int sig UNUSED_PARAM)
803 debug_printf_jobs("got sig %d\n", sig);
804 // as usual we can have all kinds of nasty problems with leaked malloc data here
805 siglongjmp(G.toplevel_jb, 1);
808 static void handler_ctrl_z(int sig UNUSED_PARAM)
812 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
815 fputs("Sorry, backgrounding (CTRL+Z) of foreground scripts not supported on nommu\n", stderr);
820 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
823 if (!pid) { /* child */
825 die_sleep = 0; /* let nofork's xfuncs die */
827 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
828 set_every_sighandler(SIG_DFL);
829 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
830 debug_printf_jobs("returning in child\n");
831 /* return to nofork, it will eventually exit now,
832 * not return back to shell */
836 /* finish filling up pipe info */
837 G.toplevel_list->pgrp = pid; /* child is in its own pgrp */
838 G.toplevel_list->cmds[0].pid = pid;
839 /* parent needs to longjmp out of running nofork.
840 * we will "return" exitcode 0, with child put in background */
841 // as usual we can have all kinds of nasty problems with leaked malloc data here
842 debug_printf_jobs("siglongjmp in parent\n");
843 siglongjmp(G.toplevel_jb, 1);
846 /* Restores tty foreground process group, and exits.
847 * May be called as signal handler for fatal signal
848 * (will faithfully resend signal to itself, producing correct exit state)
849 * or called directly with -EXITCODE.
850 * We also call it if xfunc is exiting. */
851 static void sigexit(int sig) NORETURN;
852 static void sigexit(int sig)
854 /* Disable all signals: job control, SIGPIPE, etc. */
855 sigprocmask_allsigs(SIG_BLOCK);
857 #if ENABLE_HUSH_INTERACTIVE
858 if (G.interactive_fd)
859 tcsetpgrp(G.interactive_fd, G.saved_tty_pgrp);
862 /* Not a signal, just exit */
866 kill_myself_with_sig(sig); /* does not return */
869 /* Restores tty foreground process group, and exits. */
870 static void hush_exit(int exitcode) NORETURN;
871 static void hush_exit(int exitcode)
873 fflush(NULL); /* flush all streams */
874 sigexit(- (exitcode & 0xff));
879 #define set_fatal_sighandler(handler) ((void)0)
880 #define set_jobctrl_sighandler(handler) ((void)0)
881 #define hush_exit(e) exit(e)
886 static const char *set_cwd(void)
888 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
889 * we must not try to free(bb_msg_unknown) */
890 if (G.cwd == bb_msg_unknown)
892 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
894 G.cwd = bb_msg_unknown;
899 /* Get/check local shell variables */
900 static struct variable *get_local_var(const char *name)
902 struct variable *cur;
908 for (cur = G.top_var; cur; cur = cur->next) {
909 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
915 /* Basically useful version until someone wants to get fancier,
916 * see the bash man page under "Parameter Expansion" */
917 static const char *lookup_param(const char *src)
919 struct variable *var = get_local_var(src);
921 return strchr(var->varstr, '=') + 1;
925 /* str holds "NAME=VAL" and is expected to be malloced.
926 * We take ownership of it.
927 * flg_export is used by:
930 * -1: if NAME is set, leave export status alone
931 * if NAME is not set, do not export
933 static int set_local_var(char *str, int flg_export)
935 struct variable *cur;
939 value = strchr(str, '=');
940 if (!value) { /* not expected to ever happen? */
945 name_len = value - str + 1; /* including '=' */
946 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
948 if (strncmp(cur->varstr, str, name_len) != 0) {
950 /* Bail out. Note that now cur points
951 * to last var in linked list */
957 /* We found an existing var with this name */
959 if (cur->flg_read_only) {
960 bb_error_msg("%s: readonly variable", str);
964 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
965 unsetenv(str); /* just in case */
967 if (strcmp(cur->varstr, str) == 0) {
972 if (cur->max_len >= strlen(str)) {
973 /* This one is from startup env, reuse space */
974 strcpy(cur->varstr, str);
977 /* max_len == 0 signifies "malloced" var, which we can
978 * (and has to) free */
982 goto set_str_and_exp;
985 /* Not found - create next variable struct */
986 cur->next = xzalloc(sizeof(*cur));
994 if (cur->flg_export) {
995 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
996 return putenv(cur->varstr);
1001 static void unset_local_var(const char *name)
1003 struct variable *cur;
1004 struct variable *prev = prev; /* for gcc */
1009 name_len = strlen(name);
1012 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1013 if (cur->flg_read_only) {
1014 bb_error_msg("%s: readonly variable", name);
1017 /* prev is ok to use here because 1st variable, HUSH_VERSION,
1018 * is ro, and we cannot reach this code on the 1st pass */
1019 prev->next = cur->next;
1020 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1021 bb_unsetenv(cur->varstr);
1036 static int static_get(struct in_str *i)
1039 if (ch == '\0') return EOF;
1043 static int static_peek(struct in_str *i)
1048 #if ENABLE_HUSH_INTERACTIVE
1050 static void cmdedit_set_initial_prompt(void)
1052 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1053 G.PS1 = getenv("PS1");
1060 static const char* setup_prompt_string(int promptmode)
1062 const char *prompt_str;
1063 debug_printf("setup_prompt_string %d ", promptmode);
1064 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1065 /* Set up the prompt */
1066 if (promptmode == 0) { /* PS1 */
1068 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1073 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1074 debug_printf("result '%s'\n", prompt_str);
1078 static void get_user_input(struct in_str *i)
1081 const char *prompt_str;
1083 prompt_str = setup_prompt_string(i->promptmode);
1084 #if ENABLE_FEATURE_EDITING
1085 /* Enable command line editing only while a command line
1086 * is actually being read */
1088 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1089 } while (r == 0); /* repeat if Ctrl-C */
1090 i->eof_flag = (r < 0);
1091 if (i->eof_flag) { /* EOF/error detected */
1092 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1093 G.user_input_buf[1] = '\0';
1096 fputs(prompt_str, stdout);
1098 G.user_input_buf[0] = r = fgetc(i->file);
1099 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1100 i->eof_flag = (r == EOF);
1102 i->p = G.user_input_buf;
1105 #endif /* INTERACTIVE */
1107 /* This is the magic location that prints prompts
1108 * and gets data back from the user */
1109 static int file_get(struct in_str *i)
1113 /* If there is data waiting, eat it up */
1114 if (i->p && *i->p) {
1115 #if ENABLE_HUSH_INTERACTIVE
1119 if (i->eof_flag && !*i->p)
1122 /* need to double check i->file because we might be doing something
1123 * more complicated by now, like sourcing or substituting. */
1124 #if ENABLE_HUSH_INTERACTIVE
1125 if (G.interactive_fd && i->promptme && i->file == stdin) {
1128 } while (!*i->p); /* need non-empty line */
1129 i->promptmode = 1; /* PS2 */
1134 ch = fgetc(i->file);
1136 debug_printf("file_get: got a '%c' %d\n", ch, ch);
1137 #if ENABLE_HUSH_INTERACTIVE
1144 /* All the callers guarantee this routine will never be
1145 * used right after a newline, so prompting is not needed.
1147 static int file_peek(struct in_str *i)
1150 if (i->p && *i->p) {
1151 if (i->eof_flag && !i->p[1])
1155 ch = fgetc(i->file);
1156 i->eof_flag = (ch == EOF);
1157 i->peek_buf[0] = ch;
1158 i->peek_buf[1] = '\0';
1160 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
1164 static void setup_file_in_str(struct in_str *i, FILE *f)
1166 i->peek = file_peek;
1168 #if ENABLE_HUSH_INTERACTIVE
1170 i->promptmode = 0; /* PS1 */
1176 static void setup_string_in_str(struct in_str *i, const char *s)
1178 i->peek = static_peek;
1179 i->get = static_get;
1180 #if ENABLE_HUSH_INTERACTIVE
1182 i->promptmode = 0; /* PS1 */
1192 #define B_CHUNK (32 * sizeof(char*))
1194 static void o_reset(o_string *o)
1202 static void o_free(o_string *o)
1205 memset(o, 0, sizeof(*o));
1208 static void o_grow_by(o_string *o, int len)
1210 if (o->length + len > o->maxlen) {
1211 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1212 o->data = xrealloc(o->data, 1 + o->maxlen);
1216 static void o_addchr(o_string *o, int ch)
1218 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1220 o->data[o->length] = ch;
1222 o->data[o->length] = '\0';
1225 static void o_addstr(o_string *o, const char *str, int len)
1228 memcpy(&o->data[o->length], str, len);
1230 o->data[o->length] = '\0';
1233 static void o_addstr_duplicate_backslash(o_string *o, const char *str, int len)
1238 && (*str != '*' && *str != '?' && *str != '[')
1246 /* My analysis of quoting semantics tells me that state information
1247 * is associated with a destination, not a source.
1249 static void o_addqchr(o_string *o, int ch)
1252 char *found = strchr("*?[\\", ch);
1257 o->data[o->length] = '\\';
1260 o->data[o->length] = ch;
1262 o->data[o->length] = '\0';
1265 static void o_addQchr(o_string *o, int ch)
1268 if (o->o_quote && strchr("*?[\\", ch)) {
1270 o->data[o->length] = '\\';
1274 o->data[o->length] = ch;
1276 o->data[o->length] = '\0';
1279 static void o_addQstr(o_string *o, const char *str, int len)
1282 o_addstr(o, str, len);
1288 int ordinary_cnt = strcspn(str, "*?[\\");
1289 if (ordinary_cnt > len) /* paranoia */
1291 o_addstr(o, str, ordinary_cnt);
1292 if (ordinary_cnt == len)
1294 str += ordinary_cnt;
1295 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
1299 if (ch) { /* it is necessarily one of "*?[\\" */
1301 o->data[o->length] = '\\';
1305 o->data[o->length] = ch;
1307 o->data[o->length] = '\0';
1311 /* A special kind of o_string for $VAR and `cmd` expansion.
1312 * It contains char* list[] at the beginning, which is grown in 16 element
1313 * increments. Actual string data starts at the next multiple of 16 * (char*).
1314 * list[i] contains an INDEX (int!) into this string data.
1315 * It means that if list[] needs to grow, data needs to be moved higher up
1316 * but list[i]'s need not be modified.
1317 * NB: remembering how many list[i]'s you have there is crucial.
1318 * o_finalize_list() operation post-processes this structure - calculates
1319 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1321 #if DEBUG_EXPAND || DEBUG_GLOB
1322 static void debug_print_list(const char *prefix, o_string *o, int n)
1324 char **list = (char**)o->data;
1325 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1327 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1328 prefix, list, n, string_start, o->length, o->maxlen);
1330 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1331 o->data + (int)list[i] + string_start,
1332 o->data + (int)list[i] + string_start);
1336 const char *p = o->data + (int)list[n - 1] + string_start;
1337 fprintf(stderr, " total_sz:%ld\n", (p + strlen(p) + 1) - o->data);
1341 #define debug_print_list(prefix, o, n) ((void)0)
1344 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1345 * in list[n] so that it points past last stored byte so far.
1346 * It returns n+1. */
1347 static int o_save_ptr_helper(o_string *o, int n)
1349 char **list = (char**)o->data;
1353 if (!o->has_empty_slot) {
1354 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1355 string_len = o->length - string_start;
1356 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1357 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
1358 /* list[n] points to string_start, make space for 16 more pointers */
1359 o->maxlen += 0x10 * sizeof(list[0]);
1360 o->data = xrealloc(o->data, o->maxlen + 1);
1361 list = (char**)o->data;
1362 memmove(list + n + 0x10, list + n, string_len);
1363 o->length += 0x10 * sizeof(list[0]);
1365 debug_printf_list("list[%d]=%d string_start=%d\n", n, string_len, string_start);
1367 /* We have empty slot at list[n], reuse without growth */
1368 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1369 string_len = o->length - string_start;
1370 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n", n, string_len, string_start);
1371 o->has_empty_slot = 0;
1373 list[n] = (char*)(ptrdiff_t)string_len;
1377 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
1378 static int o_get_last_ptr(o_string *o, int n)
1380 char **list = (char**)o->data;
1381 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1383 return ((int)(ptrdiff_t)list[n-1]) + string_start;
1386 /* o_glob performs globbing on last list[], saving each result
1387 * as a new list[]. */
1388 static int o_glob(o_string *o, int n)
1394 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
1396 return o_save_ptr_helper(o, n);
1397 pattern = o->data + o_get_last_ptr(o, n);
1398 debug_printf_glob("glob pattern '%s'\n", pattern);
1399 if (!glob_needed(pattern)) {
1401 o->length = unbackslash(pattern) - o->data;
1402 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
1403 return o_save_ptr_helper(o, n);
1406 memset(&globdata, 0, sizeof(globdata));
1407 gr = glob(pattern, 0, NULL, &globdata);
1408 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1409 if (gr == GLOB_NOSPACE)
1410 bb_error_msg_and_die("out of memory during glob");
1411 if (gr == GLOB_NOMATCH) {
1412 globfree(&globdata);
1415 if (gr != 0) { /* GLOB_ABORTED ? */
1416 //TODO: testcase for bad glob pattern behavior
1417 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1419 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1420 char **argv = globdata.gl_pathv;
1421 o->length = pattern - o->data; /* "forget" pattern */
1423 o_addstr(o, *argv, strlen(*argv) + 1);
1424 n = o_save_ptr_helper(o, n);
1430 globfree(&globdata);
1432 debug_print_list("o_glob returning", o, n);
1436 /* If o->o_glob == 1, glob the string so far remembered.
1437 * Otherwise, just finish current list[] and start new */
1438 static int o_save_ptr(o_string *o, int n)
1440 if (o->o_glob) { /* if globbing is requested */
1441 /* If o->has_empty_slot, list[n] was already globbed
1442 * (if it was requested back then when it was filled)
1443 * so don't do that again! */
1444 if (!o->has_empty_slot)
1445 return o_glob(o, n); /* o_save_ptr_helper is inside */
1447 return o_save_ptr_helper(o, n);
1450 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
1451 static char **o_finalize_list(o_string *o, int n)
1456 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1458 debug_print_list("finalized", o, n);
1459 debug_printf_expand("finalized n:%d\n", n);
1460 list = (char**)o->data;
1461 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1465 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
1471 /* expand_strvec_to_strvec() takes a list of strings, expands
1472 * all variable references within and returns a pointer to
1473 * a list of expanded strings, possibly with larger number
1474 * of strings. (Think VAR="a b"; echo $VAR).
1475 * This new list is allocated as a single malloc block.
1476 * NULL-terminated list of char* pointers is at the beginning of it,
1477 * followed by strings themself.
1478 * Caller can deallocate entire list by single free(list). */
1480 /* Store given string, finalizing the word and starting new one whenever
1481 * we encounter IFS char(s). This is used for expanding variable values.
1482 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
1483 static int expand_on_ifs(o_string *output, int n, const char *str)
1486 int word_len = strcspn(str, G.ifs);
1488 if (output->o_quote || !output->o_glob)
1489 o_addQstr(output, str, word_len);
1490 else /* protect backslashes against globbing up :) */
1491 o_addstr_duplicate_backslash(output, str, word_len);
1494 if (!*str) /* EOL - do not finalize word */
1496 o_addchr(output, '\0');
1497 debug_print_list("expand_on_ifs", output, n);
1498 n = o_save_ptr(output, n);
1499 str += strspn(str, G.ifs); /* skip ifs chars */
1501 debug_print_list("expand_on_ifs[1]", output, n);
1505 #if ENABLE_HUSH_TICK
1506 static int process_command_subs(o_string *dest,
1507 struct in_str *input, const char *subst_end);
1510 /* Expand all variable references in given string, adding words to list[]
1511 * at n, n+1,... positions. Return updated n (so that list[n] is next one
1512 * to be filled). This routine is extremely tricky: has to deal with
1513 * variables/parameters with whitespace, $* and $@, and constructs like
1514 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
1515 static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
1517 /* or_mask is either 0 (normal case) or 0x80
1518 * (expansion of right-hand side of assignment == 1-element expand.
1519 * It will also do no globbing, and thus we must not backslash-quote!) */
1521 char first_ch, ored_ch;
1528 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
1529 debug_print_list("expand_vars_to_list", output, n);
1530 n = o_save_ptr(output, n);
1531 debug_print_list("expand_vars_to_list[0]", output, n);
1533 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
1534 #if ENABLE_HUSH_TICK
1535 o_string subst_result = NULL_O_STRING;
1537 o_addstr(output, arg, p - arg);
1538 debug_print_list("expand_vars_to_list[1]", output, n);
1540 p = strchr(p, SPECIAL_VAR_SYMBOL);
1542 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
1543 /* "$@" is special. Even if quoted, it can still
1544 * expand to nothing (not even an empty string) */
1545 if ((first_ch & 0x7f) != '@')
1546 ored_ch |= first_ch;
1548 switch (first_ch & 0x7f) {
1549 /* Highest bit in first_ch indicates that var is double-quoted */
1551 val = utoa(G.root_pid);
1553 case '!': /* bg pid */
1554 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
1556 case '?': /* exitcode */
1557 val = utoa(G.last_return_code);
1559 case '#': /* argc */
1560 if (arg[1] != SPECIAL_VAR_SYMBOL)
1561 /* actually, it's a ${#var} */
1563 val = utoa(G.global_argc ? G.global_argc-1 : 0);
1568 if (!G.global_argv[i])
1570 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
1571 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
1572 smallint sv = output->o_quote;
1573 /* unquoted var's contents should be globbed, so don't quote */
1574 output->o_quote = 0;
1575 while (G.global_argv[i]) {
1576 n = expand_on_ifs(output, n, G.global_argv[i]);
1577 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
1578 if (G.global_argv[i++][0] && G.global_argv[i]) {
1579 /* this argv[] is not empty and not last:
1580 * put terminating NUL, start new word */
1581 o_addchr(output, '\0');
1582 debug_print_list("expand_vars_to_list[2]", output, n);
1583 n = o_save_ptr(output, n);
1584 debug_print_list("expand_vars_to_list[3]", output, n);
1587 output->o_quote = sv;
1589 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
1590 * and in this case should treat it like '$*' - see 'else...' below */
1591 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
1593 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1594 if (++i >= G.global_argc)
1596 o_addchr(output, '\0');
1597 debug_print_list("expand_vars_to_list[4]", output, n);
1598 n = o_save_ptr(output, n);
1600 } else { /* quoted $*: add as one word */
1602 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1603 if (!G.global_argv[++i])
1606 o_addchr(output, G.ifs[0]);
1610 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
1611 /* "Empty variable", used to make "" etc to not disappear */
1615 #if ENABLE_HUSH_TICK
1616 case '`': { /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
1617 struct in_str input;
1620 //TODO: can we just stuff it into "output" directly?
1621 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
1622 setup_string_in_str(&input, arg);
1623 process_command_subs(&subst_result, &input, NULL);
1624 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
1625 val = subst_result.data;
1629 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
1631 bool exp_len = false, exp_null = false;
1632 char *var = arg, exp_save, exp_op, *exp_word;
1635 arg[0] = first_ch & 0x7f;
1637 /* prepare for expansions */
1638 if (var[0] == '#') {
1639 /* handle length expansion ${#var} */
1643 /* maybe handle parameter expansion */
1644 exp_off = strcspn(var, ":-=+?");
1648 exp_save = var[exp_off];
1649 exp_null = exp_save == ':';
1650 exp_word = var + exp_off;
1651 if (exp_null) ++exp_word;
1652 exp_op = *exp_word++;
1653 var[exp_off] = '\0';
1657 /* lookup the variable in question */
1658 if (isdigit(var[0])) {
1660 if (i < G.global_argc)
1661 val = G.global_argv[i];
1662 /* else val remains NULL: $N with too big N */
1664 val = lookup_param(var);
1666 /* handle any expansions */
1668 debug_printf_expand("expand: length of '%s' = ", val);
1669 val = utoa(val ? strlen(val) : 0);
1670 debug_printf_expand("%s\n", val);
1671 } else if (exp_off) {
1672 /* we need to do an expansion */
1673 int exp_test = (!val || (exp_null && !val[0]));
1675 exp_test = !exp_test;
1676 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
1677 exp_null ? "true" : "false", exp_test);
1680 maybe_die(var, *exp_word ? exp_word : "parameter null or not set");
1684 if (exp_op == '=') {
1685 if (isdigit(var[0]) || var[0] == '#') {
1686 maybe_die(var, "special vars cannot assign in this way");
1689 char *new_var = xmalloc(strlen(var) + strlen(val) + 2);
1690 sprintf(new_var, "%s=%s", var, val);
1691 set_local_var(new_var, -1);
1695 var[exp_off] = exp_save;
1700 #if ENABLE_HUSH_TICK
1703 if (!(first_ch & 0x80)) { /* unquoted $VAR */
1704 debug_printf_expand("unquoted '%s', output->o_quote:%d\n", val, output->o_quote);
1706 /* unquoted var's contents should be globbed, so don't quote */
1707 smallint sv = output->o_quote;
1708 output->o_quote = 0;
1709 n = expand_on_ifs(output, n, val);
1711 output->o_quote = sv;
1713 } else { /* quoted $VAR, val will be appended below */
1714 debug_printf_expand("quoted '%s', output->o_quote:%d\n", val, output->o_quote);
1719 o_addQstr(output, val, strlen(val));
1721 /* Do the check to avoid writing to a const string */
1722 if (p && *p != SPECIAL_VAR_SYMBOL)
1723 *p = SPECIAL_VAR_SYMBOL;
1725 #if ENABLE_HUSH_TICK
1726 o_free(&subst_result);
1729 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
1732 debug_print_list("expand_vars_to_list[a]", output, n);
1733 /* this part is literal, and it was already pre-quoted
1734 * if needed (much earlier), do not use o_addQstr here! */
1735 o_addstr(output, arg, strlen(arg) + 1);
1736 debug_print_list("expand_vars_to_list[b]", output, n);
1737 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
1738 && !(ored_ch & 0x80) /* and all vars were not quoted. */
1741 /* allow to reuse list[n] later without re-growth */
1742 output->has_empty_slot = 1;
1744 o_addchr(output, '\0');
1749 static char **expand_variables(char **argv, int or_mask)
1754 o_string output = NULL_O_STRING;
1756 if (or_mask & 0x100) {
1757 output.o_quote = 1; /* protect against globbing for "$var" */
1758 /* (unquoted $var will temporarily switch it off) */
1765 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
1768 debug_print_list("expand_variables", &output, n);
1770 /* output.data (malloced in one block) gets returned in "list" */
1771 list = o_finalize_list(&output, n);
1772 debug_print_strings("expand_variables[1]", list);
1776 static char **expand_strvec_to_strvec(char **argv)
1778 return expand_variables(argv, 0x100);
1781 /* Used for expansion of right hand of assignments */
1782 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
1784 static char *expand_string_to_string(const char *str)
1786 char *argv[2], **list;
1788 argv[0] = (char*)str;
1790 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
1792 if (!list[0] || list[1])
1793 bb_error_msg_and_die("BUG in varexp2");
1794 /* actually, just move string 2*sizeof(char*) bytes back */
1795 overlapping_strcpy((char*)list, list[0]);
1796 debug_printf_expand("string_to_string='%s'\n", (char*)list);
1800 /* Used for "eval" builtin */
1801 static char* expand_strvec_to_string(char **argv)
1805 list = expand_variables(argv, 0x80);
1806 /* Convert all NULs to spaces */
1811 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
1812 bb_error_msg_and_die("BUG in varexp3");
1813 list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
1817 overlapping_strcpy((char*)list, list[0]);
1818 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
1822 static char **expand_assignments(char **argv, int count)
1826 /* Expand assignments into one string each */
1827 for (i = 0; i < count; i++) {
1828 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
1834 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
1835 * and stderr if they are redirected. */
1836 static int setup_redirects(struct command *prog, int squirrel[])
1839 struct redir_struct *redir;
1841 for (redir = prog->redirects; redir; redir = redir->next) {
1842 if (redir->dup == -1 && redir->rd_filename == NULL) {
1843 /* something went wrong in the parse. Pretend it didn't happen */
1846 if (redir->dup == -1) {
1848 mode = redir_table[redir->rd_type].mode;
1849 //TODO: check redir for names like '\\'
1850 p = expand_string_to_string(redir->rd_filename);
1851 openfd = open_or_warn(p, mode);
1854 /* this could get lost if stderr has been redirected, but
1855 bash and ash both lose it as well (though zsh doesn't!) */
1859 openfd = redir->dup;
1862 if (openfd != redir->fd) {
1863 if (squirrel && redir->fd < 3) {
1864 squirrel[redir->fd] = dup(redir->fd);
1867 //close(openfd); // close(-3) ??!
1869 dup2(openfd, redir->fd);
1870 if (redir->dup == -1)
1878 static void restore_redirects(int squirrel[])
1881 for (i = 0; i < 3; i++) {
1884 /* We simply die on error */
1891 #if !defined(DEBUG_CLEAN)
1892 #define free_pipe_list(head, indent) free_pipe_list(head)
1893 #define free_pipe(pi, indent) free_pipe(pi)
1895 static int free_pipe_list(struct pipe *head, int indent);
1897 /* return code is the exit status of the pipe */
1898 static int free_pipe(struct pipe *pi, int indent)
1901 struct command *command;
1902 struct redir_struct *r, *rnext;
1903 int a, i, ret_code = 0;
1905 if (pi->stopped_cmds > 0)
1907 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
1908 for (i = 0; i < pi->num_cmds; i++) {
1909 command = &pi->cmds[i];
1910 debug_printf_clean("%s command %d:\n", indenter(indent), i);
1911 if (command->argv) {
1912 for (a = 0, p = command->argv; *p; a++, p++) {
1913 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
1915 free_strings(command->argv);
1916 command->argv = NULL;
1917 } else if (command->group) {
1918 debug_printf_clean("%s begin group (grp_type:%d)\n", indenter(indent), command->grp_type);
1919 ret_code = free_pipe_list(command->group, indent+3);
1920 debug_printf_clean("%s end group\n", indenter(indent));
1922 debug_printf_clean("%s (nil)\n", indenter(indent));
1924 for (r = command->redirects; r; r = rnext) {
1925 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->rd_type].descrip);
1927 /* guard against the case >$FOO, where foo is unset or blank */
1928 if (r->rd_filename) {
1929 debug_printf_clean(" %s\n", r->rd_filename);
1930 free(r->rd_filename);
1931 r->rd_filename = NULL;
1934 debug_printf_clean("&%d\n", r->dup);
1939 command->redirects = NULL;
1941 free(pi->cmds); /* children are an array, they get freed all at once */
1950 static int free_pipe_list(struct pipe *head, int indent)
1952 int rcode = 0; /* if list has no members */
1953 struct pipe *pi, *next;
1955 for (pi = head; pi; pi = next) {
1957 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
1959 rcode = free_pipe(pi, indent);
1960 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
1962 /*pi->next = NULL;*/
1970 typedef struct nommu_save_t {
1976 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
1977 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
1978 #define pseudo_exec(nommu_save, command, argv_expanded) \
1979 pseudo_exec(command, argv_expanded)
1982 /* Called after [v]fork() in run_pipe(), or from builtin_exec().
1984 * XXX no exit() here. If you don't exec, use _exit instead.
1985 * The at_exit handlers apparently confuse the calling process,
1986 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
1987 static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded) NORETURN;
1988 static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded)
1992 const struct built_in_command *x;
1994 /* If a variable is assigned in a forest, and nobody listens,
1995 * was it ever really set?
1997 if (!argv[assignment_cnt])
1998 _exit(EXIT_SUCCESS);
2000 new_env = expand_assignments(argv, assignment_cnt);
2002 putenv_all(new_env);
2003 free(new_env); /* optional */
2005 nommu_save->new_env = new_env;
2006 nommu_save->old_env = putenv_all_and_save_old(new_env);
2008 if (argv_expanded) {
2009 argv = argv_expanded;
2011 argv = expand_strvec_to_strvec(argv);
2013 nommu_save->argv = argv;
2018 * Check if the command matches any of the builtins.
2019 * Depending on context, this might be redundant. But it's
2020 * easier to waste a few CPU cycles than it is to figure out
2021 * if this is one of those cases.
2023 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2024 if (strcmp(argv[0], x->cmd) == 0) {
2025 debug_printf_exec("running builtin '%s'\n", argv[0]);
2026 rcode = x->function(argv);
2032 /* Check if the command matches any busybox applets */
2033 #if ENABLE_FEATURE_SH_STANDALONE
2034 if (strchr(argv[0], '/') == NULL) {
2035 int a = find_applet_by_name(argv[0]);
2037 if (APPLET_IS_NOEXEC(a)) {
2038 debug_printf_exec("running applet '%s'\n", argv[0]);
2039 // is it ok that run_applet_no_and_exit() does exit(), not _exit()?
2040 run_applet_no_and_exit(a, argv);
2042 /* re-exec ourselves with the new arguments */
2043 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
2044 execvp(bb_busybox_exec_path, argv);
2045 /* If they called chroot or otherwise made the binary no longer
2046 * executable, fall through */
2051 debug_printf_exec("execing '%s'\n", argv[0]);
2052 execvp(argv[0], argv);
2053 bb_perror_msg("can't exec '%s'", argv[0]);
2054 _exit(EXIT_FAILURE);
2057 static int run_list(struct pipe *pi);
2059 /* Called after [v]fork() in run_pipe()
2061 static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded) NORETURN;
2062 static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded)
2065 pseudo_exec_argv(nommu_save, command->argv, command->assignment_cnt, argv_expanded);
2067 if (command->group) {
2069 bb_error_msg_and_die("nested lists are not supported on NOMMU");
2072 debug_printf_exec("pseudo_exec: run_list\n");
2073 rcode = run_list(command->group);
2074 /* OK to leak memory by not calling free_pipe_list,
2075 * since this process is about to exit */
2080 /* Can happen. See what bash does with ">foo" by itself. */
2081 debug_printf("trying to pseudo_exec null command\n");
2082 _exit(EXIT_SUCCESS);
2086 static const char *get_cmdtext(struct pipe *pi)
2092 /* This is subtle. ->cmdtext is created only on first backgrounding.
2093 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
2094 * On subsequent bg argv is trashed, but we won't use it */
2097 argv = pi->cmds[0].argv;
2098 if (!argv || !argv[0]) {
2099 pi->cmdtext = xzalloc(1);
2104 do len += strlen(*argv) + 1; while (*++argv);
2105 pi->cmdtext = p = xmalloc(len);
2106 argv = pi->cmds[0].argv;
2108 len = strlen(*argv);
2109 memcpy(p, *argv, len);
2117 static void insert_bg_job(struct pipe *pi)
2119 struct pipe *thejob;
2122 /* Linear search for the ID of the job to use */
2124 for (thejob = G.job_list; thejob; thejob = thejob->next)
2125 if (thejob->jobid >= pi->jobid)
2126 pi->jobid = thejob->jobid + 1;
2128 /* Add thejob to the list of running jobs */
2130 thejob = G.job_list = xmalloc(sizeof(*thejob));
2132 for (thejob = G.job_list; thejob->next; thejob = thejob->next)
2134 thejob->next = xmalloc(sizeof(*thejob));
2135 thejob = thejob->next;
2138 /* Physically copy the struct job */
2139 memcpy(thejob, pi, sizeof(struct pipe));
2140 thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
2141 /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
2142 for (i = 0; i < pi->num_cmds; i++) {
2143 // TODO: do we really need to have so many fields which are just dead weight
2144 // at execution stage?
2145 thejob->cmds[i].pid = pi->cmds[i].pid;
2146 /* all other fields are not used and stay zero */
2148 thejob->next = NULL;
2149 thejob->cmdtext = xstrdup(get_cmdtext(pi));
2151 /* We don't wait for background thejobs to return -- append it
2152 to the list of backgrounded thejobs and leave it alone */
2153 printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
2154 G.last_bg_pid = thejob->cmds[0].pid;
2155 G.last_jobid = thejob->jobid;
2158 static void remove_bg_job(struct pipe *pi)
2160 struct pipe *prev_pipe;
2162 if (pi == G.job_list) {
2163 G.job_list = pi->next;
2165 prev_pipe = G.job_list;
2166 while (prev_pipe->next != pi)
2167 prev_pipe = prev_pipe->next;
2168 prev_pipe->next = pi->next;
2171 G.last_jobid = G.job_list->jobid;
2176 /* Remove a backgrounded job */
2177 static void delete_finished_bg_job(struct pipe *pi)
2180 pi->stopped_cmds = 0;
2186 /* Check to see if any processes have exited -- if they
2187 * have, figure out why and see if a job has completed */
2188 static int checkjobs(struct pipe* fg_pipe)
2198 attributes = WUNTRACED;
2199 if (fg_pipe == NULL)
2200 attributes |= WNOHANG;
2202 /* Do we do this right?
2203 * bash-3.00# sleep 20 | false
2205 * [3]+ Stopped sleep 20 | false
2206 * bash-3.00# echo $?
2207 * 1 <========== bg pipe is not fully done, but exitcode is already known!
2210 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
2211 //are stopped. Testcase: "cat | cat" in a script (not on command line)
2212 // + killall -STOP cat
2215 // TODO: safe_waitpid?
2216 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
2218 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
2220 if (WIFSTOPPED(status))
2221 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
2222 childpid, WSTOPSIG(status), WEXITSTATUS(status));
2223 if (WIFSIGNALED(status))
2224 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
2225 childpid, WTERMSIG(status), WEXITSTATUS(status));
2226 if (WIFEXITED(status))
2227 debug_printf_jobs("pid %d exited, exitcode %d\n",
2228 childpid, WEXITSTATUS(status));
2230 /* Were we asked to wait for fg pipe? */
2232 for (i = 0; i < fg_pipe->num_cmds; i++) {
2233 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
2234 if (fg_pipe->cmds[i].pid != childpid)
2236 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
2238 fg_pipe->cmds[i].pid = 0;
2239 fg_pipe->alive_cmds--;
2240 if (i == fg_pipe->num_cmds - 1) {
2241 /* last process gives overall exitstatus */
2242 rcode = WEXITSTATUS(status);
2243 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
2246 fg_pipe->cmds[i].is_stopped = 1;
2247 fg_pipe->stopped_cmds++;
2249 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
2250 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
2251 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
2252 /* All processes in fg pipe have exited/stopped */
2254 if (fg_pipe->alive_cmds)
2255 insert_bg_job(fg_pipe);
2259 /* There are still running processes in the fg pipe */
2260 goto wait_more; /* do waitpid again */
2262 /* it wasnt fg_pipe, look for process in bg pipes */
2266 /* We asked to wait for bg or orphaned children */
2267 /* No need to remember exitcode in this case */
2268 for (pi = G.job_list; pi; pi = pi->next) {
2269 for (i = 0; i < pi->num_cmds; i++) {
2270 if (pi->cmds[i].pid == childpid)
2271 goto found_pi_and_prognum;
2274 /* Happens when shell is used as init process (init=/bin/sh) */
2275 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
2276 continue; /* do waitpid again */
2278 found_pi_and_prognum:
2281 pi->cmds[i].pid = 0;
2283 if (!pi->alive_cmds) {
2284 printf(JOB_STATUS_FORMAT, pi->jobid,
2285 "Done", pi->cmdtext);
2286 delete_finished_bg_job(pi);
2290 pi->cmds[i].is_stopped = 1;
2294 } /* while (waitpid succeeds)... */
2296 /* wait found no children or failed */
2298 if (childpid && errno != ECHILD)
2299 bb_perror_msg("waitpid");
2304 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
2307 int rcode = checkjobs(fg_pipe);
2308 /* Job finished, move the shell to the foreground */
2309 p = getpgid(0); /* pgid of our process */
2310 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
2311 tcsetpgrp(G.interactive_fd, p);
2316 /* run_pipe() starts all the jobs, but doesn't wait for anything
2317 * to finish. See checkjobs().
2319 * return code is normally -1, when the caller has to wait for children
2320 * to finish to determine the exit status of the pipe. If the pipe
2321 * is a simple builtin command, however, the action is done by the
2322 * time run_pipe returns, and the exit code is provided as the
2325 * The input of the pipe is always stdin, the output is always
2326 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
2327 * because it tries to avoid running the command substitution in
2328 * subshell, when that is in fact necessary. The subshell process
2329 * now has its stdout directed to the input of the appropriate pipe,
2330 * so this routine is noticeably simpler.
2332 * Returns -1 only if started some children. IOW: we have to
2333 * mask out retvals of builtins etc with 0xff!
2335 static int run_pipe(struct pipe *pi)
2339 int pipefds[2]; /* pipefds[0] is for reading */
2340 struct command *command;
2341 char **argv_expanded;
2343 const struct built_in_command *x;
2345 /* it is not always needed, but we aim to smaller code */
2346 int squirrel[] = { -1, -1, -1 };
2348 const int single_and_fg = (pi->num_cmds == 1 && pi->followup != PIPE_BG);
2350 debug_printf_exec("run_pipe start: single_and_fg=%d\n", single_and_fg);
2356 pi->stopped_cmds = 0;
2358 /* Check if this is a simple builtin (not part of a pipe).
2359 * Builtins within pipes have to fork anyway, and are handled in
2360 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
2362 command = &(pi->cmds[0]);
2364 #if ENABLE_HUSH_FUNCTIONS
2365 if (single_and_fg && command->group && command->grp_type == GRP_FUNCTION) {
2366 /* We "execute" function definition */
2367 bb_error_msg("here we ought to remember function definition, and go on");
2368 return EXIT_SUCCESS;
2372 if (single_and_fg && command->group && command->grp_type == GRP_NORMAL) {
2373 debug_printf("non-subshell grouping\n");
2374 setup_redirects(command, squirrel);
2375 debug_printf_exec(": run_list\n");
2376 rcode = run_list(command->group) & 0xff;
2377 restore_redirects(squirrel);
2378 debug_printf_exec("run_pipe return %d\n", rcode);
2379 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2383 argv = command->argv;
2384 argv_expanded = NULL;
2386 if (single_and_fg && argv != NULL) {
2387 char **new_env = NULL;
2388 char **old_env = NULL;
2390 i = command->assignment_cnt;
2391 if (i != 0 && argv[i] == NULL) {
2392 /* assignments, but no command: set local environment */
2393 for (i = 0; argv[i] != NULL; i++) {
2394 debug_printf("local environment set: %s\n", argv[i]);
2395 p = expand_string_to_string(argv[i]);
2396 set_local_var(p, 0);
2398 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
2401 /* Expand the rest into (possibly) many strings each */
2402 argv_expanded = expand_strvec_to_strvec(argv + i);
2404 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2405 if (strcmp(argv_expanded[0], x->cmd) != 0)
2407 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
2408 debug_printf("exec with redirects only\n");
2409 setup_redirects(command, NULL);
2410 rcode = EXIT_SUCCESS;
2411 goto clean_up_and_ret1;
2413 debug_printf("builtin inline %s\n", argv_expanded[0]);
2414 /* XXX setup_redirects acts on file descriptors, not FILEs.
2415 * This is perfect for work that comes after exec().
2416 * Is it really safe for inline use? Experimentally,
2417 * things seem to work with glibc. */
2418 setup_redirects(command, squirrel);
2419 new_env = expand_assignments(argv, command->assignment_cnt);
2420 old_env = putenv_all_and_save_old(new_env);
2421 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv_expanded[1]);
2422 rcode = x->function(argv_expanded) & 0xff;
2423 #if ENABLE_FEATURE_SH_STANDALONE
2426 restore_redirects(squirrel);
2427 free_strings_and_unsetenv(new_env, 1);
2428 putenv_all(old_env);
2429 free(old_env); /* not free_strings()! */
2431 free(argv_expanded);
2432 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
2433 debug_printf_exec("run_pipe return %d\n", rcode);
2436 #if ENABLE_FEATURE_SH_STANDALONE
2437 i = find_applet_by_name(argv_expanded[0]);
2438 if (i >= 0 && APPLET_IS_NOFORK(i)) {
2439 setup_redirects(command, squirrel);
2440 save_nofork_data(&G.nofork_save);
2441 new_env = expand_assignments(argv, command->assignment_cnt);
2442 old_env = putenv_all_and_save_old(new_env);
2443 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
2444 rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
2445 goto clean_up_and_ret;
2450 /* NB: argv_expanded may already be created, and that
2451 * might include `cmd` runs! Do not rerun it! We *must*
2452 * use argv_expanded if it's non-NULL */
2454 /* Disable job control signals for shell (parent) and
2455 * for initial child code after fork */
2456 set_jobctrl_sighandler(SIG_IGN);
2458 /* Going to fork a child per each pipe member */
2462 for (i = 0; i < pi->num_cmds; i++) {
2464 volatile nommu_save_t nommu_save;
2465 nommu_save.new_env = NULL;
2466 nommu_save.old_env = NULL;
2467 nommu_save.argv = NULL;
2469 command = &(pi->cmds[i]);
2470 if (command->argv) {
2471 debug_printf_exec(": pipe member '%s' '%s'...\n", command->argv[0], command->argv[1]);
2473 debug_printf_exec(": pipe member with no argv\n");
2475 /* pipes are inserted between pairs of commands */
2478 if ((i + 1) < pi->num_cmds)
2481 command->pid = BB_MMU ? fork() : vfork();
2482 if (!command->pid) { /* child */
2483 if (ENABLE_HUSH_JOB)
2484 die_sleep = 0; /* let nofork's xfuncs die */
2486 /* Every child adds itself to new process group
2487 * with pgid == pid_of_first_child_in_pipe */
2488 if (G.run_list_level == 1 && G.interactive_fd) {
2490 /* Don't do pgrp restore anymore on fatal signals */
2491 set_fatal_sighandler(SIG_DFL);
2493 if (pgrp < 0) /* true for 1st process only */
2495 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
2496 /* We do it in *every* child, not just first,
2498 tcsetpgrp(G.interactive_fd, pgrp);
2502 xmove_fd(nextin, 0);
2503 xmove_fd(pipefds[1], 1); /* write end */
2505 close(pipefds[0]); /* read end */
2506 /* Like bash, explicit redirects override pipes,
2507 * and the pipe fd is available for dup'ing. */
2508 setup_redirects(command, NULL);
2510 /* Restore default handlers just prior to exec */
2511 set_jobctrl_sighandler(SIG_DFL);
2512 set_misc_sighandler(SIG_DFL);
2513 signal(SIGCHLD, SIG_DFL);
2514 /* Stores to nommu_save list of env vars putenv'ed
2515 * (NOMMU, on MMU we don't need that) */
2516 /* cast away volatility... */
2517 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
2518 /* pseudo_exec() does not return */
2522 /* Clean up after vforked child */
2523 free(nommu_save.argv);
2524 free_strings_and_unsetenv(nommu_save.new_env, 1);
2525 putenv_all(nommu_save.old_env);
2527 free(argv_expanded);
2528 argv_expanded = NULL;
2529 if (command->pid < 0) { /* [v]fork failed */
2530 /* Clearly indicate, was it fork or vfork */
2531 bb_perror_msg(BB_MMU ? "fork" : "vfork");
2535 /* Second and next children need to know pid of first one */
2537 pi->pgrp = command->pid;
2543 if ((i + 1) < pi->num_cmds)
2544 close(pipefds[1]); /* write end */
2545 /* Pass read (output) pipe end to next iteration */
2546 nextin = pipefds[0];
2549 if (!pi->alive_cmds) {
2550 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
2554 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
2558 #ifndef debug_print_tree
2559 static void debug_print_tree(struct pipe *pi, int lvl)
2561 static const char *const PIPE[] = {
2567 static const char *RES[] = {
2568 [RES_NONE ] = "NONE" ,
2571 [RES_THEN ] = "THEN" ,
2572 [RES_ELIF ] = "ELIF" ,
2573 [RES_ELSE ] = "ELSE" ,
2576 #if ENABLE_HUSH_LOOPS
2577 [RES_FOR ] = "FOR" ,
2578 [RES_WHILE] = "WHILE",
2579 [RES_UNTIL] = "UNTIL",
2581 [RES_DONE ] = "DONE" ,
2583 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2586 #if ENABLE_HUSH_CASE
2587 [RES_CASE ] = "CASE" ,
2588 [RES_MATCH] = "MATCH",
2589 [RES_CASEI] = "CASEI",
2590 [RES_ESAC ] = "ESAC" ,
2592 [RES_XXXX ] = "XXXX" ,
2593 [RES_SNTX ] = "SNTX" ,
2595 static const char *const GRPTYPE[] = {
2598 #if ENABLE_HUSH_FUNCTIONS
2607 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2608 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2610 while (prn < pi->num_cmds) {
2611 struct command *command = &pi->cmds[prn];
2612 char **argv = command->argv;
2614 fprintf(stderr, "%*s prog %d assignment_cnt:%d", lvl*2, "", prn, command->assignment_cnt);
2615 if (command->group) {
2616 fprintf(stderr, " group %s: (argv=%p)\n",
2617 GRPTYPE[command->grp_type],
2619 debug_print_tree(command->group, lvl+1);
2623 if (argv) while (*argv) {
2624 fprintf(stderr, " '%s'", *argv);
2627 fprintf(stderr, "\n");
2636 /* NB: called by pseudo_exec, and therefore must not modify any
2637 * global data until exec/_exit (we can be a child after vfork!) */
2638 static int run_list(struct pipe *pi)
2640 #if ENABLE_HUSH_CASE
2641 char *case_word = NULL;
2643 #if ENABLE_HUSH_LOOPS
2644 struct pipe *loop_top = NULL;
2645 char *for_varname = NULL;
2646 char **for_lcur = NULL;
2647 char **for_list = NULL;
2649 smallint flag_skip = 1;
2650 smalluint rcode = 0; /* probably just for compiler */
2651 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
2652 smalluint cond_code = 0;
2654 enum { cond_code = 0, };
2656 /*enum reserved_style*/ smallint rword = RES_NONE;
2657 /*enum reserved_style*/ smallint skip_more_for_this_rword = RES_XXXX;
2659 debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
2661 #if ENABLE_HUSH_LOOPS
2662 /* Check syntax for "for" */
2663 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
2664 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
2666 /* current word is FOR or IN (BOLD in comments below) */
2667 if (cpipe->next == NULL) {
2668 syntax("malformed for");
2669 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
2672 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
2673 if (cpipe->next->res_word == RES_DO)
2675 /* next word is not "do". It must be "in" then ("FOR v in ...") */
2676 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
2677 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
2679 syntax("malformed for");
2680 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
2686 /* Past this point, all code paths should jump to ret: label
2687 * in order to return, no direct "return" statements please.
2688 * This helps to ensure that no memory is leaked. */
2691 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
2692 * We are saving state before entering outermost list ("while...done")
2693 * so that ctrl-Z will correctly background _entire_ outermost list,
2694 * not just a part of it (like "sleep 1 | exit 2") */
2695 if (++G.run_list_level == 1 && G.interactive_fd) {
2696 if (sigsetjmp(G.toplevel_jb, 1)) {
2697 /* ctrl-Z forked and we are parent; or ctrl-C.
2698 * Sighandler has longjmped us here */
2699 signal(SIGINT, SIG_IGN);
2700 signal(SIGTSTP, SIG_IGN);
2701 /* Restore level (we can be coming from deep inside
2703 G.run_list_level = 1;
2704 #if ENABLE_FEATURE_SH_STANDALONE
2705 if (G.nofork_save.saved) { /* if save area is valid */
2706 debug_printf_jobs("exiting nofork early\n");
2707 restore_nofork_data(&G.nofork_save);
2710 if (G.ctrl_z_flag) {
2711 /* ctrl-Z has forked and stored pid of the child in pi->pid.
2712 * Remember this child as background job */
2715 /* ctrl-C. We just stop doing whatever we were doing */
2718 USE_HUSH_LOOPS(loop_top = NULL;)
2719 USE_HUSH_LOOPS(G.depth_of_loop = 0;)
2723 /* ctrl-Z handler will store pid etc in pi */
2724 G.toplevel_list = pi;
2726 #if ENABLE_FEATURE_SH_STANDALONE
2727 G.nofork_save.saved = 0; /* in case we will run a nofork later */
2729 signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
2730 signal(SIGINT, handler_ctrl_c);
2734 /* Go through list of pipes, (maybe) executing them. */
2735 for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
2736 IF_HAS_KEYWORDS(rword = pi->res_word;)
2737 IF_HAS_NO_KEYWORDS(rword = RES_NONE;)
2738 debug_printf_exec(": rword=%d cond_code=%d skip_more=%d\n",
2739 rword, cond_code, skip_more_for_this_rword);
2740 #if ENABLE_HUSH_LOOPS
2741 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
2742 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
2744 /* start of a loop: remember where loop starts */
2749 if (rword == skip_more_for_this_rword && flag_skip) {
2750 if (pi->followup == PIPE_SEQ)
2752 /* it is "<false> && CMD" or "<true> || CMD"
2753 * and we should not execute CMD */
2757 skip_more_for_this_rword = RES_XXXX;
2760 if (rword == RES_THEN) {
2761 /* "if <false> THEN cmd": skip cmd */
2765 if (rword == RES_ELSE || rword == RES_ELIF) {
2766 /* "if <true> then ... ELSE/ELIF cmd":
2767 * skip cmd and all following ones */
2772 #if ENABLE_HUSH_LOOPS
2773 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
2775 /* first loop through for */
2777 static const char encoded_dollar_at[] ALIGN1 = {
2778 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
2779 }; /* encoded representation of "$@" */
2780 static const char *const encoded_dollar_at_argv[] = {
2781 encoded_dollar_at, NULL
2782 }; /* argv list with one element: "$@" */
2785 vals = (char**)encoded_dollar_at_argv;
2786 if (pi->next->res_word == RES_IN) {
2787 /* if no variable values after "in" we skip "for" */
2788 if (!pi->next->cmds[0].argv)
2790 vals = pi->next->cmds[0].argv;
2791 } /* else: "for var; do..." -> assume "$@" list */
2792 /* create list of variable values */
2793 debug_print_strings("for_list made from", vals);
2794 for_list = expand_strvec_to_strvec(vals);
2795 for_lcur = for_list;
2796 debug_print_strings("for_list", for_list);
2797 for_varname = pi->cmds[0].argv[0];
2798 pi->cmds[0].argv[0] = NULL;
2800 free(pi->cmds[0].argv[0]);
2802 /* "for" loop is over, clean up */
2806 pi->cmds[0].argv[0] = for_varname;
2809 /* insert next value from for_lcur */
2810 //TODO: does it need escaping?
2811 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
2812 pi->cmds[0].assignment_cnt = 1;
2814 if (rword == RES_IN) /* "for v IN list;..." - "in" has no cmds anyway */
2816 if (rword == RES_DONE) {
2817 continue; /* "done" has no cmds too */
2820 #if ENABLE_HUSH_CASE
2821 if (rword == RES_CASE) {
2822 case_word = expand_strvec_to_string(pi->cmds->argv);
2825 if (rword == RES_MATCH) {
2828 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
2830 /* all prev words didn't match, does this one match? */
2831 argv = pi->cmds->argv;
2833 char *pattern = expand_string_to_string(*argv);
2834 /* TODO: which FNM_xxx flags to use? */
2835 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
2837 if (cond_code == 0) { /* match! we will execute this branch */
2838 free(case_word); /* make future "word)" stop */
2846 if (rword == RES_CASEI) { /* inside of a case branch */
2848 continue; /* not matched yet, skip this pipe */
2851 if (pi->num_cmds == 0)
2854 /* After analyzing all keywords and conditions, we decided
2855 * to execute this pipe. NB: has to do checkjobs(NULL)
2856 * after run_pipe() to collect any background children,
2857 * even if list execution is to be stopped. */
2858 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
2861 #if ENABLE_HUSH_LOOPS
2862 G.flag_break_continue = 0;
2864 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
2866 /* we only ran a builtin: rcode is already known
2867 * and we don't need to wait for anything. */
2868 #if ENABLE_HUSH_LOOPS
2869 /* was it "break" or "continue"? */
2870 if (G.flag_break_continue) {
2871 smallint fbc = G.flag_break_continue;
2872 /* we might fall into outer *loop*,
2873 * don't want to break it too */
2875 G.depth_break_continue--;
2876 if (G.depth_break_continue == 0)
2877 G.flag_break_continue = 0;
2878 /* else: e.g. "continue 2" should *break* once, *then* continue */
2879 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
2880 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
2881 goto check_jobs_and_break;
2882 /* "continue": simulate end of loop */
2887 } else if (pi->followup == PIPE_BG) {
2888 /* what does bash do with attempts to background builtins? */
2889 /* even bash 3.2 doesn't do that well with nested bg:
2890 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
2891 * I'm NOT treating inner &'s as jobs */
2893 if (G.run_list_level == 1)
2896 rcode = 0; /* EXIT_SUCCESS */
2899 if (G.run_list_level == 1 && G.interactive_fd) {
2900 /* waits for completion, then fg's main shell */
2901 rcode = checkjobs_and_fg_shell(pi);
2902 debug_printf_exec(": checkjobs_and_fg_shell returned %d\n", rcode);
2905 { /* this one just waits for completion */
2906 rcode = checkjobs(pi);
2907 debug_printf_exec(": checkjobs returned %d\n", rcode);
2911 debug_printf_exec(": setting last_return_code=%d\n", rcode);
2912 G.last_return_code = rcode;
2914 /* Analyze how result affects subsequent commands */
2916 if (rword == RES_IF || rword == RES_ELIF)
2919 #if ENABLE_HUSH_LOOPS
2920 if (rword == RES_WHILE) {
2922 rcode = 0; /* "while false; do...done" - exitcode 0 */
2923 goto check_jobs_and_break;
2926 if (rword == RES_UNTIL) {
2928 check_jobs_and_break:
2934 if ((rcode == 0 && pi->followup == PIPE_OR)
2935 || (rcode != 0 && pi->followup == PIPE_AND)
2937 skip_more_for_this_rword = rword;
2943 if (G.ctrl_z_flag) {
2944 /* ctrl-Z forked somewhere in the past, we are the child,
2945 * and now we completed running the list. Exit. */
2950 if (!--G.run_list_level && G.interactive_fd) {
2951 signal(SIGTSTP, SIG_IGN);
2952 signal(SIGINT, SIG_IGN);
2955 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
2956 #if ENABLE_HUSH_LOOPS
2961 #if ENABLE_HUSH_CASE
2967 /* Select which version we will use */
2968 static int run_and_free_list(struct pipe *pi)
2971 debug_printf_exec("run_and_free_list entered\n");
2973 debug_printf_exec(": run_list with %d members\n", pi->num_cmds);
2974 rcode = run_list(pi);
2976 /* free_pipe_list has the side effect of clearing memory.
2977 * In the long run that function can be merged with run_list,
2978 * but doing that now would hobble the debugging effort. */
2979 free_pipe_list(pi, /* indent: */ 0);
2980 debug_printf_exec("run_and_free_list return %d\n", rcode);
2985 /* Peek ahead in the in_str to find out if we have a "&n" construct,
2986 * as in "2>&1", that represents duplicating a file descriptor.
2987 * Return either -2 (syntax error), -1 (no &), or the number found.
2989 static int redirect_dup_num(struct in_str *input)
2991 int ch, d = 0, ok = 0;
2993 if (ch != '&') return -1;
2995 i_getch(input); /* get the & */
2999 return -3; /* "-" represents "close me" */
3001 while (isdigit(ch)) {
3002 d = d*10 + (ch-'0');
3009 bb_error_msg("ambiguous redirect");
3013 /* The src parameter allows us to peek forward to a possible &n syntax
3014 * for file descriptor duplication, e.g., "2>&1".
3015 * Return code is 0 normally, 1 if a syntax error is detected in src.
3016 * Resource errors (in xmalloc) cause the process to exit */
3017 static int setup_redirect(struct parse_context *ctx, int fd, redir_type style,
3018 struct in_str *input)
3020 struct command *command = ctx->command;
3021 struct redir_struct *redir = command->redirects;
3022 struct redir_struct *last_redir = NULL;
3024 /* Create a new redir_struct and drop it onto the end of the linked list */
3027 redir = redir->next;
3029 redir = xzalloc(sizeof(struct redir_struct));
3030 /* redir->next = NULL; */
3031 /* redir->rd_filename = NULL; */
3033 last_redir->next = redir;
3035 command->redirects = redir;
3038 redir->rd_type = style;
3039 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
3041 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
3043 /* Check for a '2>&1' type redirect */
3044 redir->dup = redirect_dup_num(input);
3045 if (redir->dup == -2)
3046 return 1; /* syntax error */
3047 if (redir->dup != -1) {
3048 /* Erik had a check here that the file descriptor in question
3049 * is legit; I postpone that to "run time"
3050 * A "-" representation of "close me" shows up as a -3 here */
3051 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
3053 /* We do _not_ try to open the file that src points to,
3054 * since we need to return and let src be expanded first.
3055 * Set ctx->pending_redirect, so we know what to do at the
3056 * end of the next parsed word. */
3057 ctx->pending_redirect = redir;
3063 static struct pipe *new_pipe(void)
3066 pi = xzalloc(sizeof(struct pipe));
3067 /*pi->followup = 0; - deliberately invalid value */
3068 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3072 /* Command (member of a pipe) is complete. The only possible error here
3073 * is out of memory, in which case xmalloc exits. */
3074 static int done_command(struct parse_context *ctx)
3076 /* The command is really already in the pipe structure, so
3077 * advance the pipe counter and make a new, null command. */
3078 struct pipe *pi = ctx->pipe;
3079 struct command *command = ctx->command;
3082 if (command->group == NULL
3083 && command->argv == NULL
3084 && command->redirects == NULL
3086 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3087 return pi->num_cmds;
3090 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3092 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3095 /* Only real trickiness here is that the uncommitted
3096 * command structure is not counted in pi->num_cmds. */
3097 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3098 command = &pi->cmds[pi->num_cmds];
3099 memset(command, 0, sizeof(*command));
3101 ctx->command = command;
3102 /* but ctx->pipe and ctx->list_head remain unchanged */
3104 return pi->num_cmds; /* used only for 0/nonzero check */
3107 static void done_pipe(struct parse_context *ctx, pipe_style type)
3111 debug_printf_parse("done_pipe entered, followup %d\n", type);
3112 /* Close previous command */
3113 not_null = done_command(ctx);
3114 ctx->pipe->followup = type;
3115 IF_HAS_KEYWORDS(ctx->pipe->pi_inverted = ctx->ctx_inverted;)
3116 IF_HAS_KEYWORDS(ctx->ctx_inverted = 0;)
3117 IF_HAS_KEYWORDS(ctx->pipe->res_word = ctx->ctx_res_w;)
3119 /* Without this check, even just <enter> on command line generates
3120 * tree of three NOPs (!). Which is harmless but annoying.
3121 * IOW: it is safe to do it unconditionally.
3122 * RES_NONE case is for "for a in; do ..." (empty IN set)
3123 * to work, possibly other cases too. */
3124 if (not_null IF_HAS_KEYWORDS(|| ctx->ctx_res_w != RES_NONE)) {
3126 debug_printf_parse("done_pipe: adding new pipe: "
3127 "not_null:%d ctx->ctx_res_w:%d\n",
3128 not_null, ctx->ctx_res_w);
3130 ctx->pipe->next = new_p;
3132 ctx->command = NULL; /* needed! */
3133 /* RES_THEN, RES_DO etc are "sticky" -
3134 * they remain set for commands inside if/while.
3135 * This is used to control execution.
3136 * RES_FOR and RES_IN are NOT sticky (needed to support
3137 * cases where variable or value happens to match a keyword):
3139 #if ENABLE_HUSH_LOOPS
3140 if (ctx->ctx_res_w == RES_FOR
3141 || ctx->ctx_res_w == RES_IN)
3142 ctx->ctx_res_w = RES_NONE;
3144 #if ENABLE_HUSH_CASE
3145 if (ctx->ctx_res_w == RES_MATCH)
3146 ctx->ctx_res_w = RES_CASEI;
3148 /* Create the memory for command, roughly:
3149 * ctx->pipe->cmds = new struct command;
3150 * ctx->command = &ctx->pipe->cmds[0];
3154 debug_printf_parse("done_pipe return\n");
3157 static void initialize_context(struct parse_context *ctx)
3159 memset(ctx, 0, sizeof(*ctx));
3160 ctx->pipe = ctx->list_head = new_pipe();
3161 /* Create the memory for command, roughly:
3162 * ctx->pipe->cmds = new struct command;
3163 * ctx->command = &ctx->pipe->cmds[0];
3169 /* If a reserved word is found and processed, parse context is modified
3170 * and 1 is returned.
3171 * Handles if, then, elif, else, fi, for, while, until, do, done.
3172 * case, function, and select are obnoxious, save those for later.
3175 struct reserved_combo {
3178 unsigned char assignment_flag;
3182 FLAG_END = (1 << RES_NONE ),
3184 FLAG_IF = (1 << RES_IF ),
3185 FLAG_THEN = (1 << RES_THEN ),
3186 FLAG_ELIF = (1 << RES_ELIF ),
3187 FLAG_ELSE = (1 << RES_ELSE ),
3188 FLAG_FI = (1 << RES_FI ),
3190 #if ENABLE_HUSH_LOOPS
3191 FLAG_FOR = (1 << RES_FOR ),
3192 FLAG_WHILE = (1 << RES_WHILE),
3193 FLAG_UNTIL = (1 << RES_UNTIL),
3194 FLAG_DO = (1 << RES_DO ),
3195 FLAG_DONE = (1 << RES_DONE ),
3196 FLAG_IN = (1 << RES_IN ),
3198 #if ENABLE_HUSH_CASE
3199 FLAG_MATCH = (1 << RES_MATCH),
3200 FLAG_ESAC = (1 << RES_ESAC ),
3202 FLAG_START = (1 << RES_XXXX ),
3205 static const struct reserved_combo* match_reserved_word(o_string *word)
3207 /* Mostly a list of accepted follow-up reserved words.
3208 * FLAG_END means we are done with the sequence, and are ready
3209 * to turn the compound list into a command.
3210 * FLAG_START means the word must start a new compound list.
3212 static const struct reserved_combo reserved_list[] = {
3214 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3215 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
3216 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3217 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
3218 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
3219 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3221 #if ENABLE_HUSH_LOOPS
3222 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3223 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3224 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3225 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3226 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
3227 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3229 #if ENABLE_HUSH_CASE
3230 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3231 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3234 const struct reserved_combo *r;
3236 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3237 if (strcmp(word->data, r->literal) == 0)
3242 static int reserved_word(o_string *word, struct parse_context *ctx)
3244 #if ENABLE_HUSH_CASE
3245 static const struct reserved_combo reserved_match = {
3246 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3249 const struct reserved_combo *r;
3251 r = match_reserved_word(word);
3255 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3256 #if ENABLE_HUSH_CASE
3257 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
3258 /* "case word IN ..." - IN part starts first match part */
3259 r = &reserved_match;
3262 if (r->flag == 0) { /* '!' */
3263 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3265 IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
3267 ctx->ctx_inverted = 1;
3270 if (r->flag & FLAG_START) {
3271 struct parse_context *new;
3272 debug_printf("push stack\n");
3273 new = xmalloc(sizeof(*new));
3274 *new = *ctx; /* physical copy */
3275 initialize_context(ctx);
3277 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3279 ctx->ctx_res_w = RES_SNTX;
3282 ctx->ctx_res_w = r->res;
3283 ctx->old_flag = r->flag;
3284 if (ctx->old_flag & FLAG_END) {
3285 struct parse_context *old;
3286 debug_printf("pop stack\n");
3287 done_pipe(ctx, PIPE_SEQ);
3289 old->command->group = ctx->list_head;
3290 old->command->grp_type = GRP_NORMAL;
3291 *ctx = *old; /* physical copy */
3294 word->o_assignment = r->assignment_flag;
3299 //TODO: many, many callers don't check error from done_word()
3301 /* Word is complete, look at it and update parsing context.
3302 * Normal return is 0. Syntax errors return 1. */
3303 static int done_word(o_string *word, struct parse_context *ctx)
3305 struct command *command = ctx->command;
3307 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3308 if (word->length == 0 && word->nonnull == 0) {
3309 debug_printf_parse("done_word return 0: true null, ignored\n");
3312 /* If this word wasn't an assignment, next ones definitely
3313 * can't be assignments. Even if they look like ones. */
3314 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3315 && word->o_assignment != WORD_IS_KEYWORD
3317 word->o_assignment = NOT_ASSIGNMENT;
3319 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3320 command->assignment_cnt++;
3321 word->o_assignment = MAYBE_ASSIGNMENT;
3324 if (ctx->pending_redirect) {
3325 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3326 * only if run as "bash", not "sh" */
3327 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3328 word->o_assignment = NOT_ASSIGNMENT;
3329 debug_printf("word stored in rd_filename: '%s'\n", word->data);
3331 /* "{ echo foo; } echo bar" - bad */
3332 /* NB: bash allows e.g. "if true; then { echo foo; } fi". TODO? */
3333 if (command->group) {
3335 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
3339 #if ENABLE_HUSH_CASE
3340 if (ctx->ctx_dsemicolon
3341 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3343 /* already done when ctx_dsemicolon was set to 1: */
3344 /* ctx->ctx_res_w = RES_MATCH; */
3345 ctx->ctx_dsemicolon = 0;
3349 if (!command->argv /* if it's the first word... */
3350 #if ENABLE_HUSH_LOOPS
3351 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3352 && ctx->ctx_res_w != RES_IN
3355 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
3356 if (reserved_word(word, ctx)) {
3358 debug_printf_parse("done_word return %d\n", (ctx->ctx_res_w == RES_SNTX));
3359 return (ctx->ctx_res_w == RES_SNTX);
3363 if (word->nonnull /* word had "xx" or 'xx' at least as part of it. */
3364 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3365 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3366 /* (otherwise it's known to be not empty and is already safe) */
3368 /* exclude "$@" - it can expand to no word despite "" */
3369 char *p = word->data;
3370 while (p[0] == SPECIAL_VAR_SYMBOL
3371 && (p[1] & 0x7f) == '@'
3372 && p[2] == SPECIAL_VAR_SYMBOL
3376 if (p == word->data || p[0] != '\0') {
3377 /* saw no "$@", or not only "$@" but some
3378 * real text is there too */
3379 /* insert "empty variable" reference, this makes
3380 * e.g. "", $empty"" etc to not disappear */
3381 o_addchr(word, SPECIAL_VAR_SYMBOL);
3382 o_addchr(word, SPECIAL_VAR_SYMBOL);
3385 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3386 debug_print_strings("word appended to argv", command->argv);
3390 ctx->pending_redirect = NULL;
3392 #if ENABLE_HUSH_LOOPS
3393 /* Force FOR to have just one word (variable name) */
3394 /* NB: basically, this makes hush see "for v in ..." syntax as if
3395 * as it is "for v; in ...". FOR and IN become two pipe structs
3397 if (ctx->ctx_res_w == RES_FOR) {
3398 //TODO: check that command->argv[0] is a valid variable name!
3399 done_pipe(ctx, PIPE_SEQ);
3402 #if ENABLE_HUSH_CASE
3403 /* Force CASE to have just one word */
3404 if (ctx->ctx_res_w == RES_CASE) {
3405 done_pipe(ctx, PIPE_SEQ);
3408 debug_printf_parse("done_word return 0\n");
3412 /* If a redirect is immediately preceded by a number, that number is
3413 * supposed to tell which file descriptor to redirect. This routine
3414 * looks for such preceding numbers. In an ideal world this routine
3415 * needs to handle all the following classes of redirects...
3416 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3417 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3418 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3419 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3420 * A -1 output from this program means no valid number was found, so the
3421 * caller should use the appropriate default for this redirection.
3423 static int redirect_opt_num(o_string *o)
3429 for (num = 0; num < o->length; num++) {
3430 if (!isdigit(o->data[num])) {
3434 num = atoi(o->data);
3439 static int parse_stream(o_string *dest, struct parse_context *ctx,
3440 struct in_str *input0, const char *end_trigger);
3442 #if ENABLE_HUSH_TICK
3443 static FILE *generate_stream_from_list(struct pipe *head)
3446 int pid, channel[2];
3449 /* *** NOMMU WARNING *** */
3450 /* By using vfork here, we suspend parent till child exits or execs.
3451 * If child will not do it before it fills the pipe, it can block forever
3452 * in write(STDOUT_FILENO), and parent (shell) will be also stuck.
3454 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >TESTFILE
3455 * huge=`cat TESTFILE` # will block here forever
3458 pid = BB_MMU ? fork() : vfork();
3460 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
3461 if (pid == 0) { /* child */
3462 if (ENABLE_HUSH_JOB)
3463 die_sleep = 0; /* let nofork's xfuncs die */
3464 close(channel[0]); /* NB: close _first_, then move fd! */
3465 xmove_fd(channel[1], 1);
3466 /* Prevent it from trying to handle ctrl-z etc */
3468 G.run_list_level = 1;
3470 /* Process substitution is not considered to be usual
3471 * 'command execution'.
3472 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not. */
3473 /* Not needed, we are relying on it being disabled
3474 * everywhere outside actual command execution. */
3475 /*set_jobctrl_sighandler(SIG_IGN);*/
3476 set_misc_sighandler(SIG_DFL);
3477 /* Freeing 'head' here would break NOMMU. */
3478 _exit(run_list(head));
3481 pf = fdopen(channel[0], "r");
3483 /* 'head' is freed by the caller */
3486 /* Return code is exit status of the process that is run. */
3487 static int process_command_subs(o_string *dest,
3488 struct in_str *input,
3489 const char *subst_end)
3491 int retcode, ch, eol_cnt;
3492 o_string result = NULL_O_STRING;
3493 struct parse_context inner;
3495 struct in_str pipe_str;
3497 initialize_context(&inner);
3499 /* Recursion to generate command */
3500 retcode = parse_stream(&result, &inner, input, subst_end);
3502 return retcode; /* syntax error or EOF */
3503 done_word(&result, &inner);
3504 done_pipe(&inner, PIPE_SEQ);
3507 p = generate_stream_from_list(inner.list_head);
3510 close_on_exec_on(fileno(p));
3511 setup_file_in_str(&pipe_str, p);
3513 /* Now send results of command back into original context */
3515 while ((ch = i_getch(&pipe_str)) != EOF) {
3521 o_addchr(dest, '\n');
3524 o_addQchr(dest, ch);
3527 debug_printf("done reading from pipe, pclose()ing\n");
3528 /* This is the step that wait()s for the child. Should be pretty
3529 * safe, since we just read an EOF from its stdout. We could try
3530 * to do better, by using wait(), and keeping track of background jobs
3531 * at the same time. That would be a lot of work, and contrary
3532 * to the KISS philosophy of this program. */
3533 retcode = fclose(p);
3534 free_pipe_list(inner.list_head, /* indent: */ 0);
3535 debug_printf("closed FILE from child, retcode=%d\n", retcode);
3540 static int parse_group(o_string *dest, struct parse_context *ctx,
3541 struct in_str *input, int ch)
3543 /* dest contains characters seen prior to ( or {.
3544 * Typically it's empty, but for functions defs,
3545 * it contains function name (without '()'). */
3547 const char *endch = NULL;
3548 struct parse_context sub;
3549 struct command *command = ctx->command;
3551 debug_printf_parse("parse_group entered\n");
3552 #if ENABLE_HUSH_FUNCTIONS
3553 if (ch == 'F') { /* function definition? */
3554 bb_error_msg("aha '%s' is a function, parsing it...", dest->data);
3555 //command->fname = dest->data;
3556 command->grp_type = GRP_FUNCTION;
3557 //TODO: review every o_reset() location... do they handle all o_string fields correctly?
3558 memset(dest, 0, sizeof(*dest));
3561 if (command->argv /* word [word](... */
3562 || dest->length /* word(... */
3563 || dest->nonnull /* ""(... */
3566 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3569 initialize_context(&sub);
3573 command->grp_type = GRP_SUBSHELL;
3575 rcode = parse_stream(dest, &sub, input, endch);
3577 done_word(dest, &sub); /* finish off the final word in the subcontext */
3578 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
3579 command->group = sub.list_head;
3581 debug_printf_parse("parse_group return %d\n", rcode);
3583 /* command remains "open", available for possible redirects */
3586 #if ENABLE_HUSH_TICK
3587 /* Subroutines for copying $(...) and `...` things */
3588 static void add_till_backquote(o_string *dest, struct in_str *input);
3590 static void add_till_single_quote(o_string *dest, struct in_str *input)
3593 int ch = i_getch(input);
3601 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3602 static void add_till_double_quote(o_string *dest, struct in_str *input)
3605 int ch = i_getch(input);
3608 if (ch == '\\') { /* \x. Copy both chars. */
3610 ch = i_getch(input);
3616 add_till_backquote(dest, input);
3620 //if (ch == '$') ...
3623 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3625 * "Within the backquoted style of command substitution, backslash
3626 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3627 * The search for the matching backquote shall be satisfied by the first
3628 * backquote found without a preceding backslash; during this search,
3629 * if a non-escaped backquote is encountered within a shell comment,
3630 * a here-document, an embedded command substitution of the $(command)
3631 * form, or a quoted string, undefined results occur. A single-quoted
3632 * or double-quoted string that begins, but does not end, within the
3633 * "`...`" sequence produces undefined results."
3635 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3637 static void add_till_backquote(o_string *dest, struct in_str *input)
3640 int ch = i_getch(input);
3643 if (ch == '\\') { /* \x. Copy both chars unless it is \` */
3644 int ch2 = i_getch(input);
3645 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
3654 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3655 * quoting and nested ()s.
3656 * "With the $(command) style of command substitution, all characters
3657 * following the open parenthesis to the matching closing parenthesis
3658 * constitute the command. Any valid shell script can be used for command,
3659 * except a script consisting solely of redirections which produces
3660 * unspecified results."
3662 * echo $(echo '(TEST)' BEST) (TEST) BEST
3663 * echo $(echo 'TEST)' BEST) TEST) BEST
3664 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3666 static void add_till_closing_curly_brace(o_string *dest, struct in_str *input)
3670 int ch = i_getch(input);
3680 add_till_single_quote(dest, input);
3685 add_till_double_quote(dest, input);
3689 if (ch == '\\') { /* \x. Copy verbatim. Important for \(, \) */
3690 ch = i_getch(input);
3698 #endif /* ENABLE_HUSH_TICK */
3700 /* Return code: 0 for OK, 1 for syntax error */
3701 static int handle_dollar(o_string *dest, struct in_str *input)
3704 int ch = i_peek(input); /* first character after the $ */
3705 unsigned char quote_mask = dest->o_quote ? 0x80 : 0;
3707 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
3711 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3713 debug_printf_parse(": '%c'\n", ch);
3714 o_addchr(dest, ch | quote_mask);
3717 if (!isalnum(ch) && ch != '_')
3721 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3722 } else if (isdigit(ch)) {
3725 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3726 debug_printf_parse(": '%c'\n", ch);
3727 o_addchr(dest, ch | quote_mask);
3728 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3729 } else switch (ch) {
3731 case '!': /* last bg pid */
3732 case '?': /* last exit code */
3733 case '#': /* number of args */
3734 case '*': /* args */
3735 case '@': /* args */
3736 goto make_one_char_var;
3740 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3742 /* XXX maybe someone will try to escape the '}' */
3746 ch = i_getch(input);
3750 if (ch == '#' && first_char)
3751 /* ${#var}: length of var contents */;
3753 else if (expansion < 2 && !isalnum(ch) && ch != '_') {
3754 /* handle parameter expansions
3755 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3760 case ':': /* null modifier */
3761 if (expansion == 0) {
3762 debug_printf_parse(": null modifier\n");
3768 #if 0 /* not implemented yet :( */
3769 case '#': /* remove prefix */
3770 case '%': /* remove suffix */
3771 if (expansion == 0) {
3772 debug_printf_parse(": remove suffix/prefix\n");
3779 case '-': /* default value */
3780 case '=': /* assign default */
3781 case '+': /* alternative */
3782 case '?': /* error indicate */
3783 debug_printf_parse(": parameter expansion\n");
3789 syntax("unterminated ${name}");
3790 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3794 debug_printf_parse(": '%c'\n", ch);
3795 o_addchr(dest, ch | quote_mask);
3799 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3802 #if ENABLE_HUSH_TICK
3804 //int pos = dest->length;
3806 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3807 o_addchr(dest, quote_mask | '`');
3808 add_till_closing_curly_brace(dest, input);
3809 //debug_printf_subst("SUBST RES2 '%s'\n", dest->data + pos);
3810 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3817 if (isalnum(ch)) { /* it's $_name or $_123 */
3823 /* still unhandled, but should be eventually */
3824 bb_error_msg("unhandled syntax: $%c", ch);
3828 o_addQchr(dest, '$');
3830 debug_printf_parse("handle_dollar return 0\n");
3834 /* Scan input, call done_word() whenever full IFS delimited word was seen.
3835 * Call done_pipe if '\n' was seen (and end_trigger != NULL).
3836 * Return code is 0 if end_trigger char is met,
3837 * -1 on EOF (but if end_trigger == NULL then return 0),
3838 * 1 for syntax error */
3839 static int parse_stream(o_string *dest, struct parse_context *ctx,
3840 struct in_str *input, const char *end_trigger)
3844 redir_type redir_style;
3845 int shadow_quote = dest->o_quote;
3848 /* Only double-quote state is handled in the state variable dest->o_quote.
3849 * A single-quote triggers a bypass of the main loop until its mate is
3850 * found. When recursing, quote state is passed in via dest->o_quote. */
3852 debug_printf_parse("parse_stream entered, end_trigger='%s' dest->o_assignment:%d\n", end_trigger, dest->o_assignment);
3857 ch = i_getch(input);
3861 next = i_peek(input);
3864 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
3865 ch, ch, m, dest->o_quote);
3866 if (m == CHAR_ORDINARY
3867 || (m != CHAR_SPECIAL && shadow_quote)
3870 syntax("unterminated \"");
3871 debug_printf_parse("parse_stream return 1: unterminated \"\n");
3874 o_addQchr(dest, ch);
3875 if ((dest->o_assignment == MAYBE_ASSIGNMENT
3876 || dest->o_assignment == WORD_IS_KEYWORD)
3878 && is_assignment(dest->data)
3880 dest->o_assignment = DEFINITELY_ASSIGNMENT;
3884 if (m == CHAR_IFS) {
3885 if (done_word(dest, ctx)) {
3886 debug_printf_parse("parse_stream return 1: done_word!=0\n");
3891 /* If we aren't performing a substitution, treat
3892 * a newline as a command separator.
3893 * [why we don't handle it exactly like ';'? --vda] */
3894 if (end_trigger && ch == '\n') {
3895 #if ENABLE_HUSH_CASE
3896 /* "case ... in <newline> word) ..." -
3897 * newlines are ignored (but ';' wouldn't be) */
3898 if (dest->length == 0 // && argv[0] == NULL
3899 && ctx->ctx_res_w == RES_MATCH
3904 done_pipe(ctx, PIPE_SEQ);
3905 dest->o_assignment = MAYBE_ASSIGNMENT;
3909 if (!shadow_quote && strchr(end_trigger, ch)) {
3910 /* Special case: (...word) makes last word terminate,
3911 * as if ';' is seen */
3913 done_word(dest, ctx);
3915 done_pipe(ctx, PIPE_SEQ);
3916 dest->o_assignment = MAYBE_ASSIGNMENT;
3919 IF_HAS_KEYWORDS(|| (ctx->ctx_res_w == RES_NONE && ctx->old_flag == 0))
3921 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
3929 if (dest->o_assignment == MAYBE_ASSIGNMENT) {
3930 /* ch is a special char and thus this word
3931 * cannot be an assignment: */
3932 dest->o_assignment = NOT_ASSIGNMENT;
3937 if (dest->length == 0 && !shadow_quote) {
3940 if (ch == EOF || ch == '\n')
3945 o_addQchr(dest, ch);
3951 debug_printf_parse("parse_stream return 1: \\<eof>\n");
3955 * "The backslash retains its special meaning [in "..."]
3956 * only when followed by one of the following characters:
3957 * $, `, ", \, or <newline>. A double quote may be quoted
3958 * within double quotes by preceding it with a backslash.
3959 * If enabled, history expansion will be performed unless
3960 * an ! appearing in double quotes is escaped using
3961 * a backslash. The backslash preceding the ! is not removed."
3963 if (shadow_quote) { //NOT SURE dest->o_quote) {
3964 if (strchr("$`\"\\", next) != NULL) {
3965 o_addqchr(dest, i_getch(input));
3967 o_addqchr(dest, '\\');
3970 o_addchr(dest, '\\');
3971 o_addchr(dest, i_getch(input));
3975 if (handle_dollar(dest, input) != 0) {
3976 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3983 ch = i_getch(input);
3985 syntax("unterminated '");
3986 debug_printf_parse("parse_stream return 1: unterminated '\n");
3991 if (dest->o_assignment == NOT_ASSIGNMENT)
3992 o_addqchr(dest, ch);
3999 shadow_quote ^= 1; /* invert */
4000 if (dest->o_assignment == NOT_ASSIGNMENT)
4003 #if ENABLE_HUSH_TICK
4005 //int pos = dest->length;
4006 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4007 o_addchr(dest, shadow_quote /*or dest->o_quote??*/ ? 0x80 | '`' : '`');
4008 add_till_backquote(dest, input);
4009 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4010 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4015 redir_fd = redirect_opt_num(dest);
4016 done_word(dest, ctx);
4017 redir_style = REDIRECT_OVERWRITE;
4019 redir_style = REDIRECT_APPEND;
4023 else if (next == '(') {
4024 syntax(">(process) not supported");
4025 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
4029 setup_redirect(ctx, redir_fd, redir_style, input);
4032 redir_fd = redirect_opt_num(dest);
4033 done_word(dest, ctx);
4034 redir_style = REDIRECT_INPUT;
4036 redir_style = REDIRECT_HEREIS;
4038 } else if (next == '>') {
4039 redir_style = REDIRECT_IO;
4043 else if (next == '(') {
4044 syntax("<(process) not supported");
4045 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
4049 setup_redirect(ctx, redir_fd, redir_style, input);
4052 #if ENABLE_HUSH_CASE
4055 done_word(dest, ctx);
4056 done_pipe(ctx, PIPE_SEQ);
4057 #if ENABLE_HUSH_CASE
4058 /* Eat multiple semicolons, detect
4059 * whether it means something special */
4065 if (ctx->ctx_res_w == RES_CASEI) {
4066 ctx->ctx_dsemicolon = 1;
4067 ctx->ctx_res_w = RES_MATCH;
4073 /* We just finished a cmd. New one may start
4074 * with an assignment */
4075 dest->o_assignment = MAYBE_ASSIGNMENT;
4078 done_word(dest, ctx);
4081 done_pipe(ctx, PIPE_AND);
4083 done_pipe(ctx, PIPE_BG);
4087 done_word(dest, ctx);
4088 #if ENABLE_HUSH_CASE
4089 if (ctx->ctx_res_w == RES_MATCH)
4090 break; /* we are in case's "word | word)" */
4092 if (next == '|') { /* || */
4094 done_pipe(ctx, PIPE_OR);
4096 /* we could pick up a file descriptor choice here
4097 * with redirect_opt_num(), but bash doesn't do it.
4098 * "echo foo 2| cat" yields "foo 2". */
4103 #if ENABLE_HUSH_CASE
4104 /* "case... in [(]word)..." - skip '(' */
4105 if (ctx->ctx_res_w == RES_MATCH
4106 && ctx->command->argv == NULL /* not (word|(... */
4107 && dest->length == 0 /* not word(... */
4108 && dest->nonnull == 0 /* not ""(... */
4113 #if ENABLE_HUSH_FUNCTIONS
4114 if (dest->length != 0 /* not just () but word() */
4115 && dest->nonnull == 0 /* not a"b"c() */
4116 && ctx->command->argv == NULL /* it's the first word */
4117 //TODO: "func ( ) {...}" - note spaces - is valid format too in bash
4118 && i_peek(input) == ')'
4119 && !match_reserved_word(dest)
4121 bb_error_msg("seems like a function definition");
4124 //TODO: do it properly.
4125 ch = i_getch(input);
4126 } while (ch == ' ' || ch == '\n');
4128 syntax("was expecting {");
4129 debug_printf_parse("parse_stream return 1\n");
4132 ch = 'F'; /* magic value */
4136 if (parse_group(dest, ctx, input, ch) != 0) {
4137 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
4142 #if ENABLE_HUSH_CASE
4143 if (ctx->ctx_res_w == RES_MATCH)
4147 /* proper use of this character is caught by end_trigger:
4148 * if we see {, we call parse_group(..., end_trigger='}')
4149 * and it will match } earlier (not here). */
4150 syntax("unexpected } or )");
4151 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
4155 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4158 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
4164 static void set_in_charmap(const char *set, int code)
4167 G.charmap[(unsigned char)*set++] = code;
4170 static void update_charmap(void)
4172 G.ifs = getenv("IFS");
4175 /* Precompute a list of 'flow through' behavior so it can be treated
4176 * quickly up front. Computation is necessary because of IFS.
4177 * Special case handling of IFS == " \t\n" is not implemented.
4178 * The charmap[] array only really needs two bits each,
4179 * and on most machines that would be faster (reduced L1 cache use).
4181 memset(G.charmap, CHAR_ORDINARY, sizeof(G.charmap));
4182 #if ENABLE_HUSH_TICK
4183 set_in_charmap("\\$\"`", CHAR_SPECIAL);
4185 set_in_charmap("\\$\"", CHAR_SPECIAL);
4187 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
4188 set_in_charmap(G.ifs, CHAR_IFS); /* are ordinary if quoted */
4191 /* Most recursion does not come through here, the exception is
4192 * from builtin_source() and builtin_eval() */
4193 static int parse_and_run_stream(struct in_str *inp, int parse_flag)
4195 struct parse_context ctx;
4196 o_string temp = NULL_O_STRING;
4200 initialize_context(&ctx);
4202 #if ENABLE_HUSH_INTERACTIVE
4203 inp->promptmode = 0; /* PS1 */
4205 /* We will stop & execute after each ';' or '\n'.
4206 * Example: "sleep 9999; echo TEST" + ctrl-C:
4207 * TEST should be printed */
4208 temp.o_assignment = MAYBE_ASSIGNMENT;
4209 rcode = parse_stream(&temp, &ctx, inp, ";\n");
4211 if (rcode != 1 && ctx.old_flag != 0) {
4215 if (rcode != 1 IF_HAS_KEYWORDS(&& ctx.old_flag == 0)) {
4216 done_word(&temp, &ctx);
4217 done_pipe(&ctx, PIPE_SEQ);
4218 debug_print_tree(ctx.list_head, 0);
4219 debug_printf_exec("parse_stream_outer: run_and_free_list\n");
4220 run_and_free_list(ctx.list_head);
4222 /* We arrive here also if rcode == 1 (error in parse_stream) */
4224 if (ctx.old_flag != 0) {
4229 /*temp.nonnull = 0; - o_free does it below */
4230 /*temp.o_quote = 0; - o_free does it below */
4231 free_pipe_list(ctx.list_head, /* indent: */ 0);
4232 /* Discard all unprocessed line input, force prompt on */
4234 #if ENABLE_HUSH_INTERACTIVE
4239 /* loop on syntax errors, return on EOF: */
4240 } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP));
4244 static int parse_and_run_string(const char *s, int parse_flag)
4246 struct in_str input;
4247 setup_string_in_str(&input, s);
4248 return parse_and_run_stream(&input, parse_flag);
4251 static int parse_and_run_file(FILE *f)
4254 struct in_str input;
4255 setup_file_in_str(&input, f);
4256 rcode = parse_and_run_stream(&input, 0 /* parse_flag */);
4261 /* Make sure we have a controlling tty. If we get started under a job
4262 * aware app (like bash for example), make sure we are now in charge so
4263 * we don't fight over who gets the foreground */
4264 static void setup_job_control(void)
4268 shell_pgrp = getpgrp();
4269 close_on_exec_on(G.interactive_fd);
4271 /* If we were ran as 'hush &',
4272 * sleep until we are in the foreground. */
4273 while (tcgetpgrp(G.interactive_fd) != shell_pgrp) {
4274 /* Send TTIN to ourself (should stop us) */
4275 kill(- shell_pgrp, SIGTTIN);
4276 shell_pgrp = getpgrp();
4279 /* Ignore job-control and misc signals. */
4280 set_jobctrl_sighandler(SIG_IGN);
4281 set_misc_sighandler(SIG_IGN);
4282 //huh? signal(SIGCHLD, SIG_IGN);
4284 /* We _must_ restore tty pgrp on fatal signals */
4285 set_fatal_sighandler(sigexit);
4287 /* Put ourselves in our own process group. */
4288 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
4289 /* Grab control of the terminal. */
4290 tcsetpgrp(G.interactive_fd, getpid());
4295 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4296 int hush_main(int argc, char **argv)
4298 static const struct variable const_shell_ver = {
4300 .varstr = (char*)hush_version_str,
4301 .max_len = 1, /* 0 can provoke free(name) */
4309 struct variable *cur_var;
4313 G.root_pid = getpid();
4315 /* Deal with HUSH_VERSION */
4316 G.shell_ver = const_shell_ver; /* copying struct here */
4317 G.top_var = &G.shell_ver;
4318 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
4319 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
4320 /* Initialize our shell local variables with the values
4321 * currently living in the environment */
4322 cur_var = G.top_var;
4325 char *value = strchr(*e, '=');
4326 if (value) { /* paranoia */
4327 cur_var->next = xzalloc(sizeof(*cur_var));
4328 cur_var = cur_var->next;
4329 cur_var->varstr = *e;
4330 cur_var->max_len = strlen(*e);
4331 cur_var->flg_export = 1;
4335 debug_printf_env("putenv '%s'\n", hush_version_str);
4336 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
4338 #if ENABLE_FEATURE_EDITING
4339 G.line_input_state = new_line_input_t(FOR_SHELL);
4341 /* XXX what should these be while sourcing /etc/profile? */
4342 G.global_argc = argc;
4343 G.global_argv = argv;
4344 /* Initialize some more globals to non-zero values */
4346 #if ENABLE_HUSH_INTERACTIVE
4347 if (ENABLE_FEATURE_EDITING)
4348 cmdedit_set_initial_prompt();
4352 if (EXIT_SUCCESS) /* otherwise is already done */
4353 G.last_return_code = EXIT_SUCCESS;
4355 if (argv[0] && argv[0][0] == '-') {
4356 debug_printf("sourcing /etc/profile\n");
4357 input = fopen_for_read("/etc/profile");
4358 if (input != NULL) {
4359 close_on_exec_on(fileno(input));
4360 parse_and_run_file(input);
4366 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
4367 while ((opt = getopt(argc, argv, "c:xins")) > 0) {
4370 G.global_argv = argv + optind;
4371 if (!argv[optind]) {
4372 /* -c 'script' (no params): prevent empty $0 */
4373 *--G.global_argv = argv[0];
4375 } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
4376 G.global_argc = argc - optind;
4377 opt = parse_and_run_string(optarg, 0 /* parse_flag */);
4380 /* Well, we cannot just declare interactiveness,
4381 * we have to have some stuff (ctty, etc) */
4382 /* G.interactive_fd++; */
4385 /* "-s" means "read from stdin", but this is how we always
4386 * operate, so simply do nothing here. */
4390 if (!builtin_set_mode('-', opt))
4394 fprintf(stderr, "Usage: sh [FILE]...\n"
4395 " or: sh -c command [args]...\n\n");
4403 /* A shell is interactive if the '-i' flag was given, or if all of
4404 * the following conditions are met:
4406 * no arguments remaining or the -s flag given
4407 * standard input is a terminal
4408 * standard output is a terminal
4409 * Refer to Posix.2, the description of the 'sh' utility. */
4410 if (argv[optind] == NULL && input == stdin
4411 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4413 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
4414 debug_printf("saved_tty_pgrp=%d\n", G.saved_tty_pgrp);
4415 if (G.saved_tty_pgrp >= 0) {
4416 /* try to dup to high fd#, >= 255 */
4417 G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4418 if (G.interactive_fd < 0) {
4419 /* try to dup to any fd */
4420 G.interactive_fd = dup(STDIN_FILENO);
4421 if (G.interactive_fd < 0)
4423 G.interactive_fd = 0;
4425 // TODO: track & disallow any attempts of user
4426 // to (inadvertently) close/redirect it
4429 debug_printf("G.interactive_fd=%d\n", G.interactive_fd);
4430 if (G.interactive_fd) {
4431 fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
4432 /* Looks like they want an interactive shell */
4433 setup_job_control();
4434 /* -1 is special - makes xfuncs longjmp, not exit
4435 * (we reset die_sleep = 0 whereever we [v]fork) */
4437 if (setjmp(die_jmp)) {
4438 /* xfunc has failed! die die die */
4439 hush_exit(xfunc_error_retval);
4442 #elif ENABLE_HUSH_INTERACTIVE
4443 /* no job control compiled, only prompt/line editing */
4444 if (argv[optind] == NULL && input == stdin
4445 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4447 G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4448 if (G.interactive_fd < 0) {
4449 /* try to dup to any fd */
4450 G.interactive_fd = dup(STDIN_FILENO);
4451 if (G.interactive_fd < 0)
4453 G.interactive_fd = 0;
4455 if (G.interactive_fd) {
4456 fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
4457 set_misc_sighandler(SIG_IGN);
4462 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G.interactive_fd) {
4463 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
4464 printf("Enter 'help' for a list of built-in commands.\n\n");
4467 if (argv[optind] == NULL) {
4468 opt = parse_and_run_file(stdin);
4470 debug_printf("\nrunning script '%s'\n", argv[optind]);
4471 G.global_argv = argv + optind;
4472 G.global_argc = argc - optind;
4473 input = xfopen_for_read(argv[optind]);
4474 fcntl(fileno(input), F_SETFD, FD_CLOEXEC);
4475 opt = parse_and_run_file(input);
4480 #if ENABLE_FEATURE_CLEAN_UP
4482 if (G.cwd != bb_msg_unknown)
4484 cur_var = G.top_var->next;
4486 struct variable *tmp = cur_var;
4487 if (!cur_var->max_len)
4488 free(cur_var->varstr);
4489 cur_var = cur_var->next;
4493 hush_exit(opt ? opt : G.last_return_code);
4498 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4499 int lash_main(int argc, char **argv)
4501 //bb_error_msg("lash is deprecated, please use hush instead");
4502 return hush_main(argc, argv);
4510 static int builtin_true(char **argv UNUSED_PARAM)
4515 static int builtin_test(char **argv)
4522 return test_main(argc, argv - argc);
4525 static int builtin_echo(char **argv)
4532 return echo_main(argc, argv - argc);
4535 static int builtin_eval(char **argv)
4537 int rcode = EXIT_SUCCESS;
4540 char *str = expand_strvec_to_string(argv + 1);
4541 parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP);
4543 rcode = G.last_return_code;
4548 static int builtin_cd(char **argv)
4551 if (argv[1] == NULL) {
4552 // bash does nothing (exitcode 0) if HOME is ""; if it's unset,
4553 // bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
4554 newdir = getenv("HOME") ? : "/";
4557 if (chdir(newdir)) {
4558 printf("cd: %s: %s\n", newdir, strerror(errno));
4559 return EXIT_FAILURE;
4562 return EXIT_SUCCESS;
4565 static int builtin_exec(char **argv)
4567 if (argv[1] == NULL)
4568 return EXIT_SUCCESS; /* bash does this */
4573 // FIXME: if exec fails, bash does NOT exit! We do...
4574 pseudo_exec_argv(&dummy, argv + 1, 0, NULL);
4579 static int builtin_exit(char **argv)
4581 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
4582 //puts("exit"); /* bash does it */
4583 // TODO: warn if we have background jobs: "There are stopped jobs"
4584 // On second consecutive 'exit', exit anyway.
4585 if (argv[1] == NULL)
4586 hush_exit(G.last_return_code);
4587 /* mimic bash: exit 123abc == exit 255 + error msg */
4588 xfunc_error_retval = 255;
4589 /* bash: exit -2 == exit 254, no error msg */
4590 hush_exit(xatoi(argv[1]) & 0xff);
4593 static int builtin_export(char **argv)
4596 char *name = argv[1];
4600 // ash emits: export VAR='VAL'
4601 // bash: declare -x VAR="VAL"
4602 // (both also escape as needed (quotes, $, etc))
4607 return EXIT_SUCCESS;
4610 value = strchr(name, '=');
4612 /* They are exporting something without a =VALUE */
4613 struct variable *var;
4615 var = get_local_var(name);
4617 var->flg_export = 1;
4618 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
4619 putenv(var->varstr);
4621 /* bash does not return an error when trying to export
4622 * an undefined variable. Do likewise. */
4623 return EXIT_SUCCESS;
4626 set_local_var(xstrdup(name), 1);
4627 return EXIT_SUCCESS;
4631 /* built-in 'fg' and 'bg' handler */
4632 static int builtin_fg_bg(char **argv)
4637 if (!G.interactive_fd)
4638 return EXIT_FAILURE;
4639 /* If they gave us no args, assume they want the last backgrounded task */
4641 for (pi = G.job_list; pi; pi = pi->next) {
4642 if (pi->jobid == G.last_jobid) {
4646 bb_error_msg("%s: no current job", argv[0]);
4647 return EXIT_FAILURE;
4649 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
4650 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
4651 return EXIT_FAILURE;
4653 for (pi = G.job_list; pi; pi = pi->next) {
4654 if (pi->jobid == jobnum) {
4658 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
4659 return EXIT_FAILURE;
4661 // TODO: bash prints a string representation
4662 // of job being foregrounded (like "sleep 1 | cat")
4663 if (*argv[0] == 'f') {
4664 /* Put the job into the foreground. */
4665 tcsetpgrp(G.interactive_fd, pi->pgrp);
4668 /* Restart the processes in the job */
4669 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
4670 for (i = 0; i < pi->num_cmds; i++) {
4671 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
4672 pi->cmds[i].is_stopped = 0;
4674 pi->stopped_cmds = 0;
4676 i = kill(- pi->pgrp, SIGCONT);
4678 if (errno == ESRCH) {
4679 delete_finished_bg_job(pi);
4680 return EXIT_SUCCESS;
4682 bb_perror_msg("kill (SIGCONT)");
4686 if (*argv[0] == 'f') {
4688 return checkjobs_and_fg_shell(pi);
4690 return EXIT_SUCCESS;
4694 #if ENABLE_HUSH_HELP
4695 static int builtin_help(char **argv UNUSED_PARAM)
4697 const struct built_in_command *x;
4699 printf("\nBuilt-in commands:\n");
4700 printf("-------------------\n");
4701 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
4702 printf("%s\t%s\n", x->cmd, x->descr);
4705 return EXIT_SUCCESS;
4710 static int builtin_jobs(char **argv UNUSED_PARAM)
4713 const char *status_string;
4715 for (job = G.job_list; job; job = job->next) {
4716 if (job->alive_cmds == job->stopped_cmds)
4717 status_string = "Stopped";
4719 status_string = "Running";
4721 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
4723 return EXIT_SUCCESS;
4727 static int builtin_pwd(char **argv UNUSED_PARAM)
4730 return EXIT_SUCCESS;
4733 static int builtin_read(char **argv)
4736 const char *name = argv[1] ? argv[1] : "REPLY";
4738 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
4739 return set_local_var(string, 0);
4742 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
4743 * built-in 'set' handler
4745 * set [-abCefhmnuvx] [-o option] [argument...]
4746 * set [+abCefhmnuvx] [+o option] [argument...]
4747 * set -- [argument...]
4750 * Implementations shall support the options in both their hyphen and
4751 * plus-sign forms. These options can also be specified as options to sh.
4753 * Write out all variables and their values: set
4754 * Set $1, $2, and $3 and set "$#" to 3: set c a b
4755 * Turn on the -x and -v options: set -xv
4756 * Unset all positional parameters: set --
4757 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
4758 * Set the positional parameters to the expansion of x, even if x expands
4759 * with a leading '-' or '+': set -- $x
4761 * So far, we only support "set -- [argument...]" and some of the short names.
4763 static int builtin_set_mode(const char cstate, const char mode)
4765 int state = (cstate == '-' ? 1 : 0);
4767 case 'n': G.fake_mode = state; break;
4768 case 'x': /*G.debug_mode = state;*/ break;
4769 default: return EXIT_FAILURE;
4771 return EXIT_SUCCESS;
4773 static int builtin_set(char **argv)
4776 char **pp, **g_argv;
4777 char *arg = *++argv;
4781 for (e = G.top_var; e; e = e->next)
4783 return EXIT_SUCCESS;
4787 if (!strcmp(arg, "--")) {
4792 if (arg[0] == '+' || arg[0] == '-') {
4793 for (n = 1; arg[n]; ++n)
4794 if (builtin_set_mode(arg[0], arg[n]))
4800 } while ((arg = *++argv) != NULL);
4801 /* Now argv[0] is 1st argument */
4803 /* Only reset global_argv if we didn't process anything */
4805 return EXIT_SUCCESS;
4808 /* NB: G.global_argv[0] ($0) is never freed/changed */
4809 g_argv = G.global_argv;
4810 if (G.global_args_malloced) {
4816 G.global_args_malloced = 1;
4817 pp = xzalloc(sizeof(pp[0]) * 2);
4818 pp[0] = g_argv[0]; /* retain $0 */
4821 /* This realloc's G.global_argv */
4822 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
4829 return EXIT_SUCCESS;
4831 /* Nothing known, so abort */
4833 bb_error_msg("set: %s: invalid option", arg);
4834 return EXIT_FAILURE;
4837 static int builtin_shift(char **argv)
4843 if (n >= 0 && n < G.global_argc) {
4844 if (G.global_args_malloced) {
4847 free(G.global_argv[m++]);
4850 memmove(&G.global_argv[1], &G.global_argv[n+1],
4851 G.global_argc * sizeof(G.global_argv[0]));
4852 return EXIT_SUCCESS;
4854 return EXIT_FAILURE;
4857 static int builtin_source(char **argv)
4862 if (argv[1] == NULL)
4863 return EXIT_FAILURE;
4865 /* XXX search through $PATH is missing */
4866 input = fopen_for_read(argv[1]);
4868 bb_error_msg("can't open '%s'", argv[1]);
4869 return EXIT_FAILURE;
4871 close_on_exec_on(fileno(input));
4873 /* Now run the file */
4874 /* XXX argv and argc are broken; need to save old G.global_argv
4875 * (pointer only is OK!) on this stack frame,
4876 * set G.global_argv=argv+1, recurse, and restore. */
4877 status = parse_and_run_file(input);
4882 static int builtin_umask(char **argv)
4885 const char *arg = argv[1];
4888 new_umask = strtoul(arg, &end, 8);
4889 if (*end != '\0' || end == arg) {
4890 return EXIT_FAILURE;
4893 new_umask = umask(0);
4894 printf("%.3o\n", (unsigned) new_umask);
4897 return EXIT_SUCCESS;
4900 static int builtin_unset(char **argv)
4902 /* bash always returns true */
4903 unset_local_var(argv[1]);
4904 return EXIT_SUCCESS;
4907 #if ENABLE_HUSH_LOOPS
4908 static int builtin_break(char **argv)
4910 if (G.depth_of_loop == 0) {
4911 bb_error_msg("%s: only meaningful in a loop", argv[0]);
4912 return EXIT_SUCCESS; /* bash compat */
4914 G.flag_break_continue++; /* BC_BREAK = 1 */
4915 G.depth_break_continue = 1;
4917 G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
4918 if (errno || !G.depth_break_continue || argv[2]) {
4919 bb_error_msg("%s: bad arguments", argv[0]);
4920 G.flag_break_continue = BC_BREAK;
4921 G.depth_break_continue = UINT_MAX;
4924 if (G.depth_of_loop < G.depth_break_continue)
4925 G.depth_break_continue = G.depth_of_loop;
4926 return EXIT_SUCCESS;
4929 static int builtin_continue(char **argv)
4931 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
4932 return builtin_break(argv);