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 */
89 /* If you comment out one of these below, it will be #defined later
90 * to perform debug printfs to stderr: */
91 #define debug_printf(...) do {} while (0)
92 /* Finer-grained debug switches */
93 #define debug_printf_parse(...) do {} while (0)
94 #define debug_print_tree(a, b) do {} while (0)
95 #define debug_printf_exec(...) do {} while (0)
96 #define debug_printf_jobs(...) do {} while (0)
97 #define debug_printf_expand(...) do {} while (0)
98 #define debug_printf_clean(...) do {} while (0)
101 #define debug_printf(...) fprintf(stderr, __VA_ARGS__)
104 #ifndef debug_printf_parse
105 #define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
108 #ifndef debug_printf_exec
109 #define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
112 #ifndef debug_printf_jobs
113 #define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
114 #define DEBUG_SHELL_JOBS 1
117 #ifndef debug_printf_expand
118 #define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
119 #define DEBUG_EXPAND 1
122 /* Keep unconditionally on for now */
123 #define ENABLE_HUSH_DEBUG 1
125 #ifndef debug_printf_clean
126 /* broken, of course, but OK for testing */
127 static const char *indenter(int i)
129 static const char blanks[] = " ";
130 return &blanks[sizeof(blanks) - i - 1];
132 #define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
133 #define DEBUG_CLEAN 1
137 #if !ENABLE_HUSH_INTERACTIVE
138 #undef ENABLE_FEATURE_EDITING
139 #define ENABLE_FEATURE_EDITING 0
140 #undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
141 #define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
144 #define SPECIAL_VAR_SYMBOL 3
146 #define PARSEFLAG_EXIT_FROM_LOOP 1
147 #define PARSEFLAG_SEMICOLON (1 << 1) /* symbol ';' is special for parser */
148 #define PARSEFLAG_REPARSING (1 << 2) /* >= 2nd pass */
152 REDIRECT_OVERWRITE = 2,
158 /* The descrip member of this structure is only used to make debugging
160 static const struct {
162 signed char default_fd;
166 { O_RDONLY, 0, "<" },
167 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
168 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
169 { O_RDONLY, -1, "<<" },
180 /* might eventually control execution */
190 #if ENABLE_HUSH_LOOPS
202 FLAG_END = (1 << RES_NONE ),
204 FLAG_IF = (1 << RES_IF ),
205 FLAG_THEN = (1 << RES_THEN ),
206 FLAG_ELIF = (1 << RES_ELIF ),
207 FLAG_ELSE = (1 << RES_ELSE ),
208 FLAG_FI = (1 << RES_FI ),
210 #if ENABLE_HUSH_LOOPS
211 FLAG_FOR = (1 << RES_FOR ),
212 FLAG_WHILE = (1 << RES_WHILE),
213 FLAG_UNTIL = (1 << RES_UNTIL),
214 FLAG_DO = (1 << RES_DO ),
215 FLAG_DONE = (1 << RES_DONE ),
216 FLAG_IN = (1 << RES_IN ),
218 FLAG_START = (1 << RES_XXXX ),
221 /* This holds pointers to the various results of parsing */
223 struct child_prog *child;
224 struct pipe *list_head;
226 struct redir_struct *pending_redirect;
228 smallint parse_type; /* bitmask of PARSEFLAG_xxx, defines type of parser : ";$" common or special symbol */
229 int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */
230 struct p_context *stack;
231 /* How about quoting status? */
234 struct redir_struct {
235 struct redir_struct *next; /* pointer to the next redirect in the list */
236 redir_type type; /* type of redirection */
237 int fd; /* file descriptor being redirected */
238 int dup; /* -1, or file descriptor being duplicated */
239 glob_t word; /* *word.gl_pathv is the filename */
243 pid_t pid; /* 0 if exited */
244 char **argv; /* program name and arguments */
245 struct pipe *group; /* if non-NULL, first in group or subshell */
246 smallint subshell; /* flag, non-zero if group must be forked */
247 smallint is_stopped; /* is the program currently running? */
248 struct redir_struct *redirects; /* I/O redirections */
249 glob_t glob_result; /* result of parameter globbing */
250 struct pipe *family; /* pointer back to the child's parent pipe */
251 //sp counting seems to be broken... so commented out, grep for '//sp:'
252 //sp: int sp; /* number of SPECIAL_VAR_SYMBOL */
253 //seems to be unused, grep for '//pt:'
254 //pt: int parse_type;
256 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
257 * and on execution these are substituted with their values.
258 * Substitution can make _several_ words out of one argv[n]!
259 * Example: argv[0]=='.^C*^C.' here: echo .$*.
264 int num_progs; /* total number of programs in job */
265 int running_progs; /* number of programs running (not exited) */
266 int stopped_progs; /* number of programs alive, but stopped */
268 int jobid; /* job number */
269 pid_t pgrp; /* process group ID for the job */
270 char *cmdtext; /* name of job */
272 char *cmdbuf; /* buffer various argv's point into */
273 struct child_prog *progs; /* array of commands in pipe */
274 int job_context; /* bitmask defining current context */
275 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
276 smallint res_word; /* needed for if, for, while, until... */
280 struct close_me *next;
284 /* On program start, environ points to initial environment.
285 * putenv adds new pointers into it, unsetenv removes them.
286 * Neither of these (de)allocates the strings.
287 * setenv allocates new strings in malloc space and does putenv,
288 * and thus setenv is unusable (leaky) for shell's purposes */
289 #define setenv(...) setenv_is_leaky_dont_use()
291 struct variable *next;
292 char *varstr; /* points to "name=" portion */
293 int max_len; /* if > 0, name is part of initial env; else name is malloced */
294 smallint flg_export; /* putenv should be done on this var */
295 smallint flg_read_only;
305 #define NULL_O_STRING {NULL,0,0,0,0}
306 /* used for initialization: o_string foo = NULL_O_STRING; */
308 /* I can almost use ordinary FILE *. Is open_memstream() universally
309 * available? Where is it documented? */
312 /* eof_flag=1: last char in ->p is really an EOF */
313 char eof_flag; /* meaningless if ->p == NULL */
315 #if ENABLE_HUSH_INTERACTIVE
317 smallint promptmode; /* 0: PS1, 1: PS2 */
320 int (*get) (struct in_str *);
321 int (*peek) (struct in_str *);
323 #define b_getch(input) ((input)->get(input))
324 #define b_peek(input) ((input)->peek(input))
328 CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
329 CHAR_IFS = 2, /* treated as ordinary if quoted */
330 CHAR_SPECIAL = 3, /* example: $ */
333 #define HUSH_VER_STR "0.02"
335 /* "Globals" within this file */
337 /* Sorted roughly by size (smaller offsets == smaller code) */
339 #if ENABLE_HUSH_INTERACTIVE
340 /* 'interactive_fd' is a fd# open to ctty, if we have one
341 * _AND_ if we decided to act interactively */
346 #if ENABLE_FEATURE_EDITING
347 line_input_t *line_input_state;
351 pid_t saved_task_pgrp;
352 pid_t saved_tty_pgrp;
354 struct pipe *job_list;
355 struct pipe *toplevel_list;
356 smallint ctrl_z_flag;
359 /* these three support $?, $#, and $1 */
362 int last_return_code;
364 struct close_me *close_me_head;
366 unsigned last_bg_pid;
367 struct variable *top_var; /* = &shell_ver (set in main()) */
368 struct variable shell_ver;
369 #if ENABLE_FEATURE_SH_STANDALONE
370 struct nofork_save_area nofork_save;
373 sigjmp_buf toplevel_jb;
375 unsigned char charmap[256];
376 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
379 #define G (*ptr_to_globals)
381 #if !ENABLE_HUSH_INTERACTIVE
382 enum { interactive_fd = 0 };
385 enum { run_list_level = 0 };
388 #if ENABLE_HUSH_INTERACTIVE
389 #define interactive_fd (G.interactive_fd )
393 #if ENABLE_FEATURE_EDITING
394 #define line_input_state (G.line_input_state)
397 #define run_list_level (G.run_list_level )
398 #define saved_task_pgrp (G.saved_task_pgrp )
399 #define saved_tty_pgrp (G.saved_tty_pgrp )
400 #define last_jobid (G.last_jobid )
401 #define job_list (G.job_list )
402 #define toplevel_list (G.toplevel_list )
403 #define toplevel_jb (G.toplevel_jb )
404 #define ctrl_z_flag (G.ctrl_z_flag )
406 #define global_argv (G.global_argv )
407 #define global_argc (G.global_argc )
408 #define last_return_code (G.last_return_code)
410 #define fake_mode (G.fake_mode )
411 #define close_me_head (G.close_me_head )
413 #define last_bg_pid (G.last_bg_pid )
414 #define top_var (G.top_var )
415 #define shell_ver (G.shell_ver )
416 #if ENABLE_FEATURE_SH_STANDALONE
417 #define nofork_save (G.nofork_save )
420 #define toplevel_jb (G.toplevel_jb )
422 #define charmap (G.charmap )
423 #define user_input_buf (G.user_input_buf )
428 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
432 static void syntax(const char *msg)
434 /* Was using fancy stuff:
435 * (interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
436 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
437 void (*fp)(const char *s, ...);
439 fp = (interactive_fd ? bb_error_msg : bb_error_msg_and_die);
440 fp(msg ? "%s: %s" : "syntax error", "syntax error", msg);
445 static void syntax_lineno(int line)
447 void (*fp)(const char *s, ...);
449 fp = (interactive_fd ? bb_error_msg : bb_error_msg_and_die);
450 fp("syntax error hush.c:%d", line);
452 #define syntax(str) syntax_lineno(__LINE__)
455 /* Index of subroutines: */
456 /* function prototypes for builtins */
457 static int builtin_cd(char **argv);
458 static int builtin_eval(char **argv);
459 static int builtin_exec(char **argv);
460 static int builtin_exit(char **argv);
461 static int builtin_export(char **argv);
463 static int builtin_fg_bg(char **argv);
464 static int builtin_jobs(char **argv);
467 static int builtin_help(char **argv);
469 static int builtin_pwd(char **argv);
470 static int builtin_read(char **argv);
471 static int builtin_set(char **argv);
472 static int builtin_shift(char **argv);
473 static int builtin_source(char **argv);
474 static int builtin_umask(char **argv);
475 static int builtin_unset(char **argv);
476 //static int builtin_not_written(char **argv);
477 /* o_string manipulation: */
478 static int b_check_space(o_string *o, int len);
479 static int b_addchr(o_string *o, int ch);
480 static void b_reset(o_string *o);
481 static int b_addqchr(o_string *o, int ch, int quote);
482 /* in_str manipulations: */
483 static int static_get(struct in_str *i);
484 static int static_peek(struct in_str *i);
485 static int file_get(struct in_str *i);
486 static int file_peek(struct in_str *i);
487 static void setup_file_in_str(struct in_str *i, FILE *f);
488 static void setup_string_in_str(struct in_str *i, const char *s);
489 /* close_me manipulations: */
490 static void mark_open(int fd);
491 static void mark_closed(int fd);
492 static void close_all(void);
493 /* "run" the final data structures: */
494 #if !defined(DEBUG_CLEAN)
495 #define free_pipe_list(head, indent) free_pipe_list(head)
496 #define free_pipe(pi, indent) free_pipe(pi)
498 static int free_pipe_list(struct pipe *head, int indent);
499 static int free_pipe(struct pipe *pi, int indent);
500 /* really run the final data structures: */
501 static int setup_redirects(struct child_prog *prog, int squirrel[]);
502 static int run_list_real(struct pipe *pi);
503 static void pseudo_exec_argv(char **argv) ATTRIBUTE_NORETURN;
504 static void pseudo_exec(struct child_prog *child) ATTRIBUTE_NORETURN;
505 static int run_pipe_real(struct pipe *pi);
506 /* extended glob support: */
507 static int globhack(const char *src, int flags, glob_t *pglob);
508 static int glob_needed(const char *s);
509 static int xglob(o_string *dest, int flags, glob_t *pglob);
510 /* variable assignment: */
511 static int is_assignment(const char *s);
512 /* data structure manipulation: */
513 static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
514 static void initialize_context(struct p_context *ctx);
515 static int done_word(o_string *dest, struct p_context *ctx);
516 static int done_command(struct p_context *ctx);
517 static int done_pipe(struct p_context *ctx, pipe_style type);
518 /* primary string parsing: */
519 static int redirect_dup_num(struct in_str *input);
520 static int redirect_opt_num(o_string *o);
522 static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, const char *subst_end);
524 static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
525 static const char *lookup_param(const char *src);
526 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
527 static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, const char *end_trigger);
529 static int parse_and_run_stream(struct in_str *inp, int parse_flag);
530 static int parse_and_run_string(const char *s, int parse_flag);
531 static int parse_and_run_file(FILE *f);
532 /* job management: */
533 static int checkjobs(struct pipe* fg_pipe);
535 static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
536 static void insert_bg_job(struct pipe *pi);
537 static void remove_bg_job(struct pipe *pi);
538 static void delete_finished_bg_job(struct pipe *pi);
540 int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
542 /* local variable support */
543 static char **expand_strvec_to_strvec(char **argv);
545 static char *expand_strvec_to_string(char **argv);
546 /* used for expansion of right hand of assignments */
547 static char *expand_string_to_string(const char *str);
548 static struct variable *get_local_var(const char *name);
549 static int set_local_var(char *str, int flg_export);
550 static void unset_local_var(const char *name);
552 /* Table of built-in functions. They can be forked or not, depending on
553 * context: within pipes, they fork. As simple commands, they do not.
554 * When used in non-forking context, they can change global variables
555 * in the parent shell process. If forked, of course they cannot.
556 * For example, 'unset foo | whatever' will parse and run, but foo will
557 * still be set at the end. */
558 struct built_in_command {
559 const char *cmd; /* name */
560 int (*function) (char **argv); /* function ptr */
562 const char *descr; /* description */
563 #define BLTIN(cmd, func, help) { cmd, func, help }
565 #define BLTIN(cmd, func, help) { cmd, func }
569 static const struct built_in_command bltins[] = {
571 BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"),
573 // BLTIN("break" , builtin_not_written, "Exit for, while or until loop"),
574 BLTIN("cd" , builtin_cd, "Change working directory"),
575 // BLTIN("continue", builtin_not_written, "Continue for, while or until loop"),
576 BLTIN("eval" , builtin_eval, "Construct and run shell command"),
577 BLTIN("exec" , builtin_exec, "Exec command, replacing this shell with the exec'd process"),
578 BLTIN("exit" , builtin_exit, "Exit from shell"),
579 BLTIN("export", builtin_export, "Set environment variable"),
581 BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"),
582 BLTIN("jobs" , builtin_jobs, "Lists the active jobs"),
584 // TODO: remove pwd? we have it as an applet...
585 BLTIN("pwd" , builtin_pwd, "Print current directory"),
586 BLTIN("read" , builtin_read, "Input environment variable"),
587 // BLTIN("return", builtin_not_written, "Return from a function"),
588 BLTIN("set" , builtin_set, "Set/unset shell local variables"),
589 BLTIN("shift" , builtin_shift, "Shift positional parameters"),
590 // BLTIN("trap" , builtin_not_written, "Trap signals"),
591 // BLTIN("ulimit", builtin_not_written, "Controls resource limits"),
592 BLTIN("umask" , builtin_umask, "Sets file creation mask"),
593 BLTIN("unset" , builtin_unset, "Unset environment variable"),
594 BLTIN("." , builtin_source, "Source-in and run commands in a file"),
596 BLTIN("help" , builtin_help, "List shell built-in commands"),
598 BLTIN(NULL, NULL, NULL)
604 static void signal_SA_RESTART(int sig, void (*handler)(int))
607 sa.sa_handler = handler;
608 sa.sa_flags = SA_RESTART;
609 sigemptyset(&sa.sa_mask);
610 sigaction(sig, &sa, NULL);
613 /* Signals are grouped, we handle them in batches */
614 static void set_fatal_sighandler(void (*handler)(int))
616 signal(SIGILL , handler);
617 signal(SIGTRAP, handler);
618 signal(SIGABRT, handler);
619 signal(SIGFPE , handler);
620 signal(SIGBUS , handler);
621 signal(SIGSEGV, handler);
622 /* bash 3.2 seems to handle these just like 'fatal' ones */
623 signal(SIGHUP , handler);
624 signal(SIGPIPE, handler);
625 signal(SIGALRM, handler);
627 static void set_jobctrl_sighandler(void (*handler)(int))
629 signal(SIGTSTP, handler);
630 signal(SIGTTIN, handler);
631 signal(SIGTTOU, handler);
633 static void set_misc_sighandler(void (*handler)(int))
635 signal(SIGINT , handler);
636 signal(SIGQUIT, handler);
637 signal(SIGTERM, handler);
639 /* SIGCHLD is special and handled separately */
641 static void set_every_sighandler(void (*handler)(int))
643 set_fatal_sighandler(handler);
644 set_jobctrl_sighandler(handler);
645 set_misc_sighandler(handler);
646 signal(SIGCHLD, handler);
649 static void handler_ctrl_c(int sig)
651 debug_printf_jobs("got sig %d\n", sig);
652 // as usual we can have all kinds of nasty problems with leaked malloc data here
653 siglongjmp(toplevel_jb, 1);
656 static void handler_ctrl_z(int sig)
660 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
662 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
665 if (!pid) { /* child */
667 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
668 set_every_sighandler(SIG_DFL);
669 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
670 debug_printf_jobs("returning in child\n");
671 /* return to nofork, it will eventually exit now,
672 * not return back to shell */
676 /* finish filling up pipe info */
677 toplevel_list->pgrp = pid; /* child is in its own pgrp */
678 toplevel_list->progs[0].pid = pid;
679 /* parent needs to longjmp out of running nofork.
680 * we will "return" exitcode 0, with child put in background */
681 // as usual we can have all kinds of nasty problems with leaked malloc data here
682 debug_printf_jobs("siglongjmp in parent\n");
683 siglongjmp(toplevel_jb, 1);
686 /* Restores tty foreground process group, and exits.
687 * May be called as signal handler for fatal signal
688 * (will faithfully resend signal to itself, producing correct exit state)
689 * or called directly with -EXITCODE.
690 * We also call it if xfunc is exiting. */
691 static void sigexit(int sig) ATTRIBUTE_NORETURN;
692 static void sigexit(int sig)
696 /* Disable all signals: job control, SIGPIPE, etc. */
697 sigfillset(&block_all);
698 sigprocmask(SIG_SETMASK, &block_all, NULL);
701 tcsetpgrp(interactive_fd, saved_tty_pgrp);
703 /* Not a signal, just exit */
707 /* Enable only this sig and kill ourself with it */
708 signal(sig, SIG_DFL);
709 sigdelset(&block_all, sig);
710 sigprocmask(SIG_SETMASK, &block_all, NULL);
712 _exit(1); /* Should not reach it */
715 /* Restores tty foreground process group, and exits. */
716 static void hush_exit(int exitcode) ATTRIBUTE_NORETURN;
717 static void hush_exit(int exitcode)
719 fflush(NULL); /* flush all streams */
720 sigexit(- (exitcode & 0xff));
725 #define set_fatal_sighandler(handler) ((void)0)
726 #define set_jobctrl_sighandler(handler) ((void)0)
727 #define set_misc_sighandler(handler) ((void)0)
728 #define hush_exit(e) exit(e)
733 static const char *set_cwd(void)
735 if (cwd == bb_msg_unknown)
736 cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
737 cwd = xrealloc_getcwd_or_warn((char *)cwd);
739 cwd = bb_msg_unknown;
743 /* built-in 'eval' handler */
744 static int builtin_eval(char **argv)
746 int rcode = EXIT_SUCCESS;
749 char *str = expand_strvec_to_string(argv + 1);
750 parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP |
751 PARSEFLAG_SEMICOLON);
753 rcode = last_return_code;
758 /* built-in 'cd <path>' handler */
759 static int builtin_cd(char **argv)
763 newdir = getenv("HOME") ? : "/";
767 printf("cd: %s: %s\n", newdir, strerror(errno));
774 /* built-in 'exec' handler */
775 static int builtin_exec(char **argv)
778 return EXIT_SUCCESS; /* Really? */
779 pseudo_exec_argv(argv + 1);
783 /* built-in 'exit' handler */
784 static int builtin_exit(char **argv)
786 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
787 //puts("exit"); /* bash does it */
788 // TODO: warn if we have background jobs: "There are stopped jobs"
789 // On second consecutive 'exit', exit anyway.
792 hush_exit(last_return_code);
793 /* mimic bash: exit 123abc == exit 255 + error msg */
794 xfunc_error_retval = 255;
795 /* bash: exit -2 == exit 254, no error msg */
796 hush_exit(xatoi(argv[1]) & 0xff);
799 /* built-in 'export VAR=value' handler */
800 static int builtin_export(char **argv)
803 char *name = argv[1];
807 // ash emits: export VAR='VAL'
808 // bash: declare -x VAR="VAL"
809 // (both also escape as needed (quotes, $, etc))
817 value = strchr(name, '=');
819 /* They are exporting something without a =VALUE */
820 struct variable *var;
822 var = get_local_var(name);
827 /* bash does not return an error when trying to export
828 * an undefined variable. Do likewise. */
832 set_local_var(xstrdup(name), 1);
837 /* built-in 'fg' and 'bg' handler */
838 static int builtin_fg_bg(char **argv)
845 /* If they gave us no args, assume they want the last backgrounded task */
847 for (pi = job_list; pi; pi = pi->next) {
848 if (pi->jobid == last_jobid) {
852 bb_error_msg("%s: no current job", argv[0]);
855 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
856 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
859 for (pi = job_list; pi; pi = pi->next) {
860 if (pi->jobid == jobnum) {
864 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
867 // TODO: bash prints a string representation
868 // of job being foregrounded (like "sleep 1 | cat")
869 if (*argv[0] == 'f') {
870 /* Put the job into the foreground. */
871 tcsetpgrp(interactive_fd, pi->pgrp);
874 /* Restart the processes in the job */
875 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_progs, pi->pgrp);
876 for (i = 0; i < pi->num_progs; i++) {
877 debug_printf_jobs("reviving pid %d\n", pi->progs[i].pid);
878 pi->progs[i].is_stopped = 0;
880 pi->stopped_progs = 0;
882 i = kill(- pi->pgrp, SIGCONT);
884 if (errno == ESRCH) {
885 delete_finished_bg_job(pi);
888 bb_perror_msg("kill (SIGCONT)");
892 if (*argv[0] == 'f') {
894 return checkjobs_and_fg_shell(pi);
900 /* built-in 'help' handler */
902 static int builtin_help(char **argv ATTRIBUTE_UNUSED)
904 const struct built_in_command *x;
906 printf("\nBuilt-in commands:\n");
907 printf("-------------------\n");
908 for (x = bltins; x->cmd; x++) {
909 printf("%s\t%s\n", x->cmd, x->descr);
917 /* built-in 'jobs' handler */
918 static int builtin_jobs(char **argv ATTRIBUTE_UNUSED)
921 const char *status_string;
923 for (job = job_list; job; job = job->next) {
924 if (job->running_progs == job->stopped_progs)
925 status_string = "Stopped";
927 status_string = "Running";
929 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
935 /* built-in 'pwd' handler */
936 static int builtin_pwd(char **argv ATTRIBUTE_UNUSED)
942 /* built-in 'read VAR' handler */
943 static int builtin_read(char **argv)
946 const char *name = argv[1] ? argv[1] : "REPLY";
948 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name));
949 return set_local_var(string, 0);
952 /* built-in 'set [VAR=value]' handler */
953 static int builtin_set(char **argv)
955 char *temp = argv[1];
959 for (e = top_var; e; e = e->next)
962 set_local_var(xstrdup(temp), 0);
968 /* Built-in 'shift' handler */
969 static int builtin_shift(char **argv)
975 if (n >= 0 && n < global_argc) {
976 global_argv[n] = global_argv[0];
984 /* Built-in '.' handler (read-in and execute commands from file) */
985 static int builtin_source(char **argv)
993 /* XXX search through $PATH is missing */
994 input = fopen(argv[1], "r");
996 bb_error_msg("cannot open '%s'", argv[1]);
1000 /* Now run the file */
1001 /* XXX argv and argc are broken; need to save old global_argv
1002 * (pointer only is OK!) on this stack frame,
1003 * set global_argv=argv+1, recurse, and restore. */
1004 mark_open(fileno(input));
1005 status = parse_and_run_file(input);
1006 mark_closed(fileno(input));
1011 static int builtin_umask(char **argv)
1014 const char *arg = argv[1];
1017 new_umask = strtoul(arg, &end, 8);
1018 if (*end != '\0' || end == arg) {
1019 return EXIT_FAILURE;
1022 new_umask = umask(0);
1023 printf("%.3o\n", (unsigned) new_umask);
1026 return EXIT_SUCCESS;
1029 /* built-in 'unset VAR' handler */
1030 static int builtin_unset(char **argv)
1032 /* bash always returns true */
1033 unset_local_var(argv[1]);
1034 return EXIT_SUCCESS;
1037 //static int builtin_not_written(char **argv)
1039 // printf("builtin_%s not written\n", argv[0]);
1040 // return EXIT_FAILURE;
1043 static int b_check_space(o_string *o, int len)
1045 /* It would be easy to drop a more restrictive policy
1046 * in here, such as setting a maximum string length */
1047 if (o->length + len > o->maxlen) {
1048 /* assert(data == NULL || o->maxlen != 0); */
1049 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1050 o->data = xrealloc(o->data, 1 + o->maxlen);
1052 return o->data == NULL;
1055 static int b_addchr(o_string *o, int ch)
1057 debug_printf("b_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1058 if (b_check_space(o, 1))
1060 o->data[o->length] = ch;
1062 o->data[o->length] = '\0';
1066 static void b_reset(o_string *o)
1070 if (o->data != NULL)
1074 static void b_free(o_string *o)
1082 /* My analysis of quoting semantics tells me that state information
1083 * is associated with a destination, not a source.
1085 static int b_addqchr(o_string *o, int ch, int quote)
1087 if (quote && strchr("*?[\\", ch)) {
1089 rc = b_addchr(o, '\\');
1093 return b_addchr(o, ch);
1096 static int static_get(struct in_str *i)
1099 if (ch == '\0') return EOF;
1103 static int static_peek(struct in_str *i)
1108 #if ENABLE_HUSH_INTERACTIVE
1109 #if ENABLE_FEATURE_EDITING
1110 static void cmdedit_set_initial_prompt(void)
1112 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1115 PS1 = getenv("PS1");
1120 #endif /* EDITING */
1122 static const char* setup_prompt_string(int promptmode)
1124 const char *prompt_str;
1125 debug_printf("setup_prompt_string %d ", promptmode);
1126 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1127 /* Set up the prompt */
1128 if (promptmode == 0) { /* PS1 */
1130 PS1 = xasprintf("%s %c ", cwd, (geteuid() != 0) ? '$' : '#');
1136 prompt_str = (promptmode == 0) ? PS1 : PS2;
1138 debug_printf("result '%s'\n", prompt_str);
1142 static void get_user_input(struct in_str *i)
1145 const char *prompt_str;
1147 prompt_str = setup_prompt_string(i->promptmode);
1148 #if ENABLE_FEATURE_EDITING
1149 /* Enable command line editing only while a command line
1150 * is actually being read; otherwise, we'll end up bequeathing
1151 * atexit() handlers and other unwanted stuff to our
1152 * child processes (rob@sysgo.de) */
1153 r = read_line_input(prompt_str, user_input_buf, BUFSIZ-1, line_input_state);
1154 i->eof_flag = (r < 0);
1155 if (i->eof_flag) { /* EOF/error detected */
1156 user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1157 user_input_buf[1] = '\0';
1160 fputs(prompt_str, stdout);
1162 user_input_buf[0] = r = fgetc(i->file);
1163 /*user_input_buf[1] = '\0'; - already is and never changed */
1164 i->eof_flag = (r == EOF);
1166 i->p = user_input_buf;
1168 #endif /* INTERACTIVE */
1170 /* This is the magic location that prints prompts
1171 * and gets data back from the user */
1172 static int file_get(struct in_str *i)
1176 /* If there is data waiting, eat it up */
1177 if (i->p && *i->p) {
1178 #if ENABLE_HUSH_INTERACTIVE
1182 if (i->eof_flag && !*i->p)
1185 /* need to double check i->file because we might be doing something
1186 * more complicated by now, like sourcing or substituting. */
1187 #if ENABLE_HUSH_INTERACTIVE
1188 if (interactive_fd && i->promptme && i->file == stdin) {
1191 } while (!*i->p); /* need non-empty line */
1192 i->promptmode = 1; /* PS2 */
1197 ch = fgetc(i->file);
1199 debug_printf("file_get: got a '%c' %d\n", ch, ch);
1200 #if ENABLE_HUSH_INTERACTIVE
1207 /* All the callers guarantee this routine will never be
1208 * used right after a newline, so prompting is not needed.
1210 static int file_peek(struct in_str *i)
1213 if (i->p && *i->p) {
1214 if (i->eof_flag && !i->p[1])
1218 ch = fgetc(i->file);
1219 i->eof_flag = (ch == EOF);
1220 i->peek_buf[0] = ch;
1221 i->peek_buf[1] = '\0';
1223 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
1227 static void setup_file_in_str(struct in_str *i, FILE *f)
1229 i->peek = file_peek;
1231 #if ENABLE_HUSH_INTERACTIVE
1233 i->promptmode = 0; /* PS1 */
1239 static void setup_string_in_str(struct in_str *i, const char *s)
1241 i->peek = static_peek;
1242 i->get = static_get;
1243 #if ENABLE_HUSH_INTERACTIVE
1245 i->promptmode = 0; /* PS1 */
1251 static void mark_open(int fd)
1253 struct close_me *new = xmalloc(sizeof(struct close_me));
1255 new->next = close_me_head;
1256 close_me_head = new;
1259 static void mark_closed(int fd)
1261 struct close_me *tmp;
1262 if (close_me_head == NULL || close_me_head->fd != fd)
1263 bb_error_msg_and_die("corrupt close_me");
1264 tmp = close_me_head;
1265 close_me_head = close_me_head->next;
1269 static void close_all(void)
1272 for (c = close_me_head; c; c = c->next) {
1275 close_me_head = NULL;
1278 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
1279 * and stderr if they are redirected. */
1280 static int setup_redirects(struct child_prog *prog, int squirrel[])
1283 struct redir_struct *redir;
1285 for (redir = prog->redirects; redir; redir = redir->next) {
1286 if (redir->dup == -1 && redir->word.gl_pathv == NULL) {
1287 /* something went wrong in the parse. Pretend it didn't happen */
1290 if (redir->dup == -1) {
1291 mode = redir_table[redir->type].mode;
1292 openfd = open_or_warn(redir->word.gl_pathv[0], mode);
1294 /* this could get lost if stderr has been redirected, but
1295 bash and ash both lose it as well (though zsh doesn't!) */
1299 openfd = redir->dup;
1302 if (openfd != redir->fd) {
1303 if (squirrel && redir->fd < 3) {
1304 squirrel[redir->fd] = dup(redir->fd);
1309 dup2(openfd, redir->fd);
1310 if (redir->dup == -1)
1318 static void restore_redirects(int squirrel[])
1321 for (i = 0; i < 3; i++) {
1324 /* We simply die on error */
1331 /* XXX no exit() here. If you don't exec, use _exit instead.
1332 * The at_exit handlers apparently confuse the calling process,
1333 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
1334 static void pseudo_exec_argv(char **argv)
1338 const struct built_in_command *x;
1340 for (i = 0; is_assignment(argv[i]); i++) {
1341 debug_printf_exec("pid %d environment modification: %s\n",
1343 // FIXME: vfork case??
1344 p = expand_string_to_string(argv[i]);
1348 /* If a variable is assigned in a forest, and nobody listens,
1349 * was it ever really set?
1351 if (argv[0] == NULL) {
1352 _exit(EXIT_SUCCESS);
1355 argv = expand_strvec_to_strvec(argv);
1358 * Check if the command matches any of the builtins.
1359 * Depending on context, this might be redundant. But it's
1360 * easier to waste a few CPU cycles than it is to figure out
1361 * if this is one of those cases.
1363 for (x = bltins; x->cmd; x++) {
1364 if (strcmp(argv[0], x->cmd) == 0) {
1365 debug_printf_exec("running builtin '%s'\n", argv[0]);
1366 rcode = x->function(argv);
1372 /* Check if the command matches any busybox applets */
1373 #if ENABLE_FEATURE_SH_STANDALONE
1374 if (strchr(argv[0], '/') == NULL) {
1375 const struct bb_applet *a = find_applet_by_name(argv[0]);
1379 debug_printf_exec("running applet '%s'\n", argv[0]);
1380 // is it ok that run_current_applet_and_exit() does exit(), not _exit()?
1381 run_current_applet_and_exit(argv);
1383 /* re-exec ourselves with the new arguments */
1384 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
1385 execvp(bb_busybox_exec_path, argv);
1386 /* If they called chroot or otherwise made the binary no longer
1387 * executable, fall through */
1392 debug_printf_exec("execing '%s'\n", argv[0]);
1393 execvp(argv[0], argv);
1394 bb_perror_msg("cannot exec '%s'", argv[0]);
1398 static void pseudo_exec(struct child_prog *child)
1400 // FIXME: buggy wrt NOMMU! Must not modify any global data
1401 // until it does exec/_exit, but currently it does.
1405 pseudo_exec_argv(child->argv);
1409 // FIXME: do not modify globals! Think vfork!
1410 #if ENABLE_HUSH_INTERACTIVE
1411 debug_printf_exec("pseudo_exec: setting interactive_fd=0\n");
1412 interactive_fd = 0; /* crucial!!!! */
1414 debug_printf_exec("pseudo_exec: run_list_real\n");
1415 rcode = run_list_real(child->group);
1416 /* OK to leak memory by not calling free_pipe_list,
1417 * since this process is about to exit */
1421 /* Can happen. See what bash does with ">foo" by itself. */
1422 debug_printf("trying to pseudo_exec null command\n");
1423 _exit(EXIT_SUCCESS);
1427 static const char *get_cmdtext(struct pipe *pi)
1433 /* This is subtle. ->cmdtext is created only on first backgrounding.
1434 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
1435 * On subsequent bg argv is trashed, but we won't use it */
1438 argv = pi->progs[0].argv;
1439 if (!argv || !argv[0])
1440 return (pi->cmdtext = xzalloc(1));
1443 do len += strlen(*argv) + 1; while (*++argv);
1444 pi->cmdtext = p = xmalloc(len);
1445 argv = pi->progs[0].argv;
1447 len = strlen(*argv);
1448 memcpy(p, *argv, len);
1456 static void insert_bg_job(struct pipe *pi)
1458 struct pipe *thejob;
1461 /* Linear search for the ID of the job to use */
1463 for (thejob = job_list; thejob; thejob = thejob->next)
1464 if (thejob->jobid >= pi->jobid)
1465 pi->jobid = thejob->jobid + 1;
1467 /* Add thejob to the list of running jobs */
1469 thejob = job_list = xmalloc(sizeof(*thejob));
1471 for (thejob = job_list; thejob->next; thejob = thejob->next)
1473 thejob->next = xmalloc(sizeof(*thejob));
1474 thejob = thejob->next;
1477 /* Physically copy the struct job */
1478 memcpy(thejob, pi, sizeof(struct pipe));
1479 thejob->progs = xzalloc(sizeof(pi->progs[0]) * pi->num_progs);
1480 /* We cannot copy entire pi->progs[] vector! Double free()s will happen */
1481 for (i = 0; i < pi->num_progs; i++) {
1482 // TODO: do we really need to have so many fields which are just dead weight
1483 // at execution stage?
1484 thejob->progs[i].pid = pi->progs[i].pid;
1485 /* all other fields are not used and stay zero */
1487 thejob->next = NULL;
1488 thejob->cmdtext = xstrdup(get_cmdtext(pi));
1490 /* We don't wait for background thejobs to return -- append it
1491 to the list of backgrounded thejobs and leave it alone */
1492 printf("[%d] %d %s\n", thejob->jobid, thejob->progs[0].pid, thejob->cmdtext);
1493 last_bg_pid = thejob->progs[0].pid;
1494 last_jobid = thejob->jobid;
1497 static void remove_bg_job(struct pipe *pi)
1499 struct pipe *prev_pipe;
1501 if (pi == job_list) {
1502 job_list = pi->next;
1504 prev_pipe = job_list;
1505 while (prev_pipe->next != pi)
1506 prev_pipe = prev_pipe->next;
1507 prev_pipe->next = pi->next;
1510 last_jobid = job_list->jobid;
1515 /* remove a backgrounded job */
1516 static void delete_finished_bg_job(struct pipe *pi)
1519 pi->stopped_progs = 0;
1525 /* Checks to see if any processes have exited -- if they
1526 have, figure out why and see if a job has completed */
1527 static int checkjobs(struct pipe* fg_pipe)
1538 attributes = WUNTRACED;
1539 if (fg_pipe == NULL) {
1540 attributes |= WNOHANG;
1543 /* Do we do this right?
1544 * bash-3.00# sleep 20 | false
1546 * [3]+ Stopped sleep 20 | false
1547 * bash-3.00# echo $?
1548 * 1 <========== bg pipe is not fully done, but exitcode is already known!
1551 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
1552 //are stopped. Testcase: "cat | cat" in a script (not on command line)
1553 // + killall -STOP cat
1556 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
1557 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
1559 #ifdef DEBUG_SHELL_JOBS
1560 if (WIFSTOPPED(status))
1561 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
1562 childpid, WSTOPSIG(status), WEXITSTATUS(status));
1563 if (WIFSIGNALED(status))
1564 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
1565 childpid, WTERMSIG(status), WEXITSTATUS(status));
1566 if (WIFEXITED(status))
1567 debug_printf_jobs("pid %d exited, exitcode %d\n",
1568 childpid, WEXITSTATUS(status));
1570 /* Were we asked to wait for fg pipe? */
1573 for (i = 0; i < fg_pipe->num_progs; i++) {
1574 debug_printf_jobs("check pid %d\n", fg_pipe->progs[i].pid);
1575 if (fg_pipe->progs[i].pid == childpid) {
1576 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
1578 fg_pipe->progs[i].pid = 0;
1579 fg_pipe->running_progs--;
1580 if (i == fg_pipe->num_progs-1)
1581 /* last process gives overall exitstatus */
1582 rcode = WEXITSTATUS(status);
1584 fg_pipe->progs[i].is_stopped = 1;
1585 fg_pipe->stopped_progs++;
1587 debug_printf_jobs("fg_pipe: running_progs %d stopped_progs %d\n",
1588 fg_pipe->running_progs, fg_pipe->stopped_progs);
1589 if (fg_pipe->running_progs - fg_pipe->stopped_progs <= 0) {
1590 /* All processes in fg pipe have exited/stopped */
1592 if (fg_pipe->running_progs)
1593 insert_bg_job(fg_pipe);
1597 /* There are still running processes in the fg pipe */
1601 /* fall through to searching process in bg pipes */
1605 /* We asked to wait for bg or orphaned children */
1606 /* No need to remember exitcode in this case */
1607 for (pi = job_list; pi; pi = pi->next) {
1609 while (prognum < pi->num_progs) {
1610 if (pi->progs[prognum].pid == childpid)
1611 goto found_pi_and_prognum;
1617 /* Happens when shell is used as init process (init=/bin/sh) */
1618 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
1622 found_pi_and_prognum:
1625 pi->progs[prognum].pid = 0;
1626 pi->running_progs--;
1627 if (!pi->running_progs) {
1628 printf(JOB_STATUS_FORMAT, pi->jobid,
1629 "Done", pi->cmdtext);
1630 delete_finished_bg_job(pi);
1634 pi->stopped_progs++;
1635 pi->progs[prognum].is_stopped = 1;
1640 /* wait found no children or failed */
1642 if (childpid && errno != ECHILD)
1643 bb_perror_msg("waitpid");
1648 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1651 int rcode = checkjobs(fg_pipe);
1652 /* Job finished, move the shell to the foreground */
1653 p = getpgid(0); /* pgid of our process */
1654 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
1655 if (tcsetpgrp(interactive_fd, p) && errno != ENOTTY)
1656 bb_perror_msg("tcsetpgrp-4a");
1661 /* run_pipe_real() starts all the jobs, but doesn't wait for anything
1662 * to finish. See checkjobs().
1664 * return code is normally -1, when the caller has to wait for children
1665 * to finish to determine the exit status of the pipe. If the pipe
1666 * is a simple builtin command, however, the action is done by the
1667 * time run_pipe_real returns, and the exit code is provided as the
1670 * The input of the pipe is always stdin, the output is always
1671 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1672 * because it tries to avoid running the command substitution in
1673 * subshell, when that is in fact necessary. The subshell process
1674 * now has its stdout directed to the input of the appropriate pipe,
1675 * so this routine is noticeably simpler.
1677 * Returns -1 only if started some children. IOW: we have to
1678 * mask out retvals of builtins etc with 0xff!
1680 static int run_pipe_real(struct pipe *pi)
1683 int nextin, nextout;
1684 int pipefds[2]; /* pipefds[0] is for reading */
1685 struct child_prog *child;
1686 const struct built_in_command *x;
1688 /* it is not always needed, but we aim to smaller code */
1689 int squirrel[] = { -1, -1, -1 };
1691 const int single_fg = (pi->num_progs == 1 && pi->followup != PIPE_BG);
1693 debug_printf_exec("run_pipe_real start: single_fg=%d\n", single_fg);
1699 pi->running_progs = 1;
1700 pi->stopped_progs = 0;
1702 /* Check if this is a simple builtin (not part of a pipe).
1703 * Builtins within pipes have to fork anyway, and are handled in
1704 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1706 child = &(pi->progs[0]);
1707 if (single_fg && child->group && child->subshell == 0) {
1708 debug_printf("non-subshell grouping\n");
1709 setup_redirects(child, squirrel);
1710 debug_printf_exec(": run_list_real\n");
1711 rcode = run_list_real(child->group);
1712 restore_redirects(squirrel);
1713 debug_printf_exec("run_pipe_real return %d\n", rcode);
1714 return rcode; // do we need to add '... & 0xff' ?
1717 if (single_fg && child->argv != NULL) {
1718 char **argv_expanded;
1719 char **argv = child->argv;
1721 for (i = 0; is_assignment(argv[i]); i++)
1723 if (i != 0 && argv[i] == NULL) {
1724 /* assignments, but no command: set the local environment */
1725 for (i = 0; argv[i] != NULL; i++) {
1726 debug_printf("local environment set: %s\n", argv[i]);
1727 p = expand_string_to_string(argv[i]);
1728 set_local_var(p, 0);
1730 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1732 for (i = 0; is_assignment(argv[i]); i++) {
1733 p = expand_string_to_string(argv[i]);
1737 for (x = bltins; x->cmd; x++) {
1738 if (strcmp(argv[i], x->cmd) == 0) {
1739 if (x->function == builtin_exec && argv[i+1] == NULL) {
1740 debug_printf("magic exec\n");
1741 setup_redirects(child, NULL);
1742 return EXIT_SUCCESS;
1744 debug_printf("builtin inline %s\n", argv[0]);
1745 /* XXX setup_redirects acts on file descriptors, not FILEs.
1746 * This is perfect for work that comes after exec().
1747 * Is it really safe for inline use? Experimentally,
1748 * things seem to work with glibc. */
1749 setup_redirects(child, squirrel);
1750 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv[i+1]);
1751 //sp: if (child->sp) /* btw we can do it unconditionally... */
1752 argv_expanded = expand_strvec_to_strvec(argv + i);
1753 rcode = x->function(argv_expanded) & 0xff;
1754 free(argv_expanded);
1755 restore_redirects(squirrel);
1756 debug_printf_exec("run_pipe_real return %d\n", rcode);
1760 #if ENABLE_FEATURE_SH_STANDALONE
1762 const struct bb_applet *a = find_applet_by_name(argv[i]);
1763 if (a && a->nofork) {
1764 setup_redirects(child, squirrel);
1765 save_nofork_data(&nofork_save);
1766 argv_expanded = argv + i;
1767 //sp: if (child->sp)
1768 argv_expanded = expand_strvec_to_strvec(argv + i);
1769 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
1770 rcode = run_nofork_applet_prime(&nofork_save, a, argv_expanded) & 0xff;
1771 free(argv_expanded);
1772 restore_redirects(squirrel);
1773 debug_printf_exec("run_pipe_real return %d\n", rcode);
1780 /* Going to fork a child per each pipe member */
1781 pi->running_progs = 0;
1783 /* Disable job control signals for shell (parent) and
1784 * for initial child code after fork */
1785 set_jobctrl_sighandler(SIG_IGN);
1787 for (i = 0; i < pi->num_progs; i++) {
1788 child = &(pi->progs[i]);
1790 debug_printf_exec(": pipe member '%s' '%s'...\n", child->argv[0], child->argv[1]);
1792 debug_printf_exec(": pipe member with no argv\n");
1794 /* pipes are inserted between pairs of commands */
1795 if ((i + 1) < pi->num_progs) {
1797 nextout = pipefds[1];
1803 /* XXX test for failed fork()? */
1805 child->pid = fork();
1807 child->pid = vfork();
1809 if (!child->pid) { /* child */
1810 /* Every child adds itself to new process group
1811 * with pgid == pid of first child in pipe */
1813 if (run_list_level == 1 && interactive_fd) {
1814 /* Don't do pgrp restore anymore on fatal signals */
1815 set_fatal_sighandler(SIG_DFL);
1816 if (pi->pgrp < 0) /* true for 1st process only */
1817 pi->pgrp = getpid();
1818 if (setpgid(0, pi->pgrp) == 0 && pi->followup != PIPE_BG) {
1819 /* We do it in *every* child, not just first,
1821 tcsetpgrp(interactive_fd, pi->pgrp);
1825 /* in non-interactive case fatal sigs are already SIG_DFL */
1835 if (pipefds[0] != -1) {
1836 close(pipefds[0]); /* opposite end of our output pipe */
1838 /* Like bash, explicit redirects override pipes,
1839 * and the pipe fd is available for dup'ing. */
1840 setup_redirects(child, NULL);
1842 /* Restore default handlers just prior to exec */
1843 set_jobctrl_sighandler(SIG_DFL);
1844 set_misc_sighandler(SIG_DFL);
1845 signal(SIGCHLD, SIG_DFL);
1849 pi->running_progs++;
1852 /* Second and next children need to know pid of first one */
1854 pi->pgrp = child->pid;
1861 /* If there isn't another process, nextin is garbage
1862 but it doesn't matter */
1863 nextin = pipefds[0];
1865 debug_printf_exec("run_pipe_real return -1\n");
1869 #ifndef debug_print_tree
1870 static void debug_print_tree(struct pipe *pi, int lvl)
1872 static const char *PIPE[] = {
1878 static const char *RES[] = {
1879 [RES_NONE ] = "NONE" ,
1882 [RES_THEN ] = "THEN" ,
1883 [RES_ELIF ] = "ELIF" ,
1884 [RES_ELSE ] = "ELSE" ,
1887 #if ENABLE_HUSH_LOOPS
1888 [RES_FOR ] = "FOR" ,
1889 [RES_WHILE] = "WHILE",
1890 [RES_UNTIL] = "UNTIL",
1892 [RES_DONE ] = "DONE" ,
1895 [RES_XXXX ] = "XXXX" ,
1896 [RES_SNTX ] = "SNTX" ,
1903 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
1904 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
1906 while (prn < pi->num_progs) {
1907 struct child_prog *child = &pi->progs[prn];
1908 char **argv = child->argv;
1910 fprintf(stderr, "%*s prog %d", lvl*2, "", prn);
1912 fprintf(stderr, " group %s: (argv=%p)\n",
1913 (child->subshell ? "()" : "{}"),
1915 debug_print_tree(child->group, lvl+1);
1919 if (argv) while (*argv) {
1920 fprintf(stderr, " '%s'", *argv);
1923 fprintf(stderr, "\n");
1932 /* NB: called by pseudo_exec, and therefore must not modify any
1933 * global data until exec/_exit (we can be a child after vfork!) */
1934 static int run_list_real(struct pipe *pi)
1937 #if ENABLE_HUSH_LOOPS
1938 char *for_varname = NULL;
1939 char **for_lcur = NULL;
1940 char **for_list = NULL;
1945 int rcode = 0; /* probably for gcc only */
1946 int flag_restore = 0;
1948 int if_code = 0, next_if_code = 0; /* need double-buffer to handle elif */
1950 enum { if_code = 0, next_if_code = 0 };
1952 reserved_style rword;
1953 reserved_style skip_more_for_this_rword = RES_XXXX;
1955 debug_printf_exec("run_list_real start lvl %d\n", run_list_level + 1);
1957 #if ENABLE_HUSH_LOOPS
1958 /* check syntax for "for" */
1959 for (rpipe = pi; rpipe; rpipe = rpipe->next) {
1960 if ((rpipe->res_word == RES_IN || rpipe->res_word == RES_FOR)
1961 && (rpipe->next == NULL)
1963 syntax("malformed for"); /* no IN or no commands after IN */
1964 debug_printf_exec("run_list_real lvl %d return 1\n", run_list_level);
1967 if ((rpipe->res_word == RES_IN && rpipe->next->res_word == RES_IN && rpipe->next->progs[0].argv != NULL)
1968 || (rpipe->res_word == RES_FOR && rpipe->next->res_word != RES_IN)
1970 /* TODO: what is tested in the first condition? */
1971 syntax("malformed for"); /* 2nd condition: not followed by IN */
1972 debug_printf_exec("run_list_real lvl %d return 1\n", run_list_level);
1981 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
1982 * We are saving state before entering outermost list ("while...done")
1983 * so that ctrl-Z will correctly background _entire_ outermost list,
1984 * not just a part of it (like "sleep 1 | exit 2") */
1985 if (++run_list_level == 1 && interactive_fd) {
1986 if (sigsetjmp(toplevel_jb, 1)) {
1987 /* ctrl-Z forked and we are parent; or ctrl-C.
1988 * Sighandler has longjmped us here */
1989 signal(SIGINT, SIG_IGN);
1990 signal(SIGTSTP, SIG_IGN);
1991 /* Restore level (we can be coming from deep inside
1994 #if ENABLE_FEATURE_SH_STANDALONE
1995 if (nofork_save.saved) { /* if save area is valid */
1996 debug_printf_jobs("exiting nofork early\n");
1997 restore_nofork_data(&nofork_save);
2001 /* ctrl-Z has forked and stored pid of the child in pi->pid.
2002 * Remember this child as background job */
2005 /* ctrl-C. We just stop doing whatever we were doing */
2011 /* ctrl-Z handler will store pid etc in pi */
2014 #if ENABLE_FEATURE_SH_STANDALONE
2015 nofork_save.saved = 0; /* in case we will run a nofork later */
2017 signal_SA_RESTART(SIGTSTP, handler_ctrl_z);
2018 signal(SIGINT, handler_ctrl_c);
2022 for (; pi; pi = flag_restore ? rpipe : pi->next) {
2023 rword = pi->res_word;
2024 #if ENABLE_HUSH_LOOPS
2025 if (rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR) {
2033 debug_printf_exec(": rword=%d if_code=%d next_if_code=%d skip_more=%d\n",
2034 rword, if_code, next_if_code, skip_more_for_this_rword);
2035 if (rword == skip_more_for_this_rword && flag_skip) {
2036 if (pi->followup == PIPE_SEQ)
2041 skip_more_for_this_rword = RES_XXXX;
2043 if (rword == RES_THEN || rword == RES_ELSE)
2044 if_code = next_if_code;
2045 if (rword == RES_THEN && if_code)
2047 if (rword == RES_ELSE && !if_code)
2049 if (rword == RES_ELIF && !if_code)
2052 #if ENABLE_HUSH_LOOPS
2053 if (rword == RES_FOR && pi->num_progs) {
2055 /* if no variable values after "in" we skip "for" */
2056 if (!pi->next->progs->argv)
2058 /* create list of variable values */
2059 for_list = expand_strvec_to_strvec(pi->next->progs->argv);
2060 for_lcur = for_list;
2061 for_varname = pi->progs->argv[0];
2062 pi->progs->argv[0] = NULL;
2065 free(pi->progs->argv[0]);
2070 pi->progs->argv[0] = for_varname;
2071 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
2074 /* insert next value from for_lcur */
2075 /* vda: does it need escaping? */
2076 pi->progs->argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
2077 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
2079 if (rword == RES_IN)
2081 if (rword == RES_DO) {
2085 if (rword == RES_DONE) {
2093 if (pi->num_progs == 0)
2095 save_num_progs = pi->num_progs; /* save number of programs */
2096 debug_printf_exec(": run_pipe_real with %d members\n", pi->num_progs);
2097 rcode = run_pipe_real(pi);
2099 /* We only ran a builtin: rcode was set by the return value
2100 * of run_pipe_real(), and we don't need to wait for anything. */
2101 } else if (pi->followup == PIPE_BG) {
2102 /* What does bash do with attempts to background builtins? */
2103 /* Even bash 3.2 doesn't do that well with nested bg:
2104 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
2105 * I'm NOT treating inner &'s as jobs */
2107 if (run_list_level == 1)
2110 rcode = EXIT_SUCCESS;
2113 /* Paranoia, just "interactive_fd" should be enough? */
2114 if (run_list_level == 1 && interactive_fd) {
2115 /* waits for completion, then fg's main shell */
2116 rcode = checkjobs_and_fg_shell(pi);
2120 /* this one just waits for completion */
2121 rcode = checkjobs(pi);
2123 debug_printf_exec(": checkjobs returned %d\n", rcode);
2125 debug_printf_exec(": setting last_return_code=%d\n", rcode);
2126 last_return_code = rcode;
2127 pi->num_progs = save_num_progs; /* restore number of programs */
2129 if (rword == RES_IF || rword == RES_ELIF)
2130 next_if_code = rcode; /* can be overwritten a number of times */
2132 #if ENABLE_HUSH_LOOPS
2133 if (rword == RES_WHILE)
2134 flag_rep = !last_return_code;
2135 if (rword == RES_UNTIL)
2136 flag_rep = last_return_code;
2138 if ((rcode == EXIT_SUCCESS && pi->followup == PIPE_OR)
2139 || (rcode != EXIT_SUCCESS && pi->followup == PIPE_AND)
2141 skip_more_for_this_rword = rword;
2148 /* ctrl-Z forked somewhere in the past, we are the child,
2149 * and now we completed running the list. Exit. */
2153 if (!--run_list_level && interactive_fd) {
2154 signal(SIGTSTP, SIG_IGN);
2155 signal(SIGINT, SIG_IGN);
2158 debug_printf_exec("run_list_real lvl %d return %d\n", run_list_level + 1, rcode);
2162 /* return code is the exit status of the pipe */
2163 static int free_pipe(struct pipe *pi, int indent)
2166 struct child_prog *child;
2167 struct redir_struct *r, *rnext;
2168 int a, i, ret_code = 0;
2170 if (pi->stopped_progs > 0)
2172 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2173 for (i = 0; i < pi->num_progs; i++) {
2174 child = &pi->progs[i];
2175 debug_printf_clean("%s command %d:\n", indenter(indent), i);
2177 for (a = 0, p = child->argv; *p; a++, p++) {
2178 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
2180 globfree(&child->glob_result);
2182 } else if (child->group) {
2183 debug_printf_clean("%s begin group (subshell:%d)\n", indenter(indent), child->subshell);
2184 ret_code = free_pipe_list(child->group, indent+3);
2185 debug_printf_clean("%s end group\n", indenter(indent));
2187 debug_printf_clean("%s (nil)\n", indenter(indent));
2189 for (r = child->redirects; r; r = rnext) {
2190 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->type].descrip);
2192 /* guard against the case >$FOO, where foo is unset or blank */
2193 if (r->word.gl_pathv) {
2194 debug_printf_clean(" %s\n", *r->word.gl_pathv);
2198 debug_printf_clean("&%d\n", r->dup);
2203 child->redirects = NULL;
2205 free(pi->progs); /* children are an array, they get freed all at once */
2214 static int free_pipe_list(struct pipe *head, int indent)
2216 int rcode = 0; /* if list has no members */
2217 struct pipe *pi, *next;
2219 for (pi = head; pi; pi = next) {
2220 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
2221 rcode = free_pipe(pi, indent);
2222 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
2224 /*pi->next = NULL;*/
2230 /* Select which version we will use */
2231 static int run_list(struct pipe *pi)
2234 debug_printf_exec("run_list entered\n");
2235 if (fake_mode == 0) {
2236 debug_printf_exec(": run_list_real with %d members\n", pi->num_progs);
2237 rcode = run_list_real(pi);
2239 /* free_pipe_list has the side effect of clearing memory.
2240 * In the long run that function can be merged with run_list_real,
2241 * but doing that now would hobble the debugging effort. */
2242 free_pipe_list(pi, 0);
2243 debug_printf_exec("run_list return %d\n", rcode);
2247 /* The API for glob is arguably broken. This routine pushes a non-matching
2248 * string into the output structure, removing non-backslashed backslashes.
2249 * If someone can prove me wrong, by performing this function within the
2250 * original glob(3) api, feel free to rewrite this routine into oblivion.
2251 * Return code (0 vs. GLOB_NOSPACE) matches glob(3).
2252 * XXX broken if the last character is '\\', check that before calling.
2254 static int globhack(const char *src, int flags, glob_t *pglob)
2259 for (cnt = 1, s = src; s && *s; s++) {
2260 if (*s == '\\') s++;
2263 dest = xmalloc(cnt);
2264 if (!(flags & GLOB_APPEND)) {
2265 pglob->gl_pathv = NULL;
2266 pglob->gl_pathc = 0;
2270 pathc = ++pglob->gl_pathc;
2271 pglob->gl_pathv = xrealloc(pglob->gl_pathv, (pathc+1) * sizeof(*pglob->gl_pathv));
2272 pglob->gl_pathv[pathc-1] = dest;
2273 pglob->gl_pathv[pathc] = NULL;
2274 for (s = src; s && *s; s++, dest++) {
2275 if (*s == '\\') s++;
2282 /* XXX broken if the last character is '\\', check that before calling */
2283 static int glob_needed(const char *s)
2286 if (*s == '\\') s++;
2287 if (strchr("*[?", *s)) return 1;
2292 static int xglob(o_string *dest, int flags, glob_t *pglob)
2296 /* short-circuit for null word */
2297 /* we can code this better when the debug_printf's are gone */
2298 if (dest->length == 0) {
2299 if (dest->nonnull) {
2300 /* bash man page calls this an "explicit" null */
2301 gr = globhack(dest->data, flags, pglob);
2302 debug_printf("globhack returned %d\n", gr);
2306 } else if (glob_needed(dest->data)) {
2307 gr = glob(dest->data, flags, NULL, pglob);
2308 debug_printf("glob returned %d\n", gr);
2309 if (gr == GLOB_NOMATCH) {
2310 /* quote removal, or more accurately, backslash removal */
2311 gr = globhack(dest->data, flags, pglob);
2312 debug_printf("globhack returned %d\n", gr);
2315 gr = globhack(dest->data, flags, pglob);
2316 debug_printf("globhack returned %d\n", gr);
2318 if (gr == GLOB_NOSPACE)
2319 bb_error_msg_and_die("out of memory during glob");
2320 if (gr != 0) { /* GLOB_ABORTED ? */
2321 bb_error_msg("glob(3) error %d", gr);
2323 /* globprint(glob_target); */
2327 /* expand_strvec_to_strvec() takes a list of strings, expands
2328 * all variable references within and returns a pointer to
2329 * a list of expanded strings, possibly with larger number
2330 * of strings. (Think VAR="a b"; echo $VAR).
2331 * This new list is allocated as a single malloc block.
2332 * NULL-terminated list of char* pointers is at the beginning of it,
2333 * followed by strings themself.
2334 * Caller can deallocate entire list by single free(list). */
2337 * count_XXX estimates size of the block we need. It's okay
2338 * to over-estimate sizes a bit, if it makes code simpler */
2339 static int count_ifs(const char *str)
2342 debug_printf_expand("count_ifs('%s') ifs='%s'", str, ifs);
2344 str += strcspn(str, ifs);
2346 str++; /* str += strspn(str, ifs); */
2347 cnt++; /* cnt += strspn(str, ifs); - but this code is larger */
2349 debug_printf_expand(" return %d\n", cnt);
2353 static void count_var_expansion_space(int *countp, int *lenp, char *arg)
2358 int count = *countp;
2362 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2365 p = strchr(p, SPECIAL_VAR_SYMBOL);
2368 switch (first_ch & 0x7f) {
2369 /* high bit in 1st_ch indicates that var is double-quoted */
2371 case '!': /* bg pid */
2372 case '?': /* exitcode */
2373 case '#': /* argc */
2374 len += sizeof(int)*3 + 1; /* enough for int */
2378 for (i = 1; i < global_argc; i++) {
2379 len += strlen(global_argv[i]) + 1;
2381 if (!(first_ch & 0x80))
2382 count += count_ifs(global_argv[i]);
2387 arg[0] = first_ch & 0x7f;
2388 if (isdigit(arg[0])) {
2391 if (i < global_argc)
2392 val = global_argv[i];
2394 val = lookup_param(arg);
2396 *p = SPECIAL_VAR_SYMBOL;
2399 len += strlen(val) + 1;
2400 if (!(first_ch & 0x80))
2401 count += count_ifs(val);
2407 len += strlen(arg) + 1;
2413 /* Store given string, finalizing the word and starting new one whenever
2414 * we encounter ifs char(s). This is used for expanding variable values.
2415 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2416 static int expand_on_ifs(char **list, int n, char **posp, const char *str)
2420 int word_len = strcspn(str, ifs);
2422 memcpy(pos, str, word_len); /* store non-ifs chars */
2426 if (!*str) /* EOL - do not finalize word */
2429 if (n) debug_printf_expand("expand_on_ifs finalized list[%d]=%p '%s' "
2430 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2431 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2433 str += strspn(str, ifs); /* skip ifs chars */
2439 /* Expand all variable references in given string, adding words to list[]
2440 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2441 * to be filled). This routine is extremely tricky: has to deal with
2442 * variables/parameters with whitespace, $* and $@, and constructs like
2443 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2444 /* NB: another bug is that we cannot detect empty strings yet:
2445 * "" or $empty"" expands to zero words, has to expand to empty word */
2446 static int expand_vars_to_list(char **list, int n, char **posp, char *arg, char or_mask)
2448 /* or_mask is either 0 (normal case) or 0x80
2449 * (expansion of right-hand side of assignment == 1-element expand) */
2451 char first_ch, ored_ch;
2459 if (n) debug_printf_expand("expand_vars_to_list finalized list[%d]=%p '%s' "
2460 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2461 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2464 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2465 memcpy(pos, arg, p - arg);
2468 p = strchr(p, SPECIAL_VAR_SYMBOL);
2470 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2471 ored_ch |= first_ch;
2473 switch (first_ch & 0x7f) {
2474 /* Highest bit in first_ch indicates that var is double-quoted */
2476 /* FIXME: (echo $$) should still print pid of main shell */
2477 val = utoa(getpid());
2479 case '!': /* bg pid */
2480 val = last_bg_pid ? utoa(last_bg_pid) : (char*)"";
2482 case '?': /* exitcode */
2483 val = utoa(last_return_code);
2485 case '#': /* argc */
2486 val = utoa(global_argc ? global_argc-1 : 0);
2491 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2492 while (i < global_argc) {
2493 n = expand_on_ifs(list, n, &pos, global_argv[i]);
2494 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, global_argc-1);
2495 if (global_argv[i++][0] && i < global_argc) {
2496 /* this argv[] is not empty and not last:
2497 * put terminating NUL, start new word */
2499 if (n) debug_printf_expand("expand_vars_to_list 2 finalized list[%d]=%p '%s' "
2500 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2501 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2506 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2507 * and in this case should theat it like '$*' */
2508 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2510 strcpy(pos, global_argv[i]);
2511 pos += strlen(global_argv[i]);
2512 if (++i >= global_argc)
2515 if (n) debug_printf_expand("expand_vars_to_list 3 finalized list[%d]=%p '%s' "
2516 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2517 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2520 } else { /* quoted $*: add as one word */
2522 strcpy(pos, global_argv[i]);
2523 pos += strlen(global_argv[i]);
2524 if (++i >= global_argc)
2533 arg[0] = first_ch & 0x7f;
2534 if (isdigit(arg[0])) {
2537 if (i < global_argc)
2538 val = global_argv[i];
2540 val = lookup_param(arg);
2542 *p = SPECIAL_VAR_SYMBOL;
2543 if (!(first_ch & 0x80)) { /* unquoted $VAR */
2545 n = expand_on_ifs(list, n, &pos, val);
2548 } /* else: quoted $VAR, val will be appended at pos */
2556 debug_printf_expand("expand_vars_to_list adding tail '%s' at %p\n", arg, pos);
2558 pos += strlen(arg) + 1;
2559 if (pos == list[n-1] + 1) { /* expansion is empty */
2560 if (!(ored_ch & 0x80)) { /* all vars were not quoted... */
2561 debug_printf_expand("expand_vars_to_list list[%d] empty, going back\n", n);
2571 static char **expand_variables(char **argv, char or_mask)
2576 char *pos, **v, **list;
2579 if (!*v) debug_printf_expand("count_var_expansion_space: "
2580 "argv[0]=NULL count=%d len=%d alloc_space=%d\n",
2581 count, len, sizeof(char*) * count + len);
2583 count_var_expansion_space(&count, &len, *v);
2584 debug_printf_expand("count_var_expansion_space: "
2585 "'%s' count=%d len=%d alloc_space=%d\n",
2586 *v, count, len, sizeof(char*) * count + len);
2589 len += sizeof(char*) * count; /* total to alloc */
2590 list = xmalloc(len);
2591 pos = (char*)(list + count);
2592 debug_printf_expand("list=%p, list[0] should be %p\n", list, pos);
2596 n = expand_vars_to_list(list, n, &pos, *v++, or_mask);
2598 if (n) debug_printf_expand("finalized list[%d]=%p '%s' "
2599 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2600 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2607 debug_printf_expand("list[%d]=%p '%s'\n", m, list[m], list[m]);
2610 debug_printf_expand("used_space=%d\n", pos - (char*)list);
2613 if (ENABLE_HUSH_DEBUG)
2614 if (pos - (char*)list > len)
2615 bb_error_msg_and_die("BUG in varexp");
2619 static char **expand_strvec_to_strvec(char **argv)
2621 return expand_variables(argv, 0);
2624 static char *expand_string_to_string(const char *str)
2626 char *argv[2], **list;
2628 argv[0] = (char*)str;
2630 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2631 if (ENABLE_HUSH_DEBUG)
2632 if (!list[0] || list[1])
2633 bb_error_msg_and_die("BUG in varexp2");
2634 /* actually, just move string 2*sizeof(char*) bytes back */
2635 strcpy((char*)list, list[0]);
2636 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2640 static char* expand_strvec_to_string(char **argv)
2644 list = expand_variables(argv, 0x80);
2645 /* Convert all NULs to spaces */
2649 if (ENABLE_HUSH_DEBUG)
2650 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2651 bb_error_msg_and_die("BUG in varexp3");
2652 list[n][-1] = ' '; /* TODO: or to ifs[0]? */
2656 strcpy((char*)list, list[0]);
2657 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2661 /* This is used to get/check local shell variables */
2662 static struct variable *get_local_var(const char *name)
2664 struct variable *cur;
2670 for (cur = top_var; cur; cur = cur->next) {
2671 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
2677 /* str holds "NAME=VAL" and is expected to be malloced.
2678 * We take ownership of it. */
2679 static int set_local_var(char *str, int flg_export)
2681 struct variable *cur;
2685 value = strchr(str, '=');
2686 if (!value) { /* not expected to ever happen? */
2691 name_len = value - str + 1; /* including '=' */
2692 cur = top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
2694 if (strncmp(cur->varstr, str, name_len) != 0) {
2696 /* Bail out. Note that now cur points
2697 * to last var in linked list */
2703 /* We found an existing var with this name */
2705 if (cur->flg_read_only) {
2706 bb_error_msg("%s: readonly variable", str);
2710 unsetenv(str); /* just in case */
2712 if (strcmp(cur->varstr, str) == 0) {
2717 if (cur->max_len >= strlen(str)) {
2718 /* This one is from startup env, reuse space */
2719 strcpy(cur->varstr, str);
2722 /* max_len == 0 signifies "malloced" var, which we can
2723 * (and has to) free */
2727 goto set_str_and_exp;
2730 /* Not found - create next variable struct */
2731 cur->next = xzalloc(sizeof(*cur));
2738 cur->flg_export = 1;
2739 if (cur->flg_export)
2740 return putenv(cur->varstr);
2744 static void unset_local_var(const char *name)
2746 struct variable *cur;
2747 struct variable *prev = prev; /* for gcc */
2752 name_len = strlen(name);
2755 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2756 if (cur->flg_read_only) {
2757 bb_error_msg("%s: readonly variable", name);
2760 /* prev is ok to use here because 1st variable, HUSH_VERSION,
2761 * is ro, and we cannot reach this code on the 1st pass */
2762 prev->next = cur->next;
2763 unsetenv(cur->varstr);
2774 static int is_assignment(const char *s)
2776 if (!s || !isalpha(*s))
2779 while (isalnum(*s) || *s == '_')
2784 /* the src parameter allows us to peek forward to a possible &n syntax
2785 * for file descriptor duplication, e.g., "2>&1".
2786 * Return code is 0 normally, 1 if a syntax error is detected in src.
2787 * Resource errors (in xmalloc) cause the process to exit */
2788 static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2789 struct in_str *input)
2791 struct child_prog *child = ctx->child;
2792 struct redir_struct *redir = child->redirects;
2793 struct redir_struct *last_redir = NULL;
2795 /* Create a new redir_struct and drop it onto the end of the linked list */
2798 redir = redir->next;
2800 redir = xmalloc(sizeof(struct redir_struct));
2802 redir->word.gl_pathv = NULL;
2804 last_redir->next = redir;
2806 child->redirects = redir;
2809 redir->type = style;
2810 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
2812 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2814 /* Check for a '2>&1' type redirect */
2815 redir->dup = redirect_dup_num(input);
2816 if (redir->dup == -2) return 1; /* syntax error */
2817 if (redir->dup != -1) {
2818 /* Erik had a check here that the file descriptor in question
2819 * is legit; I postpone that to "run time"
2820 * A "-" representation of "close me" shows up as a -3 here */
2821 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2823 /* We do _not_ try to open the file that src points to,
2824 * since we need to return and let src be expanded first.
2825 * Set ctx->pending_redirect, so we know what to do at the
2826 * end of the next parsed word. */
2827 ctx->pending_redirect = redir;
2832 static struct pipe *new_pipe(void)
2835 pi = xzalloc(sizeof(struct pipe));
2836 /*pi->num_progs = 0;*/
2837 /*pi->progs = NULL;*/
2838 /*pi->next = NULL;*/
2839 /*pi->followup = 0; invalid */
2841 pi->res_word = RES_NONE;
2845 static void initialize_context(struct p_context *ctx)
2848 ctx->pipe = ctx->list_head = new_pipe();
2849 ctx->pending_redirect = NULL;
2850 ctx->res_w = RES_NONE;
2851 //only ctx->parse_type is not touched... is this intentional?
2854 done_command(ctx); /* creates the memory for working child */
2857 /* normal return is 0
2858 * if a reserved word is found, and processed, return 1
2859 * should handle if, then, elif, else, fi, for, while, until, do, done.
2860 * case, function, and select are obnoxious, save those for later.
2862 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS
2863 static int reserved_word(o_string *dest, struct p_context *ctx)
2865 struct reserved_combo {
2870 /* Mostly a list of accepted follow-up reserved words.
2871 * FLAG_END means we are done with the sequence, and are ready
2872 * to turn the compound list into a command.
2873 * FLAG_START means the word must start a new compound list.
2875 static const struct reserved_combo reserved_list[] = {
2877 { "if", RES_IF, FLAG_THEN | FLAG_START },
2878 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2879 { "elif", RES_ELIF, FLAG_THEN },
2880 { "else", RES_ELSE, FLAG_FI },
2881 { "fi", RES_FI, FLAG_END },
2883 #if ENABLE_HUSH_LOOPS
2884 { "for", RES_FOR, FLAG_IN | FLAG_START },
2885 { "while", RES_WHILE, FLAG_DO | FLAG_START },
2886 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
2887 { "in", RES_IN, FLAG_DO },
2888 { "do", RES_DO, FLAG_DONE },
2889 { "done", RES_DONE, FLAG_END }
2893 const struct reserved_combo *r;
2895 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
2896 if (strcmp(dest->data, r->literal) != 0)
2898 debug_printf("found reserved word %s, code %d\n", r->literal, r->code);
2899 if (r->flag & FLAG_START) {
2900 struct p_context *new;
2901 debug_printf("push stack\n");
2902 #if ENABLE_HUSH_LOOPS
2903 if (ctx->res_w == RES_IN || ctx->res_w == RES_FOR) {
2904 syntax("malformed for"); /* example: 'for if' */
2905 ctx->res_w = RES_SNTX;
2910 new = xmalloc(sizeof(*new));
2911 *new = *ctx; /* physical copy */
2912 initialize_context(ctx);
2914 } else if (ctx->res_w == RES_NONE || !(ctx->old_flag & (1 << r->code))) {
2916 ctx->res_w = RES_SNTX;
2920 ctx->res_w = r->code;
2921 ctx->old_flag = r->flag;
2922 if (ctx->old_flag & FLAG_END) {
2923 struct p_context *old;
2924 debug_printf("pop stack\n");
2925 done_pipe(ctx, PIPE_SEQ);
2927 old->child->group = ctx->list_head;
2928 old->child->subshell = 0;
2929 *ctx = *old; /* physical copy */
2938 #define reserved_word(dest, ctx) ((int)0)
2941 /* Normal return is 0.
2942 * Syntax or xglob errors return 1. */
2943 static int done_word(o_string *dest, struct p_context *ctx)
2945 struct child_prog *child = ctx->child;
2946 glob_t *glob_target;
2949 debug_printf_parse("done_word entered: '%s' %p\n", dest->data, child);
2950 if (dest->length == 0 && !dest->nonnull) {
2951 debug_printf_parse("done_word return 0: true null, ignored\n");
2954 if (ctx->pending_redirect) {
2955 glob_target = &ctx->pending_redirect->word;
2959 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
2962 if (!child->argv && (ctx->parse_type & PARSEFLAG_SEMICOLON)) {
2963 debug_printf_parse(": checking '%s' for reserved-ness\n", dest->data);
2964 if (reserved_word(dest, ctx)) {
2965 debug_printf_parse("done_word return %d\n", (ctx->res_w == RES_SNTX));
2966 return (ctx->res_w == RES_SNTX);
2969 glob_target = &child->glob_result;
2971 flags |= GLOB_APPEND;
2973 gr = xglob(dest, flags, glob_target);
2975 debug_printf_parse("done_word return 1: xglob returned %d\n", gr);
2980 if (ctx->pending_redirect) {
2981 ctx->pending_redirect = NULL;
2982 if (glob_target->gl_pathc != 1) {
2983 bb_error_msg("ambiguous redirect");
2984 debug_printf_parse("done_word return 1: ambiguous redirect\n");
2988 child->argv = glob_target->gl_pathv;
2990 #if ENABLE_HUSH_LOOPS
2991 if (ctx->res_w == RES_FOR) {
2992 done_word(dest, ctx);
2993 done_pipe(ctx, PIPE_SEQ);
2996 debug_printf_parse("done_word return 0\n");
3000 /* The only possible error here is out of memory, in which case
3002 static int done_command(struct p_context *ctx)
3004 /* The child is really already in the pipe structure, so
3005 * advance the pipe counter and make a new, null child. */
3006 struct pipe *pi = ctx->pipe;
3007 struct child_prog *child = ctx->child;
3010 if (child->group == NULL
3011 && child->argv == NULL
3012 && child->redirects == NULL
3014 debug_printf_parse("done_command: skipping null cmd, num_progs=%d\n", pi->num_progs);
3015 return pi->num_progs;
3018 debug_printf_parse("done_command: ++num_progs=%d\n", pi->num_progs);
3020 debug_printf_parse("done_command: initializing, num_progs=%d\n", pi->num_progs);
3023 /* Only real trickiness here is that the uncommitted
3024 * child structure is not counted in pi->num_progs. */
3025 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
3026 child = &pi->progs[pi->num_progs];
3028 memset(child, 0, sizeof(*child));
3029 /*child->redirects = NULL;*/
3030 /*child->argv = NULL;*/
3031 /*child->is_stopped = 0;*/
3032 /*child->group = NULL;*/
3033 /*child->glob_result.gl_pathv = NULL;*/
3035 //sp: /*child->sp = 0;*/
3036 //pt: child->parse_type = ctx->parse_type;
3039 /* but ctx->pipe and ctx->list_head remain unchanged */
3041 return pi->num_progs; /* used only for 0/nonzero check */
3044 static int done_pipe(struct p_context *ctx, pipe_style type)
3049 debug_printf_parse("done_pipe entered, followup %d\n", type);
3050 not_null = done_command(ctx); /* implicit closure of previous command */
3051 ctx->pipe->followup = type;
3052 ctx->pipe->res_word = ctx->res_w;
3053 /* Without this check, even just <enter> on command line generates
3054 * tree of three NOPs (!). Which is harmless but annoying.
3055 * IOW: it is safe to do it unconditionally. */
3058 ctx->pipe->next = new_p;
3061 done_command(ctx); /* set up new pipe to accept commands */
3063 debug_printf_parse("done_pipe return 0\n");
3067 /* peek ahead in the in_str to find out if we have a "&n" construct,
3068 * as in "2>&1", that represents duplicating a file descriptor.
3069 * returns either -2 (syntax error), -1 (no &), or the number found.
3071 static int redirect_dup_num(struct in_str *input)
3073 int ch, d = 0, ok = 0;
3075 if (ch != '&') return -1;
3077 b_getch(input); /* get the & */
3081 return -3; /* "-" represents "close me" */
3083 while (isdigit(ch)) {
3084 d = d*10 + (ch-'0');
3091 bb_error_msg("ambiguous redirect");
3095 /* If a redirect is immediately preceded by a number, that number is
3096 * supposed to tell which file descriptor to redirect. This routine
3097 * looks for such preceding numbers. In an ideal world this routine
3098 * needs to handle all the following classes of redirects...
3099 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3100 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3101 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3102 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3103 * A -1 output from this program means no valid number was found, so the
3104 * caller should use the appropriate default for this redirection.
3106 static int redirect_opt_num(o_string *o)
3112 for (num = 0; num < o->length; num++) {
3113 if (!isdigit(*(o->data + num))) {
3117 /* reuse num (and save an int) */
3118 num = atoi(o->data);
3123 #if ENABLE_HUSH_TICK
3124 static FILE *generate_stream_from_list(struct pipe *head)
3127 int pid, channel[2];
3136 bb_perror_msg_and_die("fork");
3137 } else if (pid == 0) {
3139 if (channel[1] != 1) {
3140 dup2(channel[1], 1);
3143 /* Prevent it from trying to handle ctrl-z etc */
3147 /* Process substitution is not considered to be usual
3148 * 'command execution'.
3149 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not. */
3150 /* Not needed, we are relying on it being disabled
3151 * everywhere outside actual command execution. */
3152 /*set_jobctrl_sighandler(SIG_IGN);*/
3153 set_misc_sighandler(SIG_DFL);
3154 _exit(run_list_real(head)); /* leaks memory */
3157 pf = fdopen(channel[0], "r");
3161 /* Return code is exit status of the process that is run. */
3162 static int process_command_subs(o_string *dest, struct p_context *ctx,
3163 struct in_str *input, const char *subst_end)
3165 int retcode, ch, eol_cnt;
3166 o_string result = NULL_O_STRING;
3167 struct p_context inner;
3169 struct in_str pipe_str;
3171 initialize_context(&inner);
3173 /* recursion to generate command */
3174 retcode = parse_stream(&result, &inner, input, subst_end);
3176 return retcode; /* syntax error or EOF */
3177 done_word(&result, &inner);
3178 done_pipe(&inner, PIPE_SEQ);
3181 p = generate_stream_from_list(inner.list_head);
3182 if (p == NULL) return 1;
3183 mark_open(fileno(p));
3184 setup_file_in_str(&pipe_str, p);
3186 /* now send results of command back into original context */
3188 while ((ch = b_getch(&pipe_str)) != EOF) {
3194 b_addqchr(dest, '\n', dest->quote);
3197 b_addqchr(dest, ch, dest->quote);
3200 debug_printf("done reading from pipe, pclose()ing\n");
3201 /* This is the step that wait()s for the child. Should be pretty
3202 * safe, since we just read an EOF from its stdout. We could try
3203 * to do better, by using wait(), and keeping track of background jobs
3204 * at the same time. That would be a lot of work, and contrary
3205 * to the KISS philosophy of this program. */
3206 mark_closed(fileno(p));
3207 retcode = fclose(p);
3208 free_pipe_list(inner.list_head, 0);
3209 debug_printf("closed FILE from child, retcode=%d\n", retcode);
3214 static int parse_group(o_string *dest, struct p_context *ctx,
3215 struct in_str *input, int ch)
3218 const char *endch = NULL;
3219 struct p_context sub;
3220 struct child_prog *child = ctx->child;
3222 debug_printf_parse("parse_group entered\n");
3225 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3228 initialize_context(&sub);
3232 child->subshell = 1;
3234 rcode = parse_stream(dest, &sub, input, endch);
3236 done_word(dest, &sub); /* finish off the final word in the subcontext */
3237 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
3238 child->group = sub.list_head;
3240 debug_printf_parse("parse_group return %d\n", rcode);
3242 /* child remains "open", available for possible redirects */
3245 /* Basically useful version until someone wants to get fancier,
3246 * see the bash man page under "Parameter Expansion" */
3247 static const char *lookup_param(const char *src)
3249 struct variable *var = get_local_var(src);
3251 return strchr(var->varstr, '=') + 1;
3255 /* return code: 0 for OK, 1 for syntax error */
3256 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
3258 int ch = b_peek(input); /* first character after the $ */
3259 unsigned char quote_mask = dest->quote ? 0x80 : 0;
3261 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
3263 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3264 //sp: ctx->child->sp++;
3266 debug_printf_parse(": '%c'\n", ch);
3268 b_addchr(dest, ch | quote_mask);
3271 if (!isalnum(ch) && ch != '_')
3274 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3275 } else if (isdigit(ch)) {
3277 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3278 //sp: ctx->child->sp++;
3279 debug_printf_parse(": '%c'\n", ch);
3281 b_addchr(dest, ch | quote_mask);
3282 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3283 } else switch (ch) {
3285 case '!': /* last bg pid */
3286 case '?': /* last exit code */
3287 case '#': /* number of args */
3288 case '*': /* args */
3289 case '@': /* args */
3290 goto make_one_char_var;
3292 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3293 //sp: ctx->child->sp++;
3295 /* XXX maybe someone will try to escape the '}' */
3297 ch = b_getch(input);
3300 if (!isalnum(ch) && ch != '_') {
3301 syntax("unterminated ${name}");
3302 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3305 debug_printf_parse(": '%c'\n", ch);
3306 b_addchr(dest, ch | quote_mask);
3309 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3311 #if ENABLE_HUSH_TICK
3314 process_command_subs(dest, ctx, input, ")");
3319 /* still unhandled, but should be eventually */
3320 bb_error_msg("unhandled syntax: $%c", ch);
3324 b_addqchr(dest, '$', dest->quote);
3326 debug_printf_parse("handle_dollar return 0\n");
3330 /* return code is 0 for normal exit, 1 for syntax error */
3331 static int parse_stream(o_string *dest, struct p_context *ctx,
3332 struct in_str *input, const char *end_trigger)
3336 redir_type redir_style;
3339 /* Only double-quote state is handled in the state variable dest->quote.
3340 * A single-quote triggers a bypass of the main loop until its mate is
3341 * found. When recursing, quote state is passed in via dest->quote. */
3343 debug_printf_parse("parse_stream entered, end_trigger='%s'\n", end_trigger);
3348 ch = b_getch(input);
3352 next = b_peek(input);
3354 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
3355 ch, ch, m, dest->quote);
3356 if (m == CHAR_ORDINARY
3357 || (m != CHAR_SPECIAL && dest->quote)
3360 syntax("unterminated \"");
3361 debug_printf_parse("parse_stream return 1: unterminated \"\n");
3364 b_addqchr(dest, ch, dest->quote);
3367 if (m == CHAR_IFS) {
3368 if (done_word(dest, ctx)) {
3369 debug_printf_parse("parse_stream return 1: done_word!=0\n");
3374 /* If we aren't performing a substitution, treat
3375 * a newline as a command separator.
3376 * [why we don't handle it exactly like ';'? --vda] */
3377 if (end_trigger && ch == '\n') {
3378 done_pipe(ctx, PIPE_SEQ);
3381 if ((end_trigger && strchr(end_trigger, ch))
3382 && !dest->quote && ctx->res_w == RES_NONE
3384 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
3391 if (dest->length == 0 && !dest->quote) {
3394 if (ch == EOF || ch == '\n')
3399 b_addqchr(dest, ch, dest->quote);
3405 debug_printf_parse("parse_stream return 1: \\<eof>\n");
3408 b_addqchr(dest, '\\', dest->quote);
3409 b_addqchr(dest, b_getch(input), dest->quote);
3412 if (handle_dollar(dest, ctx, input) != 0) {
3413 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3420 ch = b_getch(input);
3421 if (ch == EOF || ch == '\'')
3426 syntax("unterminated '");
3427 debug_printf_parse("parse_stream return 1: unterminated '\n");
3433 dest->quote = !dest->quote;
3435 #if ENABLE_HUSH_TICK
3437 process_command_subs(dest, ctx, input, "`");
3441 redir_fd = redirect_opt_num(dest);
3442 done_word(dest, ctx);
3443 redir_style = REDIRECT_OVERWRITE;
3445 redir_style = REDIRECT_APPEND;
3449 else if (next == '(') {
3450 syntax(">(process) not supported");
3451 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
3455 setup_redirect(ctx, redir_fd, redir_style, input);
3458 redir_fd = redirect_opt_num(dest);
3459 done_word(dest, ctx);
3460 redir_style = REDIRECT_INPUT;
3462 redir_style = REDIRECT_HEREIS;
3464 } else if (next == '>') {
3465 redir_style = REDIRECT_IO;
3469 else if (next == '(') {
3470 syntax("<(process) not supported");
3471 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
3475 setup_redirect(ctx, redir_fd, redir_style, input);
3478 done_word(dest, ctx);
3479 done_pipe(ctx, PIPE_SEQ);
3482 done_word(dest, ctx);
3485 done_pipe(ctx, PIPE_AND);
3487 done_pipe(ctx, PIPE_BG);
3491 done_word(dest, ctx);
3494 done_pipe(ctx, PIPE_OR);
3496 /* we could pick up a file descriptor choice here
3497 * with redirect_opt_num(), but bash doesn't do it.
3498 * "echo foo 2| cat" yields "foo 2". */
3504 if (parse_group(dest, ctx, input, ch) != 0) {
3505 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
3511 syntax("unexpected }"); /* Proper use of this character is caught by end_trigger */
3512 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
3515 if (ENABLE_HUSH_DEBUG)
3516 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
3519 /* Complain if quote? No, maybe we just finished a command substitution
3520 * that was quoted. Example:
3521 * $ echo "`cat foo` plus more"
3522 * and we just got the EOF generated by the subshell that ran "cat foo"
3523 * The only real complaint is if we got an EOF when end_trigger != NULL,
3524 * that is, we were really supposed to get end_trigger, and never got
3525 * one before the EOF. Can't use the standard "syntax error" return code,
3526 * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
3527 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
3533 static void set_in_charmap(const char *set, int code)
3536 charmap[(unsigned char)*set++] = code;
3539 static void update_charmap(void)
3541 /* char *ifs and char charmap[256] are both globals. */
3542 ifs = getenv("IFS");
3545 /* Precompute a list of 'flow through' behavior so it can be treated
3546 * quickly up front. Computation is necessary because of IFS.
3547 * Special case handling of IFS == " \t\n" is not implemented.
3548 * The charmap[] array only really needs two bits each,
3549 * and on most machines that would be faster (reduced L1 cache use).
3551 memset(charmap, CHAR_ORDINARY, sizeof(charmap));
3552 #if ENABLE_HUSH_TICK
3553 set_in_charmap("\\$\"`", CHAR_SPECIAL);
3555 set_in_charmap("\\$\"", CHAR_SPECIAL);
3557 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
3558 set_in_charmap(ifs, CHAR_IFS); /* are ordinary if quoted */
3561 /* most recursion does not come through here, the exception is
3562 * from builtin_source() and builtin_eval() */
3563 static int parse_and_run_stream(struct in_str *inp, int parse_flag)
3565 struct p_context ctx;
3566 o_string temp = NULL_O_STRING;
3569 ctx.parse_type = parse_flag;
3570 initialize_context(&ctx);
3572 if (!(parse_flag & PARSEFLAG_SEMICOLON) || (parse_flag & PARSEFLAG_REPARSING))
3573 set_in_charmap(";$&|", CHAR_ORDINARY);
3574 #if ENABLE_HUSH_INTERACTIVE
3575 inp->promptmode = 0; /* PS1 */
3577 /* We will stop & execute after each ';' or '\n'.
3578 * Example: "sleep 9999; echo TEST" + ctrl-C:
3579 * TEST should be printed */
3580 rcode = parse_stream(&temp, &ctx, inp, ";\n");
3581 if (rcode != 1 && ctx.old_flag != 0) {
3584 if (rcode != 1 && ctx.old_flag == 0) {
3585 done_word(&temp, &ctx);
3586 done_pipe(&ctx, PIPE_SEQ);
3587 debug_print_tree(ctx.list_head, 0);
3588 debug_printf_exec("parse_stream_outer: run_list\n");
3589 run_list(ctx.list_head);
3591 if (ctx.old_flag != 0) {
3598 free_pipe_list(ctx.list_head, 0);
3601 } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP)); /* loop on syntax errors, return on EOF */
3605 static int parse_and_run_string(const char *s, int parse_flag)
3607 struct in_str input;
3608 setup_string_in_str(&input, s);
3609 return parse_and_run_stream(&input, parse_flag);
3612 static int parse_and_run_file(FILE *f)
3615 struct in_str input;
3616 setup_file_in_str(&input, f);
3617 rcode = parse_and_run_stream(&input, PARSEFLAG_SEMICOLON);
3622 /* Make sure we have a controlling tty. If we get started under a job
3623 * aware app (like bash for example), make sure we are now in charge so
3624 * we don't fight over who gets the foreground */
3625 static void setup_job_control(void)
3629 saved_task_pgrp = shell_pgrp = getpgrp();
3630 debug_printf_jobs("saved_task_pgrp=%d\n", saved_task_pgrp);
3631 fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
3633 /* If we were ran as 'hush &',
3634 * sleep until we are in the foreground. */
3635 while (tcgetpgrp(interactive_fd) != shell_pgrp) {
3636 /* Send TTIN to ourself (should stop us) */
3637 kill(- shell_pgrp, SIGTTIN);
3638 shell_pgrp = getpgrp();
3641 /* Ignore job-control and misc signals. */
3642 set_jobctrl_sighandler(SIG_IGN);
3643 set_misc_sighandler(SIG_IGN);
3644 //huh? signal(SIGCHLD, SIG_IGN);
3646 /* We _must_ restore tty pgrp on fatal signals */
3647 set_fatal_sighandler(sigexit);
3649 /* Put ourselves in our own process group. */
3650 setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
3651 /* Grab control of the terminal. */
3652 tcsetpgrp(interactive_fd, getpid());
3656 int hush_main(int argc, char **argv);
3657 int hush_main(int argc, char **argv)
3659 static const char version_str[] = "HUSH_VERSION="HUSH_VER_STR;
3660 static const struct variable const_shell_ver = {
3662 .varstr = (char*)version_str,
3663 .max_len = 1, /* 0 can provoke free(name) */
3671 struct variable *cur_var;
3673 PTR_TO_GLOBALS = xzalloc(sizeof(G));
3675 /* Deal with HUSH_VERSION */
3676 shell_ver = const_shell_ver; /* copying struct here */
3677 top_var = &shell_ver;
3678 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
3679 /* Initialize our shell local variables with the values
3680 * currently living in the environment */
3684 char *value = strchr(*e, '=');
3685 if (value) { /* paranoia */
3686 cur_var->next = xzalloc(sizeof(*cur_var));
3687 cur_var = cur_var->next;
3688 cur_var->varstr = *e;
3689 cur_var->max_len = strlen(*e);
3690 cur_var->flg_export = 1;
3694 putenv((char *)version_str); /* reinstate HUSH_VERSION */
3696 #if ENABLE_FEATURE_EDITING
3697 line_input_state = new_line_input_t(FOR_SHELL);
3699 /* XXX what should these be while sourcing /etc/profile? */
3702 /* Initialize some more globals to non-zero values */
3704 #if ENABLE_HUSH_INTERACTIVE
3705 #if ENABLE_FEATURE_EDITING
3706 cmdedit_set_initial_prompt();
3711 if (EXIT_SUCCESS) /* otherwise is already done */
3712 last_return_code = EXIT_SUCCESS;
3714 if (argv[0] && argv[0][0] == '-') {
3715 debug_printf("sourcing /etc/profile\n");
3716 input = fopen("/etc/profile", "r");
3717 if (input != NULL) {
3718 mark_open(fileno(input));
3719 parse_and_run_file(input);
3720 mark_closed(fileno(input));
3726 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
3729 global_argv = argv + optind;
3730 global_argc = argc - optind;
3731 opt = parse_and_run_string(optarg, PARSEFLAG_SEMICOLON);
3734 /* Well, we cannot just declare interactiveness,
3735 * we have to have some stuff (ctty, etc) */
3736 /* interactive_fd++; */
3743 fprintf(stderr, "Usage: sh [FILE]...\n"
3744 " or: sh -c command [args]...\n\n");
3752 /* A shell is interactive if the '-i' flag was given, or if all of
3753 * the following conditions are met:
3755 * no arguments remaining or the -s flag given
3756 * standard input is a terminal
3757 * standard output is a terminal
3758 * Refer to Posix.2, the description of the 'sh' utility. */
3759 if (argv[optind] == NULL && input == stdin
3760 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3762 saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
3763 debug_printf("saved_tty_pgrp=%d\n", saved_tty_pgrp);
3764 if (saved_tty_pgrp >= 0) {
3765 /* try to dup to high fd#, >= 255 */
3766 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3767 if (interactive_fd < 0) {
3768 /* try to dup to any fd */
3769 interactive_fd = dup(STDIN_FILENO);
3770 if (interactive_fd < 0)
3774 // TODO: track & disallow any attempts of user
3775 // to (inadvertently) close/redirect it
3778 debug_printf("interactive_fd=%d\n", interactive_fd);
3779 if (interactive_fd) {
3780 /* Looks like they want an interactive shell */
3781 setup_job_control();
3782 /* Make xfuncs do cleanup on exit */
3783 die_sleep = -1; /* flag */
3784 // FIXME: should we reset die_sleep = 0 whereever we fork?
3785 if (setjmp(die_jmp)) {
3786 /* xfunc has failed! die die die */
3787 hush_exit(xfunc_error_retval);
3789 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
3790 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
3791 printf("Enter 'help' for a list of built-in commands.\n\n");
3794 #elif ENABLE_HUSH_INTERACTIVE
3795 /* no job control compiled, only prompt/line editing */
3796 if (argv[optind] == NULL && input == stdin
3797 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3799 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3800 if (interactive_fd < 0) {
3801 /* try to dup to any fd */
3802 interactive_fd = dup(STDIN_FILENO);
3803 if (interactive_fd < 0)
3811 if (argv[optind] == NULL) {
3812 opt = parse_and_run_file(stdin);
3816 debug_printf("\nrunning script '%s'\n", argv[optind]);
3817 global_argv = argv + optind;
3818 global_argc = argc - optind;
3819 input = xfopen(argv[optind], "r");
3820 opt = parse_and_run_file(input);
3824 #if ENABLE_FEATURE_CLEAN_UP
3826 if (cwd != bb_msg_unknown)
3828 cur_var = top_var->next;
3830 struct variable *tmp = cur_var;
3831 if (!cur_var->max_len)
3832 free(cur_var->varstr);
3833 cur_var = cur_var->next;
3837 hush_exit(opt ? opt : last_return_code);