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 * b_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 * ! negation operator for pipes
42 * &> and >& redirection of stdout+stderr
45 * fancy forms of Parameter Expansion
47 * Arithmetic Expansion
48 * <(list) and >(list) Process Substitution
49 * reserved words: case, esac, select, function
50 * Here Documents ( << word )
53 * job handling woefully incomplete and buggy (improved --vda)
54 * reserved word execution woefully incomplete and buggy
56 * port selected bugfixes from post-0.49 busybox lash - done?
57 * finish implementing reserved words: for, while, until, do, done
58 * change { and } from special chars to reserved words
59 * builtins: break, continue, eval, return, set, trap, ulimit
61 * handle children going into background
62 * clean up recognition of null pipes
63 * check setting of global_argc and global_argv
64 * control-C handling, probably with longjmp
65 * follow IFS rules more precisely, including update semantics
66 * figure out what to do with backslash-newline
67 * explain why we use signal instead of sigaction
68 * propagate syntax errors, die on resource errors?
69 * continuation lines, both explicit and implicit - done?
70 * memory leak finding and plugging - done?
71 * more testing, especially quoting rules and redirection
72 * document how quoting rules not precisely followed for variable assignments
73 * maybe change charmap[] to use 2-bit entries
74 * (eventually) remove all the printf's
76 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
80 #include <glob.h> /* glob, of course */
81 #include <getopt.h> /* should be pretty obvious */
82 /* #include <dmalloc.h> */
84 extern char **environ; /* This is in <unistd.h>, but protected with __USE_GNU */
86 #include "busybox.h" /* for struct bb_applet */
90 /* A bit drastic. Can allow some simpler commands
91 * by analysing command in generate_stream_from_list()
93 #undef ENABLE_HUSH_TICK
94 #define ENABLE_HUSH_TICK 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
147 #if !ENABLE_HUSH_INTERACTIVE
148 #undef ENABLE_FEATURE_EDITING
149 #define ENABLE_FEATURE_EDITING 0
150 #undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
151 #define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
154 #define SPECIAL_VAR_SYMBOL 3
156 #define PARSEFLAG_EXIT_FROM_LOOP 1
157 #define PARSEFLAG_SEMICOLON (1 << 1) /* symbol ';' is special for parser */
158 #define PARSEFLAG_REPARSING (1 << 2) /* >= 2nd pass */
162 REDIRECT_OVERWRITE = 2,
168 /* The descrip member of this structure is only used to make debugging
170 static const struct {
172 signed char default_fd;
176 { O_RDONLY, 0, "<" },
177 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
178 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
179 { O_RDONLY, -1, "<<" },
190 /* might eventually control execution */
200 #if ENABLE_HUSH_LOOPS
212 FLAG_END = (1 << RES_NONE ),
214 FLAG_IF = (1 << RES_IF ),
215 FLAG_THEN = (1 << RES_THEN ),
216 FLAG_ELIF = (1 << RES_ELIF ),
217 FLAG_ELSE = (1 << RES_ELSE ),
218 FLAG_FI = (1 << RES_FI ),
220 #if ENABLE_HUSH_LOOPS
221 FLAG_FOR = (1 << RES_FOR ),
222 FLAG_WHILE = (1 << RES_WHILE),
223 FLAG_UNTIL = (1 << RES_UNTIL),
224 FLAG_DO = (1 << RES_DO ),
225 FLAG_DONE = (1 << RES_DONE ),
226 FLAG_IN = (1 << RES_IN ),
228 FLAG_START = (1 << RES_XXXX ),
231 /* This holds pointers to the various results of parsing */
233 struct child_prog *child;
234 struct pipe *list_head;
236 struct redir_struct *pending_redirect;
238 smallint parse_type; /* bitmask of PARSEFLAG_xxx, defines type of parser : ";$" common or special symbol */
239 int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */
240 struct p_context *stack;
241 /* How about quoting status? */
244 struct redir_struct {
245 struct redir_struct *next; /* pointer to the next redirect in the list */
246 redir_type type; /* type of redirection */
247 int fd; /* file descriptor being redirected */
248 int dup; /* -1, or file descriptor being duplicated */
249 char **glob_word; /* *word.gl_pathv is the filename */
253 pid_t pid; /* 0 if exited */
254 char **argv; /* program name and arguments */
255 struct pipe *group; /* if non-NULL, first in group or subshell */
256 smallint subshell; /* flag, non-zero if group must be forked */
257 smallint is_stopped; /* is the program currently running? */
258 struct redir_struct *redirects; /* I/O redirections */
259 char **glob_result; /* result of parameter globbing */
260 struct pipe *family; /* pointer back to the child's parent pipe */
261 //sp counting seems to be broken... so commented out, grep for '//sp:'
262 //sp: int sp; /* number of SPECIAL_VAR_SYMBOL */
263 //seems to be unused, grep for '//pt:'
264 //pt: int parse_type;
266 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
267 * and on execution these are substituted with their values.
268 * Substitution can make _several_ words out of one argv[n]!
269 * Example: argv[0]=='.^C*^C.' here: echo .$*.
274 int num_progs; /* total number of programs in job */
275 int running_progs; /* number of programs running (not exited) */
276 int stopped_progs; /* number of programs alive, but stopped */
278 int jobid; /* job number */
279 pid_t pgrp; /* process group ID for the job */
280 char *cmdtext; /* name of job */
282 char *cmdbuf; /* buffer various argv's point into */
283 struct child_prog *progs; /* array of commands in pipe */
284 int job_context; /* bitmask defining current context */
285 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
286 smallint res_word; /* needed for if, for, while, until... */
289 /* On program start, environ points to initial environment.
290 * putenv adds new pointers into it, unsetenv removes them.
291 * Neither of these (de)allocates the strings.
292 * setenv allocates new strings in malloc space and does putenv,
293 * and thus setenv is unusable (leaky) for shell's purposes */
294 #define setenv(...) setenv_is_leaky_dont_use()
296 struct variable *next;
297 char *varstr; /* points to "name=" portion */
298 int max_len; /* if > 0, name is part of initial env; else name is malloced */
299 smallint flg_export; /* putenv should be done on this var */
300 smallint flg_read_only;
310 #define NULL_O_STRING {NULL,0,0,0,0}
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 b_getch(input) ((input)->get(input))
329 #define b_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 )
431 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
435 static void syntax(const char *msg)
437 /* Was using fancy stuff:
438 * (interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
439 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
440 void (*fp)(const char *s, ...);
442 fp = (interactive_fd ? bb_error_msg : bb_error_msg_and_die);
443 fp(msg ? "%s: %s" : "syntax error", "syntax error", msg);
448 static void syntax_lineno(int line)
450 void (*fp)(const char *s, ...);
452 fp = (interactive_fd ? bb_error_msg : bb_error_msg_and_die);
453 fp("syntax error hush.c:%d", line);
455 #define syntax(str) syntax_lineno(__LINE__)
458 /* Index of subroutines: */
459 /* function prototypes for builtins */
460 static int builtin_cd(char **argv);
461 static int builtin_eval(char **argv);
462 static int builtin_exec(char **argv);
463 static int builtin_exit(char **argv);
464 static int builtin_export(char **argv);
466 static int builtin_fg_bg(char **argv);
467 static int builtin_jobs(char **argv);
470 static int builtin_help(char **argv);
472 static int builtin_pwd(char **argv);
473 static int builtin_read(char **argv);
474 static int builtin_set(char **argv);
475 static int builtin_shift(char **argv);
476 static int builtin_source(char **argv);
477 static int builtin_umask(char **argv);
478 static int builtin_unset(char **argv);
479 //static int builtin_not_written(char **argv);
480 /* o_string manipulation: */
481 static int b_check_space(o_string *o, int len);
482 static int b_addchr(o_string *o, int ch);
483 static void b_reset(o_string *o);
484 static int b_addqchr(o_string *o, int ch, int quote);
485 /* in_str manipulations: */
486 static int static_get(struct in_str *i);
487 static int static_peek(struct in_str *i);
488 static int file_get(struct in_str *i);
489 static int file_peek(struct in_str *i);
490 static void setup_file_in_str(struct in_str *i, FILE *f);
491 static void setup_string_in_str(struct in_str *i, const char *s);
492 /* "run" the final data structures: */
493 #if !defined(DEBUG_CLEAN)
494 #define free_pipe_list(head, indent) free_pipe_list(head)
495 #define free_pipe(pi, indent) free_pipe(pi)
497 static int free_pipe_list(struct pipe *head, int indent);
498 static int free_pipe(struct pipe *pi, int indent);
499 /* really run the final data structures: */
500 static int setup_redirects(struct child_prog *prog, int squirrel[]);
501 static int run_list_real(struct pipe *pi);
502 static void pseudo_exec_argv(char **argv) ATTRIBUTE_NORETURN;
503 static void pseudo_exec(struct child_prog *child) ATTRIBUTE_NORETURN;
504 static int run_pipe_real(struct pipe *pi);
505 /* extended glob support: */
506 static char **globhack(const char *src, char **strings);
507 static int glob_needed(const char *s);
508 static int xglob(o_string *dest, char ***pglob);
509 /* variable assignment: */
510 static int is_assignment(const char *s);
511 /* data structure manipulation: */
512 static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
513 static void initialize_context(struct p_context *ctx);
514 static int done_word(o_string *dest, struct p_context *ctx);
515 static int done_command(struct p_context *ctx);
516 static int done_pipe(struct p_context *ctx, pipe_style type);
517 /* primary string parsing: */
518 static int redirect_dup_num(struct in_str *input);
519 static int redirect_opt_num(o_string *o);
521 static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, const char *subst_end);
523 static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
524 static const char *lookup_param(const char *src);
525 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
526 static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, const char *end_trigger);
528 static int parse_and_run_stream(struct in_str *inp, int parse_flag);
529 static int parse_and_run_string(const char *s, int parse_flag);
530 static int parse_and_run_file(FILE *f);
531 /* job management: */
532 static int checkjobs(struct pipe* fg_pipe);
534 static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
535 static void insert_bg_job(struct pipe *pi);
536 static void remove_bg_job(struct pipe *pi);
537 static void delete_finished_bg_job(struct pipe *pi);
539 int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
541 /* local variable support */
542 static char **expand_strvec_to_strvec(char **argv);
544 static char *expand_strvec_to_string(char **argv);
545 /* used for expansion of right hand of assignments */
546 static char *expand_string_to_string(const char *str);
547 static struct variable *get_local_var(const char *name);
548 static int set_local_var(char *str, int flg_export);
549 static void unset_local_var(const char *name);
552 static char **add_strings_to_strings(int need_xstrdup, char **strings, char **add)
573 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
574 v[count1 + count2] = NULL;
577 v[count1 + i] = need_xstrdup ? xstrdup(add[i]) : add[i];
581 /* 'add' should be a malloced pointer */
582 static char **add_string_to_strings(char **strings, char *add)
589 return add_strings_to_strings(0, strings, v);
592 static void free_strings(char **strings)
603 /* Table of built-in functions. They can be forked or not, depending on
604 * context: within pipes, they fork. As simple commands, they do not.
605 * When used in non-forking context, they can change global variables
606 * in the parent shell process. If forked, of course they cannot.
607 * For example, 'unset foo | whatever' will parse and run, but foo will
608 * still be set at the end. */
609 struct built_in_command {
610 const char *cmd; /* name */
611 int (*function) (char **argv); /* function ptr */
613 const char *descr; /* description */
614 #define BLTIN(cmd, func, help) { cmd, func, help }
616 #define BLTIN(cmd, func, help) { cmd, func }
620 static const struct built_in_command bltins[] = {
622 BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"),
624 // BLTIN("break" , builtin_not_written, "Exit for, while or until loop"),
625 BLTIN("cd" , builtin_cd, "Change working directory"),
626 // BLTIN("continue", builtin_not_written, "Continue for, while or until loop"),
627 BLTIN("eval" , builtin_eval, "Construct and run shell command"),
628 BLTIN("exec" , builtin_exec, "Exec command, replacing this shell with the exec'd process"),
629 BLTIN("exit" , builtin_exit, "Exit from shell"),
630 BLTIN("export", builtin_export, "Set environment variable"),
632 BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"),
633 BLTIN("jobs" , builtin_jobs, "Lists the active jobs"),
635 // TODO: remove pwd? we have it as an applet...
636 BLTIN("pwd" , builtin_pwd, "Print current directory"),
637 BLTIN("read" , builtin_read, "Input environment variable"),
638 // BLTIN("return", builtin_not_written, "Return from a function"),
639 BLTIN("set" , builtin_set, "Set/unset shell local variables"),
640 BLTIN("shift" , builtin_shift, "Shift positional parameters"),
641 // BLTIN("trap" , builtin_not_written, "Trap signals"),
642 // BLTIN("ulimit", builtin_not_written, "Controls resource limits"),
643 BLTIN("umask" , builtin_umask, "Sets file creation mask"),
644 BLTIN("unset" , builtin_unset, "Unset environment variable"),
645 BLTIN("." , builtin_source, "Source-in and run commands in a file"),
647 BLTIN("help" , builtin_help, "List shell built-in commands"),
649 BLTIN(NULL, NULL, NULL)
655 static void signal_SA_RESTART(int sig, void (*handler)(int))
658 sa.sa_handler = handler;
659 sa.sa_flags = SA_RESTART;
660 sigemptyset(&sa.sa_mask);
661 sigaction(sig, &sa, NULL);
664 /* Signals are grouped, we handle them in batches */
665 static void set_fatal_sighandler(void (*handler)(int))
667 signal(SIGILL , handler);
668 signal(SIGTRAP, handler);
669 signal(SIGABRT, handler);
670 signal(SIGFPE , handler);
671 signal(SIGBUS , handler);
672 signal(SIGSEGV, handler);
673 /* bash 3.2 seems to handle these just like 'fatal' ones */
674 signal(SIGHUP , handler);
675 signal(SIGPIPE, handler);
676 signal(SIGALRM, handler);
678 static void set_jobctrl_sighandler(void (*handler)(int))
680 signal(SIGTSTP, handler);
681 signal(SIGTTIN, handler);
682 signal(SIGTTOU, handler);
684 static void set_misc_sighandler(void (*handler)(int))
686 signal(SIGINT , handler);
687 signal(SIGQUIT, handler);
688 signal(SIGTERM, handler);
690 /* SIGCHLD is special and handled separately */
692 static void set_every_sighandler(void (*handler)(int))
694 set_fatal_sighandler(handler);
695 set_jobctrl_sighandler(handler);
696 set_misc_sighandler(handler);
697 signal(SIGCHLD, handler);
700 static void handler_ctrl_c(int sig)
702 debug_printf_jobs("got sig %d\n", sig);
703 // as usual we can have all kinds of nasty problems with leaked malloc data here
704 siglongjmp(toplevel_jb, 1);
707 static void handler_ctrl_z(int sig)
711 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
713 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
716 if (!pid) { /* child */
718 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
719 set_every_sighandler(SIG_DFL);
720 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
721 debug_printf_jobs("returning in child\n");
722 /* return to nofork, it will eventually exit now,
723 * not return back to shell */
727 /* finish filling up pipe info */
728 toplevel_list->pgrp = pid; /* child is in its own pgrp */
729 toplevel_list->progs[0].pid = pid;
730 /* parent needs to longjmp out of running nofork.
731 * we will "return" exitcode 0, with child put in background */
732 // as usual we can have all kinds of nasty problems with leaked malloc data here
733 debug_printf_jobs("siglongjmp in parent\n");
734 siglongjmp(toplevel_jb, 1);
737 /* Restores tty foreground process group, and exits.
738 * May be called as signal handler for fatal signal
739 * (will faithfully resend signal to itself, producing correct exit state)
740 * or called directly with -EXITCODE.
741 * We also call it if xfunc is exiting. */
742 static void sigexit(int sig) ATTRIBUTE_NORETURN;
743 static void sigexit(int sig)
747 /* Disable all signals: job control, SIGPIPE, etc. */
748 sigfillset(&block_all);
749 sigprocmask(SIG_SETMASK, &block_all, NULL);
752 tcsetpgrp(interactive_fd, saved_tty_pgrp);
754 /* Not a signal, just exit */
758 /* Enable only this sig and kill ourself with it */
759 signal(sig, SIG_DFL);
760 sigdelset(&block_all, sig);
761 sigprocmask(SIG_SETMASK, &block_all, NULL);
763 _exit(1); /* Should not reach it */
766 /* Restores tty foreground process group, and exits. */
767 static void hush_exit(int exitcode) ATTRIBUTE_NORETURN;
768 static void hush_exit(int exitcode)
770 fflush(NULL); /* flush all streams */
771 sigexit(- (exitcode & 0xff));
776 #define set_fatal_sighandler(handler) ((void)0)
777 #define set_jobctrl_sighandler(handler) ((void)0)
778 #define set_misc_sighandler(handler) ((void)0)
779 #define hush_exit(e) exit(e)
784 static const char *set_cwd(void)
786 if (cwd == bb_msg_unknown)
787 cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
788 cwd = xrealloc_getcwd_or_warn((char *)cwd);
790 cwd = bb_msg_unknown;
794 /* built-in 'eval' handler */
795 static int builtin_eval(char **argv)
797 int rcode = EXIT_SUCCESS;
800 char *str = expand_strvec_to_string(argv + 1);
801 parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP |
802 PARSEFLAG_SEMICOLON);
804 rcode = last_return_code;
809 /* built-in 'cd <path>' handler */
810 static int builtin_cd(char **argv)
813 if (argv[1] == NULL) {
814 // bash does nothing (exitcode 0) if HOME is ""; if it's unset,
815 // bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
816 newdir = getenv("HOME") ? : "/";
820 printf("cd: %s: %s\n", newdir, strerror(errno));
827 /* built-in 'exec' handler */
828 static int builtin_exec(char **argv)
831 return EXIT_SUCCESS; /* Really? */
832 pseudo_exec_argv(argv + 1);
836 /* built-in 'exit' handler */
837 static int builtin_exit(char **argv)
839 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
840 //puts("exit"); /* bash does it */
841 // TODO: warn if we have background jobs: "There are stopped jobs"
842 // On second consecutive 'exit', exit anyway.
845 hush_exit(last_return_code);
846 /* mimic bash: exit 123abc == exit 255 + error msg */
847 xfunc_error_retval = 255;
848 /* bash: exit -2 == exit 254, no error msg */
849 hush_exit(xatoi(argv[1]) & 0xff);
852 /* built-in 'export VAR=value' handler */
853 static int builtin_export(char **argv)
856 char *name = argv[1];
860 // ash emits: export VAR='VAL'
861 // bash: declare -x VAR="VAL"
862 // (both also escape as needed (quotes, $, etc))
870 value = strchr(name, '=');
872 /* They are exporting something without a =VALUE */
873 struct variable *var;
875 var = get_local_var(name);
880 /* bash does not return an error when trying to export
881 * an undefined variable. Do likewise. */
885 set_local_var(xstrdup(name), 1);
890 /* built-in 'fg' and 'bg' handler */
891 static int builtin_fg_bg(char **argv)
898 /* If they gave us no args, assume they want the last backgrounded task */
900 for (pi = job_list; pi; pi = pi->next) {
901 if (pi->jobid == last_jobid) {
905 bb_error_msg("%s: no current job", argv[0]);
908 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
909 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
912 for (pi = job_list; pi; pi = pi->next) {
913 if (pi->jobid == jobnum) {
917 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
920 // TODO: bash prints a string representation
921 // of job being foregrounded (like "sleep 1 | cat")
922 if (*argv[0] == 'f') {
923 /* Put the job into the foreground. */
924 tcsetpgrp(interactive_fd, pi->pgrp);
927 /* Restart the processes in the job */
928 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_progs, pi->pgrp);
929 for (i = 0; i < pi->num_progs; i++) {
930 debug_printf_jobs("reviving pid %d\n", pi->progs[i].pid);
931 pi->progs[i].is_stopped = 0;
933 pi->stopped_progs = 0;
935 i = kill(- pi->pgrp, SIGCONT);
937 if (errno == ESRCH) {
938 delete_finished_bg_job(pi);
941 bb_perror_msg("kill (SIGCONT)");
945 if (*argv[0] == 'f') {
947 return checkjobs_and_fg_shell(pi);
953 /* built-in 'help' handler */
955 static int builtin_help(char **argv ATTRIBUTE_UNUSED)
957 const struct built_in_command *x;
959 printf("\nBuilt-in commands:\n");
960 printf("-------------------\n");
961 for (x = bltins; x->cmd; x++) {
962 printf("%s\t%s\n", x->cmd, x->descr);
970 /* built-in 'jobs' handler */
971 static int builtin_jobs(char **argv ATTRIBUTE_UNUSED)
974 const char *status_string;
976 for (job = job_list; job; job = job->next) {
977 if (job->running_progs == job->stopped_progs)
978 status_string = "Stopped";
980 status_string = "Running";
982 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
988 /* built-in 'pwd' handler */
989 static int builtin_pwd(char **argv ATTRIBUTE_UNUSED)
995 /* built-in 'read VAR' handler */
996 static int builtin_read(char **argv)
999 const char *name = argv[1] ? argv[1] : "REPLY";
1001 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name));
1002 return set_local_var(string, 0);
1005 /* built-in 'set [VAR=value]' handler */
1006 static int builtin_set(char **argv)
1008 char *temp = argv[1];
1012 for (e = top_var; e; e = e->next)
1015 set_local_var(xstrdup(temp), 0);
1017 return EXIT_SUCCESS;
1021 /* Built-in 'shift' handler */
1022 static int builtin_shift(char **argv)
1028 if (n >= 0 && n < global_argc) {
1029 global_argv[n] = global_argv[0];
1032 return EXIT_SUCCESS;
1034 return EXIT_FAILURE;
1037 /* Built-in '.' handler (read-in and execute commands from file) */
1038 static int builtin_source(char **argv)
1043 if (argv[1] == NULL)
1044 return EXIT_FAILURE;
1046 /* XXX search through $PATH is missing */
1047 input = fopen(argv[1], "r");
1049 bb_error_msg("cannot open '%s'", argv[1]);
1050 return EXIT_FAILURE;
1052 close_on_exec_on(fileno(input));
1054 /* Now run the file */
1055 /* XXX argv and argc are broken; need to save old global_argv
1056 * (pointer only is OK!) on this stack frame,
1057 * set global_argv=argv+1, recurse, and restore. */
1058 status = parse_and_run_file(input);
1063 static int builtin_umask(char **argv)
1066 const char *arg = argv[1];
1069 new_umask = strtoul(arg, &end, 8);
1070 if (*end != '\0' || end == arg) {
1071 return EXIT_FAILURE;
1074 new_umask = umask(0);
1075 printf("%.3o\n", (unsigned) new_umask);
1078 return EXIT_SUCCESS;
1081 /* built-in 'unset VAR' handler */
1082 static int builtin_unset(char **argv)
1084 /* bash always returns true */
1085 unset_local_var(argv[1]);
1086 return EXIT_SUCCESS;
1089 //static int builtin_not_written(char **argv)
1091 // printf("builtin_%s not written\n", argv[0]);
1092 // return EXIT_FAILURE;
1095 static int b_check_space(o_string *o, int len)
1097 /* It would be easy to drop a more restrictive policy
1098 * in here, such as setting a maximum string length */
1099 if (o->length + len > o->maxlen) {
1100 /* assert(data == NULL || o->maxlen != 0); */
1101 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1102 o->data = xrealloc(o->data, 1 + o->maxlen);
1104 return o->data == NULL;
1107 static int b_addchr(o_string *o, int ch)
1109 debug_printf("b_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1110 if (b_check_space(o, 1))
1112 o->data[o->length] = ch;
1114 o->data[o->length] = '\0';
1118 static void b_reset(o_string *o)
1126 static void b_free(o_string *o)
1129 memset(o, 0, sizeof(*o));
1132 /* My analysis of quoting semantics tells me that state information
1133 * is associated with a destination, not a source.
1135 static int b_addqchr(o_string *o, int ch, int quote)
1137 if (quote && strchr("*?[\\", ch)) {
1139 rc = b_addchr(o, '\\');
1143 return b_addchr(o, ch);
1146 static int static_get(struct in_str *i)
1149 if (ch == '\0') return EOF;
1153 static int static_peek(struct in_str *i)
1158 #if ENABLE_HUSH_INTERACTIVE
1159 #if ENABLE_FEATURE_EDITING
1160 static void cmdedit_set_initial_prompt(void)
1162 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1165 PS1 = getenv("PS1");
1170 #endif /* EDITING */
1172 static const char* setup_prompt_string(int promptmode)
1174 const char *prompt_str;
1175 debug_printf("setup_prompt_string %d ", promptmode);
1176 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1177 /* Set up the prompt */
1178 if (promptmode == 0) { /* PS1 */
1180 PS1 = xasprintf("%s %c ", cwd, (geteuid() != 0) ? '$' : '#');
1186 prompt_str = (promptmode == 0) ? PS1 : PS2;
1188 debug_printf("result '%s'\n", prompt_str);
1192 static void get_user_input(struct in_str *i)
1195 const char *prompt_str;
1197 prompt_str = setup_prompt_string(i->promptmode);
1198 #if ENABLE_FEATURE_EDITING
1199 /* Enable command line editing only while a command line
1200 * is actually being read; otherwise, we'll end up bequeathing
1201 * atexit() handlers and other unwanted stuff to our
1202 * child processes (rob@sysgo.de) */
1203 r = read_line_input(prompt_str, user_input_buf, BUFSIZ-1, line_input_state);
1204 i->eof_flag = (r < 0);
1205 if (i->eof_flag) { /* EOF/error detected */
1206 user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1207 user_input_buf[1] = '\0';
1210 fputs(prompt_str, stdout);
1212 user_input_buf[0] = r = fgetc(i->file);
1213 /*user_input_buf[1] = '\0'; - already is and never changed */
1214 i->eof_flag = (r == EOF);
1216 i->p = user_input_buf;
1218 #endif /* INTERACTIVE */
1220 /* This is the magic location that prints prompts
1221 * and gets data back from the user */
1222 static int file_get(struct in_str *i)
1226 /* If there is data waiting, eat it up */
1227 if (i->p && *i->p) {
1228 #if ENABLE_HUSH_INTERACTIVE
1232 if (i->eof_flag && !*i->p)
1235 /* need to double check i->file because we might be doing something
1236 * more complicated by now, like sourcing or substituting. */
1237 #if ENABLE_HUSH_INTERACTIVE
1238 if (interactive_fd && i->promptme && i->file == stdin) {
1241 } while (!*i->p); /* need non-empty line */
1242 i->promptmode = 1; /* PS2 */
1247 ch = fgetc(i->file);
1249 debug_printf("file_get: got a '%c' %d\n", ch, ch);
1250 #if ENABLE_HUSH_INTERACTIVE
1257 /* All the callers guarantee this routine will never be
1258 * used right after a newline, so prompting is not needed.
1260 static int file_peek(struct in_str *i)
1263 if (i->p && *i->p) {
1264 if (i->eof_flag && !i->p[1])
1268 ch = fgetc(i->file);
1269 i->eof_flag = (ch == EOF);
1270 i->peek_buf[0] = ch;
1271 i->peek_buf[1] = '\0';
1273 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
1277 static void setup_file_in_str(struct in_str *i, FILE *f)
1279 i->peek = file_peek;
1281 #if ENABLE_HUSH_INTERACTIVE
1283 i->promptmode = 0; /* PS1 */
1289 static void setup_string_in_str(struct in_str *i, const char *s)
1291 i->peek = static_peek;
1292 i->get = static_get;
1293 #if ENABLE_HUSH_INTERACTIVE
1295 i->promptmode = 0; /* PS1 */
1301 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
1302 * and stderr if they are redirected. */
1303 static int setup_redirects(struct child_prog *prog, int squirrel[])
1306 struct redir_struct *redir;
1308 for (redir = prog->redirects; redir; redir = redir->next) {
1309 if (redir->dup == -1 && redir->glob_word == NULL) {
1310 /* something went wrong in the parse. Pretend it didn't happen */
1313 if (redir->dup == -1) {
1314 mode = redir_table[redir->type].mode;
1315 openfd = open_or_warn(redir->glob_word[0], mode);
1317 /* this could get lost if stderr has been redirected, but
1318 bash and ash both lose it as well (though zsh doesn't!) */
1322 openfd = redir->dup;
1325 if (openfd != redir->fd) {
1326 if (squirrel && redir->fd < 3) {
1327 squirrel[redir->fd] = dup(redir->fd);
1330 //close(openfd); // close(-3) ??!
1332 dup2(openfd, redir->fd);
1333 if (redir->dup == -1)
1341 static void restore_redirects(int squirrel[])
1344 for (i = 0; i < 3; i++) {
1347 /* We simply die on error */
1353 /* Called after [v]fork() in run_pipe_real(), or from builtin_exec().
1355 * XXX no exit() here. If you don't exec, use _exit instead.
1356 * The at_exit handlers apparently confuse the calling process,
1357 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
1358 static void pseudo_exec_argv(char **argv)
1362 const struct built_in_command *x;
1364 for (i = 0; is_assignment(argv[i]); i++) {
1365 debug_printf_exec("pid %d environment modification: %s\n",
1367 // FIXME: vfork case??
1368 p = expand_string_to_string(argv[i]);
1372 /* If a variable is assigned in a forest, and nobody listens,
1373 * was it ever really set?
1375 if (argv[0] == NULL) {
1376 _exit(EXIT_SUCCESS);
1379 argv = expand_strvec_to_strvec(argv);
1382 * Check if the command matches any of the builtins.
1383 * Depending on context, this might be redundant. But it's
1384 * easier to waste a few CPU cycles than it is to figure out
1385 * if this is one of those cases.
1387 for (x = bltins; x->cmd; x++) {
1388 if (strcmp(argv[0], x->cmd) == 0) {
1389 debug_printf_exec("running builtin '%s'\n", argv[0]);
1390 rcode = x->function(argv);
1396 /* Check if the command matches any busybox applets */
1397 #if ENABLE_FEATURE_SH_STANDALONE
1398 if (strchr(argv[0], '/') == NULL) {
1399 const struct bb_applet *a = find_applet_by_name(argv[0]);
1402 debug_printf_exec("running applet '%s'\n", argv[0]);
1403 // is it ok that run_appletstruct_and_exit() does exit(), not _exit()?
1404 run_appletstruct_and_exit(a, argv);
1406 /* re-exec ourselves with the new arguments */
1407 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
1408 execvp(bb_busybox_exec_path, argv);
1409 /* If they called chroot or otherwise made the binary no longer
1410 * executable, fall through */
1415 debug_printf_exec("execing '%s'\n", argv[0]);
1416 execvp(argv[0], argv);
1417 bb_perror_msg("cannot exec '%s'", argv[0]);
1421 /* Called after [v]fork() in run_pipe_real()
1423 static void pseudo_exec(struct child_prog *child)
1425 // FIXME: buggy wrt NOMMU! Must not modify any global data
1426 // until it does exec/_exit, but currently it does.
1430 pseudo_exec_argv(child->argv);
1435 bb_error_msg_and_exit("nested lists are not supported on NOMMU");
1437 #if ENABLE_HUSH_INTERACTIVE
1438 debug_printf_exec("pseudo_exec: setting interactive_fd=0\n");
1439 interactive_fd = 0; /* crucial!!!! */
1441 debug_printf_exec("pseudo_exec: run_list_real\n");
1442 rcode = run_list_real(child->group);
1443 /* OK to leak memory by not calling free_pipe_list,
1444 * since this process is about to exit */
1449 /* Can happen. See what bash does with ">foo" by itself. */
1450 debug_printf("trying to pseudo_exec null command\n");
1451 _exit(EXIT_SUCCESS);
1455 static const char *get_cmdtext(struct pipe *pi)
1461 /* This is subtle. ->cmdtext is created only on first backgrounding.
1462 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
1463 * On subsequent bg argv is trashed, but we won't use it */
1466 argv = pi->progs[0].argv;
1467 if (!argv || !argv[0])
1468 return (pi->cmdtext = xzalloc(1));
1471 do len += strlen(*argv) + 1; while (*++argv);
1472 pi->cmdtext = p = xmalloc(len);
1473 argv = pi->progs[0].argv;
1475 len = strlen(*argv);
1476 memcpy(p, *argv, len);
1484 static void insert_bg_job(struct pipe *pi)
1486 struct pipe *thejob;
1489 /* Linear search for the ID of the job to use */
1491 for (thejob = job_list; thejob; thejob = thejob->next)
1492 if (thejob->jobid >= pi->jobid)
1493 pi->jobid = thejob->jobid + 1;
1495 /* Add thejob to the list of running jobs */
1497 thejob = job_list = xmalloc(sizeof(*thejob));
1499 for (thejob = job_list; thejob->next; thejob = thejob->next)
1501 thejob->next = xmalloc(sizeof(*thejob));
1502 thejob = thejob->next;
1505 /* Physically copy the struct job */
1506 memcpy(thejob, pi, sizeof(struct pipe));
1507 thejob->progs = xzalloc(sizeof(pi->progs[0]) * pi->num_progs);
1508 /* We cannot copy entire pi->progs[] vector! Double free()s will happen */
1509 for (i = 0; i < pi->num_progs; i++) {
1510 // TODO: do we really need to have so many fields which are just dead weight
1511 // at execution stage?
1512 thejob->progs[i].pid = pi->progs[i].pid;
1513 /* all other fields are not used and stay zero */
1515 thejob->next = NULL;
1516 thejob->cmdtext = xstrdup(get_cmdtext(pi));
1518 /* We don't wait for background thejobs to return -- append it
1519 to the list of backgrounded thejobs and leave it alone */
1520 printf("[%d] %d %s\n", thejob->jobid, thejob->progs[0].pid, thejob->cmdtext);
1521 last_bg_pid = thejob->progs[0].pid;
1522 last_jobid = thejob->jobid;
1525 static void remove_bg_job(struct pipe *pi)
1527 struct pipe *prev_pipe;
1529 if (pi == job_list) {
1530 job_list = pi->next;
1532 prev_pipe = job_list;
1533 while (prev_pipe->next != pi)
1534 prev_pipe = prev_pipe->next;
1535 prev_pipe->next = pi->next;
1538 last_jobid = job_list->jobid;
1543 /* remove a backgrounded job */
1544 static void delete_finished_bg_job(struct pipe *pi)
1547 pi->stopped_progs = 0;
1553 /* Checks to see if any processes have exited -- if they
1554 have, figure out why and see if a job has completed */
1555 static int checkjobs(struct pipe* fg_pipe)
1566 attributes = WUNTRACED;
1567 if (fg_pipe == NULL) {
1568 attributes |= WNOHANG;
1571 /* Do we do this right?
1572 * bash-3.00# sleep 20 | false
1574 * [3]+ Stopped sleep 20 | false
1575 * bash-3.00# echo $?
1576 * 1 <========== bg pipe is not fully done, but exitcode is already known!
1579 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
1580 //are stopped. Testcase: "cat | cat" in a script (not on command line)
1581 // + killall -STOP cat
1584 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
1585 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
1587 #ifdef DEBUG_SHELL_JOBS
1588 if (WIFSTOPPED(status))
1589 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
1590 childpid, WSTOPSIG(status), WEXITSTATUS(status));
1591 if (WIFSIGNALED(status))
1592 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
1593 childpid, WTERMSIG(status), WEXITSTATUS(status));
1594 if (WIFEXITED(status))
1595 debug_printf_jobs("pid %d exited, exitcode %d\n",
1596 childpid, WEXITSTATUS(status));
1598 /* Were we asked to wait for fg pipe? */
1601 for (i = 0; i < fg_pipe->num_progs; i++) {
1602 debug_printf_jobs("check pid %d\n", fg_pipe->progs[i].pid);
1603 if (fg_pipe->progs[i].pid == childpid) {
1604 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
1606 fg_pipe->progs[i].pid = 0;
1607 fg_pipe->running_progs--;
1608 if (i == fg_pipe->num_progs-1)
1609 /* last process gives overall exitstatus */
1610 rcode = WEXITSTATUS(status);
1612 fg_pipe->progs[i].is_stopped = 1;
1613 fg_pipe->stopped_progs++;
1615 debug_printf_jobs("fg_pipe: running_progs %d stopped_progs %d\n",
1616 fg_pipe->running_progs, fg_pipe->stopped_progs);
1617 if (fg_pipe->running_progs - fg_pipe->stopped_progs <= 0) {
1618 /* All processes in fg pipe have exited/stopped */
1620 if (fg_pipe->running_progs)
1621 insert_bg_job(fg_pipe);
1625 /* There are still running processes in the fg pipe */
1629 /* fall through to searching process in bg pipes */
1633 /* We asked to wait for bg or orphaned children */
1634 /* No need to remember exitcode in this case */
1635 for (pi = job_list; pi; pi = pi->next) {
1637 while (prognum < pi->num_progs) {
1638 if (pi->progs[prognum].pid == childpid)
1639 goto found_pi_and_prognum;
1645 /* Happens when shell is used as init process (init=/bin/sh) */
1646 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
1650 found_pi_and_prognum:
1653 pi->progs[prognum].pid = 0;
1654 pi->running_progs--;
1655 if (!pi->running_progs) {
1656 printf(JOB_STATUS_FORMAT, pi->jobid,
1657 "Done", pi->cmdtext);
1658 delete_finished_bg_job(pi);
1662 pi->stopped_progs++;
1663 pi->progs[prognum].is_stopped = 1;
1668 /* wait found no children or failed */
1670 if (childpid && errno != ECHILD)
1671 bb_perror_msg("waitpid");
1676 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1679 int rcode = checkjobs(fg_pipe);
1680 /* Job finished, move the shell to the foreground */
1681 p = getpgid(0); /* pgid of our process */
1682 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
1683 if (tcsetpgrp(interactive_fd, p) && errno != ENOTTY)
1684 bb_perror_msg("tcsetpgrp-4a");
1689 /* run_pipe_real() starts all the jobs, but doesn't wait for anything
1690 * to finish. See checkjobs().
1692 * return code is normally -1, when the caller has to wait for children
1693 * to finish to determine the exit status of the pipe. If the pipe
1694 * is a simple builtin command, however, the action is done by the
1695 * time run_pipe_real returns, and the exit code is provided as the
1698 * The input of the pipe is always stdin, the output is always
1699 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1700 * because it tries to avoid running the command substitution in
1701 * subshell, when that is in fact necessary. The subshell process
1702 * now has its stdout directed to the input of the appropriate pipe,
1703 * so this routine is noticeably simpler.
1705 * Returns -1 only if started some children. IOW: we have to
1706 * mask out retvals of builtins etc with 0xff!
1708 static int run_pipe_real(struct pipe *pi)
1711 int nextin, nextout;
1712 int pipefds[2]; /* pipefds[0] is for reading */
1713 struct child_prog *child;
1714 const struct built_in_command *x;
1716 /* it is not always needed, but we aim to smaller code */
1717 int squirrel[] = { -1, -1, -1 };
1719 const int single_fg = (pi->num_progs == 1 && pi->followup != PIPE_BG);
1721 debug_printf_exec("run_pipe_real start: single_fg=%d\n", single_fg);
1727 pi->running_progs = 1;
1728 pi->stopped_progs = 0;
1730 /* Check if this is a simple builtin (not part of a pipe).
1731 * Builtins within pipes have to fork anyway, and are handled in
1732 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1734 child = &(pi->progs[0]);
1735 if (single_fg && child->group && child->subshell == 0) {
1736 debug_printf("non-subshell grouping\n");
1737 setup_redirects(child, squirrel);
1738 debug_printf_exec(": run_list_real\n");
1739 rcode = run_list_real(child->group);
1740 restore_redirects(squirrel);
1741 debug_printf_exec("run_pipe_real return %d\n", rcode);
1742 return rcode; // do we need to add '... & 0xff' ?
1745 if (single_fg && child->argv != NULL) {
1746 char **argv_expanded;
1747 char **argv = child->argv;
1749 for (i = 0; is_assignment(argv[i]); i++)
1751 if (i != 0 && argv[i] == NULL) {
1752 /* assignments, but no command: set the local environment */
1753 for (i = 0; argv[i] != NULL; i++) {
1754 debug_printf("local environment set: %s\n", argv[i]);
1755 p = expand_string_to_string(argv[i]);
1756 set_local_var(p, 0);
1758 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1760 for (i = 0; is_assignment(argv[i]); i++) {
1761 p = expand_string_to_string(argv[i]);
1765 for (x = bltins; x->cmd; x++) {
1766 if (strcmp(argv[i], x->cmd) == 0) {
1767 if (x->function == builtin_exec && argv[i+1] == NULL) {
1768 debug_printf("magic exec\n");
1769 setup_redirects(child, NULL);
1770 return EXIT_SUCCESS;
1772 debug_printf("builtin inline %s\n", argv[0]);
1773 /* XXX setup_redirects acts on file descriptors, not FILEs.
1774 * This is perfect for work that comes after exec().
1775 * Is it really safe for inline use? Experimentally,
1776 * things seem to work with glibc. */
1777 setup_redirects(child, squirrel);
1778 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv[i+1]);
1779 //sp: if (child->sp) /* btw we can do it unconditionally... */
1780 argv_expanded = expand_strvec_to_strvec(argv + i);
1781 rcode = x->function(argv_expanded) & 0xff;
1782 free(argv_expanded);
1783 restore_redirects(squirrel);
1784 debug_printf_exec("run_pipe_real return %d\n", rcode);
1788 #if ENABLE_FEATURE_SH_STANDALONE
1790 const struct bb_applet *a = find_applet_by_name(argv[i]);
1791 if (a && a->nofork) {
1792 setup_redirects(child, squirrel);
1793 save_nofork_data(&nofork_save);
1794 argv_expanded = argv + i;
1795 //sp: if (child->sp)
1796 argv_expanded = expand_strvec_to_strvec(argv + i);
1797 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
1798 rcode = run_nofork_applet_prime(&nofork_save, a, argv_expanded) & 0xff;
1799 free(argv_expanded);
1800 restore_redirects(squirrel);
1801 debug_printf_exec("run_pipe_real return %d\n", rcode);
1808 /* Going to fork a child per each pipe member */
1809 pi->running_progs = 0;
1811 /* Disable job control signals for shell (parent) and
1812 * for initial child code after fork */
1813 set_jobctrl_sighandler(SIG_IGN);
1815 for (i = 0; i < pi->num_progs; i++) {
1816 child = &(pi->progs[i]);
1818 debug_printf_exec(": pipe member '%s' '%s'...\n", child->argv[0], child->argv[1]);
1820 debug_printf_exec(": pipe member with no argv\n");
1822 /* pipes are inserted between pairs of commands */
1823 if ((i + 1) < pi->num_progs) {
1825 nextout = pipefds[1];
1831 /* XXX test for failed fork()? */
1833 child->pid = fork();
1835 child->pid = vfork();
1837 if (!child->pid) { /* child */
1838 /* Every child adds itself to new process group
1839 * with pgid == pid of first child in pipe */
1841 if (run_list_level == 1 && interactive_fd) {
1842 /* Don't do pgrp restore anymore on fatal signals */
1843 set_fatal_sighandler(SIG_DFL);
1844 if (pi->pgrp < 0) /* true for 1st process only */
1845 pi->pgrp = getpid();
1846 if (setpgid(0, pi->pgrp) == 0 && pi->followup != PIPE_BG) {
1847 /* We do it in *every* child, not just first,
1849 tcsetpgrp(interactive_fd, pi->pgrp);
1853 /* in non-interactive case fatal sigs are already SIG_DFL */
1854 xmove_fd(nextin, 0);
1855 xmove_fd(nextout, 1);
1856 if (pipefds[0] != -1) {
1857 close(pipefds[0]); /* opposite end of our output pipe */
1859 /* Like bash, explicit redirects override pipes,
1860 * and the pipe fd is available for dup'ing. */
1861 setup_redirects(child, NULL);
1863 /* Restore default handlers just prior to exec */
1864 set_jobctrl_sighandler(SIG_DFL);
1865 set_misc_sighandler(SIG_DFL);
1866 signal(SIGCHLD, SIG_DFL);
1870 pi->running_progs++;
1873 /* Second and next children need to know pid of first one */
1875 pi->pgrp = child->pid;
1882 /* If there isn't another process, nextin is garbage
1883 but it doesn't matter */
1884 nextin = pipefds[0];
1886 debug_printf_exec("run_pipe_real return -1\n");
1890 #ifndef debug_print_tree
1891 static void debug_print_tree(struct pipe *pi, int lvl)
1893 static const char *PIPE[] = {
1899 static const char *RES[] = {
1900 [RES_NONE ] = "NONE" ,
1903 [RES_THEN ] = "THEN" ,
1904 [RES_ELIF ] = "ELIF" ,
1905 [RES_ELSE ] = "ELSE" ,
1908 #if ENABLE_HUSH_LOOPS
1909 [RES_FOR ] = "FOR" ,
1910 [RES_WHILE] = "WHILE",
1911 [RES_UNTIL] = "UNTIL",
1913 [RES_DONE ] = "DONE" ,
1916 [RES_XXXX ] = "XXXX" ,
1917 [RES_SNTX ] = "SNTX" ,
1924 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
1925 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
1927 while (prn < pi->num_progs) {
1928 struct child_prog *child = &pi->progs[prn];
1929 char **argv = child->argv;
1931 fprintf(stderr, "%*s prog %d", lvl*2, "", prn);
1933 fprintf(stderr, " group %s: (argv=%p)\n",
1934 (child->subshell ? "()" : "{}"),
1936 debug_print_tree(child->group, lvl+1);
1940 if (argv) while (*argv) {
1941 fprintf(stderr, " '%s'", *argv);
1944 fprintf(stderr, "\n");
1953 /* NB: called by pseudo_exec, and therefore must not modify any
1954 * global data until exec/_exit (we can be a child after vfork!) */
1955 static int run_list_real(struct pipe *pi)
1958 #if ENABLE_HUSH_LOOPS
1959 char *for_varname = NULL;
1960 char **for_lcur = NULL;
1961 char **for_list = NULL;
1966 int rcode = 0; /* probably for gcc only */
1967 int flag_restore = 0;
1969 int if_code = 0, next_if_code = 0; /* need double-buffer to handle elif */
1971 enum { if_code = 0, next_if_code = 0 };
1973 reserved_style rword;
1974 reserved_style skip_more_for_this_rword = RES_XXXX;
1976 debug_printf_exec("run_list_real start lvl %d\n", run_list_level + 1);
1978 #if ENABLE_HUSH_LOOPS
1979 /* check syntax for "for" */
1980 for (rpipe = pi; rpipe; rpipe = rpipe->next) {
1981 if ((rpipe->res_word == RES_IN || rpipe->res_word == RES_FOR)
1982 && (rpipe->next == NULL)
1984 syntax("malformed for"); /* no IN or no commands after IN */
1985 debug_printf_exec("run_list_real lvl %d return 1\n", run_list_level);
1988 if ((rpipe->res_word == RES_IN && rpipe->next->res_word == RES_IN && rpipe->next->progs[0].argv != NULL)
1989 || (rpipe->res_word == RES_FOR && rpipe->next->res_word != RES_IN)
1991 /* TODO: what is tested in the first condition? */
1992 syntax("malformed for"); /* 2nd condition: not followed by IN */
1993 debug_printf_exec("run_list_real lvl %d return 1\n", run_list_level);
2002 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
2003 * We are saving state before entering outermost list ("while...done")
2004 * so that ctrl-Z will correctly background _entire_ outermost list,
2005 * not just a part of it (like "sleep 1 | exit 2") */
2006 if (++run_list_level == 1 && interactive_fd) {
2007 if (sigsetjmp(toplevel_jb, 1)) {
2008 /* ctrl-Z forked and we are parent; or ctrl-C.
2009 * Sighandler has longjmped us here */
2010 signal(SIGINT, SIG_IGN);
2011 signal(SIGTSTP, SIG_IGN);
2012 /* Restore level (we can be coming from deep inside
2015 #if ENABLE_FEATURE_SH_STANDALONE
2016 if (nofork_save.saved) { /* if save area is valid */
2017 debug_printf_jobs("exiting nofork early\n");
2018 restore_nofork_data(&nofork_save);
2022 /* ctrl-Z has forked and stored pid of the child in pi->pid.
2023 * Remember this child as background job */
2026 /* ctrl-C. We just stop doing whatever we were doing */
2032 /* ctrl-Z handler will store pid etc in pi */
2035 #if ENABLE_FEATURE_SH_STANDALONE
2036 nofork_save.saved = 0; /* in case we will run a nofork later */
2038 signal_SA_RESTART(SIGTSTP, handler_ctrl_z);
2039 signal(SIGINT, handler_ctrl_c);
2043 for (; pi; pi = flag_restore ? rpipe : pi->next) {
2044 rword = pi->res_word;
2045 #if ENABLE_HUSH_LOOPS
2046 if (rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR) {
2054 debug_printf_exec(": rword=%d if_code=%d next_if_code=%d skip_more=%d\n",
2055 rword, if_code, next_if_code, skip_more_for_this_rword);
2056 if (rword == skip_more_for_this_rword && flag_skip) {
2057 if (pi->followup == PIPE_SEQ)
2062 skip_more_for_this_rword = RES_XXXX;
2064 if (rword == RES_THEN || rword == RES_ELSE)
2065 if_code = next_if_code;
2066 if (rword == RES_THEN && if_code)
2068 if (rword == RES_ELSE && !if_code)
2070 if (rword == RES_ELIF && !if_code)
2073 #if ENABLE_HUSH_LOOPS
2074 if (rword == RES_FOR && pi->num_progs) {
2076 /* first loop through for */
2077 /* if no variable values after "in" we skip "for" */
2078 if (!pi->next->progs->argv)
2080 /* create list of variable values */
2081 for_list = expand_strvec_to_strvec(pi->next->progs->argv);
2082 for_lcur = for_list;
2083 for_varname = pi->progs->argv[0];
2084 pi->progs->argv[0] = NULL;
2087 free(pi->progs->argv[0]);
2089 /* for loop is over, clean up */
2093 pi->progs->argv[0] = for_varname;
2096 /* insert next value from for_lcur */
2097 /* vda: does it need escaping? */
2098 pi->progs->argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
2100 if (rword == RES_IN)
2102 if (rword == RES_DO) {
2106 if (rword == RES_DONE) {
2114 if (pi->num_progs == 0)
2116 save_num_progs = pi->num_progs; /* save number of programs */
2117 debug_printf_exec(": run_pipe_real with %d members\n", pi->num_progs);
2118 rcode = run_pipe_real(pi);
2120 /* We only ran a builtin: rcode was set by the return value
2121 * of run_pipe_real(), and we don't need to wait for anything. */
2122 } else if (pi->followup == PIPE_BG) {
2123 /* What does bash do with attempts to background builtins? */
2124 /* Even bash 3.2 doesn't do that well with nested bg:
2125 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
2126 * I'm NOT treating inner &'s as jobs */
2128 if (run_list_level == 1)
2131 rcode = EXIT_SUCCESS;
2134 /* Paranoia, just "interactive_fd" should be enough? */
2135 if (run_list_level == 1 && interactive_fd) {
2136 /* waits for completion, then fg's main shell */
2137 rcode = checkjobs_and_fg_shell(pi);
2141 /* this one just waits for completion */
2142 rcode = checkjobs(pi);
2144 debug_printf_exec(": checkjobs returned %d\n", rcode);
2146 debug_printf_exec(": setting last_return_code=%d\n", rcode);
2147 last_return_code = rcode;
2148 pi->num_progs = save_num_progs; /* restore number of programs */
2150 if (rword == RES_IF || rword == RES_ELIF)
2151 next_if_code = rcode; /* can be overwritten a number of times */
2153 #if ENABLE_HUSH_LOOPS
2154 if (rword == RES_WHILE)
2155 flag_rep = !last_return_code;
2156 if (rword == RES_UNTIL)
2157 flag_rep = last_return_code;
2159 if ((rcode == EXIT_SUCCESS && pi->followup == PIPE_OR)
2160 || (rcode != EXIT_SUCCESS && pi->followup == PIPE_AND)
2162 skip_more_for_this_rword = rword;
2169 /* ctrl-Z forked somewhere in the past, we are the child,
2170 * and now we completed running the list. Exit. */
2174 if (!--run_list_level && interactive_fd) {
2175 signal(SIGTSTP, SIG_IGN);
2176 signal(SIGINT, SIG_IGN);
2179 debug_printf_exec("run_list_real lvl %d return %d\n", run_list_level + 1, rcode);
2183 /* return code is the exit status of the pipe */
2184 static int free_pipe(struct pipe *pi, int indent)
2187 struct child_prog *child;
2188 struct redir_struct *r, *rnext;
2189 int a, i, ret_code = 0;
2191 if (pi->stopped_progs > 0)
2193 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2194 for (i = 0; i < pi->num_progs; i++) {
2195 child = &pi->progs[i];
2196 debug_printf_clean("%s command %d:\n", indenter(indent), i);
2198 for (a = 0, p = child->argv; *p; a++, p++) {
2199 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
2201 free_strings(child->glob_result);
2202 child->glob_result = NULL;
2203 } else if (child->group) {
2204 debug_printf_clean("%s begin group (subshell:%d)\n", indenter(indent), child->subshell);
2205 ret_code = free_pipe_list(child->group, indent+3);
2206 debug_printf_clean("%s end group\n", indenter(indent));
2208 debug_printf_clean("%s (nil)\n", indenter(indent));
2210 for (r = child->redirects; r; r = rnext) {
2211 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->type].descrip);
2213 /* guard against the case >$FOO, where foo is unset or blank */
2215 debug_printf_clean(" %s\n", r->glob_word[0]);
2216 free_strings(r->glob_word);
2217 r->glob_word = NULL;
2220 debug_printf_clean("&%d\n", r->dup);
2225 child->redirects = NULL;
2227 free(pi->progs); /* children are an array, they get freed all at once */
2236 static int free_pipe_list(struct pipe *head, int indent)
2238 int rcode = 0; /* if list has no members */
2239 struct pipe *pi, *next;
2241 for (pi = head; pi; pi = next) {
2242 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
2243 rcode = free_pipe(pi, indent);
2244 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
2246 /*pi->next = NULL;*/
2252 /* Select which version we will use */
2253 static int run_list(struct pipe *pi)
2256 debug_printf_exec("run_list entered\n");
2257 if (fake_mode == 0) {
2258 debug_printf_exec(": run_list_real with %d members\n", pi->num_progs);
2259 rcode = run_list_real(pi);
2261 /* free_pipe_list has the side effect of clearing memory.
2262 * In the long run that function can be merged with run_list_real,
2263 * but doing that now would hobble the debugging effort. */
2264 free_pipe_list(pi, 0);
2265 debug_printf_exec("run_list return %d\n", rcode);
2269 /* Whoever decided to muck with glob internal data is AN IDIOT! */
2270 /* uclibc happily changed the way it works (and it has rights to do so!),
2271 all hell broke loose (SEGVs) */
2273 /* The API for glob is arguably broken. This routine pushes a non-matching
2274 * string into the output structure, removing non-backslashed backslashes.
2275 * If someone can prove me wrong, by performing this function within the
2276 * original glob(3) api, feel free to rewrite this routine into oblivion.
2277 * XXX broken if the last character is '\\', check that before calling.
2279 static char **globhack(const char *src, char **strings)
2285 for (cnt = 1, s = src; s && *s; s++) {
2286 if (*s == '\\') s++;
2289 v = dest = xmalloc(cnt);
2290 for (s = src; s && *s; s++, dest++) {
2291 if (*s == '\\') s++;
2296 return add_string_to_strings(strings, v);
2299 /* XXX broken if the last character is '\\', check that before calling */
2300 static int glob_needed(const char *s)
2305 if (strchr("*[?", *s))
2311 static int xglob(o_string *dest, char ***pglob)
2313 /* short-circuit for null word */
2314 /* we can code this better when the debug_printf's are gone */
2315 if (dest->length == 0) {
2316 if (dest->nonnull) {
2317 /* bash man page calls this an "explicit" null */
2318 *pglob = globhack(dest->data, *pglob);
2323 if (glob_needed(dest->data)) {
2327 memset(&globdata, 0, sizeof(globdata));
2328 gr = glob(dest->data, 0, NULL, &globdata);
2329 debug_printf("glob returned %d\n", gr);
2330 if (gr == GLOB_NOSPACE)
2331 bb_error_msg_and_die("out of memory during glob");
2332 if (gr == GLOB_NOMATCH) {
2333 debug_printf("globhack returned %d\n", gr);
2334 /* quote removal, or more accurately, backslash removal */
2335 *pglob = globhack(dest->data, *pglob);
2338 if (gr != 0) { /* GLOB_ABORTED ? */
2339 bb_error_msg("glob(3) error %d", gr);
2341 if (globdata.gl_pathv && globdata.gl_pathv[0])
2342 *pglob = add_strings_to_strings(1, *pglob, globdata.gl_pathv);
2343 /* globprint(glob_target); */
2344 globfree(&globdata);
2348 *pglob = globhack(dest->data, *pglob);
2352 /* expand_strvec_to_strvec() takes a list of strings, expands
2353 * all variable references within and returns a pointer to
2354 * a list of expanded strings, possibly with larger number
2355 * of strings. (Think VAR="a b"; echo $VAR).
2356 * This new list is allocated as a single malloc block.
2357 * NULL-terminated list of char* pointers is at the beginning of it,
2358 * followed by strings themself.
2359 * Caller can deallocate entire list by single free(list). */
2362 * count_XXX estimates size of the block we need. It's okay
2363 * to over-estimate sizes a bit, if it makes code simpler */
2364 static int count_ifs(const char *str)
2367 debug_printf_expand("count_ifs('%s') ifs='%s'", str, ifs);
2369 str += strcspn(str, ifs);
2371 str++; /* str += strspn(str, ifs); */
2372 cnt++; /* cnt += strspn(str, ifs); - but this code is larger */
2374 debug_printf_expand(" return %d\n", cnt);
2378 static void count_var_expansion_space(int *countp, int *lenp, char *arg)
2383 int count = *countp;
2387 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2390 p = strchr(p, SPECIAL_VAR_SYMBOL);
2393 switch (first_ch & 0x7f) {
2394 /* high bit in 1st_ch indicates that var is double-quoted */
2396 case '!': /* bg pid */
2397 case '?': /* exitcode */
2398 case '#': /* argc */
2399 len += sizeof(int)*3 + 1; /* enough for int */
2403 for (i = 1; i < global_argc; i++) {
2404 len += strlen(global_argv[i]) + 1;
2406 if (!(first_ch & 0x80))
2407 count += count_ifs(global_argv[i]);
2412 arg[0] = first_ch & 0x7f;
2413 if (isdigit(arg[0])) {
2416 if (i < global_argc)
2417 val = global_argv[i];
2419 val = lookup_param(arg);
2421 *p = SPECIAL_VAR_SYMBOL;
2424 len += strlen(val) + 1;
2425 if (!(first_ch & 0x80))
2426 count += count_ifs(val);
2432 len += strlen(arg) + 1;
2438 /* Store given string, finalizing the word and starting new one whenever
2439 * we encounter ifs char(s). This is used for expanding variable values.
2440 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2441 static int expand_on_ifs(char **list, int n, char **posp, const char *str)
2445 int word_len = strcspn(str, ifs);
2447 memcpy(pos, str, word_len); /* store non-ifs chars */
2451 if (!*str) /* EOL - do not finalize word */
2454 if (n) debug_printf_expand("expand_on_ifs finalized list[%d]=%p '%s' "
2455 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2456 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2458 str += strspn(str, ifs); /* skip ifs chars */
2464 /* Expand all variable references in given string, adding words to list[]
2465 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2466 * to be filled). This routine is extremely tricky: has to deal with
2467 * variables/parameters with whitespace, $* and $@, and constructs like
2468 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2469 /* NB: another bug is that we cannot detect empty strings yet:
2470 * "" or $empty"" expands to zero words, has to expand to empty word */
2471 static int expand_vars_to_list(char **list, int n, char **posp, char *arg, char or_mask)
2473 /* or_mask is either 0 (normal case) or 0x80
2474 * (expansion of right-hand side of assignment == 1-element expand) */
2476 char first_ch, ored_ch;
2484 if (n) debug_printf_expand("expand_vars_to_list finalized list[%d]=%p '%s' "
2485 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2486 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2489 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2490 memcpy(pos, arg, p - arg);
2493 p = strchr(p, SPECIAL_VAR_SYMBOL);
2495 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2496 ored_ch |= first_ch;
2498 switch (first_ch & 0x7f) {
2499 /* Highest bit in first_ch indicates that var is double-quoted */
2501 /* FIXME: (echo $$) should still print pid of main shell */
2502 val = utoa(getpid());
2504 case '!': /* bg pid */
2505 val = last_bg_pid ? utoa(last_bg_pid) : (char*)"";
2507 case '?': /* exitcode */
2508 val = utoa(last_return_code);
2510 case '#': /* argc */
2511 val = utoa(global_argc ? global_argc-1 : 0);
2516 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2517 while (i < global_argc) {
2518 n = expand_on_ifs(list, n, &pos, global_argv[i]);
2519 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, global_argc-1);
2520 if (global_argv[i++][0] && i < global_argc) {
2521 /* this argv[] is not empty and not last:
2522 * put terminating NUL, start new word */
2524 if (n) debug_printf_expand("expand_vars_to_list 2 finalized list[%d]=%p '%s' "
2525 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2526 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2531 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2532 * and in this case should theat it like '$*' */
2533 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2535 strcpy(pos, global_argv[i]);
2536 pos += strlen(global_argv[i]);
2537 if (++i >= global_argc)
2540 if (n) debug_printf_expand("expand_vars_to_list 3 finalized list[%d]=%p '%s' "
2541 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2542 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2545 } else { /* quoted $*: add as one word */
2547 strcpy(pos, global_argv[i]);
2548 pos += strlen(global_argv[i]);
2549 if (++i >= global_argc)
2558 arg[0] = first_ch & 0x7f;
2559 if (isdigit(arg[0])) {
2562 if (i < global_argc)
2563 val = global_argv[i];
2565 val = lookup_param(arg);
2567 *p = SPECIAL_VAR_SYMBOL;
2568 if (!(first_ch & 0x80)) { /* unquoted $VAR */
2570 n = expand_on_ifs(list, n, &pos, val);
2573 } /* else: quoted $VAR, val will be appended at pos */
2581 debug_printf_expand("expand_vars_to_list adding tail '%s' at %p\n", arg, pos);
2583 pos += strlen(arg) + 1;
2584 if (pos == list[n-1] + 1) { /* expansion is empty */
2585 if (!(ored_ch & 0x80)) { /* all vars were not quoted... */
2586 debug_printf_expand("expand_vars_to_list list[%d] empty, going back\n", n);
2596 static char **expand_variables(char **argv, char or_mask)
2601 char *pos, **v, **list;
2604 if (!*v) debug_printf_expand("count_var_expansion_space: "
2605 "argv[0]=NULL count=%d len=%d alloc_space=%d\n",
2606 count, len, sizeof(char*) * count + len);
2608 count_var_expansion_space(&count, &len, *v);
2609 debug_printf_expand("count_var_expansion_space: "
2610 "'%s' count=%d len=%d alloc_space=%d\n",
2611 *v, count, len, sizeof(char*) * count + len);
2614 len += sizeof(char*) * count; /* total to alloc */
2615 list = xmalloc(len);
2616 pos = (char*)(list + count);
2617 debug_printf_expand("list=%p, list[0] should be %p\n", list, pos);
2621 n = expand_vars_to_list(list, n, &pos, *v++, or_mask);
2623 if (n) debug_printf_expand("finalized list[%d]=%p '%s' "
2624 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2625 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2632 debug_printf_expand("list[%d]=%p '%s'\n", m, list[m], list[m]);
2635 debug_printf_expand("used_space=%d\n", pos - (char*)list);
2638 if (ENABLE_HUSH_DEBUG)
2639 if (pos - (char*)list > len)
2640 bb_error_msg_and_die("BUG in varexp");
2644 static char **expand_strvec_to_strvec(char **argv)
2646 return expand_variables(argv, 0);
2649 static char *expand_string_to_string(const char *str)
2651 char *argv[2], **list;
2653 argv[0] = (char*)str;
2655 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2656 if (ENABLE_HUSH_DEBUG)
2657 if (!list[0] || list[1])
2658 bb_error_msg_and_die("BUG in varexp2");
2659 /* actually, just move string 2*sizeof(char*) bytes back */
2660 strcpy((char*)list, list[0]);
2661 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2665 static char* expand_strvec_to_string(char **argv)
2669 list = expand_variables(argv, 0x80);
2670 /* Convert all NULs to spaces */
2674 if (ENABLE_HUSH_DEBUG)
2675 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2676 bb_error_msg_and_die("BUG in varexp3");
2677 list[n][-1] = ' '; /* TODO: or to ifs[0]? */
2681 strcpy((char*)list, list[0]);
2682 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2686 /* This is used to get/check local shell variables */
2687 static struct variable *get_local_var(const char *name)
2689 struct variable *cur;
2695 for (cur = top_var; cur; cur = cur->next) {
2696 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
2702 /* str holds "NAME=VAL" and is expected to be malloced.
2703 * We take ownership of it. */
2704 static int set_local_var(char *str, int flg_export)
2706 struct variable *cur;
2710 value = strchr(str, '=');
2711 if (!value) { /* not expected to ever happen? */
2716 name_len = value - str + 1; /* including '=' */
2717 cur = top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
2719 if (strncmp(cur->varstr, str, name_len) != 0) {
2721 /* Bail out. Note that now cur points
2722 * to last var in linked list */
2728 /* We found an existing var with this name */
2730 if (cur->flg_read_only) {
2731 bb_error_msg("%s: readonly variable", str);
2735 unsetenv(str); /* just in case */
2737 if (strcmp(cur->varstr, str) == 0) {
2742 if (cur->max_len >= strlen(str)) {
2743 /* This one is from startup env, reuse space */
2744 strcpy(cur->varstr, str);
2747 /* max_len == 0 signifies "malloced" var, which we can
2748 * (and has to) free */
2752 goto set_str_and_exp;
2755 /* Not found - create next variable struct */
2756 cur->next = xzalloc(sizeof(*cur));
2763 cur->flg_export = 1;
2764 if (cur->flg_export)
2765 return putenv(cur->varstr);
2769 static void unset_local_var(const char *name)
2771 struct variable *cur;
2772 struct variable *prev = prev; /* for gcc */
2777 name_len = strlen(name);
2780 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2781 if (cur->flg_read_only) {
2782 bb_error_msg("%s: readonly variable", name);
2785 /* prev is ok to use here because 1st variable, HUSH_VERSION,
2786 * is ro, and we cannot reach this code on the 1st pass */
2787 prev->next = cur->next;
2788 unsetenv(cur->varstr);
2799 static int is_assignment(const char *s)
2801 if (!s || !isalpha(*s))
2804 while (isalnum(*s) || *s == '_')
2809 /* the src parameter allows us to peek forward to a possible &n syntax
2810 * for file descriptor duplication, e.g., "2>&1".
2811 * Return code is 0 normally, 1 if a syntax error is detected in src.
2812 * Resource errors (in xmalloc) cause the process to exit */
2813 static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2814 struct in_str *input)
2816 struct child_prog *child = ctx->child;
2817 struct redir_struct *redir = child->redirects;
2818 struct redir_struct *last_redir = NULL;
2820 /* Create a new redir_struct and drop it onto the end of the linked list */
2823 redir = redir->next;
2825 redir = xzalloc(sizeof(struct redir_struct));
2826 /* redir->next = NULL; */
2827 /* redir->glob_word = NULL; */
2829 last_redir->next = redir;
2831 child->redirects = redir;
2834 redir->type = style;
2835 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
2837 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2839 /* Check for a '2>&1' type redirect */
2840 redir->dup = redirect_dup_num(input);
2841 if (redir->dup == -2) return 1; /* syntax error */
2842 if (redir->dup != -1) {
2843 /* Erik had a check here that the file descriptor in question
2844 * is legit; I postpone that to "run time"
2845 * A "-" representation of "close me" shows up as a -3 here */
2846 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2848 /* We do _not_ try to open the file that src points to,
2849 * since we need to return and let src be expanded first.
2850 * Set ctx->pending_redirect, so we know what to do at the
2851 * end of the next parsed word. */
2852 ctx->pending_redirect = redir;
2857 static struct pipe *new_pipe(void)
2860 pi = xzalloc(sizeof(struct pipe));
2861 /*pi->num_progs = 0;*/
2862 /*pi->progs = NULL;*/
2863 /*pi->next = NULL;*/
2864 /*pi->followup = 0; invalid */
2866 pi->res_word = RES_NONE;
2870 static void initialize_context(struct p_context *ctx)
2873 ctx->pipe = ctx->list_head = new_pipe();
2874 ctx->pending_redirect = NULL;
2875 ctx->res_w = RES_NONE;
2876 //only ctx->parse_type is not touched... is this intentional?
2879 done_command(ctx); /* creates the memory for working child */
2882 /* normal return is 0
2883 * if a reserved word is found, and processed, return 1
2884 * should handle if, then, elif, else, fi, for, while, until, do, done.
2885 * case, function, and select are obnoxious, save those for later.
2887 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS
2888 static int reserved_word(o_string *dest, struct p_context *ctx)
2890 struct reserved_combo {
2895 /* Mostly a list of accepted follow-up reserved words.
2896 * FLAG_END means we are done with the sequence, and are ready
2897 * to turn the compound list into a command.
2898 * FLAG_START means the word must start a new compound list.
2900 static const struct reserved_combo reserved_list[] = {
2902 { "if", RES_IF, FLAG_THEN | FLAG_START },
2903 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2904 { "elif", RES_ELIF, FLAG_THEN },
2905 { "else", RES_ELSE, FLAG_FI },
2906 { "fi", RES_FI, FLAG_END },
2908 #if ENABLE_HUSH_LOOPS
2909 { "for", RES_FOR, FLAG_IN | FLAG_START },
2910 { "while", RES_WHILE, FLAG_DO | FLAG_START },
2911 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
2912 { "in", RES_IN, FLAG_DO },
2913 { "do", RES_DO, FLAG_DONE },
2914 { "done", RES_DONE, FLAG_END }
2918 const struct reserved_combo *r;
2920 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
2921 if (strcmp(dest->data, r->literal) != 0)
2923 debug_printf("found reserved word %s, code %d\n", r->literal, r->code);
2924 if (r->flag & FLAG_START) {
2925 struct p_context *new;
2926 debug_printf("push stack\n");
2927 #if ENABLE_HUSH_LOOPS
2928 if (ctx->res_w == RES_IN || ctx->res_w == RES_FOR) {
2929 syntax("malformed for"); /* example: 'for if' */
2930 ctx->res_w = RES_SNTX;
2935 new = xmalloc(sizeof(*new));
2936 *new = *ctx; /* physical copy */
2937 initialize_context(ctx);
2939 } else if (ctx->res_w == RES_NONE || !(ctx->old_flag & (1 << r->code))) {
2941 ctx->res_w = RES_SNTX;
2945 ctx->res_w = r->code;
2946 ctx->old_flag = r->flag;
2947 if (ctx->old_flag & FLAG_END) {
2948 struct p_context *old;
2949 debug_printf("pop stack\n");
2950 done_pipe(ctx, PIPE_SEQ);
2952 old->child->group = ctx->list_head;
2953 old->child->subshell = 0;
2954 *ctx = *old; /* physical copy */
2963 #define reserved_word(dest, ctx) ((int)0)
2966 /* Normal return is 0.
2967 * Syntax or xglob errors return 1. */
2968 static int done_word(o_string *dest, struct p_context *ctx)
2970 struct child_prog *child = ctx->child;
2971 char ***glob_target;
2974 debug_printf_parse("done_word entered: '%s' %p\n", dest->data, child);
2975 if (dest->length == 0 && !dest->nonnull) {
2976 debug_printf_parse("done_word return 0: true null, ignored\n");
2979 if (ctx->pending_redirect) {
2980 glob_target = &ctx->pending_redirect->glob_word;
2984 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
2987 if (!child->argv && (ctx->parse_type & PARSEFLAG_SEMICOLON)) {
2988 debug_printf_parse(": checking '%s' for reserved-ness\n", dest->data);
2989 if (reserved_word(dest, ctx)) {
2990 debug_printf_parse("done_word return %d\n", (ctx->res_w == RES_SNTX));
2991 return (ctx->res_w == RES_SNTX);
2994 glob_target = &child->argv;
2996 gr = xglob(dest, glob_target);
2998 debug_printf_parse("done_word return 1: xglob returned %d\n", gr);
3003 if (ctx->pending_redirect) {
3004 if (ctx->pending_redirect->glob_word
3005 && ctx->pending_redirect->glob_word[0]
3006 && ctx->pending_redirect->glob_word[1]
3008 /* more than one word resulted from globbing redir */
3009 ctx->pending_redirect = NULL;
3010 bb_error_msg("ambiguous redirect");
3011 debug_printf_parse("done_word return 1: ambiguous redirect\n");
3014 ctx->pending_redirect = NULL;
3016 #if ENABLE_HUSH_LOOPS
3017 if (ctx->res_w == RES_FOR) {
3018 done_word(dest, ctx);
3019 done_pipe(ctx, PIPE_SEQ);
3022 debug_printf_parse("done_word return 0\n");
3026 /* The only possible error here is out of memory, in which case
3028 static int done_command(struct p_context *ctx)
3030 /* The child is really already in the pipe structure, so
3031 * advance the pipe counter and make a new, null child. */
3032 struct pipe *pi = ctx->pipe;
3033 struct child_prog *child = ctx->child;
3036 if (child->group == NULL
3037 && child->argv == NULL
3038 && child->redirects == NULL
3040 debug_printf_parse("done_command: skipping null cmd, num_progs=%d\n", pi->num_progs);
3041 return pi->num_progs;
3044 debug_printf_parse("done_command: ++num_progs=%d\n", pi->num_progs);
3046 debug_printf_parse("done_command: initializing, num_progs=%d\n", pi->num_progs);
3049 /* Only real trickiness here is that the uncommitted
3050 * child structure is not counted in pi->num_progs. */
3051 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
3052 child = &pi->progs[pi->num_progs];
3054 memset(child, 0, sizeof(*child));
3055 /*child->redirects = NULL;*/
3056 /*child->argv = NULL;*/
3057 /*child->is_stopped = 0;*/
3058 /*child->group = NULL;*/
3059 /*child->glob_result = NULL;*/
3061 //sp: /*child->sp = 0;*/
3062 //pt: child->parse_type = ctx->parse_type;
3065 /* but ctx->pipe and ctx->list_head remain unchanged */
3067 return pi->num_progs; /* used only for 0/nonzero check */
3070 static int done_pipe(struct p_context *ctx, pipe_style type)
3075 debug_printf_parse("done_pipe entered, followup %d\n", type);
3076 not_null = done_command(ctx); /* implicit closure of previous command */
3077 ctx->pipe->followup = type;
3078 ctx->pipe->res_word = ctx->res_w;
3079 /* Without this check, even just <enter> on command line generates
3080 * tree of three NOPs (!). Which is harmless but annoying.
3081 * IOW: it is safe to do it unconditionally. */
3084 ctx->pipe->next = new_p;
3087 done_command(ctx); /* set up new pipe to accept commands */
3089 debug_printf_parse("done_pipe return 0\n");
3093 /* peek ahead in the in_str to find out if we have a "&n" construct,
3094 * as in "2>&1", that represents duplicating a file descriptor.
3095 * returns either -2 (syntax error), -1 (no &), or the number found.
3097 static int redirect_dup_num(struct in_str *input)
3099 int ch, d = 0, ok = 0;
3101 if (ch != '&') return -1;
3103 b_getch(input); /* get the & */
3107 return -3; /* "-" represents "close me" */
3109 while (isdigit(ch)) {
3110 d = d*10 + (ch-'0');
3117 bb_error_msg("ambiguous redirect");
3121 /* If a redirect is immediately preceded by a number, that number is
3122 * supposed to tell which file descriptor to redirect. This routine
3123 * looks for such preceding numbers. In an ideal world this routine
3124 * needs to handle all the following classes of redirects...
3125 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3126 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3127 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3128 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3129 * A -1 output from this program means no valid number was found, so the
3130 * caller should use the appropriate default for this redirection.
3132 static int redirect_opt_num(o_string *o)
3138 for (num = 0; num < o->length; num++) {
3139 if (!isdigit(*(o->data + num))) {
3143 /* reuse num (and save an int) */
3144 num = atoi(o->data);
3149 #if ENABLE_HUSH_TICK
3150 /* NB: currently disabled on NOMMU */
3151 static FILE *generate_stream_from_list(struct pipe *head)
3154 int pid, channel[2];
3159 bb_perror_msg_and_die("fork");
3160 } else if (pid == 0) {
3162 if (channel[1] != 1) {
3163 dup2(channel[1], 1);
3166 /* Prevent it from trying to handle ctrl-z etc */
3170 /* Process substitution is not considered to be usual
3171 * 'command execution'.
3172 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not. */
3173 /* Not needed, we are relying on it being disabled
3174 * everywhere outside actual command execution. */
3175 /*set_jobctrl_sighandler(SIG_IGN);*/
3176 set_misc_sighandler(SIG_DFL);
3177 _exit(run_list_real(head)); /* leaks memory */
3180 pf = fdopen(channel[0], "r");
3184 /* Return code is exit status of the process that is run. */
3185 static int process_command_subs(o_string *dest, struct p_context *ctx,
3186 struct in_str *input, const char *subst_end)
3188 int retcode, ch, eol_cnt;
3189 o_string result = NULL_O_STRING;
3190 struct p_context inner;
3192 struct in_str pipe_str;
3194 initialize_context(&inner);
3196 /* recursion to generate command */
3197 retcode = parse_stream(&result, &inner, input, subst_end);
3199 return retcode; /* syntax error or EOF */
3200 done_word(&result, &inner);
3201 done_pipe(&inner, PIPE_SEQ);
3204 p = generate_stream_from_list(inner.list_head);
3205 if (p == NULL) return 1;
3206 close_on_exec_on(fileno(p));
3207 setup_file_in_str(&pipe_str, p);
3209 /* now send results of command back into original context */
3211 while ((ch = b_getch(&pipe_str)) != EOF) {
3217 b_addqchr(dest, '\n', dest->o_quote);
3220 b_addqchr(dest, ch, dest->o_quote);
3223 debug_printf("done reading from pipe, pclose()ing\n");
3224 /* This is the step that wait()s for the child. Should be pretty
3225 * safe, since we just read an EOF from its stdout. We could try
3226 * to do better, by using wait(), and keeping track of background jobs
3227 * at the same time. That would be a lot of work, and contrary
3228 * to the KISS philosophy of this program. */
3229 retcode = fclose(p);
3230 free_pipe_list(inner.list_head, 0);
3231 debug_printf("closed FILE from child, retcode=%d\n", retcode);
3236 static int parse_group(o_string *dest, struct p_context *ctx,
3237 struct in_str *input, int ch)
3240 const char *endch = NULL;
3241 struct p_context sub;
3242 struct child_prog *child = ctx->child;
3244 debug_printf_parse("parse_group entered\n");
3247 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3250 initialize_context(&sub);
3254 child->subshell = 1;
3256 rcode = parse_stream(dest, &sub, input, endch);
3258 done_word(dest, &sub); /* finish off the final word in the subcontext */
3259 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
3260 child->group = sub.list_head;
3262 debug_printf_parse("parse_group return %d\n", rcode);
3264 /* child remains "open", available for possible redirects */
3267 /* Basically useful version until someone wants to get fancier,
3268 * see the bash man page under "Parameter Expansion" */
3269 static const char *lookup_param(const char *src)
3271 struct variable *var = get_local_var(src);
3273 return strchr(var->varstr, '=') + 1;
3277 /* return code: 0 for OK, 1 for syntax error */
3278 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
3280 int ch = b_peek(input); /* first character after the $ */
3281 unsigned char quote_mask = dest->o_quote ? 0x80 : 0;
3283 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
3285 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3286 //sp: ctx->child->sp++;
3288 debug_printf_parse(": '%c'\n", ch);
3290 b_addchr(dest, ch | quote_mask);
3293 if (!isalnum(ch) && ch != '_')
3296 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3297 } else if (isdigit(ch)) {
3299 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3300 //sp: ctx->child->sp++;
3301 debug_printf_parse(": '%c'\n", ch);
3303 b_addchr(dest, ch | quote_mask);
3304 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3305 } else switch (ch) {
3307 case '!': /* last bg pid */
3308 case '?': /* last exit code */
3309 case '#': /* number of args */
3310 case '*': /* args */
3311 case '@': /* args */
3312 goto make_one_char_var;
3314 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3315 //sp: ctx->child->sp++;
3317 /* XXX maybe someone will try to escape the '}' */
3319 ch = b_getch(input);
3322 if (!isalnum(ch) && ch != '_') {
3323 syntax("unterminated ${name}");
3324 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3327 debug_printf_parse(": '%c'\n", ch);
3328 b_addchr(dest, ch | quote_mask);
3331 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3333 #if ENABLE_HUSH_TICK
3336 process_command_subs(dest, ctx, input, ")");
3341 /* still unhandled, but should be eventually */
3342 bb_error_msg("unhandled syntax: $%c", ch);
3346 b_addqchr(dest, '$', dest->o_quote);
3348 debug_printf_parse("handle_dollar return 0\n");
3352 /* return code is 0 for normal exit, 1 for syntax error */
3353 static int parse_stream(o_string *dest, struct p_context *ctx,
3354 struct in_str *input, const char *end_trigger)
3358 redir_type redir_style;
3361 /* Only double-quote state is handled in the state variable dest->o_quote.
3362 * A single-quote triggers a bypass of the main loop until its mate is
3363 * found. When recursing, quote state is passed in via dest->o_quote. */
3365 debug_printf_parse("parse_stream entered, end_trigger='%s'\n", end_trigger);
3370 ch = b_getch(input);
3374 next = b_peek(input);
3376 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
3377 ch, ch, m, dest->o_quote);
3378 if (m == CHAR_ORDINARY
3379 || (m != CHAR_SPECIAL && dest->o_quote)
3382 syntax("unterminated \"");
3383 debug_printf_parse("parse_stream return 1: unterminated \"\n");
3386 b_addqchr(dest, ch, dest->o_quote);
3389 if (m == CHAR_IFS) {
3390 if (done_word(dest, ctx)) {
3391 debug_printf_parse("parse_stream return 1: done_word!=0\n");
3396 /* If we aren't performing a substitution, treat
3397 * a newline as a command separator.
3398 * [why we don't handle it exactly like ';'? --vda] */
3399 if (end_trigger && ch == '\n') {
3400 done_pipe(ctx, PIPE_SEQ);
3403 if ((end_trigger && strchr(end_trigger, ch))
3404 && !dest->o_quote && ctx->res_w == RES_NONE
3406 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
3413 if (dest->length == 0 && !dest->o_quote) {
3416 if (ch == EOF || ch == '\n')
3421 b_addqchr(dest, ch, dest->o_quote);
3427 debug_printf_parse("parse_stream return 1: \\<eof>\n");
3430 b_addqchr(dest, '\\', dest->o_quote);
3431 b_addqchr(dest, b_getch(input), dest->o_quote);
3434 if (handle_dollar(dest, ctx, input) != 0) {
3435 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3442 ch = b_getch(input);
3443 if (ch == EOF || ch == '\'')
3448 syntax("unterminated '");
3449 debug_printf_parse("parse_stream return 1: unterminated '\n");
3455 dest->o_quote ^= 1; /* invert */
3457 #if ENABLE_HUSH_TICK
3459 process_command_subs(dest, ctx, input, "`");
3463 redir_fd = redirect_opt_num(dest);
3464 done_word(dest, ctx);
3465 redir_style = REDIRECT_OVERWRITE;
3467 redir_style = REDIRECT_APPEND;
3471 else if (next == '(') {
3472 syntax(">(process) not supported");
3473 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
3477 setup_redirect(ctx, redir_fd, redir_style, input);
3480 redir_fd = redirect_opt_num(dest);
3481 done_word(dest, ctx);
3482 redir_style = REDIRECT_INPUT;
3484 redir_style = REDIRECT_HEREIS;
3486 } else if (next == '>') {
3487 redir_style = REDIRECT_IO;
3491 else if (next == '(') {
3492 syntax("<(process) not supported");
3493 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
3497 setup_redirect(ctx, redir_fd, redir_style, input);
3500 done_word(dest, ctx);
3501 done_pipe(ctx, PIPE_SEQ);
3504 done_word(dest, ctx);
3507 done_pipe(ctx, PIPE_AND);
3509 done_pipe(ctx, PIPE_BG);
3513 done_word(dest, ctx);
3516 done_pipe(ctx, PIPE_OR);
3518 /* we could pick up a file descriptor choice here
3519 * with redirect_opt_num(), but bash doesn't do it.
3520 * "echo foo 2| cat" yields "foo 2". */
3526 if (parse_group(dest, ctx, input, ch) != 0) {
3527 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
3533 syntax("unexpected }"); /* Proper use of this character is caught by end_trigger */
3534 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
3537 if (ENABLE_HUSH_DEBUG)
3538 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
3541 /* Complain if quote? No, maybe we just finished a command substitution
3542 * that was quoted. Example:
3543 * $ echo "`cat foo` plus more"
3544 * and we just got the EOF generated by the subshell that ran "cat foo"
3545 * The only real complaint is if we got an EOF when end_trigger != NULL,
3546 * that is, we were really supposed to get end_trigger, and never got
3547 * one before the EOF. Can't use the standard "syntax error" return code,
3548 * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
3549 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
3555 static void set_in_charmap(const char *set, int code)
3558 charmap[(unsigned char)*set++] = code;
3561 static void update_charmap(void)
3563 /* char *ifs and char charmap[256] are both globals. */
3564 ifs = getenv("IFS");
3567 /* Precompute a list of 'flow through' behavior so it can be treated
3568 * quickly up front. Computation is necessary because of IFS.
3569 * Special case handling of IFS == " \t\n" is not implemented.
3570 * The charmap[] array only really needs two bits each,
3571 * and on most machines that would be faster (reduced L1 cache use).
3573 memset(charmap, CHAR_ORDINARY, sizeof(charmap));
3574 #if ENABLE_HUSH_TICK
3575 set_in_charmap("\\$\"`", CHAR_SPECIAL);
3577 set_in_charmap("\\$\"", CHAR_SPECIAL);
3579 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
3580 set_in_charmap(ifs, CHAR_IFS); /* are ordinary if quoted */
3583 /* most recursion does not come through here, the exception is
3584 * from builtin_source() and builtin_eval() */
3585 static int parse_and_run_stream(struct in_str *inp, int parse_flag)
3587 struct p_context ctx;
3588 o_string temp = NULL_O_STRING;
3591 ctx.parse_type = parse_flag;
3592 initialize_context(&ctx);
3594 if (!(parse_flag & PARSEFLAG_SEMICOLON) || (parse_flag & PARSEFLAG_REPARSING))
3595 set_in_charmap(";$&|", CHAR_ORDINARY);
3596 #if ENABLE_HUSH_INTERACTIVE
3597 inp->promptmode = 0; /* PS1 */
3599 /* We will stop & execute after each ';' or '\n'.
3600 * Example: "sleep 9999; echo TEST" + ctrl-C:
3601 * TEST should be printed */
3602 rcode = parse_stream(&temp, &ctx, inp, ";\n");
3603 if (rcode != 1 && ctx.old_flag != 0) {
3606 if (rcode != 1 && ctx.old_flag == 0) {
3607 done_word(&temp, &ctx);
3608 done_pipe(&ctx, PIPE_SEQ);
3609 debug_print_tree(ctx.list_head, 0);
3610 debug_printf_exec("parse_stream_outer: run_list\n");
3611 run_list(ctx.list_head);
3613 if (ctx.old_flag != 0) {
3620 free_pipe_list(ctx.list_head, 0);
3623 } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP)); /* loop on syntax errors, return on EOF */
3627 static int parse_and_run_string(const char *s, int parse_flag)
3629 struct in_str input;
3630 setup_string_in_str(&input, s);
3631 return parse_and_run_stream(&input, parse_flag);
3634 static int parse_and_run_file(FILE *f)
3637 struct in_str input;
3638 setup_file_in_str(&input, f);
3639 rcode = parse_and_run_stream(&input, PARSEFLAG_SEMICOLON);
3644 /* Make sure we have a controlling tty. If we get started under a job
3645 * aware app (like bash for example), make sure we are now in charge so
3646 * we don't fight over who gets the foreground */
3647 static void setup_job_control(void)
3651 saved_task_pgrp = shell_pgrp = getpgrp();
3652 debug_printf_jobs("saved_task_pgrp=%d\n", saved_task_pgrp);
3653 close_on_exec_on(interactive_fd);
3655 /* If we were ran as 'hush &',
3656 * sleep until we are in the foreground. */
3657 while (tcgetpgrp(interactive_fd) != shell_pgrp) {
3658 /* Send TTIN to ourself (should stop us) */
3659 kill(- shell_pgrp, SIGTTIN);
3660 shell_pgrp = getpgrp();
3663 /* Ignore job-control and misc signals. */
3664 set_jobctrl_sighandler(SIG_IGN);
3665 set_misc_sighandler(SIG_IGN);
3666 //huh? signal(SIGCHLD, SIG_IGN);
3668 /* We _must_ restore tty pgrp on fatal signals */
3669 set_fatal_sighandler(sigexit);
3671 /* Put ourselves in our own process group. */
3672 setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
3673 /* Grab control of the terminal. */
3674 tcsetpgrp(interactive_fd, getpid());
3678 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
3679 int hush_main(int argc, char **argv)
3681 static const char version_str[] ALIGN1 = "HUSH_VERSION="HUSH_VER_STR;
3682 static const struct variable const_shell_ver = {
3684 .varstr = (char*)version_str,
3685 .max_len = 1, /* 0 can provoke free(name) */
3693 struct variable *cur_var;
3695 PTR_TO_GLOBALS = xzalloc(sizeof(G));
3697 /* Deal with HUSH_VERSION */
3698 shell_ver = const_shell_ver; /* copying struct here */
3699 top_var = &shell_ver;
3700 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
3701 /* Initialize our shell local variables with the values
3702 * currently living in the environment */
3706 char *value = strchr(*e, '=');
3707 if (value) { /* paranoia */
3708 cur_var->next = xzalloc(sizeof(*cur_var));
3709 cur_var = cur_var->next;
3710 cur_var->varstr = *e;
3711 cur_var->max_len = strlen(*e);
3712 cur_var->flg_export = 1;
3716 putenv((char *)version_str); /* reinstate HUSH_VERSION */
3718 #if ENABLE_FEATURE_EDITING
3719 line_input_state = new_line_input_t(FOR_SHELL);
3721 /* XXX what should these be while sourcing /etc/profile? */
3724 /* Initialize some more globals to non-zero values */
3726 #if ENABLE_HUSH_INTERACTIVE
3727 #if ENABLE_FEATURE_EDITING
3728 cmdedit_set_initial_prompt();
3733 if (EXIT_SUCCESS) /* otherwise is already done */
3734 last_return_code = EXIT_SUCCESS;
3736 if (argv[0] && argv[0][0] == '-') {
3737 debug_printf("sourcing /etc/profile\n");
3738 input = fopen("/etc/profile", "r");
3739 if (input != NULL) {
3740 close_on_exec_on(fileno(input));
3741 parse_and_run_file(input);
3747 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
3750 global_argv = argv + optind;
3751 global_argc = argc - optind;
3752 opt = parse_and_run_string(optarg, PARSEFLAG_SEMICOLON);
3755 /* Well, we cannot just declare interactiveness,
3756 * we have to have some stuff (ctty, etc) */
3757 /* interactive_fd++; */
3764 fprintf(stderr, "Usage: sh [FILE]...\n"
3765 " or: sh -c command [args]...\n\n");
3773 /* A shell is interactive if the '-i' flag was given, or if all of
3774 * the following conditions are met:
3776 * no arguments remaining or the -s flag given
3777 * standard input is a terminal
3778 * standard output is a terminal
3779 * Refer to Posix.2, the description of the 'sh' utility. */
3780 if (argv[optind] == NULL && input == stdin
3781 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3783 saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
3784 debug_printf("saved_tty_pgrp=%d\n", saved_tty_pgrp);
3785 if (saved_tty_pgrp >= 0) {
3786 /* try to dup to high fd#, >= 255 */
3787 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3788 if (interactive_fd < 0) {
3789 /* try to dup to any fd */
3790 interactive_fd = dup(STDIN_FILENO);
3791 if (interactive_fd < 0)
3795 // TODO: track & disallow any attempts of user
3796 // to (inadvertently) close/redirect it
3799 debug_printf("interactive_fd=%d\n", interactive_fd);
3800 if (interactive_fd) {
3801 /* Looks like they want an interactive shell */
3802 setup_job_control();
3803 /* Make xfuncs do cleanup on exit */
3804 die_sleep = -1; /* flag */
3805 // FIXME: should we reset die_sleep = 0 whereever we fork?
3806 if (setjmp(die_jmp)) {
3807 /* xfunc has failed! die die die */
3808 hush_exit(xfunc_error_retval);
3810 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
3811 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
3812 printf("Enter 'help' for a list of built-in commands.\n\n");
3815 #elif ENABLE_HUSH_INTERACTIVE
3816 /* no job control compiled, only prompt/line editing */
3817 if (argv[optind] == NULL && input == stdin
3818 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3820 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3821 if (interactive_fd < 0) {
3822 /* try to dup to any fd */
3823 interactive_fd = dup(STDIN_FILENO);
3824 if (interactive_fd < 0)
3832 if (argv[optind] == NULL) {
3833 opt = parse_and_run_file(stdin);
3837 debug_printf("\nrunning script '%s'\n", argv[optind]);
3838 global_argv = argv + optind;
3839 global_argc = argc - optind;
3840 input = xfopen(argv[optind], "r");
3841 opt = parse_and_run_file(input);
3845 #if ENABLE_FEATURE_CLEAN_UP
3847 if (cwd != bb_msg_unknown)
3849 cur_var = top_var->next;
3851 struct variable *tmp = cur_var;
3852 if (!cur_var->max_len)
3853 free(cur_var->varstr);
3854 cur_var = cur_var->next;
3858 hush_exit(opt ? opt : last_return_code);