1 /* vi: set sw=4 ts=4: */
3 * sh.c -- 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 * Bash grammar not implemented: (how many of these were in original sh?)
41 * &> and >& redirection of stdout+stderr
44 * fancy forms of Parameter Expansion
46 * Arithmetic Expansion
47 * <(list) and >(list) Process Substitution
48 * reserved words: case, esac, select, function
49 * Here Documents ( << word )
52 * job handling woefully incomplete and buggy (improved --vda)
53 * reserved word execution woefully incomplete and buggy
55 * port selected bugfixes from post-0.49 busybox lash - done?
56 * change { and } from special chars to reserved words
57 * builtins: break, continue, eval, return, set, trap, ulimit
59 * check setting of global_argc and global_argv
60 * follow IFS rules more precisely, including update semantics
61 * figure out what to do with backslash-newline
62 * propagate syntax errors, die on resource errors?
63 * continuation lines, both explicit and implicit - done?
64 * memory leak finding and plugging - 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.
71 #include <glob.h> /* glob, of course */
72 /* #include <dmalloc.h> */
74 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
77 #if !BB_MMU && ENABLE_HUSH_TICK
78 //#undef ENABLE_HUSH_TICK
79 //#define ENABLE_HUSH_TICK 0
80 #warning On NOMMU, hush command substitution is dangerous.
81 #warning Dont use it for commands which produce lots of output.
82 #warning For more info see shell/hush.c, generate_stream_from_list().
85 #if !BB_MMU && ENABLE_HUSH_JOB
86 #undef ENABLE_HUSH_JOB
87 #define ENABLE_HUSH_JOB 0
90 #if !ENABLE_HUSH_INTERACTIVE
91 #undef ENABLE_FEATURE_EDITING
92 #define ENABLE_FEATURE_EDITING 0
93 #undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
94 #define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
98 /* If you comment out one of these below, it will be #defined later
99 * to perform debug printfs to stderr: */
100 #define debug_printf(...) do {} while (0)
101 /* Finer-grained debug switches */
102 #define debug_printf_parse(...) do {} while (0)
103 #define debug_print_tree(a, b) do {} while (0)
104 #define debug_printf_exec(...) do {} while (0)
105 #define debug_printf_jobs(...) do {} while (0)
106 #define debug_printf_expand(...) do {} while (0)
107 #define debug_printf_clean(...) do {} while (0)
110 #define debug_printf(...) fprintf(stderr, __VA_ARGS__)
113 #ifndef debug_printf_parse
114 #define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
117 #ifndef debug_printf_exec
118 #define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
121 #ifndef debug_printf_jobs
122 #define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
123 #define DEBUG_SHELL_JOBS 1
126 #ifndef debug_printf_expand
127 #define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
128 #define DEBUG_EXPAND 1
131 /* Keep unconditionally on for now */
132 #define ENABLE_HUSH_DEBUG 1
134 #ifndef debug_printf_clean
135 /* broken, of course, but OK for testing */
136 static const char *indenter(int i)
138 static const char blanks[] ALIGN1 =
140 return &blanks[sizeof(blanks) - i - 1];
142 #define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
143 #define DEBUG_CLEAN 1
148 * Leak hunting. Use hush_leaktool.sh for post-processing.
150 #ifdef FOR_HUSH_LEAKTOOL
151 void *xxmalloc(int lineno, size_t size)
153 void *ptr = xmalloc((size + 0xff) & ~0xff);
154 fprintf(stderr, "line %d: malloc %p\n", lineno, ptr);
157 void *xxrealloc(int lineno, void *ptr, size_t size)
159 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
160 fprintf(stderr, "line %d: realloc %p\n", lineno, ptr);
163 char *xxstrdup(int lineno, const char *str)
165 char *ptr = xstrdup(str);
166 fprintf(stderr, "line %d: strdup %p\n", lineno, ptr);
169 void xxfree(void *ptr)
171 fprintf(stderr, "free %p\n", ptr);
174 #define xmalloc(s) xxmalloc(__LINE__, s)
175 #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
176 #define xstrdup(s) xxstrdup(__LINE__, s)
177 #define free(p) xxfree(p)
181 #define SPECIAL_VAR_SYMBOL 3
182 #define PARSEFLAG_EXIT_FROM_LOOP 1
186 REDIRECT_OVERWRITE = 2,
192 /* The descrip member of this structure is only used to make debugging
194 static const struct {
196 signed char default_fd;
200 { O_RDONLY, 0, "<" },
201 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
202 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
203 { O_RDONLY, -1, "<<" },
214 /* might eventually control execution */
224 #if ENABLE_HUSH_LOOPS
235 /* This holds pointers to the various results of parsing */
237 struct child_prog *child;
238 struct pipe *list_head;
240 struct redir_struct *pending_redirect;
242 smallint ctx_inverted; /* "! cmd | cmd" */
243 int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */
244 struct p_context *stack;
247 struct redir_struct {
248 struct redir_struct *next; /* pointer to the next redirect in the list */
249 redir_type type; /* type of redirection */
250 int fd; /* file descriptor being redirected */
251 int dup; /* -1, or file descriptor being duplicated */
252 char **glob_word; /* *word.gl_pathv is the filename */
256 pid_t pid; /* 0 if exited */
257 char **argv; /* program name and arguments */
258 struct pipe *group; /* if non-NULL, first in group or subshell */
259 smallint subshell; /* flag, non-zero if group must be forked */
260 smallint is_stopped; /* is the program currently running? */
261 struct redir_struct *redirects; /* I/O redirections */
262 struct pipe *family; /* pointer back to the child's parent pipe */
264 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
265 * and on execution these are substituted with their values.
266 * Substitution can make _several_ words out of one argv[n]!
267 * Example: argv[0]=='.^C*^C.' here: echo .$*.
272 int num_progs; /* total number of programs in job */
273 int running_progs; /* number of programs running (not exited) */
274 int stopped_progs; /* number of programs alive, but stopped */
276 int jobid; /* job number */
277 pid_t pgrp; /* process group ID for the job */
278 char *cmdtext; /* name of job */
280 char *cmdbuf; /* buffer various argv's point into */
281 struct child_prog *progs; /* array of commands in pipe */
282 int job_context; /* bitmask defining current context */
283 smallint pi_inverted; /* "! cmd | cmd" */
284 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
285 smallint res_word; /* needed for if, for, while, until... */
288 /* On program start, environ points to initial environment.
289 * putenv adds new pointers into it, unsetenv removes them.
290 * Neither of these (de)allocates the strings.
291 * setenv allocates new strings in malloc space and does putenv,
292 * and thus setenv is unusable (leaky) for shell's purposes */
293 #define setenv(...) setenv_is_leaky_dont_use()
295 struct variable *next;
296 char *varstr; /* points to "name=" portion */
297 int max_len; /* if > 0, name is part of initial env; else name is malloced */
298 smallint flg_export; /* putenv should be done on this var */
299 smallint flg_read_only;
308 smallint has_empty_slot;
310 #define NULL_O_STRING { NULL }
311 /* used for initialization: o_string foo = NULL_O_STRING; */
313 /* I can almost use ordinary FILE *. Is open_memstream() universally
314 * available? Where is it documented? */
317 /* eof_flag=1: last char in ->p is really an EOF */
318 char eof_flag; /* meaningless if ->p == NULL */
320 #if ENABLE_HUSH_INTERACTIVE
322 smallint promptmode; /* 0: PS1, 1: PS2 */
325 int (*get) (struct in_str *);
326 int (*peek) (struct in_str *);
328 #define i_getch(input) ((input)->get(input))
329 #define i_peek(input) ((input)->peek(input))
333 CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
334 CHAR_IFS = 2, /* treated as ordinary if quoted */
335 CHAR_SPECIAL = 3, /* example: $ */
338 #define HUSH_VER_STR "0.02"
340 /* "Globals" within this file */
342 /* Sorted roughly by size (smaller offsets == smaller code) */
344 #if ENABLE_HUSH_INTERACTIVE
345 /* 'interactive_fd' is a fd# open to ctty, if we have one
346 * _AND_ if we decided to act interactively */
351 #if ENABLE_FEATURE_EDITING
352 line_input_t *line_input_state;
356 pid_t saved_task_pgrp;
357 pid_t saved_tty_pgrp;
359 struct pipe *job_list;
360 struct pipe *toplevel_list;
361 smallint ctrl_z_flag;
364 /* these three support $?, $#, and $1 */
367 int last_return_code;
370 unsigned last_bg_pid;
371 struct variable *top_var; /* = &shell_ver (set in main()) */
372 struct variable shell_ver;
373 #if ENABLE_FEATURE_SH_STANDALONE
374 struct nofork_save_area nofork_save;
377 sigjmp_buf toplevel_jb;
379 unsigned char charmap[256];
380 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
383 #define G (*ptr_to_globals)
385 #if !ENABLE_HUSH_INTERACTIVE
386 enum { interactive_fd = 0 };
389 enum { run_list_level = 0 };
392 #if ENABLE_HUSH_INTERACTIVE
393 #define interactive_fd (G.interactive_fd )
397 #if ENABLE_FEATURE_EDITING
398 #define line_input_state (G.line_input_state)
401 #define run_list_level (G.run_list_level )
402 #define saved_task_pgrp (G.saved_task_pgrp )
403 #define saved_tty_pgrp (G.saved_tty_pgrp )
404 #define last_jobid (G.last_jobid )
405 #define job_list (G.job_list )
406 #define toplevel_list (G.toplevel_list )
407 #define toplevel_jb (G.toplevel_jb )
408 #define ctrl_z_flag (G.ctrl_z_flag )
410 #define global_argv (G.global_argv )
411 #define global_argc (G.global_argc )
412 #define last_return_code (G.last_return_code)
414 #define fake_mode (G.fake_mode )
416 #define last_bg_pid (G.last_bg_pid )
417 #define top_var (G.top_var )
418 #define shell_ver (G.shell_ver )
419 #if ENABLE_FEATURE_SH_STANDALONE
420 #define nofork_save (G.nofork_save )
423 #define toplevel_jb (G.toplevel_jb )
425 #define charmap (G.charmap )
426 #define user_input_buf (G.user_input_buf )
427 #define INIT_G() do { \
428 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
432 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
436 static void syntax(const char *msg)
438 /* Was using fancy stuff:
439 * (interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
440 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
441 void (*fp)(const char *s, ...);
443 fp = (interactive_fd ? bb_error_msg : bb_error_msg_and_die);
444 fp(msg ? "%s: %s" : "syntax error", "syntax error", msg);
449 static void syntax_lineno(int line)
451 void (*fp)(const char *s, ...);
453 fp = (interactive_fd ? bb_error_msg : bb_error_msg_and_die);
454 fp("syntax error hush.c:%d", line);
456 #define syntax(str) syntax_lineno(__LINE__)
459 /* Index of subroutines: */
460 /* in_str manipulations: */
461 static int static_get(struct in_str *i);
462 static int static_peek(struct in_str *i);
463 static int file_get(struct in_str *i);
464 static int file_peek(struct in_str *i);
465 static void setup_file_in_str(struct in_str *i, FILE *f);
466 static void setup_string_in_str(struct in_str *i, const char *s);
467 /* "run" the final data structures: */
468 #if !defined(DEBUG_CLEAN)
469 #define free_pipe_list(head, indent) free_pipe_list(head)
470 #define free_pipe(pi, indent) free_pipe(pi)
472 static int free_pipe_list(struct pipe *head, int indent);
473 static int free_pipe(struct pipe *pi, int indent);
474 /* really run the final data structures: */
475 static int setup_redirects(struct child_prog *prog, int squirrel[]);
476 static int run_list(struct pipe *pi);
478 #define pseudo_exec_argv(ptrs2free, argv) pseudo_exec_argv(argv)
479 #define pseudo_exec(ptrs2free, child) pseudo_exec(child)
481 static void pseudo_exec_argv(char **ptrs2free, char **argv) ATTRIBUTE_NORETURN;
482 static void pseudo_exec(char **ptrs2free, struct child_prog *child) ATTRIBUTE_NORETURN;
483 static int run_pipe(struct pipe *pi);
484 /* variable assignment: */
485 static int is_assignment(const char *s);
486 /* data structure manipulation: */
487 static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
488 static void initialize_context(struct p_context *ctx);
489 static int done_word(o_string *dest, struct p_context *ctx);
490 static int done_command(struct p_context *ctx);
491 static void done_pipe(struct p_context *ctx, pipe_style type);
492 /* primary string parsing: */
493 static int redirect_dup_num(struct in_str *input);
494 static int redirect_opt_num(o_string *o);
496 static int process_command_subs(o_string *dest,
497 struct in_str *input, const char *subst_end);
499 static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
500 static const char *lookup_param(const char *src);
501 static int handle_dollar(o_string *dest,
502 struct in_str *input);
503 static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, const char *end_trigger);
505 static int parse_and_run_stream(struct in_str *inp, int parse_flag);
506 static int parse_and_run_string(const char *s, int parse_flag);
507 static int parse_and_run_file(FILE *f);
508 /* job management: */
509 static int checkjobs(struct pipe* fg_pipe);
511 static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
512 static void insert_bg_job(struct pipe *pi);
513 static void remove_bg_job(struct pipe *pi);
514 static void delete_finished_bg_job(struct pipe *pi);
516 int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
518 /* local variable support */
519 static char **expand_strvec_to_strvec(char **argv);
521 static char *expand_strvec_to_string(char **argv);
522 /* used for expansion of right hand of assignments */
523 static char *expand_string_to_string(const char *str);
524 static struct variable *get_local_var(const char *name);
525 static int set_local_var(char *str, int flg_export);
526 static void unset_local_var(const char *name);
529 static char **add_strings_to_strings(int need_xstrdup, char **strings, char **add)
550 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
551 v[count1 + count2] = NULL;
554 v[count1 + i] = need_xstrdup ? xstrdup(add[i]) : add[i];
558 /* 'add' should be a malloced pointer */
559 static char **add_string_to_strings(char **strings, char *add)
566 return add_strings_to_strings(0, strings, v);
569 static void free_strings(char **strings)
580 #define EXTRA_PTRS 5 /* 1 for NULL, 1 for args, 3 for paranoid reasons */
581 static char **alloc_ptrs(char **argv)
586 return xzalloc((v - argv + EXTRA_PTRS) * sizeof(v[0]));
591 static void debug_print_strings(const char *prefix, char **vv)
593 fprintf(stderr, "%s:\n", prefix);
595 fprintf(stderr, " '%s'\n", *vv++);
598 #define debug_print_strings(prefix, vv) ((void)0)
602 /* Function prototypes for builtins */
603 static int builtin_cd(char **argv);
604 static int builtin_echo(char **argv);
605 static int builtin_eval(char **argv);
606 static int builtin_exec(char **argv);
607 static int builtin_exit(char **argv);
608 static int builtin_export(char **argv);
610 static int builtin_fg_bg(char **argv);
611 static int builtin_jobs(char **argv);
614 static int builtin_help(char **argv);
616 static int builtin_pwd(char **argv);
617 static int builtin_read(char **argv);
618 static int builtin_test(char **argv);
619 static int builtin_true(char **argv);
620 static int builtin_set(char **argv);
621 static int builtin_shift(char **argv);
622 static int builtin_source(char **argv);
623 static int builtin_umask(char **argv);
624 static int builtin_unset(char **argv);
625 //static int builtin_not_written(char **argv);
627 /* Table of built-in functions. They can be forked or not, depending on
628 * context: within pipes, they fork. As simple commands, they do not.
629 * When used in non-forking context, they can change global variables
630 * in the parent shell process. If forked, of course they cannot.
631 * For example, 'unset foo | whatever' will parse and run, but foo will
632 * still be set at the end. */
633 struct built_in_command {
635 int (*function)(char **argv);
638 #define BLTIN(cmd, func, help) { cmd, func, help }
640 #define BLTIN(cmd, func, help) { cmd, func }
644 /* For now, echo and test are unconditionally enabled.
645 * Maybe make it configurable? */
646 static const struct built_in_command bltins[] = {
647 BLTIN("." , builtin_source, "Run commands in a file"),
648 BLTIN(":" , builtin_true, "No-op"),
649 BLTIN("[" , builtin_test, "Test condition"),
650 BLTIN("[[" , builtin_test, "Test condition"),
652 BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"),
654 // BLTIN("break" , builtin_not_written, "Exit for, while or until loop"),
655 BLTIN("cd" , builtin_cd, "Change directory"),
656 // BLTIN("continue", builtin_not_written, "Continue for, while or until loop"),
657 BLTIN("echo" , builtin_echo, "Write strings to stdout"),
658 BLTIN("eval" , builtin_eval, "Construct and run shell command"),
659 BLTIN("exec" , builtin_exec, "Execute command, don't return to shell"),
660 BLTIN("exit" , builtin_exit, "Exit"),
661 BLTIN("export", builtin_export, "Set environment variable"),
663 BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"),
664 BLTIN("jobs" , builtin_jobs, "List active jobs"),
666 BLTIN("pwd" , builtin_pwd, "Print current directory"),
667 BLTIN("read" , builtin_read, "Input environment variable"),
668 // BLTIN("return", builtin_not_written, "Return from a function"),
669 BLTIN("set" , builtin_set, "Set/unset shell local variables"),
670 BLTIN("shift" , builtin_shift, "Shift positional parameters"),
671 // BLTIN("trap" , builtin_not_written, "Trap signals"),
672 BLTIN("test" , builtin_test, "Test condition"),
673 // BLTIN("ulimit", builtin_not_written, "Control resource limits"),
674 BLTIN("umask" , builtin_umask, "Set file creation mask"),
675 BLTIN("unset" , builtin_unset, "Unset environment variable"),
677 BLTIN("help" , builtin_help, "List shell built-in commands"),
681 /* Signals are grouped, we handle them in batches */
682 static void set_misc_sighandler(void (*handler)(int))
693 static void set_fatal_sighandler(void (*handler)(int))
702 /* bash 3.2 seems to handle these just like 'fatal' ones */
708 static void set_jobctrl_sighandler(void (*handler)(int))
716 /* SIGCHLD is special and handled separately */
718 static void set_every_sighandler(void (*handler)(int))
720 set_fatal_sighandler(handler);
721 set_jobctrl_sighandler(handler);
722 set_misc_sighandler(handler);
723 signal(SIGCHLD, handler);
726 static void handler_ctrl_c(int sig ATTRIBUTE_UNUSED)
728 debug_printf_jobs("got sig %d\n", sig);
729 // as usual we can have all kinds of nasty problems with leaked malloc data here
730 siglongjmp(toplevel_jb, 1);
733 static void handler_ctrl_z(int sig ATTRIBUTE_UNUSED)
737 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
739 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
742 if (!pid) { /* child */
744 die_sleep = 0; /* let nofork's xfuncs die */
746 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
747 set_every_sighandler(SIG_DFL);
748 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
749 debug_printf_jobs("returning in child\n");
750 /* return to nofork, it will eventually exit now,
751 * not return back to shell */
755 /* finish filling up pipe info */
756 toplevel_list->pgrp = pid; /* child is in its own pgrp */
757 toplevel_list->progs[0].pid = pid;
758 /* parent needs to longjmp out of running nofork.
759 * we will "return" exitcode 0, with child put in background */
760 // as usual we can have all kinds of nasty problems with leaked malloc data here
761 debug_printf_jobs("siglongjmp in parent\n");
762 siglongjmp(toplevel_jb, 1);
765 /* Restores tty foreground process group, and exits.
766 * May be called as signal handler for fatal signal
767 * (will faithfully resend signal to itself, producing correct exit state)
768 * or called directly with -EXITCODE.
769 * We also call it if xfunc is exiting. */
770 static void sigexit(int sig) ATTRIBUTE_NORETURN;
771 static void sigexit(int sig)
773 /* Disable all signals: job control, SIGPIPE, etc. */
774 sigprocmask_allsigs(SIG_BLOCK);
777 tcsetpgrp(interactive_fd, saved_tty_pgrp);
779 /* Not a signal, just exit */
783 kill_myself_with_sig(sig); /* does not return */
786 /* Restores tty foreground process group, and exits. */
787 static void hush_exit(int exitcode) ATTRIBUTE_NORETURN;
788 static void hush_exit(int exitcode)
790 fflush(NULL); /* flush all streams */
791 sigexit(- (exitcode & 0xff));
796 #define set_fatal_sighandler(handler) ((void)0)
797 #define set_jobctrl_sighandler(handler) ((void)0)
798 #define hush_exit(e) exit(e)
803 static const char *set_cwd(void)
805 if (cwd == bb_msg_unknown)
806 cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
807 cwd = xrealloc_getcwd_or_warn((char *)cwd);
809 cwd = bb_msg_unknown;
814 /* built-in 'true' handler */
815 static int builtin_true(char **argv ATTRIBUTE_UNUSED)
820 /* built-in 'test' handler */
821 static int builtin_test(char **argv)
828 return test_main(argc, argv - argc);
831 /* built-in 'test' handler */
832 static int builtin_echo(char **argv)
839 return echo_main(argc, argv - argc);
842 /* built-in 'eval' handler */
843 static int builtin_eval(char **argv)
845 int rcode = EXIT_SUCCESS;
848 char *str = expand_strvec_to_string(argv + 1);
849 parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP);
851 rcode = last_return_code;
856 /* built-in 'cd <path>' handler */
857 static int builtin_cd(char **argv)
860 if (argv[1] == NULL) {
861 // bash does nothing (exitcode 0) if HOME is ""; if it's unset,
862 // bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
863 newdir = getenv("HOME") ? : "/";
867 printf("cd: %s: %s\n", newdir, strerror(errno));
874 /* built-in 'exec' handler */
875 static int builtin_exec(char **argv)
878 return EXIT_SUCCESS; /* bash does this */
881 char **ptrs2free = alloc_ptrs(argv);
883 // FIXME: if exec fails, bash does NOT exit! We do...
884 pseudo_exec_argv(ptrs2free, argv + 1);
889 /* built-in 'exit' handler */
890 static int builtin_exit(char **argv)
892 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
893 //puts("exit"); /* bash does it */
894 // TODO: warn if we have background jobs: "There are stopped jobs"
895 // On second consecutive 'exit', exit anyway.
897 hush_exit(last_return_code);
898 /* mimic bash: exit 123abc == exit 255 + error msg */
899 xfunc_error_retval = 255;
900 /* bash: exit -2 == exit 254, no error msg */
901 hush_exit(xatoi(argv[1]) & 0xff);
904 /* built-in 'export VAR=value' handler */
905 static int builtin_export(char **argv)
908 char *name = argv[1];
912 // ash emits: export VAR='VAL'
913 // bash: declare -x VAR="VAL"
914 // (both also escape as needed (quotes, $, etc))
922 value = strchr(name, '=');
924 /* They are exporting something without a =VALUE */
925 struct variable *var;
927 var = get_local_var(name);
932 /* bash does not return an error when trying to export
933 * an undefined variable. Do likewise. */
937 set_local_var(xstrdup(name), 1);
942 /* built-in 'fg' and 'bg' handler */
943 static int builtin_fg_bg(char **argv)
950 /* If they gave us no args, assume they want the last backgrounded task */
952 for (pi = job_list; pi; pi = pi->next) {
953 if (pi->jobid == last_jobid) {
957 bb_error_msg("%s: no current job", argv[0]);
960 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
961 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
964 for (pi = job_list; pi; pi = pi->next) {
965 if (pi->jobid == jobnum) {
969 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
972 // TODO: bash prints a string representation
973 // of job being foregrounded (like "sleep 1 | cat")
974 if (*argv[0] == 'f') {
975 /* Put the job into the foreground. */
976 tcsetpgrp(interactive_fd, pi->pgrp);
979 /* Restart the processes in the job */
980 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_progs, pi->pgrp);
981 for (i = 0; i < pi->num_progs; i++) {
982 debug_printf_jobs("reviving pid %d\n", pi->progs[i].pid);
983 pi->progs[i].is_stopped = 0;
985 pi->stopped_progs = 0;
987 i = kill(- pi->pgrp, SIGCONT);
989 if (errno == ESRCH) {
990 delete_finished_bg_job(pi);
993 bb_perror_msg("kill (SIGCONT)");
997 if (*argv[0] == 'f') {
999 return checkjobs_and_fg_shell(pi);
1001 return EXIT_SUCCESS;
1005 /* built-in 'help' handler */
1006 #if ENABLE_HUSH_HELP
1007 static int builtin_help(char **argv ATTRIBUTE_UNUSED)
1009 const struct built_in_command *x;
1011 printf("\nBuilt-in commands:\n");
1012 printf("-------------------\n");
1013 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
1014 printf("%s\t%s\n", x->cmd, x->descr);
1017 return EXIT_SUCCESS;
1022 /* built-in 'jobs' handler */
1023 static int builtin_jobs(char **argv ATTRIBUTE_UNUSED)
1026 const char *status_string;
1028 for (job = job_list; job; job = job->next) {
1029 if (job->running_progs == job->stopped_progs)
1030 status_string = "Stopped";
1032 status_string = "Running";
1034 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
1036 return EXIT_SUCCESS;
1040 /* built-in 'pwd' handler */
1041 static int builtin_pwd(char **argv ATTRIBUTE_UNUSED)
1044 return EXIT_SUCCESS;
1047 /* built-in 'read VAR' handler */
1048 static int builtin_read(char **argv)
1051 const char *name = argv[1] ? argv[1] : "REPLY";
1053 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
1054 return set_local_var(string, 0);
1057 /* built-in 'set [VAR=value]' handler */
1058 static int builtin_set(char **argv)
1060 char *temp = argv[1];
1064 for (e = top_var; e; e = e->next)
1067 set_local_var(xstrdup(temp), 0);
1069 return EXIT_SUCCESS;
1073 /* Built-in 'shift' handler */
1074 static int builtin_shift(char **argv)
1080 if (n >= 0 && n < global_argc) {
1081 global_argv[n] = global_argv[0];
1084 return EXIT_SUCCESS;
1086 return EXIT_FAILURE;
1089 /* Built-in '.' handler (read-in and execute commands from file) */
1090 static int builtin_source(char **argv)
1095 if (argv[1] == NULL)
1096 return EXIT_FAILURE;
1098 /* XXX search through $PATH is missing */
1099 input = fopen(argv[1], "r");
1101 bb_error_msg("cannot open '%s'", argv[1]);
1102 return EXIT_FAILURE;
1104 close_on_exec_on(fileno(input));
1106 /* Now run the file */
1107 /* XXX argv and argc are broken; need to save old global_argv
1108 * (pointer only is OK!) on this stack frame,
1109 * set global_argv=argv+1, recurse, and restore. */
1110 status = parse_and_run_file(input);
1115 static int builtin_umask(char **argv)
1118 const char *arg = argv[1];
1121 new_umask = strtoul(arg, &end, 8);
1122 if (*end != '\0' || end == arg) {
1123 return EXIT_FAILURE;
1126 new_umask = umask(0);
1127 printf("%.3o\n", (unsigned) new_umask);
1130 return EXIT_SUCCESS;
1133 /* built-in 'unset VAR' handler */
1134 static int builtin_unset(char **argv)
1136 /* bash always returns true */
1137 unset_local_var(argv[1]);
1138 return EXIT_SUCCESS;
1144 #define B_CHUNK (32 * sizeof(char*))
1146 static void o_reset(o_string *o)
1154 static void o_free(o_string *o)
1157 memset(o, 0, sizeof(*o));
1160 static void o_grow_by(o_string *o, int len)
1162 if (o->length + len > o->maxlen) {
1163 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1164 o->data = xrealloc(o->data, 1 + o->maxlen);
1168 static void o_addchr(o_string *o, int ch)
1170 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1172 o->data[o->length] = ch;
1174 o->data[o->length] = '\0';
1177 static void o_addstr(o_string *o, const char *str, int len)
1180 memcpy(&o->data[o->length], str, len);
1182 o->data[o->length] = '\0';
1185 /* My analysis of quoting semantics tells me that state information
1186 * is associated with a destination, not a source.
1188 static void o_addqchr(o_string *o, int ch)
1191 if (strchr("*?[\\", ch)) {
1193 o->data[o->length] = '\\';
1197 o->data[o->length] = ch;
1199 o->data[o->length] = '\0';
1202 static void o_addQchr(o_string *o, int ch)
1205 if (o->o_quote && strchr("*?[\\", ch)) {
1207 o->data[o->length] = '\\';
1211 o->data[o->length] = ch;
1213 o->data[o->length] = '\0';
1216 static void o_addQstr(o_string *o, const char *str, int len)
1219 o_addstr(o, str, len);
1225 int ordinary_cnt = strcspn(str, "*?[\\");
1226 if (ordinary_cnt > len) /* paranoia */
1228 o_addstr(o, str, ordinary_cnt);
1229 if (ordinary_cnt == len)
1231 str += ordinary_cnt;
1232 len -= ordinary_cnt - 1; /* we are processing + 1 char below */
1236 if (ch) { /* it is necessarily one of "*?[\\" */
1238 o->data[o->length] = '\\';
1242 o->data[o->length] = ch;
1244 o->data[o->length] = '\0';
1248 /* A special kind of o_string for $VAR and `cmd` expansion.
1249 * It contains char* list[] at the beginning, which is grown in 16 element
1250 * increments. Actual string data starts at the next multiple of 16.
1251 * list[i] contains an INDEX (int!) into this string data.
1252 * It means that if list[] needs to grow, data needs to be moved higher up
1253 * but list[i]'s need not be modified.
1254 * NB: remembering how many list[i]'s you have there is crucial.
1255 * o_finalize_list() operation post-processes this structure - calculates
1256 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1258 static int o_save_ptr(o_string *o, int n)
1260 char **list = (char**)o->data;
1264 if (!o->has_empty_slot) {
1265 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1266 string_len = o->length - string_start;
1267 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1268 //bb_error_msg("list[%d]=%d string_start=%d (growing)", n, string_len, string_start);
1269 /* list[n] points to string_start, make space for 16 more pointers */
1270 o->maxlen += 0x10 * sizeof(list[0]);
1271 o->data = xrealloc(o->data, o->maxlen + 1);
1272 list = (char**)o->data;
1273 memmove(list + n + 0x10, list + n, string_len);
1274 o->length += 0x10 * sizeof(list[0]);
1276 //else bb_error_msg("list[%d]=%d string_start=%d", n, string_len, string_start);
1278 /* We have empty slot at list[n], reuse without growth */
1279 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1280 string_len = o->length - string_start;
1281 //bb_error_msg("list[%d]=%d string_start=%d (empty slot)", n, string_len, string_start);
1282 o->has_empty_slot = 0;
1284 list[n] = (char*)string_len;
1288 static int o_get_last_ptr(o_string *o, int n)
1290 char **list = (char**)o->data;
1291 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1293 return ((int)list[n-1]) + string_start;
1296 static char **o_finalize_list(o_string *o, int n)
1298 char **list = (char**)o->data;
1301 o_save_ptr(o, n); /* force growth for list[n] if necessary */
1302 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]);
1306 list[n] = o->data + (int)list[n] + string_start;
1312 static void o_debug_list(const char *prefix, o_string *o, int n)
1314 char **list = (char**)o->data;
1315 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1317 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1318 prefix, list, n, string_start, o->length, o->maxlen);
1320 fprintf(stderr, " list[%d]=%d '%s'\n", i, (int)list[i],
1321 o->data + (int)list[i] + string_start);
1325 const char *p = o->data + (int)list[n] + string_start;
1326 fprintf(stderr, " total_sz:%d\n", (p + strlen(p) + 1) - o->data);
1330 #define o_debug_list(prefix, o, n) ((void)0)
1337 static int static_get(struct in_str *i)
1340 if (ch == '\0') return EOF;
1344 static int static_peek(struct in_str *i)
1349 #if ENABLE_HUSH_INTERACTIVE
1350 #if ENABLE_FEATURE_EDITING
1351 static void cmdedit_set_initial_prompt(void)
1353 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1356 PS1 = getenv("PS1");
1361 #endif /* EDITING */
1363 static const char* setup_prompt_string(int promptmode)
1365 const char *prompt_str;
1366 debug_printf("setup_prompt_string %d ", promptmode);
1367 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1368 /* Set up the prompt */
1369 if (promptmode == 0) { /* PS1 */
1371 PS1 = xasprintf("%s %c ", cwd, (geteuid() != 0) ? '$' : '#');
1377 prompt_str = (promptmode == 0) ? PS1 : PS2;
1379 debug_printf("result '%s'\n", prompt_str);
1383 static void get_user_input(struct in_str *i)
1386 const char *prompt_str;
1388 prompt_str = setup_prompt_string(i->promptmode);
1389 #if ENABLE_FEATURE_EDITING
1390 /* Enable command line editing only while a command line
1391 * is actually being read */
1393 r = read_line_input(prompt_str, user_input_buf, BUFSIZ-1, line_input_state);
1394 } while (r == 0); /* repeat if Ctrl-C */
1395 i->eof_flag = (r < 0);
1396 if (i->eof_flag) { /* EOF/error detected */
1397 user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1398 user_input_buf[1] = '\0';
1401 fputs(prompt_str, stdout);
1403 user_input_buf[0] = r = fgetc(i->file);
1404 /*user_input_buf[1] = '\0'; - already is and never changed */
1405 i->eof_flag = (r == EOF);
1407 i->p = user_input_buf;
1409 #endif /* INTERACTIVE */
1411 /* This is the magic location that prints prompts
1412 * and gets data back from the user */
1413 static int file_get(struct in_str *i)
1417 /* If there is data waiting, eat it up */
1418 if (i->p && *i->p) {
1419 #if ENABLE_HUSH_INTERACTIVE
1423 if (i->eof_flag && !*i->p)
1426 /* need to double check i->file because we might be doing something
1427 * more complicated by now, like sourcing or substituting. */
1428 #if ENABLE_HUSH_INTERACTIVE
1429 if (interactive_fd && i->promptme && i->file == stdin) {
1432 } while (!*i->p); /* need non-empty line */
1433 i->promptmode = 1; /* PS2 */
1438 ch = fgetc(i->file);
1440 debug_printf("file_get: got a '%c' %d\n", ch, ch);
1441 #if ENABLE_HUSH_INTERACTIVE
1448 /* All the callers guarantee this routine will never be
1449 * used right after a newline, so prompting is not needed.
1451 static int file_peek(struct in_str *i)
1454 if (i->p && *i->p) {
1455 if (i->eof_flag && !i->p[1])
1459 ch = fgetc(i->file);
1460 i->eof_flag = (ch == EOF);
1461 i->peek_buf[0] = ch;
1462 i->peek_buf[1] = '\0';
1464 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
1468 static void setup_file_in_str(struct in_str *i, FILE *f)
1470 i->peek = file_peek;
1472 #if ENABLE_HUSH_INTERACTIVE
1474 i->promptmode = 0; /* PS1 */
1480 static void setup_string_in_str(struct in_str *i, const char *s)
1482 i->peek = static_peek;
1483 i->get = static_get;
1484 #if ENABLE_HUSH_INTERACTIVE
1486 i->promptmode = 0; /* PS1 */
1492 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
1493 * and stderr if they are redirected. */
1494 static int setup_redirects(struct child_prog *prog, int squirrel[])
1497 struct redir_struct *redir;
1499 for (redir = prog->redirects; redir; redir = redir->next) {
1500 if (redir->dup == -1 && redir->glob_word == NULL) {
1501 /* something went wrong in the parse. Pretend it didn't happen */
1504 if (redir->dup == -1) {
1506 mode = redir_table[redir->type].mode;
1507 p = expand_string_to_string(redir->glob_word[0]);
1508 openfd = open_or_warn(p, mode);
1511 /* this could get lost if stderr has been redirected, but
1512 bash and ash both lose it as well (though zsh doesn't!) */
1516 openfd = redir->dup;
1519 if (openfd != redir->fd) {
1520 if (squirrel && redir->fd < 3) {
1521 squirrel[redir->fd] = dup(redir->fd);
1524 //close(openfd); // close(-3) ??!
1526 dup2(openfd, redir->fd);
1527 if (redir->dup == -1)
1535 static void restore_redirects(int squirrel[])
1538 for (i = 0; i < 3; i++) {
1541 /* We simply die on error */
1547 /* Called after [v]fork() in run_pipe(), or from builtin_exec().
1549 * XXX no exit() here. If you don't exec, use _exit instead.
1550 * The at_exit handlers apparently confuse the calling process,
1551 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
1552 static void pseudo_exec_argv(char **ptrs2free, char **argv)
1556 const struct built_in_command *x;
1558 for (i = 0; is_assignment(argv[i]); i++) {
1559 debug_printf_exec("pid %d environment modification: %s\n",
1561 p = expand_string_to_string(argv[i]);
1568 /* If a variable is assigned in a forest, and nobody listens,
1569 * was it ever really set?
1572 _exit(EXIT_SUCCESS);
1574 argv = expand_strvec_to_strvec(argv);
1576 *ptrs2free++ = (char*) argv;
1580 * Check if the command matches any of the builtins.
1581 * Depending on context, this might be redundant. But it's
1582 * easier to waste a few CPU cycles than it is to figure out
1583 * if this is one of those cases.
1585 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
1586 if (strcmp(argv[0], x->cmd) == 0) {
1587 debug_printf_exec("running builtin '%s'\n", argv[0]);
1588 rcode = x->function(argv);
1594 /* Check if the command matches any busybox applets */
1595 #if ENABLE_FEATURE_SH_STANDALONE
1596 if (strchr(argv[0], '/') == NULL) {
1597 int a = find_applet_by_name(argv[0]);
1599 if (APPLET_IS_NOEXEC(a)) {
1600 debug_printf_exec("running applet '%s'\n", argv[0]);
1601 // is it ok that run_applet_no_and_exit() does exit(), not _exit()?
1602 run_applet_no_and_exit(a, argv);
1604 /* re-exec ourselves with the new arguments */
1605 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
1606 execvp(bb_busybox_exec_path, argv);
1607 /* If they called chroot or otherwise made the binary no longer
1608 * executable, fall through */
1613 debug_printf_exec("execing '%s'\n", argv[0]);
1614 execvp(argv[0], argv);
1615 bb_perror_msg("cannot exec '%s'", argv[0]);
1616 _exit(EXIT_FAILURE);
1619 /* Called after [v]fork() in run_pipe()
1621 static void pseudo_exec(char **ptrs2free, struct child_prog *child)
1624 pseudo_exec_argv(ptrs2free, child->argv);
1628 bb_error_msg_and_die("nested lists are not supported on NOMMU");
1631 debug_printf_exec("pseudo_exec: run_list\n");
1632 rcode = run_list(child->group);
1633 /* OK to leak memory by not calling free_pipe_list,
1634 * since this process is about to exit */
1639 /* Can happen. See what bash does with ">foo" by itself. */
1640 debug_printf("trying to pseudo_exec null command\n");
1641 _exit(EXIT_SUCCESS);
1645 static const char *get_cmdtext(struct pipe *pi)
1651 /* This is subtle. ->cmdtext is created only on first backgrounding.
1652 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
1653 * On subsequent bg argv is trashed, but we won't use it */
1656 argv = pi->progs[0].argv;
1657 if (!argv || !argv[0]) {
1658 pi->cmdtext = xzalloc(1);
1663 do len += strlen(*argv) + 1; while (*++argv);
1664 pi->cmdtext = p = xmalloc(len);
1665 argv = pi->progs[0].argv;
1667 len = strlen(*argv);
1668 memcpy(p, *argv, len);
1676 static void insert_bg_job(struct pipe *pi)
1678 struct pipe *thejob;
1681 /* Linear search for the ID of the job to use */
1683 for (thejob = job_list; thejob; thejob = thejob->next)
1684 if (thejob->jobid >= pi->jobid)
1685 pi->jobid = thejob->jobid + 1;
1687 /* Add thejob to the list of running jobs */
1689 thejob = job_list = xmalloc(sizeof(*thejob));
1691 for (thejob = job_list; thejob->next; thejob = thejob->next)
1693 thejob->next = xmalloc(sizeof(*thejob));
1694 thejob = thejob->next;
1697 /* Physically copy the struct job */
1698 memcpy(thejob, pi, sizeof(struct pipe));
1699 thejob->progs = xzalloc(sizeof(pi->progs[0]) * pi->num_progs);
1700 /* We cannot copy entire pi->progs[] vector! Double free()s will happen */
1701 for (i = 0; i < pi->num_progs; i++) {
1702 // TODO: do we really need to have so many fields which are just dead weight
1703 // at execution stage?
1704 thejob->progs[i].pid = pi->progs[i].pid;
1705 /* all other fields are not used and stay zero */
1707 thejob->next = NULL;
1708 thejob->cmdtext = xstrdup(get_cmdtext(pi));
1710 /* We don't wait for background thejobs to return -- append it
1711 to the list of backgrounded thejobs and leave it alone */
1712 printf("[%d] %d %s\n", thejob->jobid, thejob->progs[0].pid, thejob->cmdtext);
1713 last_bg_pid = thejob->progs[0].pid;
1714 last_jobid = thejob->jobid;
1717 static void remove_bg_job(struct pipe *pi)
1719 struct pipe *prev_pipe;
1721 if (pi == job_list) {
1722 job_list = pi->next;
1724 prev_pipe = job_list;
1725 while (prev_pipe->next != pi)
1726 prev_pipe = prev_pipe->next;
1727 prev_pipe->next = pi->next;
1730 last_jobid = job_list->jobid;
1735 /* remove a backgrounded job */
1736 static void delete_finished_bg_job(struct pipe *pi)
1739 pi->stopped_progs = 0;
1745 /* Checks to see if any processes have exited -- if they
1746 have, figure out why and see if a job has completed */
1747 static int checkjobs(struct pipe* fg_pipe)
1758 attributes = WUNTRACED;
1759 if (fg_pipe == NULL) {
1760 attributes |= WNOHANG;
1763 /* Do we do this right?
1764 * bash-3.00# sleep 20 | false
1766 * [3]+ Stopped sleep 20 | false
1767 * bash-3.00# echo $?
1768 * 1 <========== bg pipe is not fully done, but exitcode is already known!
1771 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
1772 //are stopped. Testcase: "cat | cat" in a script (not on command line)
1773 // + killall -STOP cat
1776 // TODO: safe_waitpid?
1777 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
1778 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
1780 #ifdef DEBUG_SHELL_JOBS
1781 if (WIFSTOPPED(status))
1782 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
1783 childpid, WSTOPSIG(status), WEXITSTATUS(status));
1784 if (WIFSIGNALED(status))
1785 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
1786 childpid, WTERMSIG(status), WEXITSTATUS(status));
1787 if (WIFEXITED(status))
1788 debug_printf_jobs("pid %d exited, exitcode %d\n",
1789 childpid, WEXITSTATUS(status));
1791 /* Were we asked to wait for fg pipe? */
1794 for (i = 0; i < fg_pipe->num_progs; i++) {
1795 debug_printf_jobs("check pid %d\n", fg_pipe->progs[i].pid);
1796 if (fg_pipe->progs[i].pid == childpid) {
1797 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
1799 fg_pipe->progs[i].pid = 0;
1800 fg_pipe->running_progs--;
1801 if (i == fg_pipe->num_progs - 1) {
1802 /* last process gives overall exitstatus */
1803 rcode = WEXITSTATUS(status);
1804 if (fg_pipe->pi_inverted)
1808 fg_pipe->progs[i].is_stopped = 1;
1809 fg_pipe->stopped_progs++;
1811 debug_printf_jobs("fg_pipe: running_progs %d stopped_progs %d\n",
1812 fg_pipe->running_progs, fg_pipe->stopped_progs);
1813 if (fg_pipe->running_progs - fg_pipe->stopped_progs <= 0) {
1814 /* All processes in fg pipe have exited/stopped */
1816 if (fg_pipe->running_progs)
1817 insert_bg_job(fg_pipe);
1821 /* There are still running processes in the fg pipe */
1825 /* fall through to searching process in bg pipes */
1829 /* We asked to wait for bg or orphaned children */
1830 /* No need to remember exitcode in this case */
1831 for (pi = job_list; pi; pi = pi->next) {
1833 while (prognum < pi->num_progs) {
1834 if (pi->progs[prognum].pid == childpid)
1835 goto found_pi_and_prognum;
1841 /* Happens when shell is used as init process (init=/bin/sh) */
1842 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
1846 found_pi_and_prognum:
1849 pi->progs[prognum].pid = 0;
1850 pi->running_progs--;
1851 if (!pi->running_progs) {
1852 printf(JOB_STATUS_FORMAT, pi->jobid,
1853 "Done", pi->cmdtext);
1854 delete_finished_bg_job(pi);
1858 pi->stopped_progs++;
1859 pi->progs[prognum].is_stopped = 1;
1864 /* wait found no children or failed */
1866 if (childpid && errno != ECHILD)
1867 bb_perror_msg("waitpid");
1872 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1875 int rcode = checkjobs(fg_pipe);
1876 /* Job finished, move the shell to the foreground */
1877 p = getpgid(0); /* pgid of our process */
1878 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
1879 if (tcsetpgrp(interactive_fd, p) && errno != ENOTTY)
1880 bb_perror_msg("tcsetpgrp-4a");
1885 /* run_pipe() starts all the jobs, but doesn't wait for anything
1886 * to finish. See checkjobs().
1888 * return code is normally -1, when the caller has to wait for children
1889 * to finish to determine the exit status of the pipe. If the pipe
1890 * is a simple builtin command, however, the action is done by the
1891 * time run_pipe returns, and the exit code is provided as the
1894 * The input of the pipe is always stdin, the output is always
1895 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1896 * because it tries to avoid running the command substitution in
1897 * subshell, when that is in fact necessary. The subshell process
1898 * now has its stdout directed to the input of the appropriate pipe,
1899 * so this routine is noticeably simpler.
1901 * Returns -1 only if started some children. IOW: we have to
1902 * mask out retvals of builtins etc with 0xff!
1904 static int run_pipe(struct pipe *pi)
1908 int pipefds[2]; /* pipefds[0] is for reading */
1909 struct child_prog *child;
1910 const struct built_in_command *x;
1912 /* it is not always needed, but we aim to smaller code */
1913 int squirrel[] = { -1, -1, -1 };
1915 const int single_fg = (pi->num_progs == 1 && pi->followup != PIPE_BG);
1917 debug_printf_exec("run_pipe start: single_fg=%d\n", single_fg);
1922 pi->running_progs = 1;
1923 pi->stopped_progs = 0;
1925 /* Check if this is a simple builtin (not part of a pipe).
1926 * Builtins within pipes have to fork anyway, and are handled in
1927 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1929 child = &(pi->progs[0]);
1930 if (single_fg && child->group && child->subshell == 0) {
1931 debug_printf("non-subshell grouping\n");
1932 setup_redirects(child, squirrel);
1933 debug_printf_exec(": run_list\n");
1934 rcode = run_list(child->group) & 0xff;
1935 restore_redirects(squirrel);
1936 debug_printf_exec("run_pipe return %d\n", rcode);
1937 if (pi->pi_inverted)
1942 if (single_fg && child->argv != NULL) {
1943 char **argv_expanded;
1944 char **argv = child->argv;
1946 for (i = 0; is_assignment(argv[i]); i++)
1948 if (i != 0 && argv[i] == NULL) {
1949 /* assignments, but no command: set the local environment */
1950 for (i = 0; argv[i] != NULL; i++) {
1951 debug_printf("local environment set: %s\n", argv[i]);
1952 p = expand_string_to_string(argv[i]);
1953 set_local_var(p, 0);
1955 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1957 for (i = 0; is_assignment(argv[i]); i++) {
1958 p = expand_string_to_string(argv[i]);
1961 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
1962 if (strcmp(argv[i], x->cmd) == 0) {
1963 if (x->function == builtin_exec && argv[i+1] == NULL) {
1964 debug_printf("magic exec\n");
1965 setup_redirects(child, NULL);
1966 return EXIT_SUCCESS;
1968 debug_printf("builtin inline %s\n", argv[0]);
1969 /* XXX setup_redirects acts on file descriptors, not FILEs.
1970 * This is perfect for work that comes after exec().
1971 * Is it really safe for inline use? Experimentally,
1972 * things seem to work with glibc. */
1973 setup_redirects(child, squirrel);
1974 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv[i+1]);
1975 argv_expanded = expand_strvec_to_strvec(argv + i);
1976 rcode = x->function(argv_expanded) & 0xff;
1977 free(argv_expanded);
1978 restore_redirects(squirrel);
1979 debug_printf_exec("run_pipe return %d\n", rcode);
1980 if (pi->pi_inverted)
1985 #if ENABLE_FEATURE_SH_STANDALONE
1987 int a = find_applet_by_name(argv[i]);
1988 if (a >= 0 && APPLET_IS_NOFORK(a)) {
1989 setup_redirects(child, squirrel);
1990 save_nofork_data(&nofork_save);
1991 argv_expanded = argv + i;
1992 argv_expanded = expand_strvec_to_strvec(argv + i);
1993 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
1994 rcode = run_nofork_applet_prime(&nofork_save, a, argv_expanded);
1995 free(argv_expanded);
1996 restore_redirects(squirrel);
1997 debug_printf_exec("run_pipe return %d\n", rcode);
1998 if (pi->pi_inverted)
2006 /* Disable job control signals for shell (parent) and
2007 * for initial child code after fork */
2008 set_jobctrl_sighandler(SIG_IGN);
2010 /* Going to fork a child per each pipe member */
2011 pi->running_progs = 0;
2014 for (i = 0; i < pi->num_progs; i++) {
2016 char **ptrs2free = NULL;
2018 child = &(pi->progs[i]);
2020 debug_printf_exec(": pipe member '%s' '%s'...\n", child->argv[0], child->argv[1]);
2022 ptrs2free = alloc_ptrs(child->argv);
2025 debug_printf_exec(": pipe member with no argv\n");
2027 /* pipes are inserted between pairs of commands */
2030 if ((i + 1) < pi->num_progs)
2033 child->pid = BB_MMU ? fork() : vfork();
2034 if (!child->pid) { /* child */
2035 if (ENABLE_HUSH_JOB)
2036 die_sleep = 0; /* let nofork's xfuncs die */
2038 /* Every child adds itself to new process group
2039 * with pgid == pid_of_first_child_in_pipe */
2040 if (run_list_level == 1 && interactive_fd) {
2042 /* Don't do pgrp restore anymore on fatal signals */
2043 set_fatal_sighandler(SIG_DFL);
2045 if (pgrp < 0) /* true for 1st process only */
2047 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
2048 /* We do it in *every* child, not just first,
2050 tcsetpgrp(interactive_fd, pgrp);
2054 xmove_fd(nextin, 0);
2055 xmove_fd(pipefds[1], 1); /* write end */
2057 close(pipefds[0]); /* read end */
2058 /* Like bash, explicit redirects override pipes,
2059 * and the pipe fd is available for dup'ing. */
2060 setup_redirects(child, NULL);
2062 /* Restore default handlers just prior to exec */
2063 set_jobctrl_sighandler(SIG_DFL);
2064 set_misc_sighandler(SIG_DFL);
2065 signal(SIGCHLD, SIG_DFL);
2066 pseudo_exec(ptrs2free, child); /* does not return */
2069 free_strings(ptrs2free);
2071 if (child->pid < 0) { /* [v]fork failed */
2072 /* Clearly indicate, was it fork or vfork */
2073 bb_perror_msg(BB_MMU ? "fork" : "vfork");
2075 pi->running_progs++;
2077 /* Second and next children need to know pid of first one */
2079 pi->pgrp = child->pid;
2085 if ((i + 1) < pi->num_progs)
2086 close(pipefds[1]); /* write end */
2087 /* Pass read (output) pipe end to next iteration */
2088 nextin = pipefds[0];
2091 if (!pi->running_progs) {
2092 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
2096 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->running_progs);
2100 #ifndef debug_print_tree
2101 static void debug_print_tree(struct pipe *pi, int lvl)
2103 static const char *PIPE[] = {
2109 static const char *RES[] = {
2110 [RES_NONE ] = "NONE" ,
2113 [RES_THEN ] = "THEN" ,
2114 [RES_ELIF ] = "ELIF" ,
2115 [RES_ELSE ] = "ELSE" ,
2118 #if ENABLE_HUSH_LOOPS
2119 [RES_FOR ] = "FOR" ,
2120 [RES_WHILE] = "WHILE",
2121 [RES_UNTIL] = "UNTIL",
2123 [RES_DONE ] = "DONE" ,
2126 [RES_XXXX ] = "XXXX" ,
2127 [RES_SNTX ] = "SNTX" ,
2134 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2135 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2137 while (prn < pi->num_progs) {
2138 struct child_prog *child = &pi->progs[prn];
2139 char **argv = child->argv;
2141 fprintf(stderr, "%*s prog %d", lvl*2, "", prn);
2143 fprintf(stderr, " group %s: (argv=%p)\n",
2144 (child->subshell ? "()" : "{}"),
2146 debug_print_tree(child->group, lvl+1);
2150 if (argv) while (*argv) {
2151 fprintf(stderr, " '%s'", *argv);
2154 fprintf(stderr, "\n");
2163 /* NB: called by pseudo_exec, and therefore must not modify any
2164 * global data until exec/_exit (we can be a child after vfork!) */
2165 static int run_list(struct pipe *pi)
2168 #if ENABLE_HUSH_LOOPS
2169 char *for_varname = NULL;
2170 char **for_lcur = NULL;
2171 char **for_list = NULL;
2175 int rcode = 0; /* probably for gcc only */
2176 int flag_restore = 0;
2178 int if_code = 0, next_if_code = 0; /* need double-buffer to handle elif */
2180 enum { if_code = 0, next_if_code = 0 };
2182 reserved_style rword;
2183 reserved_style skip_more_for_this_rword = RES_XXXX;
2185 debug_printf_exec("run_list start lvl %d\n", run_list_level + 1);
2187 #if ENABLE_HUSH_LOOPS
2188 /* check syntax for "for" */
2189 for (rpipe = pi; rpipe; rpipe = rpipe->next) {
2190 if ((rpipe->res_word == RES_IN || rpipe->res_word == RES_FOR)
2191 && (rpipe->next == NULL)
2193 syntax("malformed for"); /* no IN or no commands after IN */
2194 debug_printf_exec("run_list lvl %d return 1\n", run_list_level);
2197 if ((rpipe->res_word == RES_IN && rpipe->next->res_word == RES_IN && rpipe->next->progs[0].argv != NULL)
2198 || (rpipe->res_word == RES_FOR && rpipe->next->res_word != RES_IN)
2200 /* TODO: what is tested in the first condition? */
2201 syntax("malformed for"); /* 2nd condition: not followed by IN */
2202 debug_printf_exec("run_list lvl %d return 1\n", run_list_level);
2211 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
2212 * We are saving state before entering outermost list ("while...done")
2213 * so that ctrl-Z will correctly background _entire_ outermost list,
2214 * not just a part of it (like "sleep 1 | exit 2") */
2215 if (++run_list_level == 1 && interactive_fd) {
2216 if (sigsetjmp(toplevel_jb, 1)) {
2217 /* ctrl-Z forked and we are parent; or ctrl-C.
2218 * Sighandler has longjmped us here */
2219 signal(SIGINT, SIG_IGN);
2220 signal(SIGTSTP, SIG_IGN);
2221 /* Restore level (we can be coming from deep inside
2224 #if ENABLE_FEATURE_SH_STANDALONE
2225 if (nofork_save.saved) { /* if save area is valid */
2226 debug_printf_jobs("exiting nofork early\n");
2227 restore_nofork_data(&nofork_save);
2231 /* ctrl-Z has forked and stored pid of the child in pi->pid.
2232 * Remember this child as background job */
2235 /* ctrl-C. We just stop doing whatever we were doing */
2241 /* ctrl-Z handler will store pid etc in pi */
2244 #if ENABLE_FEATURE_SH_STANDALONE
2245 nofork_save.saved = 0; /* in case we will run a nofork later */
2247 signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
2248 signal(SIGINT, handler_ctrl_c);
2252 for (; pi; pi = flag_restore ? rpipe : pi->next) {
2253 rword = pi->res_word;
2254 #if ENABLE_HUSH_LOOPS
2255 if (rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR) {
2263 debug_printf_exec(": rword=%d if_code=%d next_if_code=%d skip_more=%d\n",
2264 rword, if_code, next_if_code, skip_more_for_this_rword);
2265 if (rword == skip_more_for_this_rword && flag_skip) {
2266 if (pi->followup == PIPE_SEQ)
2271 skip_more_for_this_rword = RES_XXXX;
2273 if (rword == RES_THEN || rword == RES_ELSE)
2274 if_code = next_if_code;
2275 if (rword == RES_THEN && if_code)
2277 if (rword == RES_ELSE && !if_code)
2279 if (rword == RES_ELIF && !if_code)
2282 #if ENABLE_HUSH_LOOPS
2283 if (rword == RES_FOR && pi->num_progs) {
2285 /* first loop through for */
2286 /* if no variable values after "in" we skip "for" */
2287 if (!pi->next->progs->argv)
2289 /* create list of variable values */
2290 debug_print_strings("for_list made from", pi->next->progs->argv);
2291 for_list = expand_strvec_to_strvec(pi->next->progs->argv);
2292 debug_print_strings("for_list", for_list);
2293 for_lcur = for_list;
2294 for_varname = pi->progs->argv[0];
2295 pi->progs->argv[0] = NULL;
2298 free(pi->progs->argv[0]);
2300 /* for loop is over, clean up */
2304 pi->progs->argv[0] = for_varname;
2307 /* insert next value from for_lcur */
2308 /* vda: does it need escaping? */
2309 pi->progs->argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
2311 if (rword == RES_IN)
2313 if (rword == RES_DO) {
2317 if (rword == RES_DONE) {
2325 if (pi->num_progs == 0)
2327 debug_printf_exec(": run_pipe with %d members\n", pi->num_progs);
2328 rcode = run_pipe(pi);
2330 /* We only ran a builtin: rcode was set by the return value
2331 * of run_pipe(), and we don't need to wait for anything. */
2332 } else if (pi->followup == PIPE_BG) {
2333 /* What does bash do with attempts to background builtins? */
2334 /* Even bash 3.2 doesn't do that well with nested bg:
2335 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
2336 * I'm NOT treating inner &'s as jobs */
2338 if (run_list_level == 1)
2341 rcode = EXIT_SUCCESS;
2344 if (run_list_level == 1 && interactive_fd) {
2345 /* waits for completion, then fg's main shell */
2346 rcode = checkjobs_and_fg_shell(pi);
2350 /* this one just waits for completion */
2351 rcode = checkjobs(pi);
2353 debug_printf_exec(": checkjobs returned %d\n", rcode);
2355 debug_printf_exec(": setting last_return_code=%d\n", rcode);
2356 last_return_code = rcode;
2358 if (rword == RES_IF || rword == RES_ELIF)
2359 next_if_code = rcode; /* can be overwritten a number of times */
2361 #if ENABLE_HUSH_LOOPS
2362 if (rword == RES_WHILE)
2363 flag_rep = !last_return_code;
2364 if (rword == RES_UNTIL)
2365 flag_rep = last_return_code;
2367 if ((rcode == EXIT_SUCCESS && pi->followup == PIPE_OR)
2368 || (rcode != EXIT_SUCCESS && pi->followup == PIPE_AND)
2370 skip_more_for_this_rword = rword;
2377 /* ctrl-Z forked somewhere in the past, we are the child,
2378 * and now we completed running the list. Exit. */
2382 if (!--run_list_level && interactive_fd) {
2383 signal(SIGTSTP, SIG_IGN);
2384 signal(SIGINT, SIG_IGN);
2387 debug_printf_exec("run_list lvl %d return %d\n", run_list_level + 1, rcode);
2391 /* return code is the exit status of the pipe */
2392 static int free_pipe(struct pipe *pi, int indent)
2395 struct child_prog *child;
2396 struct redir_struct *r, *rnext;
2397 int a, i, ret_code = 0;
2399 if (pi->stopped_progs > 0)
2401 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2402 for (i = 0; i < pi->num_progs; i++) {
2403 child = &pi->progs[i];
2404 debug_printf_clean("%s command %d:\n", indenter(indent), i);
2406 for (a = 0, p = child->argv; *p; a++, p++) {
2407 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
2409 free_strings(child->argv);
2411 } else if (child->group) {
2412 debug_printf_clean("%s begin group (subshell:%d)\n", indenter(indent), child->subshell);
2413 ret_code = free_pipe_list(child->group, indent+3);
2414 debug_printf_clean("%s end group\n", indenter(indent));
2416 debug_printf_clean("%s (nil)\n", indenter(indent));
2418 for (r = child->redirects; r; r = rnext) {
2419 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->type].descrip);
2421 /* guard against the case >$FOO, where foo is unset or blank */
2423 debug_printf_clean(" %s\n", r->glob_word[0]);
2424 free_strings(r->glob_word);
2425 r->glob_word = NULL;
2428 debug_printf_clean("&%d\n", r->dup);
2433 child->redirects = NULL;
2435 free(pi->progs); /* children are an array, they get freed all at once */
2444 static int free_pipe_list(struct pipe *head, int indent)
2446 int rcode = 0; /* if list has no members */
2447 struct pipe *pi, *next;
2449 for (pi = head; pi; pi = next) {
2450 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
2451 rcode = free_pipe(pi, indent);
2452 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
2454 /*pi->next = NULL;*/
2460 /* Select which version we will use */
2461 static int run_and_free_list(struct pipe *pi)
2464 debug_printf_exec("run_and_free_list entered\n");
2466 debug_printf_exec(": run_list with %d members\n", pi->num_progs);
2467 rcode = run_list(pi);
2469 /* free_pipe_list has the side effect of clearing memory.
2470 * In the long run that function can be merged with run_list,
2471 * but doing that now would hobble the debugging effort. */
2472 free_pipe_list(pi, /* indent: */ 0);
2473 debug_printf_exec("run_and_free_list return %d\n", rcode);
2477 /* Remove non-backslashed backslashes and add to "strings" vector.
2478 * XXX broken if the last character is '\\', check that before calling.
2480 static char **add_unq_string_to_strings(char **strings, const char *src)
2486 for (cnt = 1, s = src; s && *s; s++) {
2487 if (*s == '\\') s++;
2490 v = dest = xmalloc(cnt);
2491 for (s = src; s && *s; s++, dest++) {
2492 if (*s == '\\') s++;
2497 return add_string_to_strings(strings, v);
2500 /* XXX broken if the last character is '\\', check that before calling */
2501 static int glob_needed(const char *s)
2506 if (strchr("*[?", *s))
2512 static int xglob(char ***pglob, const char *pattern)
2514 if (glob_needed(pattern)) {
2518 memset(&globdata, 0, sizeof(globdata));
2519 gr = glob(pattern, 0, NULL, &globdata);
2520 debug_printf("glob returned %d\n", gr);
2521 if (gr == GLOB_NOSPACE)
2522 bb_error_msg_and_die("out of memory during glob");
2523 if (gr == GLOB_NOMATCH) {
2524 globfree(&globdata);
2527 if (gr != 0) { /* GLOB_ABORTED ? */
2528 bb_error_msg("glob(3) error %d", gr);
2530 if (globdata.gl_pathv && globdata.gl_pathv[0])
2531 *pglob = add_strings_to_strings(1, *pglob, globdata.gl_pathv);
2532 globfree(&globdata);
2537 /* quote removal, or more accurately, backslash removal */
2538 *pglob = add_unq_string_to_strings(*pglob, pattern);
2539 debug_print_strings("after xglob", *pglob);
2543 /* expand_strvec_to_strvec() takes a list of strings, expands
2544 * all variable references within and returns a pointer to
2545 * a list of expanded strings, possibly with larger number
2546 * of strings. (Think VAR="a b"; echo $VAR).
2547 * This new list is allocated as a single malloc block.
2548 * NULL-terminated list of char* pointers is at the beginning of it,
2549 * followed by strings themself.
2550 * Caller can deallocate entire list by single free(list). */
2552 /* Store given string, finalizing the word and starting new one whenever
2553 * we encounter ifs char(s). This is used for expanding variable values.
2554 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2555 static int expand_on_ifs(o_string *output, int n, const char *str)
2558 int word_len = strcspn(str, ifs);
2560 o_addQstr(output, str, word_len);
2563 if (!*str) /* EOL - do not finalize word */
2565 o_addchr(output, '\0');
2566 o_debug_list("expand_on_ifs", output, n);
2567 n = o_save_ptr(output, n);
2568 str += strspn(str, ifs); /* skip ifs chars */
2570 o_debug_list("expand_on_ifs[1]", output, n);
2574 /* Expand all variable references in given string, adding words to list[]
2575 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2576 * to be filled). This routine is extremely tricky: has to deal with
2577 * variables/parameters with whitespace, $* and $@, and constructs like
2578 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2579 /* NB: another bug is that we cannot detect empty strings yet:
2580 * "" or $empty"" expands to zero words, has to expand to empty word */
2581 static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
2583 /* or_mask is either 0 (normal case) or 0x80
2584 * (expansion of right-hand side of assignment == 1-element expand) */
2586 char first_ch, ored_ch;
2593 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
2594 o_debug_list("expand_vars_to_list", output, n);
2595 n = o_save_ptr(output, n);
2596 o_debug_list("expand_vars_to_list[0]", output, n);
2598 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
2599 o_string subst_result = NULL_O_STRING;
2601 o_addQstr(output, arg, p - arg);
2602 o_debug_list("expand_vars_to_list[1]", output, n);
2604 p = strchr(p, SPECIAL_VAR_SYMBOL);
2606 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2607 ored_ch |= first_ch;
2609 switch (first_ch & 0x7f) {
2610 /* Highest bit in first_ch indicates that var is double-quoted */
2612 /* FIXME: (echo $$) should still print pid of main shell */
2613 val = utoa(getpid()); /* rootpid? */
2615 case '!': /* bg pid */
2616 val = last_bg_pid ? utoa(last_bg_pid) : (char*)"";
2618 case '?': /* exitcode */
2619 val = utoa(last_return_code);
2621 case '#': /* argc */
2622 val = utoa(global_argc ? global_argc-1 : 0);
2627 if (!global_argv[i])
2629 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2630 while (global_argv[i]) {
2631 n = expand_on_ifs(output, n, global_argv[i]);
2632 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, global_argc-1);
2633 if (global_argv[i++][0] && global_argv[i]) {
2634 /* this argv[] is not empty and not last:
2635 * put terminating NUL, start new word */
2636 o_addchr(output, '\0');
2637 o_debug_list("expand_vars_to_list[2]", output, n);
2638 n = o_save_ptr(output, n);
2639 o_debug_list("expand_vars_to_list[3]", output, n);
2643 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2644 * and in this case should treat it like '$*' - see 'else...' below */
2645 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2647 o_addQstr(output, global_argv[i], strlen(global_argv[i]));
2648 if (++i >= global_argc)
2650 o_addchr(output, '\0');
2651 o_debug_list("expand_vars_to_list[4]", output, n);
2652 n = o_save_ptr(output, n);
2654 } else { /* quoted $*: add as one word */
2656 o_addQstr(output, global_argv[i], strlen(global_argv[i]));
2657 if (!global_argv[++i])
2660 o_addchr(output, ifs[0]);
2665 struct in_str input;
2668 //bb_error_msg("SUBST '%s' first_ch %x", arg, first_ch);
2669 setup_string_in_str(&input, arg);
2670 process_command_subs(&subst_result, &input, NULL);
2671 //bb_error_msg("RES '%s'", subst_result.data);
2672 val = subst_result.data;
2677 arg[0] = first_ch & 0x7f;
2678 if (isdigit(arg[0])) {
2681 if (i < global_argc)
2682 val = global_argv[i];
2684 val = lookup_param(arg);
2687 *p = SPECIAL_VAR_SYMBOL;
2688 if (!(first_ch & 0x80)) { /* unquoted $VAR */
2690 n = expand_on_ifs(output, n, val);
2693 } /* else: quoted $VAR, val will be appended below */
2696 o_addQstr(output, val, strlen(val));
2699 o_free(&subst_result);
2701 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2704 o_debug_list("expand_vars_to_list[a]", output, n);
2705 o_addQstr(output, arg, strlen(arg) + 1);
2706 o_debug_list("expand_vars_to_list[b]", output, n);
2707 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2708 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2711 /* allow to reuse list[n] later without re-growth */
2712 output->has_empty_slot = 1;
2714 o_addchr(output, '\0');
2719 static char **expand_variables(char **argv, char or_mask)
2724 o_string output = NULL_O_STRING;
2729 n = expand_vars_to_list(&output, n, *v++, or_mask);
2730 o_debug_list("expand_variables", &output, n);
2732 /* output.data (malloced in one block) gets returned in "list" */
2733 list = o_finalize_list(&output, n);
2739 debug_printf_expand("list[%d]=%p '%s'\n", m, list[m], list[m]);
2747 static char **expand_strvec_to_strvec(char **argv)
2752 debug_print_strings("expand_strvec_to_strvec: pre expand", argv);
2753 exp = argv = expand_variables(argv, 0);
2754 debug_print_strings("expand_strvec_to_strvec: post expand", argv);
2756 int r = xglob(&res, *argv);
2758 bb_error_msg("xglob returned %d on '%s'", r, *argv);
2759 //TODO: testcase for bad glob pattern behavior
2763 debug_print_strings("expand_strvec_to_strvec: res", res);
2767 /* used for expansion of right hand of assignments */
2768 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2770 static char *expand_string_to_string(const char *str)
2772 char *argv[2], **list;
2774 argv[0] = (char*)str;
2776 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2777 if (ENABLE_HUSH_DEBUG)
2778 if (!list[0] || list[1])
2779 bb_error_msg_and_die("BUG in varexp2");
2780 /* actually, just move string 2*sizeof(char*) bytes back */
2781 strcpy((char*)list, list[0]);
2782 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2787 static char* expand_strvec_to_string(char **argv)
2791 list = expand_variables(argv, 0x80);
2792 /* Convert all NULs to spaces */
2796 if (ENABLE_HUSH_DEBUG)
2797 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2798 bb_error_msg_and_die("BUG in varexp3");
2799 list[n][-1] = ' '; /* TODO: or to ifs[0]? */
2803 strcpy((char*)list, list[0]);
2804 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2808 /* This is used to get/check local shell variables */
2809 static struct variable *get_local_var(const char *name)
2811 struct variable *cur;
2817 for (cur = top_var; cur; cur = cur->next) {
2818 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
2824 /* str holds "NAME=VAL" and is expected to be malloced.
2825 * We take ownership of it. */
2826 static int set_local_var(char *str, int flg_export)
2828 struct variable *cur;
2832 value = strchr(str, '=');
2833 if (!value) { /* not expected to ever happen? */
2838 name_len = value - str + 1; /* including '=' */
2839 cur = top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
2841 if (strncmp(cur->varstr, str, name_len) != 0) {
2843 /* Bail out. Note that now cur points
2844 * to last var in linked list */
2850 /* We found an existing var with this name */
2852 if (cur->flg_read_only) {
2853 bb_error_msg("%s: readonly variable", str);
2857 unsetenv(str); /* just in case */
2859 if (strcmp(cur->varstr, str) == 0) {
2864 if (cur->max_len >= strlen(str)) {
2865 /* This one is from startup env, reuse space */
2866 strcpy(cur->varstr, str);
2869 /* max_len == 0 signifies "malloced" var, which we can
2870 * (and has to) free */
2874 goto set_str_and_exp;
2877 /* Not found - create next variable struct */
2878 cur->next = xzalloc(sizeof(*cur));
2885 cur->flg_export = 1;
2886 if (cur->flg_export)
2887 return putenv(cur->varstr);
2891 static void unset_local_var(const char *name)
2893 struct variable *cur;
2894 struct variable *prev = prev; /* for gcc */
2899 name_len = strlen(name);
2902 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2903 if (cur->flg_read_only) {
2904 bb_error_msg("%s: readonly variable", name);
2907 /* prev is ok to use here because 1st variable, HUSH_VERSION,
2908 * is ro, and we cannot reach this code on the 1st pass */
2909 prev->next = cur->next;
2910 unsetenv(cur->varstr);
2921 static int is_assignment(const char *s)
2923 if (!s || !isalpha(*s))
2926 while (isalnum(*s) || *s == '_')
2931 /* the src parameter allows us to peek forward to a possible &n syntax
2932 * for file descriptor duplication, e.g., "2>&1".
2933 * Return code is 0 normally, 1 if a syntax error is detected in src.
2934 * Resource errors (in xmalloc) cause the process to exit */
2935 static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2936 struct in_str *input)
2938 struct child_prog *child = ctx->child;
2939 struct redir_struct *redir = child->redirects;
2940 struct redir_struct *last_redir = NULL;
2942 /* Create a new redir_struct and drop it onto the end of the linked list */
2945 redir = redir->next;
2947 redir = xzalloc(sizeof(struct redir_struct));
2948 /* redir->next = NULL; */
2949 /* redir->glob_word = NULL; */
2951 last_redir->next = redir;
2953 child->redirects = redir;
2956 redir->type = style;
2957 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
2959 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2961 /* Check for a '2>&1' type redirect */
2962 redir->dup = redirect_dup_num(input);
2963 if (redir->dup == -2)
2964 return 1; /* syntax error */
2965 if (redir->dup != -1) {
2966 /* Erik had a check here that the file descriptor in question
2967 * is legit; I postpone that to "run time"
2968 * A "-" representation of "close me" shows up as a -3 here */
2969 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2971 /* We do _not_ try to open the file that src points to,
2972 * since we need to return and let src be expanded first.
2973 * Set ctx->pending_redirect, so we know what to do at the
2974 * end of the next parsed word. */
2975 ctx->pending_redirect = redir;
2980 static struct pipe *new_pipe(void)
2983 pi = xzalloc(sizeof(struct pipe));
2984 /*pi->followup = 0; - deliberately invalid value */
2986 pi->res_word = RES_NONE;
2990 static void initialize_context(struct p_context *ctx)
2992 memset(ctx, 0, sizeof(*ctx));
2993 ctx->pipe = ctx->list_head = new_pipe();
2994 /* Create the memory for child, roughly:
2995 * ctx->pipe->progs = new struct child_prog;
2996 * ctx->pipe->progs[0].family = ctx->pipe;
2997 * ctx->child = &ctx->pipe->progs[0];
3002 /* If a reserved word is found and processed, parse context is modified
3003 * and 1 is returned.
3004 * Handles if, then, elif, else, fi, for, while, until, do, done.
3005 * case, function, and select are obnoxious, save those for later.
3007 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS
3008 static int reserved_word(const o_string *word, struct p_context *ctx)
3010 struct reserved_combo {
3016 FLAG_END = (1 << RES_NONE ),
3018 FLAG_IF = (1 << RES_IF ),
3019 FLAG_THEN = (1 << RES_THEN ),
3020 FLAG_ELIF = (1 << RES_ELIF ),
3021 FLAG_ELSE = (1 << RES_ELSE ),
3022 FLAG_FI = (1 << RES_FI ),
3024 #if ENABLE_HUSH_LOOPS
3025 FLAG_FOR = (1 << RES_FOR ),
3026 FLAG_WHILE = (1 << RES_WHILE),
3027 FLAG_UNTIL = (1 << RES_UNTIL),
3028 FLAG_DO = (1 << RES_DO ),
3029 FLAG_DONE = (1 << RES_DONE ),
3030 FLAG_IN = (1 << RES_IN ),
3032 FLAG_START = (1 << RES_XXXX ),
3034 /* Mostly a list of accepted follow-up reserved words.
3035 * FLAG_END means we are done with the sequence, and are ready
3036 * to turn the compound list into a command.
3037 * FLAG_START means the word must start a new compound list.
3039 static const struct reserved_combo reserved_list[] = {
3041 { "!", RES_NONE, 0 },
3042 { "if", RES_IF, FLAG_THEN | FLAG_START },
3043 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3044 { "elif", RES_ELIF, FLAG_THEN },
3045 { "else", RES_ELSE, FLAG_FI },
3046 { "fi", RES_FI, FLAG_END },
3048 #if ENABLE_HUSH_LOOPS
3049 { "for", RES_FOR, FLAG_IN | FLAG_START },
3050 { "while", RES_WHILE, FLAG_DO | FLAG_START },
3051 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
3052 { "in", RES_IN, FLAG_DO },
3053 { "do", RES_DO, FLAG_DONE },
3054 { "done", RES_DONE, FLAG_END }
3058 const struct reserved_combo *r;
3060 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3061 if (strcmp(word->data, r->literal) != 0)
3063 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3064 if (r->flag == 0) { /* '!' */
3065 if (ctx->res_w == RES_IN) {
3066 /* 'for a in ! a b c; ...' - ! isn't a keyword here */
3069 if (ctx->res_w == RES_FOR /* example: 'for ! a' */
3070 || ctx->ctx_inverted /* bash doesn't accept '! ! true' */
3073 ctx->res_w = RES_SNTX;
3075 ctx->ctx_inverted = 1;
3078 if (r->flag & FLAG_START) {
3079 struct p_context *new;
3080 debug_printf("push stack\n");
3081 #if ENABLE_HUSH_LOOPS
3082 if (ctx->res_w == RES_IN || ctx->res_w == RES_FOR) {
3083 syntax("malformed for"); /* example: 'for if' */
3084 ctx->res_w = RES_SNTX;
3088 new = xmalloc(sizeof(*new));
3089 *new = *ctx; /* physical copy */
3090 initialize_context(ctx);
3092 } else if (ctx->res_w == RES_NONE || !(ctx->old_flag & (1 << r->res))) {
3094 ctx->res_w = RES_SNTX;
3097 ctx->res_w = r->res;
3098 ctx->old_flag = r->flag;
3099 if (ctx->old_flag & FLAG_END) {
3100 struct p_context *old;
3101 debug_printf("pop stack\n");
3102 done_pipe(ctx, PIPE_SEQ);
3104 old->child->group = ctx->list_head;
3105 old->child->subshell = 0;
3106 *ctx = *old; /* physical copy */
3114 #define reserved_word(word, ctx) ((int)0)
3117 /* Word is complete, look at it and update parsing context.
3118 * Normal return is 0.
3119 * Syntax or xglob errors return 1. */
3120 static int done_word(o_string *word, struct p_context *ctx)
3122 struct child_prog *child = ctx->child;
3123 char ***glob_target;
3125 debug_printf_parse("done_word entered: '%s' %p\n", word->data, child);
3126 if (word->length == 0 && !word->nonnull) {
3127 debug_printf_parse("done_word return 0: true null, ignored\n");
3130 if (ctx->pending_redirect) {
3131 glob_target = &ctx->pending_redirect->glob_word;
3133 if (child->group) { /* TODO: example how to trigger? */
3135 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
3139 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
3140 if (reserved_word(word, ctx)) {
3142 debug_printf_parse("done_word return %d\n", (ctx->res_w == RES_SNTX));
3143 return (ctx->res_w == RES_SNTX);
3146 glob_target = &child->argv;
3149 if (word->length || word->nonnull) {
3150 *glob_target = add_string_to_strings(*glob_target, xstrdup(word->data));
3151 debug_print_strings("glob_target appended", *glob_target);
3155 if (ctx->pending_redirect) {
3156 /* NB: don't free_strings(ctx->pending_redirect->glob_word) here */
3157 if (ctx->pending_redirect->glob_word
3158 && ctx->pending_redirect->glob_word[0]
3159 && ctx->pending_redirect->glob_word[1]
3161 /* more than one word resulted from globbing redir */
3162 ctx->pending_redirect = NULL;
3163 bb_error_msg("ambiguous redirect");
3164 debug_printf_parse("done_word return 1: ambiguous redirect\n");
3167 ctx->pending_redirect = NULL;
3169 #if ENABLE_HUSH_LOOPS
3170 if (ctx->res_w == RES_FOR) { /* comment? */
3172 //looks like (word->length == 0 && !word->nonnull) is true here, always
3173 //(due to o_reset). done_word would return at once. Why then?
3174 // done_word(word, ctx);
3175 done_pipe(ctx, PIPE_SEQ);
3178 debug_printf_parse("done_word return 0\n");
3182 /* The only possible error here is out of memory, in which case
3184 static int done_command(struct p_context *ctx)
3186 /* The child is really already in the pipe structure, so
3187 * advance the pipe counter and make a new, null child. */
3188 struct pipe *pi = ctx->pipe;
3189 struct child_prog *child = ctx->child;
3192 if (child->group == NULL
3193 && child->argv == NULL
3194 && child->redirects == NULL
3196 debug_printf_parse("done_command: skipping null cmd, num_progs=%d\n", pi->num_progs);
3197 return pi->num_progs;
3200 debug_printf_parse("done_command: ++num_progs=%d\n", pi->num_progs);
3202 debug_printf_parse("done_command: initializing, num_progs=%d\n", pi->num_progs);
3205 /* Only real trickiness here is that the uncommitted
3206 * child structure is not counted in pi->num_progs. */
3207 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
3208 child = &pi->progs[pi->num_progs];
3210 memset(child, 0, sizeof(*child));
3214 /* but ctx->pipe and ctx->list_head remain unchanged */
3216 return pi->num_progs; /* used only for 0/nonzero check */
3219 static void done_pipe(struct p_context *ctx, pipe_style type)
3224 debug_printf_parse("done_pipe entered, followup %d\n", type);
3225 not_null = done_command(ctx); /* implicit closure of previous command */
3226 ctx->pipe->followup = type;
3227 ctx->pipe->res_word = ctx->res_w;
3228 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3229 ctx->ctx_inverted = 0;
3230 /* Without this check, even just <enter> on command line generates
3231 * tree of three NOPs (!). Which is harmless but annoying.
3232 * IOW: it is safe to do it unconditionally. */
3235 ctx->pipe->next = new_p;
3237 ctx->child = NULL; /* needed! */
3238 /* Create the memory for child, roughly:
3239 * ctx->pipe->progs = new struct child_prog;
3240 * ctx->pipe->progs[0].family = ctx->pipe;
3241 * ctx->child = &ctx->pipe->progs[0];
3245 debug_printf_parse("done_pipe return\n");
3248 /* peek ahead in the in_str to find out if we have a "&n" construct,
3249 * as in "2>&1", that represents duplicating a file descriptor.
3250 * returns either -2 (syntax error), -1 (no &), or the number found.
3252 static int redirect_dup_num(struct in_str *input)
3254 int ch, d = 0, ok = 0;
3256 if (ch != '&') return -1;
3258 i_getch(input); /* get the & */
3262 return -3; /* "-" represents "close me" */
3264 while (isdigit(ch)) {
3265 d = d*10 + (ch-'0');
3272 bb_error_msg("ambiguous redirect");
3276 /* If a redirect is immediately preceded by a number, that number is
3277 * supposed to tell which file descriptor to redirect. This routine
3278 * looks for such preceding numbers. In an ideal world this routine
3279 * needs to handle all the following classes of redirects...
3280 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3281 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3282 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3283 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3284 * A -1 output from this program means no valid number was found, so the
3285 * caller should use the appropriate default for this redirection.
3287 static int redirect_opt_num(o_string *o)
3293 for (num = 0; num < o->length; num++) {
3294 if (!isdigit(*(o->data + num))) {
3298 /* reuse num (and save an int) */
3299 num = atoi(o->data);
3304 #if ENABLE_HUSH_TICK
3305 static FILE *generate_stream_from_list(struct pipe *head)
3308 int pid, channel[2];
3311 /* *** NOMMU WARNING *** */
3312 /* By using vfork here, we suspend parent till child exits or execs.
3313 * If child will not do it before it fills the pipe, it can block forever
3314 * in write(STDOUT_FILENO), and parent (shell) will be also stuck.
3316 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >TESTFILE
3317 * huge=`cat TESTFILE` # will block here forever
3320 pid = BB_MMU ? fork() : vfork();
3322 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
3323 if (pid == 0) { /* child */
3324 if (ENABLE_HUSH_JOB)
3325 die_sleep = 0; /* let nofork's xfuncs die */
3326 close(channel[0]); /* NB: close _first_, then move fd! */
3327 xmove_fd(channel[1], 1);
3328 /* Prevent it from trying to handle ctrl-z etc */
3332 /* Process substitution is not considered to be usual
3333 * 'command execution'.
3334 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not. */
3335 /* Not needed, we are relying on it being disabled
3336 * everywhere outside actual command execution. */
3337 /*set_jobctrl_sighandler(SIG_IGN);*/
3338 set_misc_sighandler(SIG_DFL);
3339 /* Freeing 'head' here would break NOMMU. */
3340 _exit(run_list(head));
3343 pf = fdopen(channel[0], "r");
3345 /* 'head' is freed by the caller */
3348 /* Return code is exit status of the process that is run. */
3349 static int process_command_subs(o_string *dest,
3350 struct in_str *input,
3351 const char *subst_end)
3353 int retcode, ch, eol_cnt;
3354 o_string result = NULL_O_STRING;
3355 struct p_context inner;
3357 struct in_str pipe_str;
3359 initialize_context(&inner);
3361 /* recursion to generate command */
3362 retcode = parse_stream(&result, &inner, input, subst_end);
3364 return retcode; /* syntax error or EOF */
3365 done_word(&result, &inner);
3366 done_pipe(&inner, PIPE_SEQ);
3369 p = generate_stream_from_list(inner.list_head);
3372 close_on_exec_on(fileno(p));
3373 setup_file_in_str(&pipe_str, p);
3375 /* now send results of command back into original context */
3377 while ((ch = i_getch(&pipe_str)) != EOF) {
3383 o_addQchr(dest, '\n');
3386 /* Even unquoted `echo '\'` results in two backslashes
3387 * (which are converted into one by globbing later) */
3388 if (!dest->o_quote && ch == '\\') {
3391 o_addQchr(dest, ch);
3394 debug_printf("done reading from pipe, pclose()ing\n");
3395 /* This is the step that wait()s for the child. Should be pretty
3396 * safe, since we just read an EOF from its stdout. We could try
3397 * to do better, by using wait(), and keeping track of background jobs
3398 * at the same time. That would be a lot of work, and contrary
3399 * to the KISS philosophy of this program. */
3400 retcode = fclose(p);
3401 free_pipe_list(inner.list_head, /* indent: */ 0);
3402 debug_printf("closed FILE from child, retcode=%d\n", retcode);
3407 static int parse_group(o_string *dest, struct p_context *ctx,
3408 struct in_str *input, int ch)
3411 const char *endch = NULL;
3412 struct p_context sub;
3413 struct child_prog *child = ctx->child;
3415 debug_printf_parse("parse_group entered\n");
3418 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3421 initialize_context(&sub);
3425 child->subshell = 1;
3427 rcode = parse_stream(dest, &sub, input, endch);
3429 done_word(dest, &sub); /* finish off the final word in the subcontext */
3430 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
3431 child->group = sub.list_head;
3433 debug_printf_parse("parse_group return %d\n", rcode);
3435 /* child remains "open", available for possible redirects */
3438 /* Basically useful version until someone wants to get fancier,
3439 * see the bash man page under "Parameter Expansion" */
3440 static const char *lookup_param(const char *src)
3442 struct variable *var = get_local_var(src);
3444 return strchr(var->varstr, '=') + 1;
3448 #if ENABLE_HUSH_TICK
3449 /* Subroutines for copying $(...) and `...` things */
3450 static void add_till_backquote(o_string *dest, struct in_str *input);
3452 static void add_till_single_quote(o_string *dest, struct in_str *input)
3455 int ch = i_getch(input);
3463 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3464 static void add_till_double_quote(o_string *dest, struct in_str *input)
3467 int ch = i_getch(input);
3470 if (ch == '\\') { /* \x. Copy both chars. */
3472 ch = i_getch(input);
3478 add_till_backquote(dest, input);
3482 //if (ch == '$') ...
3485 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3487 * "Within the backquoted style of command substitution, backslash
3488 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3489 * The search for the matching backquote shall be satisfied by the first
3490 * backquote found without a preceding backslash; during this search,
3491 * if a non-escaped backquote is encountered within a shell comment,
3492 * a here-document, an embedded command substitution of the $(command)
3493 * form, or a quoted string, undefined results occur. A single-quoted
3494 * or double-quoted string that begins, but does not end, within the
3495 * "`...`" sequence produces undefined results."
3497 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3499 static void add_till_backquote(o_string *dest, struct in_str *input)
3502 int ch = i_getch(input);
3505 if (ch == '\\') { /* \x. Copy both chars unless it is \` */
3506 int ch2 = i_getch(input);
3507 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
3516 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3517 * quoting and nested ()s.
3518 * "With the $(command) style of command substitution, all characters
3519 * following the open parenthesis to the matching closing parenthesis
3520 * constitute the command. Any valid shell script can be used for command,
3521 * except a script consisting solely of redirections which produces
3522 * unspecified results."
3524 * echo $(echo '(TEST)' BEST) (TEST) BEST
3525 * echo $(echo 'TEST)' BEST) TEST) BEST
3526 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3528 static void add_till_closing_curly_brace(o_string *dest, struct in_str *input)
3532 int ch = i_getch(input);
3542 add_till_single_quote(dest, input);
3547 add_till_double_quote(dest, input);
3551 if (ch == '\\') { /* \x. Copy verbatim. Important for \(, \) */
3552 ch = i_getch(input);
3560 #endif /* ENABLE_HUSH_TICK */
3562 /* return code: 0 for OK, 1 for syntax error */
3563 static int handle_dollar(o_string *dest, struct in_str *input)
3565 int ch = i_peek(input); /* first character after the $ */
3566 unsigned char quote_mask = dest->o_quote ? 0x80 : 0;
3568 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
3570 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3572 debug_printf_parse(": '%c'\n", ch);
3574 o_addchr(dest, ch | quote_mask);
3577 if (!isalnum(ch) && ch != '_')
3580 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3581 } else if (isdigit(ch)) {
3583 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3584 debug_printf_parse(": '%c'\n", ch);
3586 o_addchr(dest, ch | quote_mask);
3587 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3588 } else switch (ch) {
3590 case '!': /* last bg pid */
3591 case '?': /* last exit code */
3592 case '#': /* number of args */
3593 case '*': /* args */
3594 case '@': /* args */
3595 goto make_one_char_var;
3597 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3599 /* XXX maybe someone will try to escape the '}' */
3601 ch = i_getch(input);
3604 if (!isalnum(ch) && ch != '_') {
3605 syntax("unterminated ${name}");
3606 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3609 debug_printf_parse(": '%c'\n", ch);
3610 o_addchr(dest, ch | quote_mask);
3613 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3615 #if ENABLE_HUSH_TICK
3617 //int pos = dest->length;
3619 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3620 o_addchr(dest, quote_mask | '`');
3621 add_till_closing_curly_brace(dest, input);
3622 //bb_error_msg("RES '%s'", dest->data + pos);
3623 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3629 /* still unhandled, but should be eventually */
3630 bb_error_msg("unhandled syntax: $%c", ch);
3634 o_addQchr(dest, '$');
3636 debug_printf_parse("handle_dollar return 0\n");
3640 /* return code is 0 for normal exit, 1 for syntax error */
3641 static int parse_stream(o_string *dest, struct p_context *ctx,
3642 struct in_str *input, const char *end_trigger)
3646 redir_type redir_style;
3649 /* Only double-quote state is handled in the state variable dest->o_quote.
3650 * A single-quote triggers a bypass of the main loop until its mate is
3651 * found. When recursing, quote state is passed in via dest->o_quote. */
3653 debug_printf_parse("parse_stream entered, end_trigger='%s'\n", end_trigger);
3658 ch = i_getch(input);
3662 next = i_peek(input);
3664 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
3665 ch, ch, m, dest->o_quote);
3666 if (m == CHAR_ORDINARY
3667 || (m != CHAR_SPECIAL && dest->o_quote)
3670 syntax("unterminated \"");
3671 debug_printf_parse("parse_stream return 1: unterminated \"\n");
3674 o_addQchr(dest, ch);
3677 if (m == CHAR_IFS) {
3678 if (done_word(dest, ctx)) {
3679 debug_printf_parse("parse_stream return 1: done_word!=0\n");
3684 /* If we aren't performing a substitution, treat
3685 * a newline as a command separator.
3686 * [why we don't handle it exactly like ';'? --vda] */
3687 if (end_trigger && ch == '\n') {
3688 done_pipe(ctx, PIPE_SEQ);
3692 if (!dest->o_quote && strchr(end_trigger, ch)) {
3693 /* Special case: (...word) makes last word terminate,
3694 * as if ';' is seen */
3696 done_word(dest, ctx);
3697 done_pipe(ctx, PIPE_SEQ);
3699 if (ctx->res_w == RES_NONE) {
3700 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
3709 if (dest->length == 0 && !dest->o_quote) {
3712 if (ch == EOF || ch == '\n')
3717 o_addQchr(dest, ch);
3723 debug_printf_parse("parse_stream return 1: \\<eof>\n");
3727 * "The backslash retains its special meaning [in "..."]
3728 * only when followed by one of the following characters:
3729 * $, `, ", \, or <newline>. A double quote may be quoted
3730 * within double quotes by preceding it with a backslash.
3731 * If enabled, history expansion will be performed unless
3732 * an ! appearing in double quotes is escaped using
3733 * a backslash. The backslash preceding the ! is not removed."
3735 if (dest->o_quote) {
3736 if (strchr("$`\"\\", next) != NULL) {
3737 o_addqchr(dest, i_getch(input));
3739 o_addqchr(dest, '\\');
3742 o_addchr(dest, '\\');
3743 o_addchr(dest, i_getch(input));
3747 if (handle_dollar(dest, input) != 0) {
3748 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3755 ch = i_getch(input);
3757 syntax("unterminated '");
3758 debug_printf_parse("parse_stream return 1: unterminated '\n");
3763 o_addqchr(dest, ch);
3768 dest->o_quote ^= 1; /* invert */
3770 #if ENABLE_HUSH_TICK
3772 //int pos = dest->length;
3773 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3774 o_addchr(dest, dest->o_quote ? 0x80 | '`' : '`');
3775 add_till_backquote(dest, input);
3776 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3777 //bb_error_msg("RES '%s'", dest->data + pos);
3782 redir_fd = redirect_opt_num(dest);
3783 done_word(dest, ctx);
3784 redir_style = REDIRECT_OVERWRITE;
3786 redir_style = REDIRECT_APPEND;
3790 else if (next == '(') {
3791 syntax(">(process) not supported");
3792 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
3796 setup_redirect(ctx, redir_fd, redir_style, input);
3799 redir_fd = redirect_opt_num(dest);
3800 done_word(dest, ctx);
3801 redir_style = REDIRECT_INPUT;
3803 redir_style = REDIRECT_HEREIS;
3805 } else if (next == '>') {
3806 redir_style = REDIRECT_IO;
3810 else if (next == '(') {
3811 syntax("<(process) not supported");
3812 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
3816 setup_redirect(ctx, redir_fd, redir_style, input);
3819 done_word(dest, ctx);
3820 done_pipe(ctx, PIPE_SEQ);
3823 done_word(dest, ctx);
3826 done_pipe(ctx, PIPE_AND);
3828 done_pipe(ctx, PIPE_BG);
3832 done_word(dest, ctx);
3835 done_pipe(ctx, PIPE_OR);
3837 /* we could pick up a file descriptor choice here
3838 * with redirect_opt_num(), but bash doesn't do it.
3839 * "echo foo 2| cat" yields "foo 2". */
3845 if (parse_group(dest, ctx, input, ch) != 0) {
3846 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
3852 /* proper use of this character is caught by end_trigger */
3853 syntax("unexpected } or )");
3854 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
3857 if (ENABLE_HUSH_DEBUG)
3858 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
3861 /* Complain if quote? No, maybe we just finished a command substitution
3862 * that was quoted. Example:
3863 * $ echo "`cat foo` plus more"
3864 * and we just got the EOF generated by the subshell that ran "cat foo"
3865 * The only real complaint is if we got an EOF when end_trigger != NULL,
3866 * that is, we were really supposed to get end_trigger, and never got
3867 * one before the EOF. Can't use the standard "syntax error" return code,
3868 * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
3869 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
3875 static void set_in_charmap(const char *set, int code)
3878 charmap[(unsigned char)*set++] = code;
3881 static void update_charmap(void)
3883 /* char *ifs and char charmap[256] are both globals. */
3884 ifs = getenv("IFS");
3887 /* Precompute a list of 'flow through' behavior so it can be treated
3888 * quickly up front. Computation is necessary because of IFS.
3889 * Special case handling of IFS == " \t\n" is not implemented.
3890 * The charmap[] array only really needs two bits each,
3891 * and on most machines that would be faster (reduced L1 cache use).
3893 memset(charmap, CHAR_ORDINARY, sizeof(charmap));
3894 #if ENABLE_HUSH_TICK
3895 set_in_charmap("\\$\"`", CHAR_SPECIAL);
3897 set_in_charmap("\\$\"", CHAR_SPECIAL);
3899 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
3900 set_in_charmap(ifs, CHAR_IFS); /* are ordinary if quoted */
3903 /* most recursion does not come through here, the exception is
3904 * from builtin_source() and builtin_eval() */
3905 static int parse_and_run_stream(struct in_str *inp, int parse_flag)
3907 struct p_context ctx;
3908 o_string temp = NULL_O_STRING;
3912 initialize_context(&ctx);
3914 #if ENABLE_HUSH_INTERACTIVE
3915 inp->promptmode = 0; /* PS1 */
3917 /* We will stop & execute after each ';' or '\n'.
3918 * Example: "sleep 9999; echo TEST" + ctrl-C:
3919 * TEST should be printed */
3920 rcode = parse_stream(&temp, &ctx, inp, ";\n");
3921 if (rcode != 1 && ctx.old_flag != 0) {
3924 if (rcode != 1 && ctx.old_flag == 0) {
3925 done_word(&temp, &ctx);
3926 done_pipe(&ctx, PIPE_SEQ);
3927 debug_print_tree(ctx.list_head, 0);
3928 debug_printf_exec("parse_stream_outer: run_and_free_list\n");
3929 run_and_free_list(ctx.list_head);
3931 /* We arrive here also if rcode == 1 (error in parse_stream) */
3932 if (ctx.old_flag != 0) {
3938 free_pipe_list(ctx.list_head, /* indent: */ 0);
3939 /* Discard all unprocessed line input, force prompt on */
3944 /* loop on syntax errors, return on EOF: */
3945 } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP));
3949 static int parse_and_run_string(const char *s, int parse_flag)
3951 struct in_str input;
3952 setup_string_in_str(&input, s);
3953 return parse_and_run_stream(&input, parse_flag);
3956 static int parse_and_run_file(FILE *f)
3959 struct in_str input;
3960 setup_file_in_str(&input, f);
3961 rcode = parse_and_run_stream(&input, 0 /* parse_flag */);
3966 /* Make sure we have a controlling tty. If we get started under a job
3967 * aware app (like bash for example), make sure we are now in charge so
3968 * we don't fight over who gets the foreground */
3969 static void setup_job_control(void)
3973 saved_task_pgrp = shell_pgrp = getpgrp();
3974 debug_printf_jobs("saved_task_pgrp=%d\n", saved_task_pgrp);
3975 close_on_exec_on(interactive_fd);
3977 /* If we were ran as 'hush &',
3978 * sleep until we are in the foreground. */
3979 while (tcgetpgrp(interactive_fd) != shell_pgrp) {
3980 /* Send TTIN to ourself (should stop us) */
3981 kill(- shell_pgrp, SIGTTIN);
3982 shell_pgrp = getpgrp();
3985 /* Ignore job-control and misc signals. */
3986 set_jobctrl_sighandler(SIG_IGN);
3987 set_misc_sighandler(SIG_IGN);
3988 //huh? signal(SIGCHLD, SIG_IGN);
3990 /* We _must_ restore tty pgrp on fatal signals */
3991 set_fatal_sighandler(sigexit);
3993 /* Put ourselves in our own process group. */
3994 setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
3995 /* Grab control of the terminal. */
3996 tcsetpgrp(interactive_fd, getpid());
4000 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4001 int hush_main(int argc, char **argv)
4003 static const char version_str[] ALIGN1 = "HUSH_VERSION="HUSH_VER_STR;
4004 static const struct variable const_shell_ver = {
4006 .varstr = (char*)version_str,
4007 .max_len = 1, /* 0 can provoke free(name) */
4015 struct variable *cur_var;
4019 /* Deal with HUSH_VERSION */
4020 shell_ver = const_shell_ver; /* copying struct here */
4021 top_var = &shell_ver;
4022 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
4023 /* Initialize our shell local variables with the values
4024 * currently living in the environment */
4028 char *value = strchr(*e, '=');
4029 if (value) { /* paranoia */
4030 cur_var->next = xzalloc(sizeof(*cur_var));
4031 cur_var = cur_var->next;
4032 cur_var->varstr = *e;
4033 cur_var->max_len = strlen(*e);
4034 cur_var->flg_export = 1;
4038 putenv((char *)version_str); /* reinstate HUSH_VERSION */
4040 #if ENABLE_FEATURE_EDITING
4041 line_input_state = new_line_input_t(FOR_SHELL);
4043 /* XXX what should these be while sourcing /etc/profile? */
4046 /* Initialize some more globals to non-zero values */
4048 #if ENABLE_HUSH_INTERACTIVE
4049 #if ENABLE_FEATURE_EDITING
4050 cmdedit_set_initial_prompt();
4055 if (EXIT_SUCCESS) /* otherwise is already done */
4056 last_return_code = EXIT_SUCCESS;
4058 if (argv[0] && argv[0][0] == '-') {
4059 debug_printf("sourcing /etc/profile\n");
4060 input = fopen("/etc/profile", "r");
4061 if (input != NULL) {
4062 close_on_exec_on(fileno(input));
4063 parse_and_run_file(input);
4069 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
4072 global_argv = argv + optind;
4073 global_argc = argc - optind;
4074 opt = parse_and_run_string(optarg, 0 /* parse_flag */);
4077 /* Well, we cannot just declare interactiveness,
4078 * we have to have some stuff (ctty, etc) */
4079 /* interactive_fd++; */
4086 fprintf(stderr, "Usage: sh [FILE]...\n"
4087 " or: sh -c command [args]...\n\n");
4095 /* A shell is interactive if the '-i' flag was given, or if all of
4096 * the following conditions are met:
4098 * no arguments remaining or the -s flag given
4099 * standard input is a terminal
4100 * standard output is a terminal
4101 * Refer to Posix.2, the description of the 'sh' utility. */
4102 if (argv[optind] == NULL && input == stdin
4103 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4105 saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
4106 debug_printf("saved_tty_pgrp=%d\n", saved_tty_pgrp);
4107 if (saved_tty_pgrp >= 0) {
4108 /* try to dup to high fd#, >= 255 */
4109 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4110 if (interactive_fd < 0) {
4111 /* try to dup to any fd */
4112 interactive_fd = dup(STDIN_FILENO);
4113 if (interactive_fd < 0)
4117 // TODO: track & disallow any attempts of user
4118 // to (inadvertently) close/redirect it
4121 debug_printf("interactive_fd=%d\n", interactive_fd);
4122 if (interactive_fd) {
4123 fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
4124 /* Looks like they want an interactive shell */
4125 setup_job_control();
4126 /* -1 is special - makes xfuncs longjmp, not exit
4127 * (we reset die_sleep = 0 whereever we [v]fork) */
4129 if (setjmp(die_jmp)) {
4130 /* xfunc has failed! die die die */
4131 hush_exit(xfunc_error_retval);
4133 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
4134 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
4135 printf("Enter 'help' for a list of built-in commands.\n\n");
4138 #elif ENABLE_HUSH_INTERACTIVE
4139 /* no job control compiled, only prompt/line editing */
4140 if (argv[optind] == NULL && input == stdin
4141 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4143 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4144 if (interactive_fd < 0) {
4145 /* try to dup to any fd */
4146 interactive_fd = dup(STDIN_FILENO);
4147 if (interactive_fd < 0)
4151 if (interactive_fd) {
4152 fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
4153 set_misc_sighandler(SIG_IGN);
4158 if (argv[optind] == NULL) {
4159 opt = parse_and_run_file(stdin);
4161 debug_printf("\nrunning script '%s'\n", argv[optind]);
4162 global_argv = argv + optind;
4163 global_argc = argc - optind;
4164 input = xfopen(argv[optind], "r");
4165 fcntl(fileno(input), F_SETFD, FD_CLOEXEC);
4166 opt = parse_and_run_file(input);
4171 #if ENABLE_FEATURE_CLEAN_UP
4173 if (cwd != bb_msg_unknown)
4175 cur_var = top_var->next;
4177 struct variable *tmp = cur_var;
4178 if (!cur_var->max_len)
4179 free(cur_var->varstr);
4180 cur_var = cur_var->next;
4184 hush_exit(opt ? opt : last_return_code);
4189 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4190 int lash_main(int argc, char **argv)
4192 //bb_error_msg("lash is deprecated, please use hush instead");
4193 return hush_main(argc, argv);