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?)
40 * $@ (those sure look like weird quoting rules)
42 * ! negation operator for pipes
43 * &> and >& redirection of stdout+stderr
46 * fancy forms of Parameter Expansion
48 * Arithmetic Expansion
49 * <(list) and >(list) Process Substitution
50 * reserved words: case, esac, select, function
51 * Here Documents ( << word )
54 * job handling woefully incomplete and buggy (improved --vda)
55 * reserved word execution woefully incomplete and buggy
57 * port selected bugfixes from post-0.49 busybox lash - done?
58 * finish implementing reserved words: for, while, until, do, done
59 * change { and } from special chars to reserved words
60 * builtins: break, continue, eval, return, set, trap, ulimit
62 * handle children going into background
63 * clean up recognition of null pipes
64 * check setting of global_argc and global_argv
65 * control-C handling, probably with longjmp
66 * follow IFS rules more precisely, including update semantics
67 * figure out what to do with backslash-newline
68 * explain why we use signal instead of sigaction
69 * propagate syntax errors, die on resource errors?
70 * continuation lines, both explicit and implicit - done?
71 * memory leak finding and plugging - done?
72 * more testing, especially quoting rules and redirection
73 * document how quoting rules not precisely followed for variable assignments
74 * maybe change charmap[] to use 2-bit entries
75 * (eventually) remove all the printf's
77 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
81 #include <glob.h> /* glob, of course */
82 #include <getopt.h> /* should be pretty obvious */
83 /* #include <dmalloc.h> */
86 /* If you comment out one of these below, it will be #defined later
87 * to perform debug printfs to stderr: */
88 #define debug_printf(...) do {} while (0)
89 /* Finer-grained debug switches */
90 #define debug_printf_parse(...) do {} while (0)
91 #define debug_print_tree(a, b) do {} while (0)
92 #define debug_printf_exec(...) do {} while (0)
93 #define debug_printf_jobs(...) do {} while (0)
94 #define debug_printf_expand(...) do {} while (0)
95 #define debug_printf_clean(...) do {} while (0)
98 #define debug_printf(...) fprintf(stderr, __VA_ARGS__)
101 #ifndef debug_printf_parse
102 #define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
105 #ifndef debug_printf_exec
106 #define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
109 #ifndef debug_printf_jobs
110 #define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
111 #define DEBUG_SHELL_JOBS 1
114 #ifndef debug_printf_expand
115 #define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
116 #define DEBUG_EXPAND 1
119 #ifndef debug_printf_clean
120 /* broken, of course, but OK for testing */
121 static const char *indenter(int i)
123 static const char blanks[] = " ";
124 return &blanks[sizeof(blanks) - i - 1];
126 #define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
130 #if !ENABLE_HUSH_INTERACTIVE
131 #undef ENABLE_FEATURE_EDITING
132 #define ENABLE_FEATURE_EDITING 0
133 #undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
134 #define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
137 #define SPECIAL_VAR_SYMBOL 3
138 #define FLAG_EXIT_FROM_LOOP 1
139 #define FLAG_PARSE_SEMICOLON (1 << 1) /* symbol ';' is special for parser */
140 #define FLAG_REPARSING (1 << 2) /* >= 2nd pass */
144 REDIRECT_OVERWRITE = 2,
150 /* The descrip member of this structure is only used to make debugging
152 static const struct {
154 signed char default_fd;
158 { O_RDONLY, 0, "<" },
159 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
160 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
161 { O_RDONLY, -1, "<<" },
172 /* might eventually control execution */
190 FLAG_END = (1 << RES_NONE ),
191 FLAG_IF = (1 << RES_IF ),
192 FLAG_THEN = (1 << RES_THEN ),
193 FLAG_ELIF = (1 << RES_ELIF ),
194 FLAG_ELSE = (1 << RES_ELSE ),
195 FLAG_FI = (1 << RES_FI ),
196 FLAG_FOR = (1 << RES_FOR ),
197 FLAG_WHILE = (1 << RES_WHILE),
198 FLAG_UNTIL = (1 << RES_UNTIL),
199 FLAG_DO = (1 << RES_DO ),
200 FLAG_DONE = (1 << RES_DONE ),
201 FLAG_IN = (1 << RES_IN ),
202 FLAG_START = (1 << RES_XXXX ),
205 /* This holds pointers to the various results of parsing */
207 struct child_prog *child;
208 struct pipe *list_head;
210 struct redir_struct *pending_redirect;
211 reserved_style res_w;
212 int old_flag; /* for figuring out valid reserved words */
213 struct p_context *stack;
214 int parse_type; /* define type of parser : ";$" common or special symbol */
215 /* How about quoting status? */
218 struct redir_struct {
219 struct redir_struct *next; /* pointer to the next redirect in the list */
220 redir_type type; /* type of redirection */
221 int fd; /* file descriptor being redirected */
222 int dup; /* -1, or file descriptor being duplicated */
223 glob_t word; /* *word.gl_pathv is the filename */
227 pid_t pid; /* 0 if exited */
228 char **argv; /* program name and arguments */
229 struct pipe *group; /* if non-NULL, first in group or subshell */
230 int subshell; /* flag, non-zero if group must be forked */
231 struct redir_struct *redirects; /* I/O redirections */
232 glob_t glob_result; /* result of parameter globbing */
233 int is_stopped; /* is the program currently running? */
234 struct pipe *family; /* pointer back to the child's parent pipe */
235 int sp; /* number of SPECIAL_VAR_SYMBOL */
238 // sp counting seems to be broken...
239 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
240 * and on execution these are substituted with their values.
241 * Substitution can make _several_ words out of one argv[n]!
242 * Example: argv[0]=='.^C*^C.' here: echo .$*.
247 int num_progs; /* total number of programs in job */
248 int running_progs; /* number of programs running (not exited) */
249 char *cmdbuf; /* buffer various argv's point into */
251 int jobid; /* job number */
252 char *cmdtext; /* name of job */
253 pid_t pgrp; /* process group ID for the job */
255 struct child_prog *progs; /* array of commands in pipe */
256 int stopped_progs; /* number of programs alive, but stopped */
257 int job_context; /* bitmask defining current context */
258 pipe_style followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
259 reserved_style r_mode; /* supports if, for, while, until */
263 struct close_me *next;
268 struct variables *next;
275 /* globals, connect us to the outside world
276 * the first three support $?, $#, and $1 */
277 static char **global_argv;
278 static int global_argc;
279 static int last_return_code;
280 extern char **environ; /* This is in <unistd.h>, but protected with __USE_GNU */
282 /* "globals" within this file */
285 CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
286 CHAR_IFS = 2, /* treated as ordinary if quoted */
287 CHAR_SPECIAL = 3, /* example: $ */
289 static unsigned char charmap[256];
290 static const char *ifs;
291 static int fake_mode;
292 static struct close_me *close_me_head;
293 static const char *cwd;
294 static unsigned last_bg_pid;
295 #if !ENABLE_HUSH_INTERACTIVE
296 enum { interactive_fd = 0 };
298 /* 'interactive_fd' is a fd# open to ctty, if we have one
299 * _AND_ if we decided to act interactively */
300 static int interactive_fd;
302 static pid_t saved_task_pgrp;
303 static pid_t saved_tty_pgrp;
304 static int last_jobid;
305 static struct pipe *job_list;
307 static const char *PS1;
308 static const char *PS2;
311 #define HUSH_VER_STR "0.02"
312 static struct variables shell_ver = { NULL, "HUSH_VERSION", HUSH_VER_STR, 1, 1 };
313 static struct variables *top_vars = &shell_ver;
325 #define NULL_O_STRING {NULL,0,0,0,0}
326 /* used for initialization:
327 o_string foo = NULL_O_STRING; */
329 /* I can almost use ordinary FILE *. Is open_memstream() universally
330 * available? Where is it documented? */
333 /* eof_flag=1: last char in ->p is really an EOF */
334 char eof_flag; /* meaningless if ->p == NULL */
336 #if ENABLE_HUSH_INTERACTIVE
341 int (*get) (struct in_str *);
342 int (*peek) (struct in_str *);
344 #define b_getch(input) ((input)->get(input))
345 #define b_peek(input) ((input)->peek(input))
347 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
349 struct built_in_command {
350 const char *cmd; /* name */
351 const char *descr; /* description */
352 int (*function) (char **argv); /* function ptr */
355 static void __syntax(int line)
357 bb_error_msg("syntax error hush.c:%d", line);
359 #define syntax() __syntax(__LINE__)
361 /* Index of subroutines: */
362 /* function prototypes for builtins */
363 static int builtin_cd(char **argv);
364 static int builtin_eval(char **argv);
365 static int builtin_exec(char **argv);
366 static int builtin_exit(char **argv);
367 static int builtin_export(char **argv);
369 static int builtin_fg_bg(char **argv);
370 static int builtin_jobs(char **argv);
372 static int builtin_help(char **argv);
373 static int builtin_pwd(char **argv);
374 static int builtin_read(char **argv);
375 static int builtin_set(char **argv);
376 static int builtin_shift(char **argv);
377 static int builtin_source(char **argv);
378 static int builtin_umask(char **argv);
379 static int builtin_unset(char **argv);
380 static int builtin_not_written(char **argv);
381 /* o_string manipulation: */
382 static int b_check_space(o_string *o, int len);
383 static int b_addchr(o_string *o, int ch);
384 static void b_reset(o_string *o);
385 static int b_addqchr(o_string *o, int ch, int quote);
386 //static int b_adduint(o_string *o, unsigned i);
387 /* in_str manipulations: */
388 static int static_get(struct in_str *i);
389 static int static_peek(struct in_str *i);
390 static int file_get(struct in_str *i);
391 static int file_peek(struct in_str *i);
392 static void setup_file_in_str(struct in_str *i, FILE *f);
393 static void setup_string_in_str(struct in_str *i, const char *s);
394 /* close_me manipulations: */
395 static void mark_open(int fd);
396 static void mark_closed(int fd);
397 static void close_all(void);
398 /* "run" the final data structures: */
399 //TODO: remove indent argument from non-debug build!
400 static int free_pipe_list(struct pipe *head, int indent);
401 static int free_pipe(struct pipe *pi, int indent);
402 /* really run the final data structures: */
403 static int setup_redirects(struct child_prog *prog, int squirrel[]);
404 static int run_list_real(struct pipe *pi);
405 static void pseudo_exec_argv(char **argv) ATTRIBUTE_NORETURN;
406 static void pseudo_exec(struct child_prog *child) ATTRIBUTE_NORETURN;
407 static int run_pipe_real(struct pipe *pi);
408 /* extended glob support: */
409 static int globhack(const char *src, int flags, glob_t *pglob);
410 static int glob_needed(const char *s);
411 static int xglob(o_string *dest, int flags, glob_t *pglob);
412 /* variable assignment: */
413 static int is_assignment(const char *s);
414 /* data structure manipulation: */
415 static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
416 static void initialize_context(struct p_context *ctx);
417 static int done_word(o_string *dest, struct p_context *ctx);
418 static int done_command(struct p_context *ctx);
419 static int done_pipe(struct p_context *ctx, pipe_style type);
420 /* primary string parsing: */
421 static int redirect_dup_num(struct in_str *input);
422 static int redirect_opt_num(o_string *o);
423 static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, const char *subst_end);
424 static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
425 static const char *lookup_param(const char *src);
426 static char *make_string(char **inp);
427 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
428 //static int parse_string(o_string *dest, struct p_context *ctx, const char *src);
429 static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, const char *end_trigger);
431 static int parse_stream_outer(struct in_str *inp, int parse_flag);
432 static int parse_string_outer(const char *s, int parse_flag);
433 static int parse_file_outer(FILE *f);
434 /* job management: */
435 static int checkjobs(struct pipe* fg_pipe);
437 static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
438 static void insert_bg_job(struct pipe *pi);
439 static void remove_bg_job(struct pipe *pi);
440 static void delete_finished_bg_job(struct pipe *pi);
442 int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
444 /* local variable support */
445 static char **do_variable_expansion(char **argv);
446 static char *insert_var_value(char *inp);
447 static const char *get_local_var(const char *var);
448 static int set_local_var(const char *s, int flg_export);
449 static void unset_local_var(const char *name);
451 /* Table of built-in functions. They can be forked or not, depending on
452 * context: within pipes, they fork. As simple commands, they do not.
453 * When used in non-forking context, they can change global variables
454 * in the parent shell process. If forked, of course they cannot.
455 * For example, 'unset foo | whatever' will parse and run, but foo will
456 * still be set at the end. */
457 static const struct built_in_command bltins[] = {
459 { "bg", "Resume a job in the background", builtin_fg_bg },
461 { "break", "Exit for, while or until loop", builtin_not_written },
462 { "cd", "Change working directory", builtin_cd },
463 { "continue", "Continue for, while or until loop", builtin_not_written },
464 { "eval", "Construct and run shell command", builtin_eval },
465 { "exec", "Exec command, replacing this shell with the exec'd process",
467 { "exit", "Exit from shell()", builtin_exit },
468 { "export", "Set environment variable", builtin_export },
470 { "fg", "Bring job into the foreground", builtin_fg_bg },
471 { "jobs", "Lists the active jobs", builtin_jobs },
473 { "pwd", "Print current directory", builtin_pwd },
474 { "read", "Input environment variable", builtin_read },
475 { "return", "Return from a function", builtin_not_written },
476 { "set", "Set/unset shell local variables", builtin_set },
477 { "shift", "Shift positional parameters", builtin_shift },
478 { "trap", "Trap signals", builtin_not_written },
479 { "ulimit","Controls resource limits", builtin_not_written },
480 { "umask","Sets file creation mask", builtin_umask },
481 { "unset", "Unset environment variable", builtin_unset },
482 { ".", "Source-in and run commands in a file", builtin_source },
483 { "help", "List shell built-in commands", builtin_help },
490 static void signal_SA_RESTART(int sig, void (*handler)(int))
493 sa.sa_handler = handler;
494 sa.sa_flags = SA_RESTART;
495 sigemptyset(&sa.sa_mask);
496 sigaction(sig, &sa, NULL);
499 /* Signals are grouped, we handle them in batches */
500 static void set_fatal_sighandler(void (*handler)(int))
502 signal(SIGILL , handler);
503 signal(SIGTRAP, handler);
504 signal(SIGABRT, handler);
505 signal(SIGFPE , handler);
506 signal(SIGBUS , handler);
507 signal(SIGSEGV, handler);
508 /* bash 3.2 seems to handle these just like 'fatal' ones */
509 signal(SIGHUP , handler);
510 signal(SIGPIPE, handler);
511 signal(SIGALRM, handler);
513 static void set_jobctrl_sighandler(void (*handler)(int))
515 signal(SIGTSTP, handler);
516 signal(SIGTTIN, handler);
517 signal(SIGTTOU, handler);
519 static void set_misc_sighandler(void (*handler)(int))
521 signal(SIGINT , handler);
522 signal(SIGQUIT, handler);
523 signal(SIGTERM, handler);
525 /* SIGCHLD is special and handled separately */
527 static void set_every_sighandler(void (*handler)(int))
529 set_fatal_sighandler(handler);
530 set_jobctrl_sighandler(handler);
531 set_misc_sighandler(handler);
532 signal(SIGCHLD, handler);
535 static struct pipe *toplevel_list;
536 static sigjmp_buf toplevel_jb;
537 smallint ctrl_z_flag;
538 #if ENABLE_FEATURE_SH_STANDALONE
539 struct nofork_save_area nofork_save;
542 static void handler_ctrl_c(int sig)
544 debug_printf_jobs("got sig %d\n", sig);
545 // as usual we can have all kinds of nasty problems with leaked malloc data here
546 siglongjmp(toplevel_jb, 1);
549 static void handler_ctrl_z(int sig)
553 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
555 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
558 if (!pid) { /* child */
560 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
561 set_every_sighandler(SIG_DFL);
562 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
563 debug_printf_jobs("returning in child\n");
564 /* return to nofork, it will eventually exit now,
565 * not return back to shell */
569 /* finish filling up pipe info */
570 toplevel_list->pgrp = pid; /* child is in its own pgrp */
571 toplevel_list->progs[0].pid = pid;
572 /* parent needs to longjmp out of running nofork.
573 * we will "return" exitcode 0, with child put in background */
574 // as usual we can have all kinds of nasty problems with leaked malloc data here
575 debug_printf_jobs("siglongjmp in parent\n");
576 siglongjmp(toplevel_jb, 1);
579 /* Restores tty foreground process group, and exits.
580 * May be called as signal handler for fatal signal
581 * (will faithfully resend signal to itself, producing correct exit state)
582 * or called directly with -EXITCODE.
583 * We also call it if xfunc is exiting. */
584 static void sigexit(int sig) ATTRIBUTE_NORETURN;
585 static void sigexit(int sig)
589 /* Disable all signals: job control, SIGPIPE, etc. */
590 sigfillset(&block_all);
591 sigprocmask(SIG_SETMASK, &block_all, NULL);
594 tcsetpgrp(interactive_fd, saved_tty_pgrp);
596 /* Not a signal, just exit */
600 /* Enable only this sig and kill ourself with it */
601 signal(sig, SIG_DFL);
602 sigdelset(&block_all, sig);
603 sigprocmask(SIG_SETMASK, &block_all, NULL);
605 _exit(1); /* Should not reach it */
608 /* Restores tty foreground process group, and exits. */
609 static void hush_exit(int exitcode) ATTRIBUTE_NORETURN;
610 static void hush_exit(int exitcode)
612 fflush(NULL); /* flush all streams */
613 sigexit(- (exitcode & 0xff));
618 #define set_fatal_sighandler(handler) ((void)0)
619 #define set_jobctrl_sighandler(handler) ((void)0)
620 #define set_misc_sighandler(handler) ((void)0)
621 #define hush_exit(e) exit(e)
626 static const char *set_cwd(void)
628 if (cwd == bb_msg_unknown)
629 cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
630 cwd = xrealloc_getcwd_or_warn((char *)cwd);
632 cwd = bb_msg_unknown;
636 /* built-in 'eval' handler */
637 static int builtin_eval(char **argv)
640 int rcode = EXIT_SUCCESS;
643 str = make_string(argv + 1);
644 parse_string_outer(str, FLAG_EXIT_FROM_LOOP |
645 FLAG_PARSE_SEMICOLON);
647 rcode = last_return_code;
652 /* built-in 'cd <path>' handler */
653 static int builtin_cd(char **argv)
657 newdir = getenv("HOME");
661 printf("cd: %s: %s\n", newdir, strerror(errno));
668 /* built-in 'exec' handler */
669 static int builtin_exec(char **argv)
672 return EXIT_SUCCESS; /* Really? */
673 pseudo_exec_argv(argv + 1);
677 /* built-in 'exit' handler */
678 static int builtin_exit(char **argv)
680 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
681 //puts("exit"); /* bash does it */
682 // TODO: warn if we have background jobs: "There are stopped jobs"
683 // On second consecutive 'exit', exit anyway.
686 hush_exit(last_return_code);
687 /* mimic bash: exit 123abc == exit 255 + error msg */
688 xfunc_error_retval = 255;
689 /* bash: exit -2 == exit 254, no error msg */
690 hush_exit(xatoi(argv[1]) & 0xff);
693 /* built-in 'export VAR=value' handler */
694 static int builtin_export(char **argv)
697 char *name = argv[1];
701 // ash emits: export VAR='VAL'
702 // bash: declare -x VAR="VAL"
703 // (both also escape as needed (quotes, $, etc))
714 const char *value = strchr(name, '=');
718 /* They are exporting something without an =VALUE */
720 value = get_local_var(name);
722 size_t ln = strlen(name);
724 tmp = realloc(name, ln+strlen(value)+2);
728 sprintf(tmp+ln, "=%s", value);
732 /* bash does not return an error when trying to export
733 * an undefined variable. Do likewise. */
739 bb_perror_msg("export");
741 res = set_local_var(name, 1);
749 /* built-in 'fg' and 'bg' handler */
750 static int builtin_fg_bg(char **argv)
757 /* If they gave us no args, assume they want the last backgrounded task */
759 for (pi = job_list; pi; pi = pi->next) {
760 if (pi->jobid == last_jobid) {
764 bb_error_msg("%s: no current job", argv[0]);
767 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
768 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
771 for (pi = job_list; pi; pi = pi->next) {
772 if (pi->jobid == jobnum) {
776 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
779 // TODO: bash prints a string representation
780 // of job being foregrounded (like "sleep 1 | cat")
781 if (*argv[0] == 'f') {
782 /* Put the job into the foreground. */
783 tcsetpgrp(interactive_fd, pi->pgrp);
786 /* Restart the processes in the job */
787 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_progs, pi->pgrp);
788 for (i = 0; i < pi->num_progs; i++) {
789 debug_printf_jobs("reviving pid %d\n", pi->progs[i].pid);
790 pi->progs[i].is_stopped = 0;
792 pi->stopped_progs = 0;
794 i = kill(- pi->pgrp, SIGCONT);
796 if (errno == ESRCH) {
797 delete_finished_bg_job(pi);
800 bb_perror_msg("kill (SIGCONT)");
804 if (*argv[0] == 'f') {
806 return checkjobs_and_fg_shell(pi);
812 /* built-in 'help' handler */
813 static int builtin_help(char **argv ATTRIBUTE_UNUSED)
815 const struct built_in_command *x;
817 printf("\nBuilt-in commands:\n");
818 printf("-------------------\n");
819 for (x = bltins; x->cmd; x++) {
820 if (x->descr == NULL)
822 printf("%s\t%s\n", x->cmd, x->descr);
829 /* built-in 'jobs' handler */
830 static int builtin_jobs(char **argv ATTRIBUTE_UNUSED)
833 const char *status_string;
835 for (job = job_list; job; job = job->next) {
836 if (job->running_progs == job->stopped_progs)
837 status_string = "Stopped";
839 status_string = "Running";
841 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
847 /* built-in 'pwd' handler */
848 static int builtin_pwd(char **argv ATTRIBUTE_UNUSED)
854 /* built-in 'read VAR' handler */
855 static int builtin_read(char **argv)
859 const char *name = argv[1] ? argv[1] : "REPLY";
860 int name_len = strlen(name);
862 if (name_len >= sizeof(string) - 2)
864 strcpy(string, name);
865 p = string + name_len;
867 *p = '\0'; /* In case stdin has only EOF */
868 /* read string. name_len+1 chars are already used by 'name=' */
869 fgets(p, sizeof(string) - 1 - name_len, stdin);
871 return set_local_var(string, 0);
874 /* built-in 'set [VAR=value]' handler */
875 static int builtin_set(char **argv)
877 char *temp = argv[1];
881 for (e = top_vars; e; e = e->next)
882 printf("%s=%s\n", e->name, e->value);
884 set_local_var(temp, 0);
890 /* Built-in 'shift' handler */
891 static int builtin_shift(char **argv)
897 if (n >= 0 && n < global_argc) {
898 /* XXX This probably breaks $0 */
906 /* Built-in '.' handler (read-in and execute commands from file) */
907 static int builtin_source(char **argv)
915 /* XXX search through $PATH is missing */
916 input = fopen(argv[1], "r");
918 bb_error_msg("cannot open '%s'", argv[1]);
922 /* Now run the file */
923 /* XXX argv and argc are broken; need to save old global_argv
924 * (pointer only is OK!) on this stack frame,
925 * set global_argv=argv+1, recurse, and restore. */
926 mark_open(fileno(input));
927 status = parse_file_outer(input);
928 mark_closed(fileno(input));
933 static int builtin_umask(char **argv)
936 const char *arg = argv[1];
939 new_umask = strtoul(arg, &end, 8);
940 if (*end != '\0' || end == arg) {
944 new_umask = umask(0);
945 printf("%.3o\n", (unsigned) new_umask);
951 /* built-in 'unset VAR' handler */
952 static int builtin_unset(char **argv)
954 /* bash always returns true */
955 unset_local_var(argv[1]);
959 static int builtin_not_written(char **argv)
961 printf("builtin_%s not written\n", argv[0]);
965 static int b_check_space(o_string *o, int len)
967 /* It would be easy to drop a more restrictive policy
968 * in here, such as setting a maximum string length */
969 if (o->length + len > o->maxlen) {
970 char *old_data = o->data;
971 /* assert(data == NULL || o->maxlen != 0); */
972 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
973 o->data = realloc(o->data, 1 + o->maxlen);
974 if (o->data == NULL) {
978 return o->data == NULL;
981 static int b_addchr(o_string *o, int ch)
983 debug_printf("b_addchr: '%c' o->lengtt=%d o=%p\n", ch, o->length, o);
984 if (b_check_space(o, 1))
986 o->data[o->length] = ch;
988 o->data[o->length] = '\0';
992 static void b_reset(o_string *o)
1000 static void b_free(o_string *o)
1008 /* My analysis of quoting semantics tells me that state information
1009 * is associated with a destination, not a source.
1011 static int b_addqchr(o_string *o, int ch, int quote)
1013 if (quote && strchr("*?[\\", ch)) {
1015 rc = b_addchr(o, '\\');
1019 return b_addchr(o, ch);
1022 //static int b_adduint(o_string *o, unsigned i)
1025 // char buf[sizeof(unsigned)*3 + 1];
1027 // *(utoa_to_buf(i, buf, sizeof(buf))) = '\0';
1028 // /* no escape checking necessary */
1029 // do r = b_addchr(o, *p++); while (r == 0 && *p);
1033 static int static_get(struct in_str *i)
1036 if (ch == '\0') return EOF;
1040 static int static_peek(struct in_str *i)
1045 #if ENABLE_HUSH_INTERACTIVE
1046 #if ENABLE_FEATURE_EDITING
1047 static void cmdedit_set_initial_prompt(void)
1049 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1052 PS1 = getenv("PS1");
1057 #endif /* EDITING */
1059 static const char* setup_prompt_string(int promptmode)
1061 const char *prompt_str;
1062 debug_printf("setup_prompt_string %d ", promptmode);
1063 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1064 /* Set up the prompt */
1065 if (promptmode == 1) {
1068 ns = xmalloc(strlen(cwd)+4);
1069 sprintf(ns, "%s %s", cwd, (geteuid() != 0) ? "$ " : "# ");
1076 prompt_str = (promptmode == 1) ? PS1 : PS2;
1078 debug_printf("result %s\n", prompt_str);
1082 #if ENABLE_FEATURE_EDITING
1083 static line_input_t *line_input_state;
1086 static void get_user_input(struct in_str *i)
1088 static char the_command[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
1091 const char *prompt_str;
1093 prompt_str = setup_prompt_string(i->promptmode);
1094 #if ENABLE_FEATURE_EDITING
1096 ** enable command line editing only while a command line
1097 ** is actually being read; otherwise, we'll end up bequeathing
1098 ** atexit() handlers and other unwanted stuff to our
1099 ** child processes (rob@sysgo.de)
1101 r = read_line_input(prompt_str, the_command, BUFSIZ-1, line_input_state);
1102 i->eof_flag = (r < 0);
1103 if (i->eof_flag) { /* EOF/error detected */
1104 the_command[0] = EOF; /* yes, it will be truncated, it's ok */
1105 the_command[1] = '\0';
1108 fputs(prompt_str, stdout);
1110 the_command[0] = r = fgetc(i->file);
1111 /*the_command[1] = '\0'; - already is and never changed */
1112 i->eof_flag = (r == EOF);
1116 #endif /* INTERACTIVE */
1118 /* This is the magic location that prints prompts
1119 * and gets data back from the user */
1120 static int file_get(struct in_str *i)
1124 /* If there is data waiting, eat it up */
1125 if (i->p && *i->p) {
1128 if (i->eof_flag && !*i->p)
1131 /* need to double check i->file because we might be doing something
1132 * more complicated by now, like sourcing or substituting. */
1133 #if ENABLE_HUSH_INTERACTIVE
1134 if (interactive_fd && i->__promptme && i->file == stdin) {
1137 } while (!*i->p); /* need non-empty line */
1144 ch = fgetc(i->file);
1147 debug_printf("file_get: got a '%c' %d\n", ch, ch);
1148 #if ENABLE_HUSH_INTERACTIVE
1155 /* All the callers guarantee this routine will never be
1156 * used right after a newline, so prompting is not needed.
1158 static int file_peek(struct in_str *i)
1161 if (i->p && *i->p) {
1162 if (i->eof_flag && !i->p[1])
1166 ch = fgetc(i->file);
1167 i->eof_flag = (ch == EOF);
1168 i->peek_buf[0] = ch;
1169 i->peek_buf[1] = '\0';
1171 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
1175 static void setup_file_in_str(struct in_str *i, FILE *f)
1177 i->peek = file_peek;
1179 #if ENABLE_HUSH_INTERACTIVE
1187 static void setup_string_in_str(struct in_str *i, const char *s)
1189 i->peek = static_peek;
1190 i->get = static_get;
1191 #if ENABLE_HUSH_INTERACTIVE
1199 static void mark_open(int fd)
1201 struct close_me *new = xmalloc(sizeof(struct close_me));
1203 new->next = close_me_head;
1204 close_me_head = new;
1207 static void mark_closed(int fd)
1209 struct close_me *tmp;
1210 if (close_me_head == NULL || close_me_head->fd != fd)
1211 bb_error_msg_and_die("corrupt close_me");
1212 tmp = close_me_head;
1213 close_me_head = close_me_head->next;
1217 static void close_all(void)
1220 for (c = close_me_head; c; c = c->next) {
1223 close_me_head = NULL;
1226 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
1227 * and stderr if they are redirected. */
1228 static int setup_redirects(struct child_prog *prog, int squirrel[])
1231 struct redir_struct *redir;
1233 for (redir = prog->redirects; redir; redir = redir->next) {
1234 if (redir->dup == -1 && redir->word.gl_pathv == NULL) {
1235 /* something went wrong in the parse. Pretend it didn't happen */
1238 if (redir->dup == -1) {
1239 mode = redir_table[redir->type].mode;
1240 openfd = open_or_warn(redir->word.gl_pathv[0], mode);
1242 /* this could get lost if stderr has been redirected, but
1243 bash and ash both lose it as well (though zsh doesn't!) */
1247 openfd = redir->dup;
1250 if (openfd != redir->fd) {
1251 if (squirrel && redir->fd < 3) {
1252 squirrel[redir->fd] = dup(redir->fd);
1257 dup2(openfd, redir->fd);
1258 if (redir->dup == -1)
1266 static void restore_redirects(int squirrel[])
1269 for (i = 0; i < 3; i++) {
1272 /* We simply die on error */
1279 /* XXX no exit() here. If you don't exec, use _exit instead.
1280 * The at_exit handlers apparently confuse the calling process,
1281 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
1282 static void pseudo_exec_argv(char **argv)
1286 const struct built_in_command *x;
1288 for (i = 0; is_assignment(argv[i]); i++) {
1289 debug_printf("pid %d environment modification: %s\n",
1291 // FIXME: vfork case??
1292 p = insert_var_value(argv[i]);
1293 putenv(p == argv[i] ? xstrdup(p) : p);
1296 /* If a variable is assigned in a forest, and nobody listens,
1297 * was it ever really set?
1299 if (argv[0] == NULL) {
1300 _exit(EXIT_SUCCESS);
1303 argv = do_variable_expansion(argv);
1306 * Check if the command matches any of the builtins.
1307 * Depending on context, this might be redundant. But it's
1308 * easier to waste a few CPU cycles than it is to figure out
1309 * if this is one of those cases.
1311 for (x = bltins; x->cmd; x++) {
1312 if (strcmp(argv[0], x->cmd) == 0) {
1313 debug_printf_exec("running builtin '%s'\n", argv[0]);
1314 rcode = x->function(argv);
1320 /* Check if the command matches any busybox internal commands
1322 * FIXME: This feature is not 100% safe, since
1323 * BusyBox is not fully reentrant, so we have no guarantee the things
1324 * from the .bss are still zeroed, or that things from .data are still
1325 * at their defaults. We could exec ourself from /proc/self/exe, but I
1326 * really dislike relying on /proc for things. We could exec ourself
1327 * from global_argv[0], but if we are in a chroot, we may not be able
1328 * to find ourself... */
1329 #if ENABLE_FEATURE_SH_STANDALONE
1330 debug_printf("running applet %s\n", argv[0]);
1331 // FIXME: check NOEXEC bit, and EXEC if not set!
1332 run_applet_and_exit(argv[0], argv);
1333 // is it ok that run_applet_and_exit() does exit(), not _exit()?
1334 // NB: IIRC on NOMMU we are after _vfork_, not fork!
1336 debug_printf("exec of %s\n", argv[0]);
1337 execvp(argv[0], argv);
1338 bb_perror_msg("cannot exec '%s'", argv[0]);
1342 static void pseudo_exec(struct child_prog *child)
1344 // FIXME: buggy wrt NOMMU! Must not modify any global data
1345 // until it does exec/_exit, but currently it does.
1349 pseudo_exec_argv(child->argv);
1353 // FIXME: do not modify globals! Think vfork!
1354 #if ENABLE_HUSH_INTERACTIVE
1355 debug_printf_exec("pseudo_exec: setting interactive_fd=0\n");
1356 interactive_fd = 0; /* crucial!!!! */
1358 debug_printf_exec("pseudo_exec: run_list_real\n");
1359 rcode = run_list_real(child->group);
1360 /* OK to leak memory by not calling free_pipe_list,
1361 * since this process is about to exit */
1365 /* Can happen. See what bash does with ">foo" by itself. */
1366 debug_printf("trying to pseudo_exec null command\n");
1367 _exit(EXIT_SUCCESS);
1371 static const char *get_cmdtext(struct pipe *pi)
1377 /* This is subtle. ->cmdtext is created only on first backgrounding.
1378 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
1379 * On subsequent bg argv is trashed, but we won't use it */
1382 argv = pi->progs[0].argv;
1383 if (!argv || !argv[0])
1384 return (pi->cmdtext = xzalloc(1));
1387 do len += strlen(*argv) + 1; while (*++argv);
1388 pi->cmdtext = p = xmalloc(len);
1389 argv = pi->progs[0].argv;
1391 len = strlen(*argv);
1392 memcpy(p, *argv, len);
1400 static void insert_bg_job(struct pipe *pi)
1402 struct pipe *thejob;
1405 /* Linear search for the ID of the job to use */
1407 for (thejob = job_list; thejob; thejob = thejob->next)
1408 if (thejob->jobid >= pi->jobid)
1409 pi->jobid = thejob->jobid + 1;
1411 /* Add thejob to the list of running jobs */
1413 thejob = job_list = xmalloc(sizeof(*thejob));
1415 for (thejob = job_list; thejob->next; thejob = thejob->next)
1417 thejob->next = xmalloc(sizeof(*thejob));
1418 thejob = thejob->next;
1421 /* Physically copy the struct job */
1422 memcpy(thejob, pi, sizeof(struct pipe));
1423 thejob->progs = xzalloc(sizeof(pi->progs[0]) * pi->num_progs);
1424 /* We cannot copy entire pi->progs[] vector! Double free()s will happen */
1425 for (i = 0; i < pi->num_progs; i++) {
1426 // TODO: do we really need to have so many fields which are just dead weight
1427 // at execution stage?
1428 thejob->progs[i].pid = pi->progs[i].pid;
1430 //char **argv; /* program name and arguments */
1431 //struct pipe *group; /* if non-NULL, first in group or subshell */
1432 //int subshell; /* flag, non-zero if group must be forked */
1433 //struct redir_struct *redirects; /* I/O redirections */
1434 //glob_t glob_result; /* result of parameter globbing */
1435 //int is_stopped; /* is the program currently running? */
1436 //struct pipe *family; /* pointer back to the child's parent pipe */
1437 //int sp; /* number of SPECIAL_VAR_SYMBOL */
1440 thejob->next = NULL;
1441 thejob->cmdtext = xstrdup(get_cmdtext(pi));
1443 /* We don't wait for background thejobs to return -- append it
1444 to the list of backgrounded thejobs and leave it alone */
1445 printf("[%d] %d %s\n", thejob->jobid, thejob->progs[0].pid, thejob->cmdtext);
1446 last_bg_pid = thejob->progs[0].pid;
1447 last_jobid = thejob->jobid;
1450 static void remove_bg_job(struct pipe *pi)
1452 struct pipe *prev_pipe;
1454 if (pi == job_list) {
1455 job_list = pi->next;
1457 prev_pipe = job_list;
1458 while (prev_pipe->next != pi)
1459 prev_pipe = prev_pipe->next;
1460 prev_pipe->next = pi->next;
1463 last_jobid = job_list->jobid;
1468 /* remove a backgrounded job */
1469 static void delete_finished_bg_job(struct pipe *pi)
1472 pi->stopped_progs = 0;
1478 /* Checks to see if any processes have exited -- if they
1479 have, figure out why and see if a job has completed */
1480 static int checkjobs(struct pipe* fg_pipe)
1491 attributes = WUNTRACED;
1492 if (fg_pipe == NULL) {
1493 attributes |= WNOHANG;
1496 /* Do we do this right?
1497 * bash-3.00# sleep 20 | false
1499 * [3]+ Stopped sleep 20 | false
1500 * bash-3.00# echo $?
1501 * 1 <========== bg pipe is not fully done, but exitcode is already known!
1504 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
1505 //are stopped. Testcase: "cat | cat" in a script (not on command line)
1506 // + killall -STOP cat
1509 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
1510 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
1512 #ifdef DEBUG_SHELL_JOBS
1513 if (WIFSTOPPED(status))
1514 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
1515 childpid, WSTOPSIG(status), WEXITSTATUS(status));
1516 if (WIFSIGNALED(status))
1517 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
1518 childpid, WTERMSIG(status), WEXITSTATUS(status));
1519 if (WIFEXITED(status))
1520 debug_printf_jobs("pid %d exited, exitcode %d\n",
1521 childpid, WEXITSTATUS(status));
1523 /* Were we asked to wait for fg pipe? */
1526 for (i = 0; i < fg_pipe->num_progs; i++) {
1527 debug_printf_jobs("check pid %d\n", fg_pipe->progs[i].pid);
1528 if (fg_pipe->progs[i].pid == childpid) {
1529 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
1531 fg_pipe->progs[i].pid = 0;
1532 fg_pipe->running_progs--;
1533 if (i == fg_pipe->num_progs-1)
1534 /* last process gives overall exitstatus */
1535 rcode = WEXITSTATUS(status);
1537 fg_pipe->progs[i].is_stopped = 1;
1538 fg_pipe->stopped_progs++;
1540 debug_printf_jobs("fg_pipe: running_progs %d stopped_progs %d\n",
1541 fg_pipe->running_progs, fg_pipe->stopped_progs);
1542 if (fg_pipe->running_progs - fg_pipe->stopped_progs <= 0) {
1543 /* All processes in fg pipe have exited/stopped */
1545 if (fg_pipe->running_progs)
1546 insert_bg_job(fg_pipe);
1550 /* There are still running processes in the fg pipe */
1554 /* fall through to searching process in bg pipes */
1558 /* We asked to wait for bg or orphaned children */
1559 /* No need to remember exitcode in this case */
1560 for (pi = job_list; pi; pi = pi->next) {
1562 while (prognum < pi->num_progs) {
1563 if (pi->progs[prognum].pid == childpid)
1564 goto found_pi_and_prognum;
1570 /* Happens when shell is used as init process (init=/bin/sh) */
1571 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
1575 found_pi_and_prognum:
1578 pi->progs[prognum].pid = 0;
1579 pi->running_progs--;
1580 if (!pi->running_progs) {
1581 printf(JOB_STATUS_FORMAT, pi->jobid,
1582 "Done", pi->cmdtext);
1583 delete_finished_bg_job(pi);
1587 pi->stopped_progs++;
1588 pi->progs[prognum].is_stopped = 1;
1593 /* wait found no children or failed */
1595 if (childpid && errno != ECHILD)
1596 bb_perror_msg("waitpid");
1598 /* move the shell to the foreground */
1599 //if (interactive_fd && tcsetpgrp(interactive_fd, getpgid(0)))
1600 // bb_perror_msg("tcsetpgrp-2");
1605 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1608 int rcode = checkjobs(fg_pipe);
1609 /* Job finished, move the shell to the foreground */
1611 debug_printf("fg'ing ourself: getpgid(0)=%d\n", (int)p);
1612 if (tcsetpgrp(interactive_fd, p) && errno != ENOTTY)
1613 bb_perror_msg("tcsetpgrp-4a");
1618 /* run_pipe_real() starts all the jobs, but doesn't wait for anything
1619 * to finish. See checkjobs().
1621 * return code is normally -1, when the caller has to wait for children
1622 * to finish to determine the exit status of the pipe. If the pipe
1623 * is a simple builtin command, however, the action is done by the
1624 * time run_pipe_real returns, and the exit code is provided as the
1627 * The input of the pipe is always stdin, the output is always
1628 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1629 * because it tries to avoid running the command substitution in
1630 * subshell, when that is in fact necessary. The subshell process
1631 * now has its stdout directed to the input of the appropriate pipe,
1632 * so this routine is noticeably simpler.
1634 static int run_pipe_real(struct pipe *pi)
1637 int nextin, nextout;
1638 int pipefds[2]; /* pipefds[0] is for reading */
1639 struct child_prog *child;
1640 const struct built_in_command *x;
1642 /* it is not always needed, but we aim to smaller code */
1643 int squirrel[] = { -1, -1, -1 };
1645 const int single_fg = (pi->num_progs == 1 && pi->followup != PIPE_BG);
1647 debug_printf_exec("run_pipe_real start: single_fg=%d\n", single_fg);
1653 pi->running_progs = 1;
1654 pi->stopped_progs = 0;
1656 /* Check if this is a simple builtin (not part of a pipe).
1657 * Builtins within pipes have to fork anyway, and are handled in
1658 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1660 child = &(pi->progs[0]);
1661 if (single_fg && child->group && child->subshell == 0) {
1662 debug_printf("non-subshell grouping\n");
1663 setup_redirects(child, squirrel);
1664 debug_printf_exec(": run_list_real\n");
1665 rcode = run_list_real(child->group);
1666 restore_redirects(squirrel);
1667 debug_printf_exec("run_pipe_real return %d\n", rcode);
1671 if (single_fg && child->argv != NULL) {
1672 char **argv_expanded, **free_me;
1673 char **argv = child->argv;
1675 for (i = 0; is_assignment(argv[i]); i++)
1677 if (i != 0 && argv[i] == NULL) {
1678 /* assignments, but no command: set the local environment */
1679 for (i = 0; argv[i] != NULL; i++) {
1680 /* Ok, this case is tricky. We have to decide if this is a
1681 * local variable, or an already exported variable. If it is
1682 * already exported, we have to export the new value. If it is
1683 * not exported, we need only set this as a local variable.
1684 * This junk is all to decide whether or not to export this
1688 name = xstrdup(argv[i]);
1689 debug_printf("local environment set: %s\n", name);
1690 value = strchr(name, '=');
1693 if (get_local_var(name)) {
1697 p = insert_var_value(argv[i]);
1698 set_local_var(p, export_me);
1702 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1704 for (i = 0; is_assignment(argv[i]); i++) {
1705 p = insert_var_value(argv[i]);
1714 for (x = bltins; x->cmd; x++) {
1715 if (strcmp(argv[i], x->cmd) == 0) {
1716 if (x->function == builtin_exec && argv[i+1] == NULL) {
1717 debug_printf("magic exec\n");
1718 setup_redirects(child, NULL);
1719 return EXIT_SUCCESS;
1721 debug_printf("builtin inline %s\n", argv[0]);
1722 /* XXX setup_redirects acts on file descriptors, not FILEs.
1723 * This is perfect for work that comes after exec().
1724 * Is it really safe for inline use? Experimentally,
1725 * things seem to work with glibc. */
1726 // TODO: fflush(NULL)?
1727 setup_redirects(child, squirrel);
1728 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv[i+1]);
1729 argv_expanded = argv + i;
1730 if (child->sp) /* btw we can do it unconditionally... */
1731 free_me = argv_expanded = do_variable_expansion(argv + i);
1732 rcode = x->function(argv_expanded);
1734 restore_redirects(squirrel);
1735 debug_printf_exec("run_pipe_real return %d\n", rcode);
1739 #if ENABLE_FEATURE_SH_STANDALONE
1741 const struct bb_applet *a = find_applet_by_name(argv[i]);
1742 if (a && a->nofork) {
1743 setup_redirects(child, squirrel);
1744 save_nofork_data(&nofork_save);
1745 argv_expanded = argv + i;
1747 free_me = argv_expanded = do_variable_expansion(argv + i);
1748 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
1749 rcode = run_nofork_applet_prime(&nofork_save, a, argv_expanded);
1751 restore_redirects(squirrel);
1752 debug_printf_exec("run_pipe_real return %d\n", rcode);
1759 /* Going to fork a child per each pipe member */
1760 pi->running_progs = 0;
1762 /* Disable job control signals for shell (parent) and
1763 * for initial child code after fork */
1764 set_jobctrl_sighandler(SIG_IGN);
1766 for (i = 0; i < pi->num_progs; i++) {
1767 child = &(pi->progs[i]);
1769 debug_printf_exec(": pipe member '%s' '%s'...\n", child->argv[0], child->argv[1]);
1771 debug_printf_exec(": pipe member with no argv\n");
1773 /* pipes are inserted between pairs of commands */
1774 if ((i + 1) < pi->num_progs) {
1775 if (pipe(pipefds) < 0)
1776 bb_perror_msg_and_die("pipe");
1777 nextout = pipefds[1];
1783 /* XXX test for failed fork()? */
1785 child->pid = fork();
1787 child->pid = vfork();
1789 if (!child->pid) { /* child */
1790 /* Every child adds itself to new process group
1791 * with pgid == pid of first child in pipe */
1793 if (interactive_fd) {
1794 /* Don't do pgrp restore anymore on fatal signals */
1795 set_fatal_sighandler(SIG_DFL);
1796 if (pi->pgrp < 0) /* true for 1st process only */
1797 pi->pgrp = getpid();
1798 if (setpgid(0, pi->pgrp) == 0 && pi->followup != PIPE_BG) {
1799 /* We do it in *every* child, not just first,
1801 tcsetpgrp(interactive_fd, pi->pgrp);
1805 // in non-interactive case fatal sigs are already SIG_DFL
1815 if (pipefds[0] != -1) {
1816 close(pipefds[0]); /* opposite end of our output pipe */
1818 /* Like bash, explicit redirects override pipes,
1819 * and the pipe fd is available for dup'ing. */
1820 setup_redirects(child, NULL);
1822 /* Restore default handlers just prior to exec */
1823 set_jobctrl_sighandler(SIG_DFL);
1824 set_misc_sighandler(SIG_DFL);
1825 signal(SIGCHLD, SIG_DFL);
1829 pi->running_progs++;
1832 /* Second and next children need to know pid of first one */
1834 pi->pgrp = child->pid;
1837 /* Don't check for errors. The child may be dead already,
1838 * in which case setpgid returns error code EACCES. */
1839 //why we do it at all?? child does it itself
1840 //if (interactive_fd)
1841 // setpgid(child->pid, pi->pgrp);
1848 /* If there isn't another process, nextin is garbage
1849 but it doesn't matter */
1850 nextin = pipefds[0];
1852 debug_printf_exec("run_pipe_real return -1\n");
1856 #ifndef debug_print_tree
1857 static void debug_print_tree(struct pipe *pi, int lvl)
1859 static const char *PIPE[] = {
1865 static const char *RES[] = {
1866 [RES_NONE ] = "NONE" ,
1868 [RES_THEN ] = "THEN" ,
1869 [RES_ELIF ] = "ELIF" ,
1870 [RES_ELSE ] = "ELSE" ,
1872 [RES_FOR ] = "FOR" ,
1873 [RES_WHILE] = "WHILE",
1874 [RES_UNTIL] = "UNTIL",
1876 [RES_DONE ] = "DONE" ,
1877 [RES_XXXX ] = "XXXX" ,
1879 [RES_SNTX ] = "SNTX" ,
1885 fprintf(stderr, "%*spipe %d r_mode=%s followup=%d %s\n", lvl*2, "",
1886 pin, RES[pi->r_mode], pi->followup, PIPE[pi->followup]);
1888 while (prn < pi->num_progs) {
1889 struct child_prog *child = &pi->progs[prn];
1890 char **argv = child->argv;
1892 fprintf(stderr, "%*s prog %d", lvl*2, "", prn);
1894 fprintf(stderr, " group %s: (argv=%p)\n",
1895 (child->subshell ? "()" : "{}"),
1897 debug_print_tree(child->group, lvl+1);
1901 if (argv) while (*argv) {
1902 fprintf(stderr, " '%s'", *argv);
1905 fprintf(stderr, "\n");
1914 // NB: called by pseudo_exec, and therefore must not modify any
1915 // global data until exec/_exit (we can be a child after vfork!)
1916 static int run_list_real(struct pipe *pi)
1924 char *for_varname = NULL;
1925 char **for_lcur = NULL;
1926 char **for_list = NULL;
1931 int rcode = 0; /* probably for gcc only */
1932 int flag_restore = 0;
1933 int if_code = 0, next_if_code = 0; /* need double-buffer to handle elif */
1934 reserved_style rmode, skip_more_in_this_rmode = RES_XXXX;
1936 debug_printf_exec("run_list_real start lvl %d\n", level + 1);
1938 /* check syntax for "for" */
1939 for (rpipe = pi; rpipe; rpipe = rpipe->next) {
1940 if ((rpipe->r_mode == RES_IN || rpipe->r_mode == RES_FOR)
1941 && (rpipe->next == NULL)
1943 syntax(); /* unterminated FOR (no IN or no commands after IN) */
1944 debug_printf_exec("run_list_real lvl %d return 1\n", level);
1947 if ((rpipe->r_mode == RES_IN && rpipe->next->r_mode == RES_IN && rpipe->next->progs[0].argv != NULL)
1948 || (rpipe->r_mode == RES_FOR && rpipe->next->r_mode != RES_IN)
1950 /* TODO: what is tested in the first condition? */
1951 syntax(); /* 2nd: malformed FOR (not followed by IN) */
1952 debug_printf_exec("run_list_real lvl %d return 1\n", level);
1958 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
1959 * We are saving state before entering outermost list ("while...done")
1960 * so that ctrl-Z will correctly background _entire_ outermost list,
1961 * not just a part of it (like "sleep 1 | exit 2") */
1962 if (++level == 1 && interactive_fd) {
1963 if (sigsetjmp(toplevel_jb, 1)) {
1964 /* ctrl-Z forked and we are parent; or ctrl-C.
1965 * Sighandler has longjmped us here */
1966 signal(SIGINT, SIG_IGN);
1967 signal(SIGTSTP, SIG_IGN);
1968 /* Restore level (we can be coming from deep inside
1971 #if ENABLE_FEATURE_SH_STANDALONE
1972 if (nofork_save.saved) { /* if save area is valid */
1973 debug_printf_jobs("exiting nofork early\n");
1974 restore_nofork_data(&nofork_save);
1978 /* ctrl-Z has forked and stored pid of the child in pi->pid.
1979 * Remember this child as background job */
1982 /* ctrl-C. We just stop doing whatever we were doing */
1988 /* ctrl-Z handler will store pid etc in pi */
1991 #if ENABLE_FEATURE_SH_STANDALONE
1992 nofork_save.saved = 0; /* in case we will run a nofork later */
1994 signal_SA_RESTART(SIGTSTP, handler_ctrl_z);
1995 signal(SIGINT, handler_ctrl_c);
1999 for (; pi; pi = flag_restore ? rpipe : pi->next) {
2001 if (rmode == RES_WHILE || rmode == RES_UNTIL || rmode == RES_FOR) {
2008 debug_printf_exec(": rmode=%d if_code=%d next_if_code=%d skip_more=%d\n",
2009 rmode, if_code, next_if_code, skip_more_in_this_rmode);
2010 if (rmode == skip_more_in_this_rmode && flag_skip) {
2011 if (pi->followup == PIPE_SEQ)
2016 skip_more_in_this_rmode = RES_XXXX;
2017 if (rmode == RES_THEN || rmode == RES_ELSE)
2018 if_code = next_if_code;
2019 if (rmode == RES_THEN && if_code)
2021 if (rmode == RES_ELSE && !if_code)
2023 if (rmode == RES_ELIF && !if_code)
2025 if (rmode == RES_FOR && pi->num_progs) {
2027 /* if no variable values after "in" we skip "for" */
2028 if (!pi->next->progs->argv)
2030 /* create list of variable values */
2031 for_list = do_variable_expansion(pi->next->progs->argv);
2032 for_lcur = for_list;
2033 for_varname = pi->progs->argv[0];
2034 pi->progs->argv[0] = NULL;
2037 free(pi->progs->argv[0]);
2042 pi->progs->argv[0] = for_varname;
2043 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
2046 /* insert next value from for_lcur */
2047 /* vda: does it need escaping? */
2048 pi->progs->argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
2049 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
2051 if (rmode == RES_IN)
2053 if (rmode == RES_DO) {
2057 if (rmode == RES_DONE) {
2064 if (pi->num_progs == 0)
2066 save_num_progs = pi->num_progs; /* save number of programs */
2067 debug_printf_exec(": run_pipe_real with %d members\n", pi->num_progs);
2068 rcode = run_pipe_real(pi);
2070 /* We only ran a builtin: rcode was set by the return value
2071 * of run_pipe_real(), and we don't need to wait for anything. */
2072 } else if (pi->followup == PIPE_BG) {
2073 /* What does bash do with attempts to background builtins? */
2075 /* Even bash 3.2 doesn't do that well with nested bg:
2076 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
2077 * I'm considering NOT treating inner bgs as jobs -
2078 * thus maybe "if (level == 1 && pi->followup == PIPE_BG)"
2083 rcode = EXIT_SUCCESS;
2086 /* Paranoia, just "interactive_fd" should be enough */
2087 if (level == 1 && interactive_fd) {
2088 rcode = checkjobs_and_fg_shell(pi);
2092 rcode = checkjobs(pi);
2094 debug_printf_exec(": checkjobs returned %d\n", rcode);
2096 debug_printf_exec(": setting last_return_code=%d\n", rcode);
2097 last_return_code = rcode;
2098 pi->num_progs = save_num_progs; /* restore number of programs */
2099 if (rmode == RES_IF || rmode == RES_ELIF)
2100 next_if_code = rcode; /* can be overwritten a number of times */
2101 if (rmode == RES_WHILE)
2102 flag_rep = !last_return_code;
2103 if (rmode == RES_UNTIL)
2104 flag_rep = last_return_code;
2105 if ((rcode == EXIT_SUCCESS && pi->followup == PIPE_OR)
2106 || (rcode != EXIT_SUCCESS && pi->followup == PIPE_AND)
2108 skip_more_in_this_rmode = rmode;
2115 /* ctrl-Z forked somewhere in the past, we are the child,
2116 * and now we completed running the list. Exit. */
2122 debug_printf_exec("run_list_real lvl %d return %d\n", level + 1, rcode);
2126 /* return code is the exit status of the pipe */
2127 static int free_pipe(struct pipe *pi, int indent)
2130 struct child_prog *child;
2131 struct redir_struct *r, *rnext;
2132 int a, i, ret_code = 0;
2134 if (pi->stopped_progs > 0)
2136 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2137 for (i = 0; i < pi->num_progs; i++) {
2138 child = &pi->progs[i];
2139 debug_printf_clean("%s command %d:\n", indenter(indent), i);
2141 for (a = 0, p = child->argv; *p; a++, p++) {
2142 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
2144 globfree(&child->glob_result);
2146 } else if (child->group) {
2147 debug_printf_clean("%s begin group (subshell:%d)\n", indenter(indent), child->subshell);
2148 ret_code = free_pipe_list(child->group, indent+3);
2149 debug_printf_clean("%s end group\n", indenter(indent));
2151 debug_printf_clean("%s (nil)\n", indenter(indent));
2153 for (r = child->redirects; r; r = rnext) {
2154 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->type].descrip);
2156 /* guard against the case >$FOO, where foo is unset or blank */
2157 if (r->word.gl_pathv) {
2158 debug_printf_clean(" %s\n", *r->word.gl_pathv);
2162 debug_printf_clean("&%d\n", r->dup);
2167 child->redirects = NULL;
2169 free(pi->progs); /* children are an array, they get freed all at once */
2178 static int free_pipe_list(struct pipe *head, int indent)
2180 int rcode = 0; /* if list has no members */
2181 struct pipe *pi, *next;
2183 for (pi = head; pi; pi = next) {
2184 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->r_mode);
2185 rcode = free_pipe(pi, indent);
2186 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
2188 /*pi->next = NULL;*/
2194 /* Select which version we will use */
2195 static int run_list(struct pipe *pi)
2198 debug_printf_exec("run_list entered\n");
2199 if (fake_mode == 0) {
2200 debug_printf_exec(": run_list_real with %d members\n", pi->num_progs);
2201 rcode = run_list_real(pi);
2203 /* free_pipe_list has the side effect of clearing memory.
2204 * In the long run that function can be merged with run_list_real,
2205 * but doing that now would hobble the debugging effort. */
2206 free_pipe_list(pi, 0);
2207 debug_printf_exec("run_list return %d\n", rcode);
2211 /* The API for glob is arguably broken. This routine pushes a non-matching
2212 * string into the output structure, removing non-backslashed backslashes.
2213 * If someone can prove me wrong, by performing this function within the
2214 * original glob(3) api, feel free to rewrite this routine into oblivion.
2215 * Return code (0 vs. GLOB_NOSPACE) matches glob(3).
2216 * XXX broken if the last character is '\\', check that before calling.
2218 static int globhack(const char *src, int flags, glob_t *pglob)
2223 for (cnt = 1, s = src; s && *s; s++) {
2224 if (*s == '\\') s++;
2229 return GLOB_NOSPACE;
2230 if (!(flags & GLOB_APPEND)) {
2231 pglob->gl_pathv = NULL;
2232 pglob->gl_pathc = 0;
2236 pathc = ++pglob->gl_pathc;
2237 pglob->gl_pathv = realloc(pglob->gl_pathv, (pathc+1) * sizeof(*pglob->gl_pathv));
2238 if (pglob->gl_pathv == NULL)
2239 return GLOB_NOSPACE;
2240 pglob->gl_pathv[pathc-1] = dest;
2241 pglob->gl_pathv[pathc] = NULL;
2242 for (s = src; s && *s; s++, dest++) {
2243 if (*s == '\\') s++;
2250 /* XXX broken if the last character is '\\', check that before calling */
2251 static int glob_needed(const char *s)
2254 if (*s == '\\') s++;
2255 if (strchr("*[?", *s)) return 1;
2260 static int xglob(o_string *dest, int flags, glob_t *pglob)
2264 /* short-circuit for null word */
2265 /* we can code this better when the debug_printf's are gone */
2266 if (dest->length == 0) {
2267 if (dest->nonnull) {
2268 /* bash man page calls this an "explicit" null */
2269 gr = globhack(dest->data, flags, pglob);
2270 debug_printf("globhack returned %d\n", gr);
2274 } else if (glob_needed(dest->data)) {
2275 gr = glob(dest->data, flags, NULL, pglob);
2276 debug_printf("glob returned %d\n", gr);
2277 if (gr == GLOB_NOMATCH) {
2278 /* quote removal, or more accurately, backslash removal */
2279 gr = globhack(dest->data, flags, pglob);
2280 debug_printf("globhack returned %d\n", gr);
2283 gr = globhack(dest->data, flags, pglob);
2284 debug_printf("globhack returned %d\n", gr);
2286 if (gr == GLOB_NOSPACE)
2287 bb_error_msg_and_die("out of memory during glob");
2288 if (gr != 0) { /* GLOB_ABORTED ? */
2289 bb_error_msg("glob(3) error %d", gr);
2291 /* globprint(glob_target); */
2296 /* do_variable_expansion() takes a list of strings, expands
2297 * all variable references within and returns a pointer to
2298 * a list of expanded strings, possibly with larger number
2299 * of strings. (Think VAR="a b"; echo $VAR).
2300 * This new list is allocated as a single malloc block.
2301 * NULL-terminated list of char* pointers is at the beginning of it,
2302 * followed by strings themself.
2303 * Caller can deallocate entire list by single free(list). */
2306 * count_XXX estimates size of the block we need. It's okay
2307 * to over-estimate sizes a bit, if it makes code simpler */
2308 static int count_ifs(const char *str)
2311 debug_printf_expand("count_ifs('%s') ifs='%s'", str, ifs);
2313 str += strcspn(str, ifs);
2315 str++; // str += strspn(str, ifs); ?
2316 cnt++; // cnt += strspn(str, ifs); ?
2318 debug_printf_expand(" return %d\n", cnt);
2322 static void count_var_expansion_space(int *countp, int *lenp, char *arg)
2327 int count = *countp;
2331 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2334 p = strchr(p, SPECIAL_VAR_SYMBOL);
2337 switch (first_ch & 0x7f) {
2338 /* high bit in 1st_ch indicates that var is double-quoted */
2340 case '!': /* bg pid */
2341 case '?': /* exitcode */
2342 case '#': /* argc */
2343 len += sizeof(int)*3 + 1; /* enough for int */
2347 for (i = 1; i < global_argc; i++) {
2348 len += strlen(global_argv[i]) + 1;
2350 if (!(first_ch & 0x80))
2351 count += count_ifs(global_argv[i]);
2356 arg[0] = first_ch & 0x7f;
2357 if (isdigit(arg[0])) {
2360 if (i < global_argc)
2361 val = global_argv[i];
2363 val = lookup_param(arg);
2365 *p = SPECIAL_VAR_SYMBOL;
2368 len += strlen(val) + 1;
2369 if (!(first_ch & 0x80))
2370 count += count_ifs(val);
2376 len += strlen(arg) + 1;
2382 /* Store given string, finalizing the word and starting new one whenever
2383 * we encounter ifs char(s). This is used for expanding variable values.
2384 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2385 static int expand_on_ifs(char **list, int n, char **posp, const char *str)
2389 int word_len = strcspn(str, ifs);
2391 memcpy(pos, str, word_len); /* store non-ifs chars */
2395 if (!*str) /* EOL - do not finalize word */
2398 if (n) debug_printf_expand("expand_on_ifs finalized list[%d]=%p '%s' "
2399 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2400 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2402 str += strspn(str, ifs); /* skip ifs chars */
2408 /* Expand all variable references in given string, adding words to list[]
2409 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2410 * to be filled). This routine is extremely tricky: has to deal with
2411 * variables/parameters with whitespace, $* and $@, and constructs like
2412 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2413 /* NB: another bug is that we cannot detect empty strings yet:
2414 * "" or $empty"" expands to zero words, has to expand to empty word */
2415 static int expand_vars_to_list(char **list, int n, char **posp, char *arg)
2417 char first_ch, ored_ch;
2425 if (n) debug_printf_expand("expand_vars_to_list finalized list[%d]=%p '%s' "
2426 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2427 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2430 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2431 memcpy(pos, arg, p - arg);
2434 p = strchr(p, SPECIAL_VAR_SYMBOL);
2437 ored_ch |= first_ch;
2439 switch (first_ch & 0x7f) {
2440 /* Highest bit in first_ch indicates that var is double-quoted */
2442 /* FIXME: (echo $$) should still print pid of main shell */
2443 val = utoa(getpid());
2445 case '!': /* bg pid */
2446 val = last_bg_pid ? utoa(last_bg_pid) : (char*)"";
2448 case '?': /* exitcode */
2449 val = utoa(last_return_code);
2451 case '#': /* argc */
2452 val = utoa(global_argc ? global_argc-1 : 0);
2457 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2458 while (i < global_argc) {
2459 n = expand_on_ifs(list, n, &pos, global_argv[i]);
2460 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, global_argc-1);
2461 if (global_argv[i++][0] && i < global_argc) {
2462 /* this argv[] is not empty and not last:
2463 * put terminating NUL, start new word */
2465 if (n) debug_printf_expand("expand_vars_to_list 2 finalized list[%d]=%p '%s' "
2466 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2467 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2471 } else if (first_ch == ('@'|0x80)) { /* quoted $@ */
2473 strcpy(pos, global_argv[i]);
2474 pos += strlen(global_argv[i]);
2475 if (++i >= global_argc)
2478 if (n) debug_printf_expand("expand_vars_to_list 3 finalized list[%d]=%p '%s' "
2479 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2480 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2483 } else { /* quoted $*: add as one word */
2485 strcpy(pos, global_argv[i]);
2486 pos += strlen(global_argv[i]);
2487 if (++i >= global_argc)
2496 arg[0] = first_ch & 0x7f;
2497 if (isdigit(arg[0])) {
2500 if (i < global_argc)
2501 val = global_argv[i];
2503 val = lookup_param(arg);
2505 *p = SPECIAL_VAR_SYMBOL;
2506 if (!(first_ch & 0x80)) { /* unquoted $VAR */
2508 n = expand_on_ifs(list, n, &pos, val);
2511 } /* else: quoted $VAR, val will be appended at pos */
2519 debug_printf_expand("expand_vars_to_list adding tail '%s' at %p\n", arg, pos);
2521 pos += strlen(arg) + 1;
2522 if (pos == list[n-1] + 1) { /* expansion is empty */
2523 if (!(ored_ch & 0x80)) { /* all vars were not quoted... */
2524 debug_printf_expand("expand_vars_to_list list[%d] empty, going back\n", n);
2534 static char **do_variable_expansion(char **argv)
2539 char *pos, **v, **list;
2542 if (!*v) debug_printf_expand("count_var_expansion_space: "
2543 "argv[0]=NULL count=%d len=%d alloc_space=%d\n",
2544 count, len, sizeof(char*) * count + len);
2546 count_var_expansion_space(&count, &len, *v);
2547 debug_printf_expand("count_var_expansion_space: "
2548 "'%s' count=%d len=%d alloc_space=%d\n",
2549 *v, count, len, sizeof(char*) * count + len);
2552 len += sizeof(char*) * count; /* total to alloc */
2553 list = xmalloc(len);
2554 pos = (char*)(list + count);
2555 debug_printf_expand("list=%p, list[0] should be %p\n", list, pos);
2559 n = expand_vars_to_list(list, n, &pos, *v++);
2561 if(n) debug_printf_expand("finalized list[%d]=%p '%s' "
2562 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2563 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2570 debug_printf_expand("list[%d]=%p '%s'\n", m, list[m], list[m]);
2573 debug_printf_expand("used_space=%d\n", pos - (char*)list);
2576 /* To be removed / made conditional later. */
2577 if (pos - (char*)list > len)
2578 bb_error_msg_and_die("BUG in varexp");
2583 static char *insert_var_value(char *inp)
2585 int res_str_len = 0;
2591 char *res_str = NULL;
2593 while ((p = strchr(inp, SPECIAL_VAR_SYMBOL))) {
2596 res_str = xrealloc(res_str, (res_str_len + len));
2597 strncpy((res_str + res_str_len), inp, len);
2601 p = strchr(inp, SPECIAL_VAR_SYMBOL);
2606 /* FIXME: (echo $$) should still print pid of main shell */
2607 p1 = utoa(getpid());
2610 p1 = last_bg_pid ? utoa(last_bg_pid) : (char*)"";
2613 p1 = utoa(last_return_code);
2616 p1 = utoa(global_argc ? global_argc-1 : 0);
2619 case '@': /* FIXME: we treat $@ as $* for now */
2621 for (i = 1; i < global_argc; i++)
2622 len += strlen(global_argv[i]) + 1;
2623 p1 = p2 = alloca(--len);
2624 for (i = 1; i < global_argc; i++) {
2625 strcpy(p2, global_argv[i]);
2626 p2 += strlen(global_argv[i]);
2632 p1 = lookup_param(inp);
2636 len = res_str_len + strlen(p1);
2637 res_str = xrealloc(res_str, 1 + len);
2638 strcpy(res_str + res_str_len, p1);
2641 *p = SPECIAL_VAR_SYMBOL;
2646 res_str = xrealloc(res_str, (1 + res_str_len + strlen(inp)));
2647 strcpy((res_str + res_str_len), inp);
2648 while ((p = strchr(res_str, '\n'))) {
2652 return (res_str == NULL) ? inp : res_str;
2656 /* This is used to get/check local shell variables */
2657 static const char *get_local_var(const char *s)
2659 struct variables *cur;
2663 for (cur = top_vars; cur; cur = cur->next) {
2664 if (strcmp(cur->name, s) == 0)
2670 /* This is used to set local shell variables
2671 flg_export == 0 if only local (not exporting) variable
2672 flg_export == 1 if "new" exporting environ
2673 flg_export > 1 if current startup environ (not call putenv()) */
2674 static int set_local_var(const char *s, int flg_export)
2678 struct variables *cur;
2682 /* Assume when we enter this function that we are already in
2683 * NAME=VALUE format. So the first order of business is to
2684 * split 's' on the '=' into 'name' and 'value' */
2685 value = strchr(name, '=');
2686 /*if (value == 0 && ++value == 0) ??? -vda */
2687 if (value == NULL || value[1] == '\0') {
2693 for (cur = top_vars; cur; cur = cur->next) {
2694 if (strcmp(cur->name, name) == 0) {
2695 if (strcmp(cur->value, value) == 0) {
2696 if (flg_export && !cur->flg_export)
2697 cur->flg_export = flg_export;
2700 } else if (cur->flg_read_only) {
2701 bb_error_msg("%s: readonly variable", name);
2704 if (flg_export > 0 || cur->flg_export > 1)
2705 cur->flg_export = 1;
2706 free((char*)cur->value);
2707 cur->value = strdup(value);
2713 // TODO: need simpler/generic rollback on malloc failure - see ash
2714 cur = malloc(sizeof(*cur));
2718 cur->name = strdup(name);
2723 struct variables *bottom = top_vars;
2724 cur->value = strdup(value);
2726 cur->flg_export = flg_export;
2727 cur->flg_read_only = 0;
2728 while (bottom->next)
2729 bottom = bottom->next;
2734 if (result == 0 && cur->flg_export == 1) {
2736 result = putenv(name);
2739 if (result > 0) /* equivalent to previous set */
2745 static void unset_local_var(const char *name)
2747 struct variables *cur, *next;
2751 for (cur = top_vars; cur; cur = cur->next) {
2752 if (strcmp(cur->name, name) == 0) {
2753 if (cur->flg_read_only) {
2754 bb_error_msg("%s: readonly variable", name);
2757 if (cur->flg_export)
2758 unsetenv(cur->name);
2759 free((char*)cur->name);
2760 free((char*)cur->value);
2762 while (next->next != cur)
2764 next->next = cur->next;
2771 static int is_assignment(const char *s)
2773 if (!s || !isalpha(*s))
2776 while (isalnum(*s) || *s == '_')
2781 /* the src parameter allows us to peek forward to a possible &n syntax
2782 * for file descriptor duplication, e.g., "2>&1".
2783 * Return code is 0 normally, 1 if a syntax error is detected in src.
2784 * Resource errors (in xmalloc) cause the process to exit */
2785 static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2786 struct in_str *input)
2788 struct child_prog *child = ctx->child;
2789 struct redir_struct *redir = child->redirects;
2790 struct redir_struct *last_redir = NULL;
2792 /* Create a new redir_struct and drop it onto the end of the linked list */
2795 redir = redir->next;
2797 redir = xmalloc(sizeof(struct redir_struct));
2799 redir->word.gl_pathv = NULL;
2801 last_redir->next = redir;
2803 child->redirects = redir;
2806 redir->type = style;
2807 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
2809 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2811 /* Check for a '2>&1' type redirect */
2812 redir->dup = redirect_dup_num(input);
2813 if (redir->dup == -2) return 1; /* syntax error */
2814 if (redir->dup != -1) {
2815 /* Erik had a check here that the file descriptor in question
2816 * is legit; I postpone that to "run time"
2817 * A "-" representation of "close me" shows up as a -3 here */
2818 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2820 /* We do _not_ try to open the file that src points to,
2821 * since we need to return and let src be expanded first.
2822 * Set ctx->pending_redirect, so we know what to do at the
2823 * end of the next parsed word.
2825 ctx->pending_redirect = redir;
2830 static struct pipe *new_pipe(void)
2833 pi = xzalloc(sizeof(struct pipe));
2834 /*pi->num_progs = 0;*/
2835 /*pi->progs = NULL;*/
2836 /*pi->next = NULL;*/
2837 /*pi->followup = 0; invalid */
2839 pi->r_mode = RES_NONE;
2843 static void initialize_context(struct p_context *ctx)
2846 ctx->pending_redirect = NULL;
2848 ctx->list_head = new_pipe();
2849 ctx->pipe = ctx->list_head;
2850 ctx->res_w = RES_NONE;
2853 done_command(ctx); /* creates the memory for working child */
2856 /* normal return is 0
2857 * if a reserved word is found, and processed, return 1
2858 * should handle if, then, elif, else, fi, for, while, until, do, done.
2859 * case, function, and select are obnoxious, save those for later.
2861 static int reserved_word(o_string *dest, struct p_context *ctx)
2863 struct reserved_combo {
2868 /* Mostly a list of accepted follow-up reserved words.
2869 * FLAG_END means we are done with the sequence, and are ready
2870 * to turn the compound list into a command.
2871 * FLAG_START means the word must start a new compound list.
2873 static const struct reserved_combo reserved_list[] = {
2874 { "if", RES_IF, FLAG_THEN | FLAG_START },
2875 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2876 { "elif", RES_ELIF, FLAG_THEN },
2877 { "else", RES_ELSE, FLAG_FI },
2878 { "fi", RES_FI, FLAG_END },
2879 { "for", RES_FOR, FLAG_IN | FLAG_START },
2880 { "while", RES_WHILE, FLAG_DO | FLAG_START },
2881 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
2882 { "in", RES_IN, FLAG_DO },
2883 { "do", RES_DO, FLAG_DONE },
2884 { "done", RES_DONE, FLAG_END }
2886 enum { NRES = sizeof(reserved_list)/sizeof(reserved_list[0]) };
2887 const struct reserved_combo *r;
2889 for (r = reserved_list; r < reserved_list + NRES; r++) {
2890 if (strcmp(dest->data, r->literal) == 0) {
2891 debug_printf("found reserved word %s, code %d\n", r->literal, r->code);
2892 if (r->flag & FLAG_START) {
2893 struct p_context *new = xmalloc(sizeof(struct p_context));
2894 debug_printf("push stack\n");
2895 if (ctx->res_w == RES_IN || ctx->res_w == RES_FOR) {
2898 ctx->res_w = RES_SNTX;
2902 *new = *ctx; /* physical copy */
2903 initialize_context(ctx);
2905 } else if (ctx->res_w == RES_NONE || !(ctx->old_flag & (1 << r->code))) {
2907 ctx->res_w = RES_SNTX;
2911 ctx->res_w = r->code;
2912 ctx->old_flag = r->flag;
2913 if (ctx->old_flag & FLAG_END) {
2914 struct p_context *old;
2915 debug_printf("pop stack\n");
2916 done_pipe(ctx, PIPE_SEQ);
2918 old->child->group = ctx->list_head;
2919 old->child->subshell = 0;
2920 *ctx = *old; /* physical copy */
2930 /* Normal return is 0.
2931 * Syntax or xglob errors return 1. */
2932 static int done_word(o_string *dest, struct p_context *ctx)
2934 struct child_prog *child = ctx->child;
2935 glob_t *glob_target;
2938 debug_printf_parse("done_word entered: '%s' %p\n", dest->data, child);
2939 if (dest->length == 0 && !dest->nonnull) {
2940 debug_printf_parse("done_word return 0: true null, ignored\n");
2943 if (ctx->pending_redirect) {
2944 glob_target = &ctx->pending_redirect->word;
2948 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
2951 if (!child->argv && (ctx->parse_type & FLAG_PARSE_SEMICOLON)) {
2952 debug_printf_parse(": checking '%s' for reserved-ness\n", dest->data);
2953 if (reserved_word(dest, ctx)) {
2954 debug_printf_parse("done_word return %d\n", (ctx->res_w == RES_SNTX));
2955 return (ctx->res_w == RES_SNTX);
2958 glob_target = &child->glob_result;
2960 flags |= GLOB_APPEND;
2962 gr = xglob(dest, flags, glob_target);
2964 debug_printf_parse("done_word return 1: xglob returned %d\n", gr);
2969 if (ctx->pending_redirect) {
2970 ctx->pending_redirect = NULL;
2971 if (glob_target->gl_pathc != 1) {
2972 bb_error_msg("ambiguous redirect");
2973 debug_printf_parse("done_word return 1: ambiguous redirect\n");
2977 child->argv = glob_target->gl_pathv;
2979 if (ctx->res_w == RES_FOR) {
2980 done_word(dest, ctx);
2981 done_pipe(ctx, PIPE_SEQ);
2983 debug_printf_parse("done_word return 0\n");
2987 /* The only possible error here is out of memory, in which case
2989 static int done_command(struct p_context *ctx)
2991 /* The child is really already in the pipe structure, so
2992 * advance the pipe counter and make a new, null child. */
2993 struct pipe *pi = ctx->pipe;
2994 struct child_prog *child = ctx->child;
2997 if (child->group == NULL
2998 && child->argv == NULL
2999 && child->redirects == NULL
3001 debug_printf_parse("done_command: skipping null cmd, num_progs=%d\n", pi->num_progs);
3002 return pi->num_progs;
3005 debug_printf_parse("done_command: ++num_progs=%d\n", pi->num_progs);
3007 debug_printf_parse("done_command: initializing, num_progs=%d\n", pi->num_progs);
3010 /* Only real trickiness here is that the uncommitted
3011 * child structure is not counted in pi->num_progs. */
3012 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
3013 child = &pi->progs[pi->num_progs];
3015 memset(child, 0, sizeof(*child));
3016 /*child->redirects = NULL;*/
3017 /*child->argv = NULL;*/
3018 /*child->is_stopped = 0;*/
3019 /*child->group = NULL;*/
3020 /*child->glob_result.gl_pathv = NULL;*/
3023 child->type = ctx->parse_type;
3026 /* but ctx->pipe and ctx->list_head remain unchanged */
3028 return pi->num_progs; /* used only for 0/nonzero check */
3031 static int done_pipe(struct p_context *ctx, pipe_style type)
3036 debug_printf_parse("done_pipe entered, followup %d\n", type);
3037 not_null = done_command(ctx); /* implicit closure of previous command */
3038 ctx->pipe->followup = type;
3039 ctx->pipe->r_mode = ctx->res_w;
3040 /* Without this check, even just <enter> on command line generates
3041 * tree of three NOPs (!). Which is harmless but annoying.
3042 * IOW: it is safe to do it unconditionally. */
3045 ctx->pipe->next = new_p;
3048 done_command(ctx); /* set up new pipe to accept commands */
3050 debug_printf_parse("done_pipe return 0\n");
3054 /* peek ahead in the in_str to find out if we have a "&n" construct,
3055 * as in "2>&1", that represents duplicating a file descriptor.
3056 * returns either -2 (syntax error), -1 (no &), or the number found.
3058 static int redirect_dup_num(struct in_str *input)
3060 int ch, d = 0, ok = 0;
3062 if (ch != '&') return -1;
3064 b_getch(input); /* get the & */
3068 return -3; /* "-" represents "close me" */
3070 while (isdigit(ch)) {
3071 d = d*10 + (ch-'0');
3078 bb_error_msg("ambiguous redirect");
3082 /* If a redirect is immediately preceded by a number, that number is
3083 * supposed to tell which file descriptor to redirect. This routine
3084 * looks for such preceding numbers. In an ideal world this routine
3085 * needs to handle all the following classes of redirects...
3086 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3087 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3088 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3089 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3090 * A -1 output from this program means no valid number was found, so the
3091 * caller should use the appropriate default for this redirection.
3093 static int redirect_opt_num(o_string *o)
3099 for (num = 0; num < o->length; num++) {
3100 if (!isdigit(*(o->data + num))) {
3104 /* reuse num (and save an int) */
3105 num = atoi(o->data);
3110 static FILE *generate_stream_from_list(struct pipe *head)
3113 int pid, channel[2];
3114 if (pipe(channel) < 0) bb_perror_msg_and_die("pipe");
3121 bb_perror_msg_and_die("fork");
3122 } else if (pid == 0) {
3124 if (channel[1] != 1) {
3125 dup2(channel[1], 1);
3128 _exit(run_list_real(head)); /* leaks memory */
3130 debug_printf("forked child %d\n", pid);
3132 pf = fdopen(channel[0], "r");
3133 debug_printf("pipe on FILE *%p\n", pf);
3137 /* Return code is exit status of the process that is run. */
3138 static int process_command_subs(o_string *dest, struct p_context *ctx,
3139 struct in_str *input, const char *subst_end)
3141 int retcode, ch, eol_cnt;
3142 o_string result = NULL_O_STRING;
3143 struct p_context inner;
3145 struct in_str pipe_str;
3147 initialize_context(&inner);
3149 /* recursion to generate command */
3150 retcode = parse_stream(&result, &inner, input, subst_end);
3151 if (retcode != 0) return retcode; /* syntax error or EOF */
3152 done_word(&result, &inner);
3153 done_pipe(&inner, PIPE_SEQ);
3156 p = generate_stream_from_list(inner.list_head);
3157 if (p == NULL) return 1;
3158 mark_open(fileno(p));
3159 setup_file_in_str(&pipe_str, p);
3161 /* now send results of command back into original context */
3163 while ((ch = b_getch(&pipe_str)) != EOF) {
3169 b_addqchr(dest, '\n', dest->quote);
3172 b_addqchr(dest, ch, dest->quote);
3175 debug_printf("done reading from pipe, pclose()ing\n");
3176 /* This is the step that wait()s for the child. Should be pretty
3177 * safe, since we just read an EOF from its stdout. We could try
3178 * to better, by using wait(), and keeping track of background jobs
3179 * at the same time. That would be a lot of work, and contrary
3180 * to the KISS philosophy of this program. */
3181 mark_closed(fileno(p));
3182 retcode = pclose(p);
3183 free_pipe_list(inner.list_head, 0);
3184 debug_printf("pclosed, retcode=%d\n", retcode);
3188 static int parse_group(o_string *dest, struct p_context *ctx,
3189 struct in_str *input, int ch)
3192 const char *endch = NULL;
3193 struct p_context sub;
3194 struct child_prog *child = ctx->child;
3196 debug_printf_parse("parse_group entered\n");
3199 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3202 initialize_context(&sub);
3206 child->subshell = 1;
3212 syntax(); /* really logic error */
3214 rcode = parse_stream(dest, &sub, input, endch);
3215 done_word(dest, &sub); /* finish off the final word in the subcontext */
3216 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
3217 child->group = sub.list_head;
3219 debug_printf_parse("parse_group return %d\n", rcode);
3221 /* child remains "open", available for possible redirects */
3224 /* Basically useful version until someone wants to get fancier,
3225 * see the bash man page under "Parameter Expansion" */
3226 static const char *lookup_param(const char *src)
3228 const char *p = NULL;
3232 p = get_local_var(src);
3237 /* Make new string for parser */
3238 static char* make_string(char **inp)
3246 for (n = 0; inp[n]; n++) {
3247 p = insert_var_value(inp[n]);
3248 val_len = strlen(p);
3249 str = xrealloc(str, len + val_len + 3); /* +3: space, '\n', <nul>*/
3251 strcpy(str + len, p);
3253 if (p != inp[n]) free(p);
3255 /* We do not check for case where loop had no iterations at all
3256 * - cannot happen? */
3262 /* return code: 0 for OK, 1 for syntax error */
3263 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
3265 int ch = b_peek(input); /* first character after the $ */
3266 unsigned char quote_mask = dest->quote ? 0x80 : 0;
3268 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
3270 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3273 debug_printf_parse(": '%c'\n", ch);
3275 b_addchr(dest, ch | quote_mask);
3278 if (!isalnum(ch) && ch != '_')
3281 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3282 } else if (isdigit(ch)) {
3284 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3286 debug_printf_parse(": '%c'\n", ch);
3288 b_addchr(dest, ch | quote_mask);
3289 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3290 } else switch (ch) {
3292 case '!': /* last bg pid */
3293 case '?': /* last exit code */
3294 case '#': /* number of args */
3295 case '*': /* args */
3296 case '@': /* args */
3297 goto make_one_char_var;
3299 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3302 /* XXX maybe someone will try to escape the '}' */
3304 ch = b_getch(input);
3307 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3312 debug_printf_parse(": '%c'\n", ch);
3313 b_addchr(dest, ch | quote_mask);
3316 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3320 process_command_subs(dest, ctx, input, ")");
3324 /* still unhandled, but should be eventually */
3325 bb_error_msg("unhandled syntax: $%c", ch);
3329 b_addqchr(dest, '$', dest->quote);
3331 debug_printf_parse("handle_dollar return 0\n");
3335 //static int parse_string(o_string *dest, struct p_context *ctx, const char *src)
3337 // struct in_str foo;
3338 // setup_string_in_str(&foo, src);
3339 // return parse_stream(dest, ctx, &foo, NULL);
3342 /* return code is 0 for normal exit, 1 for syntax error */
3343 static int parse_stream(o_string *dest, struct p_context *ctx,
3344 struct in_str *input, const char *end_trigger)
3348 redir_type redir_style;
3351 /* Only double-quote state is handled in the state variable dest->quote.
3352 * A single-quote triggers a bypass of the main loop until its mate is
3353 * found. When recursing, quote state is passed in via dest->quote. */
3355 debug_printf_parse("parse_stream entered, end_trigger='%s'\n", end_trigger);
3357 while ((ch = b_getch(input)) != EOF) {
3359 next = (ch == '\n') ? '\0' : b_peek(input);
3360 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
3361 ch, ch, m, dest->quote);
3362 if (m == CHAR_ORDINARY
3363 || (m != CHAR_SPECIAL && dest->quote)
3365 b_addqchr(dest, ch, dest->quote);
3368 if (m == CHAR_IFS) {
3369 if (done_word(dest, ctx)) {
3370 debug_printf_parse("parse_stream return 1: done_word!=0\n");
3373 /* If we aren't performing a substitution, treat
3374 * a newline as a command separator.
3375 * [why we don't handle it exactly like ';'? --vda] */
3376 if (end_trigger && ch == '\n') {
3377 done_pipe(ctx, PIPE_SEQ);
3380 if ((end_trigger && strchr(end_trigger, ch))
3381 && !dest->quote && ctx->res_w == RES_NONE
3383 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
3390 if (dest->length == 0 && !dest->quote) {
3393 if (ch == EOF || ch == '\n')
3398 b_addqchr(dest, ch, dest->quote);
3404 debug_printf_parse("parse_stream return 1: \\<eof>\n");
3407 b_addqchr(dest, '\\', dest->quote);
3408 b_addqchr(dest, b_getch(input), dest->quote);
3411 if (handle_dollar(dest, ctx, input) != 0) {
3412 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3419 ch = b_getch(input);
3420 if (ch == EOF || ch == '\'')
3426 debug_printf_parse("parse_stream return 1: unterminated '\n");
3432 dest->quote = !dest->quote;
3435 process_command_subs(dest, ctx, input, "`");
3438 redir_fd = redirect_opt_num(dest);
3439 done_word(dest, ctx);
3440 redir_style = REDIRECT_OVERWRITE;
3442 redir_style = REDIRECT_APPEND;
3444 } else if (next == '(') {
3445 syntax(); /* until we support >(list) Process Substitution */
3446 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
3449 setup_redirect(ctx, redir_fd, redir_style, input);
3452 redir_fd = redirect_opt_num(dest);
3453 done_word(dest, ctx);
3454 redir_style = REDIRECT_INPUT;
3456 redir_style = REDIRECT_HEREIS;
3458 } else if (next == '>') {
3459 redir_style = REDIRECT_IO;
3461 } else if (next == '(') {
3462 syntax(); /* until we support <(list) Process Substitution */
3463 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
3466 setup_redirect(ctx, redir_fd, redir_style, input);
3469 done_word(dest, ctx);
3470 done_pipe(ctx, PIPE_SEQ);
3473 done_word(dest, ctx);
3476 done_pipe(ctx, PIPE_AND);
3478 done_pipe(ctx, PIPE_BG);
3482 done_word(dest, ctx);
3485 done_pipe(ctx, PIPE_OR);
3487 /* we could pick up a file descriptor choice here
3488 * with redirect_opt_num(), but bash doesn't do it.
3489 * "echo foo 2| cat" yields "foo 2". */
3495 if (parse_group(dest, ctx, input, ch) != 0) {
3496 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
3502 syntax(); /* Proper use of this character is caught by end_trigger */
3503 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
3506 syntax(); /* this is really an internal logic error */
3507 debug_printf_parse("parse_stream return 1: internal logic error\n");
3511 /* Complain if quote? No, maybe we just finished a command substitution
3512 * that was quoted. Example:
3513 * $ echo "`cat foo` plus more"
3514 * and we just got the EOF generated by the subshell that ran "cat foo"
3515 * The only real complaint is if we got an EOF when end_trigger != NULL,
3516 * that is, we were really supposed to get end_trigger, and never got
3517 * one before the EOF. Can't use the standard "syntax error" return code,
3518 * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
3519 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
3525 static void set_in_charmap(const char *set, int code)
3528 charmap[(unsigned char)*set++] = code;
3531 static void update_charmap(void)
3533 /* char *ifs and char charmap[256] are both globals. */
3534 ifs = getenv("IFS");
3537 /* Precompute a list of 'flow through' behavior so it can be treated
3538 * quickly up front. Computation is necessary because of IFS.
3539 * Special case handling of IFS == " \t\n" is not implemented.
3540 * The charmap[] array only really needs two bits each,
3541 * and on most machines that would be faster (reduced L1 cache use).
3543 memset(charmap, CHAR_ORDINARY, sizeof(charmap));
3544 set_in_charmap("\\$\"`", CHAR_SPECIAL);
3545 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
3546 set_in_charmap(ifs, CHAR_IFS); /* also flow through if quoted */
3549 /* most recursion does not come through here, the exception is
3550 * from builtin_source() */
3551 static int parse_stream_outer(struct in_str *inp, int parse_flag)
3553 struct p_context ctx;
3554 o_string temp = NULL_O_STRING;
3557 ctx.parse_type = parse_flag;
3558 initialize_context(&ctx);
3560 if (!(parse_flag & FLAG_PARSE_SEMICOLON) || (parse_flag & FLAG_REPARSING))
3561 set_in_charmap(";$&|", CHAR_ORDINARY);
3562 #if ENABLE_HUSH_INTERACTIVE
3563 inp->promptmode = 1;
3565 /* We will stop & execute after each ';' or '\n'.
3566 * Example: "sleep 9999; echo TEST" + ctrl-C:
3567 * TEST should be printed */
3568 rcode = parse_stream(&temp, &ctx, inp, ";\n");
3569 if (rcode != 1 && ctx.old_flag != 0) {
3572 if (rcode != 1 && ctx.old_flag == 0) {
3573 done_word(&temp, &ctx);
3574 done_pipe(&ctx, PIPE_SEQ);
3575 debug_print_tree(ctx.list_head, 0);
3576 debug_printf_exec("parse_stream_outer: run_list\n");
3577 run_list(ctx.list_head);
3579 if (ctx.old_flag != 0) {
3586 free_pipe_list(ctx.list_head, 0);
3589 } while (rcode != -1 && !(parse_flag & FLAG_EXIT_FROM_LOOP)); /* loop on syntax errors, return on EOF */
3593 static int parse_string_outer(const char *s, int parse_flag)
3595 struct in_str input;
3596 setup_string_in_str(&input, s);
3597 return parse_stream_outer(&input, parse_flag);
3600 static int parse_file_outer(FILE *f)
3603 struct in_str input;
3604 setup_file_in_str(&input, f);
3605 rcode = parse_stream_outer(&input, FLAG_PARSE_SEMICOLON);
3610 /* Make sure we have a controlling tty. If we get started under a job
3611 * aware app (like bash for example), make sure we are now in charge so
3612 * we don't fight over who gets the foreground */
3613 static void setup_job_control(void)
3617 saved_task_pgrp = shell_pgrp = getpgrp();
3618 debug_printf_jobs("saved_task_pgrp=%d\n", saved_task_pgrp);
3619 fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
3621 /* If we were ran as 'hush &',
3622 * sleep until we are in the foreground. */
3623 while (tcgetpgrp(interactive_fd) != shell_pgrp) {
3624 /* Send TTIN to ourself (should stop us) */
3625 kill(- shell_pgrp, SIGTTIN);
3626 shell_pgrp = getpgrp();
3629 /* Ignore job-control and misc signals. */
3630 set_jobctrl_sighandler(SIG_IGN);
3631 set_misc_sighandler(SIG_IGN);
3632 //huh? signal(SIGCHLD, SIG_IGN);
3634 /* We _must_ restore tty pgrp on fatal signals */
3635 set_fatal_sighandler(sigexit);
3637 /* Put ourselves in our own process group. */
3638 setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
3639 /* Grab control of the terminal. */
3640 tcsetpgrp(interactive_fd, getpid());
3644 int hush_main(int argc, char **argv);
3645 int hush_main(int argc, char **argv)
3651 #if ENABLE_FEATURE_EDITING
3652 line_input_state = new_line_input_t(FOR_SHELL);
3655 /* XXX what should these be while sourcing /etc/profile? */
3659 /* (re?) initialize globals. Sometimes hush_main() ends up calling
3660 * hush_main(), therefore we cannot rely on the BSS to zero out this
3661 * stuff. Reset these to 0 every time. */
3663 /* charmap[] is taken care of with call to update_charmap() */
3665 close_me_head = NULL;
3666 #if ENABLE_HUSH_INTERACTIVE
3675 /* Initialize some more globals to non-zero values */
3677 #if ENABLE_HUSH_INTERACTIVE
3678 #if ENABLE_FEATURE_EDITING
3679 cmdedit_set_initial_prompt();
3685 /* initialize our shell local variables with the values
3686 * currently living in the environment */
3690 set_local_var(*e++, 2); /* without call putenv() */
3692 last_return_code = EXIT_SUCCESS;
3694 if (argv[0] && argv[0][0] == '-') {
3695 debug_printf("sourcing /etc/profile\n");
3696 input = fopen("/etc/profile", "r");
3697 if (input != NULL) {
3698 mark_open(fileno(input));
3699 parse_file_outer(input);
3700 mark_closed(fileno(input));
3706 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
3709 global_argv = argv + optind;
3710 global_argc = argc - optind;
3711 opt = parse_string_outer(optarg, FLAG_PARSE_SEMICOLON);
3714 // Well, we cannot just declare interactiveness,
3715 // we have to have some stuff (ctty, etc)
3716 /*interactive_fd++;*/
3723 fprintf(stderr, "Usage: sh [FILE]...\n"
3724 " or: sh -c command [args]...\n\n");
3732 /* A shell is interactive if the '-i' flag was given, or if all of
3733 * the following conditions are met:
3735 * no arguments remaining or the -s flag given
3736 * standard input is a terminal
3737 * standard output is a terminal
3738 * Refer to Posix.2, the description of the 'sh' utility. */
3739 if (argv[optind] == NULL && input == stdin
3740 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3742 saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
3743 debug_printf("saved_tty_pgrp=%d\n", saved_tty_pgrp);
3744 if (saved_tty_pgrp >= 0) {
3745 /* try to dup to high fd#, >= 255 */
3746 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3747 if (interactive_fd < 0) {
3748 /* try to dup to any fd */
3749 interactive_fd = dup(STDIN_FILENO);
3750 if (interactive_fd < 0)
3754 // TODO: track & disallow any attempts of user
3755 // to (inadvertently) close/redirect it
3758 debug_printf("interactive_fd=%d\n", interactive_fd);
3759 if (interactive_fd) {
3760 /* Looks like they want an interactive shell */
3761 setup_job_control();
3762 /* Make xfuncs do cleanup on exit */
3763 die_sleep = -1; /* flag */
3764 // FIXME: should we reset die_sleep = 0 whereever we fork?
3765 if (setjmp(die_jmp)) {
3766 /* xfunc has failed! die die die */
3767 hush_exit(xfunc_error_retval);
3769 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
3770 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", BB_BANNER);
3771 printf("Enter 'help' for a list of built-in commands.\n\n");
3774 #elif ENABLE_HUSH_INTERACTIVE
3775 /* no job control compiled, only prompt/line editing */
3776 if (argv[optind] == NULL && input == stdin
3777 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3779 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3780 if (interactive_fd < 0) {
3781 /* try to dup to any fd */
3782 interactive_fd = dup(STDIN_FILENO);
3783 if (interactive_fd < 0)
3791 if (argv[optind] == NULL) {
3792 opt = parse_file_outer(stdin);
3796 debug_printf("\nrunning script '%s'\n", argv[optind]);
3797 global_argv = argv + optind;
3798 global_argc = argc - optind;
3799 input = xfopen(argv[optind], "r");
3800 opt = parse_file_outer(input);
3802 #if ENABLE_FEATURE_CLEAN_UP
3804 if (cwd != bb_msg_unknown)
3807 struct variables *cur, *tmp;
3808 for (cur = top_vars; cur; cur = tmp) {
3810 if (!cur->flg_read_only) {
3811 free((char*)cur->name);
3812 free((char*)cur->value);
3820 hush_exit(opt ? opt : last_return_code);