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
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 map[] 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 */
84 /* #include <dmalloc.h> */
86 /* Finer-grained debug switch */
87 //#define DEBUG_SHELL_JOBS
90 #define SPECIAL_VAR_SYMBOL 03
91 #define FLAG_EXIT_FROM_LOOP 1
92 #define FLAG_PARSE_SEMICOLON (1 << 1) /* symbol ';' is special for parser */
93 #define FLAG_REPARSING (1 << 2) /* >=2nd pass */
97 REDIRECT_OVERWRITE = 2,
103 /* The descrip member of this structure is only used to make debugging
105 static const struct {
111 { O_RDONLY, 0, "<" },
112 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
113 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
114 { O_RDONLY, -1, "<<" },
125 /* might eventually control execution */
143 FLAG_END = (1 << RES_NONE ),
144 FLAG_IF = (1 << RES_IF ),
145 FLAG_THEN = (1 << RES_THEN ),
146 FLAG_ELIF = (1 << RES_ELIF ),
147 FLAG_ELSE = (1 << RES_ELSE ),
148 FLAG_FI = (1 << RES_FI ),
149 FLAG_FOR = (1 << RES_FOR ),
150 FLAG_WHILE = (1 << RES_WHILE),
151 FLAG_UNTIL = (1 << RES_UNTIL),
152 FLAG_DO = (1 << RES_DO ),
153 FLAG_DONE = (1 << RES_DONE ),
154 FLAG_IN = (1 << RES_IN ),
155 FLAG_START = (1 << RES_XXXX ),
158 /* This holds pointers to the various results of parsing */
160 struct child_prog *child;
161 struct pipe *list_head;
163 struct redir_struct *pending_redirect;
165 int old_flag; /* for figuring out valid reserved words */
166 struct p_context *stack;
167 int type; /* define type of parser : ";$" common or special symbol */
168 /* How about quoting status? */
171 struct redir_struct {
172 redir_type type; /* type of redirection */
173 int fd; /* file descriptor being redirected */
174 int dup; /* -1, or file descriptor being duplicated */
175 struct redir_struct *next; /* pointer to the next redirect in the list */
176 glob_t word; /* *word.gl_pathv is the filename */
180 pid_t pid; /* 0 if exited */
181 char **argv; /* program name and arguments */
182 struct pipe *group; /* if non-NULL, first in group or subshell */
183 int subshell; /* flag, non-zero if group must be forked */
184 struct redir_struct *redirects; /* I/O redirections */
185 glob_t glob_result; /* result of parameter globbing */
186 int is_stopped; /* is the program currently running? */
187 struct pipe *family; /* pointer back to the child's parent pipe */
188 int sp; /* number of SPECIAL_VAR_SYMBOL */
193 int jobid; /* job number */
194 int num_progs; /* total number of programs in job */
195 int running_progs; /* number of programs running (not exited) */
196 char *text; /* name of job */
197 char *cmdbuf; /* buffer various argv's point into */
198 pid_t pgrp; /* process group ID for the job */
199 struct child_prog *progs; /* array of commands in pipe */
200 struct pipe *next; /* to track background commands */
201 int stopped_progs; /* number of programs alive, but stopped */
202 int job_context; /* bitmask defining current context */
203 pipe_style followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
204 reserved_style r_mode; /* supports if, for, while, until */
209 struct close_me *next;
217 struct variables *next;
220 /* globals, connect us to the outside world
221 * the first three support $?, $#, and $1 */
222 static char **global_argv;
223 static int global_argc;
224 static int last_return_code;
225 extern char **environ; /* This is in <unistd.h>, but protected with __USE_GNU */
227 /* "globals" within this file */
228 static const char *ifs;
229 static unsigned char map[256];
230 static int fake_mode;
231 static struct close_me *close_me_head;
232 static const char *cwd;
233 static struct pipe *job_list;
234 static unsigned last_bg_pid;
235 static int last_jobid;
236 /* 'interactive_fd' is a fd# open to ctty, if we have one
237 * _AND_ if we decided to mess with job control */
238 static int interactive_fd;
239 static pid_t saved_task_pgrp;
240 static pid_t saved_tty_pgrp;
242 static const char *PS1;
243 static const char *PS2;
244 static struct variables shell_ver = { "HUSH_VERSION", "0.01", 1, 1, 0 };
245 static struct variables *top_vars = &shell_ver;
248 #define B_CHUNK (100)
258 #define NULL_O_STRING {NULL,0,0,0,0}
259 /* used for initialization:
260 o_string foo = NULL_O_STRING; */
262 /* I can almost use ordinary FILE *. Is open_memstream() universally
263 * available? Where is it documented? */
270 int (*get) (struct in_str *);
271 int (*peek) (struct in_str *);
273 #define b_getch(input) ((input)->get(input))
274 #define b_peek(input) ((input)->peek(input))
276 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
278 struct built_in_command {
279 const char *cmd; /* name */
280 const char *descr; /* description */
281 int (*function) (char **argv); /* function ptr */
284 /* belongs in busybox.h */
285 static int max(int a, int b)
287 return (a > b) ? a : b;
291 #define debug_printf(...) fprintf(stderr, __VA_ARGS__)
292 /* broken, of course, but OK for testing */
293 static char *indenter(int i)
295 static char blanks[] = " ";
296 return &blanks[sizeof(blanks) - i - 1];
299 #define debug_printf(...) do {} while (0)
302 #ifdef DEBUG_SHELL_JOBS
303 #define debug_jobs_printf(...) fprintf(stderr, __VA_ARGS__)
305 #define debug_jobs_printf(...) do {} while (0)
308 #define final_printf debug_printf
310 static void __syntax(const char *file, int line)
312 bb_error_msg("syntax error %s:%d", file, line);
314 /* NB: was __FILE__, but that produces full path sometimes, so... */
315 #define syntax() __syntax("hush.c", __LINE__)
317 /* Index of subroutines: */
318 /* function prototypes for builtins */
319 static int builtin_cd(char **argv);
320 static int builtin_env(char **argv);
321 static int builtin_eval(char **argv);
322 static int builtin_exec(char **argv);
323 static int builtin_exit(char **argv);
324 static int builtin_export(char **argv);
325 static int builtin_fg_bg(char **argv);
326 static int builtin_help(char **argv);
327 static int builtin_jobs(char **argv);
328 static int builtin_pwd(char **argv);
329 static int builtin_read(char **argv);
330 static int builtin_set(char **argv);
331 static int builtin_shift(char **argv);
332 static int builtin_source(char **argv);
333 static int builtin_umask(char **argv);
334 static int builtin_unset(char **argv);
335 static int builtin_not_written(char **argv);
336 /* o_string manipulation: */
337 static int b_check_space(o_string *o, int len);
338 static int b_addchr(o_string *o, int ch);
339 static void b_reset(o_string *o);
340 static int b_addqchr(o_string *o, int ch, int quote);
341 static int b_adduint(o_string *o, unsigned i);
342 /* in_str manipulations: */
343 static int static_get(struct in_str *i);
344 static int static_peek(struct in_str *i);
345 static int file_get(struct in_str *i);
346 static int file_peek(struct in_str *i);
347 static void setup_file_in_str(struct in_str *i, FILE *f);
348 static void setup_string_in_str(struct in_str *i, const char *s);
349 /* close_me manipulations: */
350 static void mark_open(int fd);
351 static void mark_closed(int fd);
352 static void close_all(void);
353 /* "run" the final data structures: */
354 static int free_pipe_list(struct pipe *head, int indent);
355 static int free_pipe(struct pipe *pi, int indent);
356 /* really run the final data structures: */
357 static int setup_redirects(struct child_prog *prog, int squirrel[]);
358 static int run_list_real(struct pipe *pi);
359 static void pseudo_exec_argv(char **argv) ATTRIBUTE_NORETURN;
360 static void pseudo_exec(struct child_prog *child) ATTRIBUTE_NORETURN;
361 static int run_pipe_real(struct pipe *pi);
362 /* extended glob support: */
363 static int globhack(const char *src, int flags, glob_t *pglob);
364 static int glob_needed(const char *s);
365 static int xglob(o_string *dest, int flags, glob_t *pglob);
366 /* variable assignment: */
367 static int is_assignment(const char *s);
368 /* data structure manipulation: */
369 static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
370 static void initialize_context(struct p_context *ctx);
371 static int done_word(o_string *dest, struct p_context *ctx);
372 static int done_command(struct p_context *ctx);
373 static int done_pipe(struct p_context *ctx, pipe_style type);
374 /* primary string parsing: */
375 static int redirect_dup_num(struct in_str *input);
376 static int redirect_opt_num(o_string *o);
377 static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end);
378 static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
379 static const char *lookup_param(const char *src);
380 static char *make_string(char **inp);
381 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
382 static int parse_string(o_string *dest, struct p_context *ctx, const char *src);
383 static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, int end_trigger);
385 static int parse_stream_outer(struct in_str *inp, int flag);
386 static int parse_string_outer(const char *s, int flag);
387 static int parse_file_outer(FILE *f);
388 /* job management: */
389 static int checkjobs(struct pipe* fg_pipe);
390 static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
391 static void insert_bg_job(struct pipe *pi);
392 static void remove_bg_job(struct pipe *pi);
393 static void delete_finished_bg_job(struct pipe *pi);
394 /* local variable support */
395 static char **make_list_in(char **inp, char *name);
396 static char *insert_var_value(char *inp);
397 static const char *get_local_var(const char *var);
398 static int set_local_var(const char *s, int flg_export);
399 static void unset_local_var(const char *name);
401 /* Table of built-in functions. They can be forked or not, depending on
402 * context: within pipes, they fork. As simple commands, they do not.
403 * When used in non-forking context, they can change global variables
404 * in the parent shell process. If forked, of course they cannot.
405 * For example, 'unset foo | whatever' will parse and run, but foo will
406 * still be set at the end. */
407 static const struct built_in_command bltins[] = {
408 { "bg", "Resume a job in the background", builtin_fg_bg },
409 { "break", "Exit for, while or until loop", builtin_not_written },
410 { "cd", "Change working directory", builtin_cd },
411 { "continue", "Continue for, while or until loop", builtin_not_written },
412 { "env", "Print all environment variables", builtin_env },
413 { "eval", "Construct and run shell command", builtin_eval },
414 { "exec", "Exec command, replacing this shell with the exec'd process",
416 { "exit", "Exit from shell()", builtin_exit },
417 { "export", "Set environment variable", builtin_export },
418 { "fg", "Bring job into the foreground", builtin_fg_bg },
419 { "jobs", "Lists the active jobs", builtin_jobs },
420 { "pwd", "Print current directory", builtin_pwd },
421 { "read", "Input environment variable", builtin_read },
422 { "return", "Return from a function", builtin_not_written },
423 { "set", "Set/unset shell local variables", builtin_set },
424 { "shift", "Shift positional parameters", builtin_shift },
425 { "trap", "Trap signals", builtin_not_written },
426 { "ulimit","Controls resource limits", builtin_not_written },
427 { "umask","Sets file creation mask", builtin_umask },
428 { "unset", "Unset environment variable", builtin_unset },
429 { ".", "Source-in and run commands in a file", builtin_source },
430 { "help", "List shell built-in commands", builtin_help },
435 static void signal_SA_RESTART(int sig, void (*handler)(int))
438 sa.sa_handler = handler;
439 sa.sa_flags = SA_RESTART;
440 sigemptyset(&sa.sa_mask);
441 sigaction(sig, &sa, NULL);
444 struct nofork_save_area nofork_save;
445 static sigjmp_buf nofork_jb;
446 static struct pipe *nofork_pipe;
448 static void handler_ctrl_z(int sig)
452 debug_jobs_printf("got tty sig %d\n", sig);
454 if (pid < 0) /* can't fork. Pretend there were no Ctrl-Z */
456 debug_jobs_printf("bg'ing nofork\n");
457 nofork_save.saved = 0; /* flag the fact that Ctrl-Z was handled */
458 nofork_pipe->running_progs = 1;
459 nofork_pipe->stopped_progs = 0;
460 if (!pid) { /* child */
461 debug_jobs_printf("setting pgrp for child\n");
463 signal(SIGTSTP, SIG_DFL); /* make child do default action (stop) */
464 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
465 debug_jobs_printf("returning to child\n");
466 /* return to nofork, it will eventually exit now,
467 * not return back to shell */
471 /* finish filling up pipe info */
472 nofork_pipe->pgrp = pid; /* child is in its own pgrp */
473 nofork_pipe->progs[0].pid = pid;
474 nofork_pipe->running_progs = 1;
475 nofork_pipe->stopped_progs = 0;
476 /* parent needs to longjmp out of running nofork.
477 * we will "return" exitcode 0, with child put in background */
478 // as usual we can have all kinds of nasty problems with leaked malloc data here
479 siglongjmp(nofork_jb, 1);
482 /* Restores tty foreground process group, and exits.
483 * May be called as signal handler for fatal signal
484 * (will faithfully resend signal to itself, producing correct exit state)
485 * or called directly with -EXITCODE.
486 * We also call it if xfunc is exiting. */
487 static void sigexit(int sig) ATTRIBUTE_NORETURN;
488 static void sigexit(int sig)
492 /* Disable all signals: job control, SIGPIPE, etc. */
493 sigfillset(&block_all);
494 sigprocmask(SIG_SETMASK, &block_all, NULL);
497 tcsetpgrp(interactive_fd, saved_tty_pgrp);
499 /* Not a signal, just exit */
503 /* Enable only this sig and kill ourself with it */
504 signal(sig, SIG_DFL);
505 sigdelset(&block_all, sig);
506 sigprocmask(SIG_SETMASK, &block_all, NULL);
508 _exit(1); /* Should not reach it */
511 /* Restores tty foreground process group, and exits. */
512 static void hush_exit(int exitcode) ATTRIBUTE_NORETURN;
513 static void hush_exit(int exitcode)
515 fflush(NULL); /* flush all streams */
516 sigexit(- (exitcode & 0xff));
519 /* Signals are grouped, we handle them in batches */
520 static void set_fatal_sighandler(void (*handler)(int))
522 signal(SIGILL , handler);
523 signal(SIGTRAP, handler);
524 signal(SIGABRT, handler);
525 signal(SIGFPE , handler);
526 signal(SIGBUS , handler);
527 signal(SIGSEGV, handler);
528 /* bash 3.2 seems to handle these just like 'fatal' ones,
529 * but _without_ printing signal name. TODO: mimic this too? */
530 signal(SIGHUP , handler);
531 signal(SIGPIPE, handler);
532 signal(SIGALRM, handler);
534 static void set_jobctrl_sighandler(void (*handler)(int))
536 signal(SIGTSTP, handler);
537 signal(SIGTTIN, handler);
538 signal(SIGTTOU, handler);
540 static void set_misc_sighandler(void (*handler)(int))
542 signal(SIGINT , handler);
543 signal(SIGQUIT, handler);
544 signal(SIGTERM, handler);
546 /* SIGCHLD is special and handled separately */
548 static const char *set_cwd(void)
550 if (cwd == bb_msg_unknown)
551 cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
552 cwd = xrealloc_getcwd_or_warn((char *)cwd);
554 cwd = bb_msg_unknown;
558 /* built-in 'eval' handler */
559 static int builtin_eval(char **argv)
562 int rcode = EXIT_SUCCESS;
565 str = make_string(argv + 1);
566 parse_string_outer(str, FLAG_EXIT_FROM_LOOP |
567 FLAG_PARSE_SEMICOLON);
569 rcode = last_return_code;
574 /* built-in 'cd <path>' handler */
575 static int builtin_cd(char **argv)
579 newdir = getenv("HOME");
583 printf("cd: %s: %s\n", newdir, strerror(errno));
590 /* built-in 'env' handler */
591 static int builtin_env(char **argv ATTRIBUTE_UNUSED)
593 /* TODO: call env applet's code instead */
603 /* built-in 'exec' handler */
604 static int builtin_exec(char **argv)
607 return EXIT_SUCCESS; /* Really? */
608 pseudo_exec_argv(argv + 1);
612 /* built-in 'exit' handler */
613 static int builtin_exit(char **argv)
615 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
616 //puts("exit"); /* bash does it */
619 hush_exit(last_return_code);
620 /* mimic bash: exit 123abc == exit 255 + error msg */
621 xfunc_error_retval = 255;
622 /* bash: exit -2 == exit 254, no error msg */
623 hush_exit(xatoi(argv[1]));
626 /* built-in 'export VAR=value' handler */
627 static int builtin_export(char **argv)
630 char *name = argv[1];
633 return builtin_env(argv);
639 const char *value = strchr(name, '=');
643 /* They are exporting something without an =VALUE */
645 value = get_local_var(name);
647 size_t ln = strlen(name);
649 tmp = realloc(name, ln+strlen(value)+2);
653 sprintf(tmp+ln, "=%s", value);
657 /* bash does not return an error when trying to export
658 * an undefined variable. Do likewise. */
664 bb_perror_msg("export");
666 res = set_local_var(name, 1);
673 /* built-in 'fg' and 'bg' handler */
674 static int builtin_fg_bg(char **argv)
681 /* If they gave us no args, assume they want the last backgrounded task */
683 for (pi = job_list; pi; pi = pi->next) {
684 if (pi->jobid == last_jobid) {
688 bb_error_msg("%s: no current job", argv[0]);
691 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
692 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
695 for (pi = job_list; pi; pi = pi->next) {
696 if (pi->jobid == jobnum) {
700 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
703 // TODO: bash prints a string representation
704 // of job being foregrounded (like "sleep 1 | cat")
705 if (*argv[0] == 'f') {
706 /* Put the job into the foreground. */
707 tcsetpgrp(interactive_fd, pi->pgrp);
710 /* Restart the processes in the job */
711 debug_jobs_printf("reviving %d procs, pgrp %d\n", pi->num_progs, pi->pgrp);
712 for (i = 0; i < pi->num_progs; i++) {
713 debug_jobs_printf("reviving pid %d\n", pi->progs[i].pid);
714 pi->progs[i].is_stopped = 0;
716 pi->stopped_progs = 0;
718 i = kill(- pi->pgrp, SIGCONT);
720 if (errno == ESRCH) {
721 delete_finished_bg_job(pi);
723 bb_perror_msg("kill (SIGCONT)");
727 if (*argv[0] == 'f') {
729 return checkjobs_and_fg_shell(pi);
734 /* built-in 'help' handler */
735 static int builtin_help(char **argv ATTRIBUTE_UNUSED)
737 const struct built_in_command *x;
739 printf("\nBuilt-in commands:\n");
740 printf("-------------------\n");
741 for (x = bltins; x->cmd; x++) {
742 if (x->descr == NULL)
744 printf("%s\t%s\n", x->cmd, x->descr);
750 /* built-in 'jobs' handler */
751 static int builtin_jobs(char **argv ATTRIBUTE_UNUSED)
754 const char *status_string;
756 for (job = job_list; job; job = job->next) {
757 if (job->running_progs == job->stopped_progs)
758 status_string = "Stopped";
760 status_string = "Running";
762 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->text);
767 /* built-in 'pwd' handler */
768 static int builtin_pwd(char **argv ATTRIBUTE_UNUSED)
774 /* built-in 'read VAR' handler */
775 static int builtin_read(char **argv)
783 string[0] = '\0'; /* In case stdin has only EOF */
785 fgets(string, sizeof(string), stdin);
787 var = malloc(strlen(argv[1]) + strlen(string) + 2);
789 sprintf(var, "%s=%s", argv[1], string);
790 res = set_local_var(var, 0);
794 bb_perror_msg("read");
795 free(var); /* So not move up to avoid breaking errno */
798 do res = getchar(); while (res != '\n' && res != EOF);
802 /* built-in 'set VAR=value' handler */
803 static int builtin_set(char **argv)
805 char *temp = argv[1];
809 for (e = top_vars; e; e = e->next)
810 printf("%s=%s\n", e->name, e->value);
812 set_local_var(temp, 0);
818 /* Built-in 'shift' handler */
819 static int builtin_shift(char **argv)
825 if (n >= 0 && n < global_argc) {
826 /* XXX This probably breaks $0 */
834 /* Built-in '.' handler (read-in and execute commands from file) */
835 static int builtin_source(char **argv)
843 /* XXX search through $PATH is missing */
844 input = fopen(argv[1], "r");
846 bb_error_msg("cannot open '%s'", argv[1]);
850 /* Now run the file */
851 /* XXX argv and argc are broken; need to save old global_argv
852 * (pointer only is OK!) on this stack frame,
853 * set global_argv=argv+1, recurse, and restore. */
854 mark_open(fileno(input));
855 status = parse_file_outer(input);
856 mark_closed(fileno(input));
861 static int builtin_umask(char **argv)
864 const char *arg = argv[1];
867 new_umask = strtoul(arg, &end, 8);
868 if (*end != '\0' || end == arg) {
872 new_umask = umask(0);
873 printf("%.3o\n", (unsigned) new_umask);
879 /* built-in 'unset VAR' handler */
880 static int builtin_unset(char **argv)
882 /* bash returned already true */
883 unset_local_var(argv[1]);
887 static int builtin_not_written(char **argv)
889 printf("builtin_%s not written\n", argv[0]);
893 static int b_check_space(o_string *o, int len)
895 /* It would be easy to drop a more restrictive policy
896 * in here, such as setting a maximum string length */
897 if (o->length + len > o->maxlen) {
898 char *old_data = o->data;
899 /* assert(data == NULL || o->maxlen != 0); */
900 o->maxlen += max(2*len, B_CHUNK);
901 o->data = realloc(o->data, 1 + o->maxlen);
902 if (o->data == NULL) {
906 return o->data == NULL;
909 static int b_addchr(o_string *o, int ch)
911 debug_printf("b_addchr: %c %d %p\n", ch, o->length, o);
912 if (b_check_space(o, 1))
914 o->data[o->length] = ch;
916 o->data[o->length] = '\0';
920 static void b_reset(o_string *o)
928 static void b_free(o_string *o)
936 /* My analysis of quoting semantics tells me that state information
937 * is associated with a destination, not a source.
939 static int b_addqchr(o_string *o, int ch, int quote)
941 if (quote && strchr("*?[\\", ch)) {
943 rc = b_addchr(o, '\\');
947 return b_addchr(o, ch);
950 static int b_adduint(o_string *o, unsigned i)
953 char buf[sizeof(unsigned)*3 + 1];
955 *(utoa_to_buf(i, buf, sizeof(buf))) = '\0';
956 /* no escape checking necessary */
957 do r = b_addchr(o, *p++); while (r == 0 && *p);
961 static int static_get(struct in_str *i)
964 if (ch == '\0') return EOF;
968 static int static_peek(struct in_str *i)
973 static void cmdedit_set_initial_prompt(void)
975 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
984 static const char* setup_prompt_string(int promptmode)
986 const char *prompt_str;
987 debug_printf("setup_prompt_string %d ", promptmode);
988 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
989 /* Set up the prompt */
990 if (promptmode == 1) {
993 ns = xmalloc(strlen(cwd)+4);
994 sprintf(ns, "%s %s", cwd, (geteuid() != 0) ? "$ " : "# ");
1001 prompt_str = (promptmode == 1) ? PS1 : PS2;
1003 debug_printf("result %s\n", prompt_str);
1007 #if ENABLE_FEATURE_EDITING
1008 static line_input_t *line_input_state;
1011 static void get_user_input(struct in_str *i)
1013 const char *prompt_str;
1014 static char the_command[BUFSIZ];
1016 prompt_str = setup_prompt_string(i->promptmode);
1017 #if ENABLE_FEATURE_EDITING
1019 ** enable command line editing only while a command line
1020 ** is actually being read; otherwise, we'll end up bequeathing
1021 ** atexit() handlers and other unwanted stuff to our
1022 ** child processes (rob@sysgo.de)
1024 read_line_input(prompt_str, the_command, BUFSIZ, line_input_state);
1026 fputs(prompt_str, stdout);
1028 the_command[0] = fgetc(i->file);
1029 the_command[1] = '\0';
1035 /* This is the magic location that prints prompts
1036 * and gets data back from the user */
1037 static int file_get(struct in_str *i)
1042 /* If there is data waiting, eat it up */
1043 if (i->p && *i->p) {
1046 /* need to double check i->file because we might be doing something
1047 * more complicated by now, like sourcing or substituting. */
1048 if (i->__promptme && interactive_fd && i->file == stdin) {
1049 while (!i->p || !(interactive_fd && strlen(i->p))) {
1054 if (i->p && *i->p) {
1058 ch = fgetc(i->file);
1061 debug_printf("b_getch: got a %d\n", ch);
1068 /* All the callers guarantee this routine will never be
1069 * used right after a newline, so prompting is not needed.
1071 static int file_peek(struct in_str *i)
1073 if (i->p && *i->p) {
1076 i->peek_buf[0] = fgetc(i->file);
1077 i->peek_buf[1] = '\0';
1079 debug_printf("b_peek: got a %d\n", *i->p);
1083 static void setup_file_in_str(struct in_str *i, FILE *f)
1085 i->peek = file_peek;
1093 static void setup_string_in_str(struct in_str *i, const char *s)
1095 i->peek = static_peek;
1096 i->get = static_get;
1102 static void mark_open(int fd)
1104 struct close_me *new = xmalloc(sizeof(struct close_me));
1106 new->next = close_me_head;
1107 close_me_head = new;
1110 static void mark_closed(int fd)
1112 struct close_me *tmp;
1113 if (close_me_head == NULL || close_me_head->fd != fd)
1114 bb_error_msg_and_die("corrupt close_me");
1115 tmp = close_me_head;
1116 close_me_head = close_me_head->next;
1120 static void close_all(void)
1123 for (c = close_me_head; c; c = c->next) {
1126 close_me_head = NULL;
1129 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
1130 * and stderr if they are redirected. */
1131 static int setup_redirects(struct child_prog *prog, int squirrel[])
1134 struct redir_struct *redir;
1136 for (redir = prog->redirects; redir; redir = redir->next) {
1137 if (redir->dup == -1 && redir->word.gl_pathv == NULL) {
1138 /* something went wrong in the parse. Pretend it didn't happen */
1141 if (redir->dup == -1) {
1142 mode = redir_table[redir->type].mode;
1143 openfd = open_or_warn(redir->word.gl_pathv[0], mode);
1145 /* this could get lost if stderr has been redirected, but
1146 bash and ash both lose it as well (though zsh doesn't!) */
1150 openfd = redir->dup;
1153 if (openfd != redir->fd) {
1154 if (squirrel && redir->fd < 3) {
1155 squirrel[redir->fd] = dup(redir->fd);
1160 dup2(openfd, redir->fd);
1161 if (redir->dup == -1)
1169 static void restore_redirects(int squirrel[])
1172 for (i = 0; i < 3; i++) {
1175 /* No error checking. I sure wouldn't know what
1176 * to do with an error if I found one! */
1184 /* XXX no exit() here. If you don't exec, use _exit instead.
1185 * The at_exit handlers apparently confuse the calling process,
1186 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
1187 static void pseudo_exec_argv(char **argv)
1191 const struct built_in_command *x;
1193 for (i = 0; is_assignment(argv[i]); i++) {
1194 debug_printf("pid %d environment modification: %s\n",
1196 // FIXME: vfork case??
1197 p = insert_var_value(argv[i]);
1203 /* If a variable is assigned in a forest, and nobody listens,
1204 * was it ever really set?
1206 if (argv[0] == NULL) {
1207 _exit(EXIT_SUCCESS);
1211 * Check if the command matches any of the builtins.
1212 * Depending on context, this might be redundant. But it's
1213 * easier to waste a few CPU cycles than it is to figure out
1214 * if this is one of those cases.
1216 for (x = bltins; x->cmd; x++) {
1217 if (strcmp(argv[0], x->cmd) == 0) {
1218 debug_printf("builtin exec %s\n", argv[0]);
1219 rcode = x->function(argv);
1225 /* Check if the command matches any busybox internal commands
1227 * FIXME: This feature is not 100% safe, since
1228 * BusyBox is not fully reentrant, so we have no guarantee the things
1229 * from the .bss are still zeroed, or that things from .data are still
1230 * at their defaults. We could exec ourself from /proc/self/exe, but I
1231 * really dislike relying on /proc for things. We could exec ourself
1232 * from global_argv[0], but if we are in a chroot, we may not be able
1233 * to find ourself... */
1234 #if ENABLE_FEATURE_SH_STANDALONE
1235 debug_printf("running applet %s\n", argv[0]);
1236 run_applet_and_exit(argv[0], argv);
1237 // is it ok that run_applet_and_exit() does exit(), not _exit()?
1238 // NB: IIRC on NOMMU we are after _vfork_, not fork!
1240 debug_printf("exec of %s\n", argv[0]);
1241 execvp(argv[0], argv);
1242 bb_perror_msg("cannot exec '%s'", argv[0]);
1246 static void pseudo_exec(struct child_prog *child)
1251 pseudo_exec_argv(child->argv);
1255 debug_printf("runtime nesting to group\n");
1256 // FIXME: do not modify globals! Think vfork!
1257 interactive_fd = 0; /* crucial!!!! */
1258 rcode = run_list_real(child->group);
1259 /* OK to leak memory by not calling free_pipe_list,
1260 * since this process is about to exit */
1264 /* Can happen. See what bash does with ">foo" by itself. */
1265 debug_printf("trying to pseudo_exec null command\n");
1266 _exit(EXIT_SUCCESS);
1269 static void insert_bg_job(struct pipe *pi)
1271 struct pipe *thejob;
1273 /* Linear search for the ID of the job to use */
1275 for (thejob = job_list; thejob; thejob = thejob->next)
1276 if (thejob->jobid >= pi->jobid)
1277 pi->jobid = thejob->jobid + 1;
1279 /* add thejob to the list of running jobs */
1281 thejob = job_list = xmalloc(sizeof(*thejob));
1283 for (thejob = job_list; thejob->next; thejob = thejob->next)
1285 thejob->next = xmalloc(sizeof(*thejob));
1286 thejob = thejob->next;
1289 /* physically copy the struct job */
1290 memcpy(thejob, pi, sizeof(struct pipe));
1291 // (pi->num_progs+1) is one-too-many I think?
1292 thejob->progs = xmalloc(sizeof(pi->progs[0]) * (pi->num_progs+1));
1293 memcpy(thejob->progs, pi->progs, sizeof(pi->progs[0]) * (pi->num_progs+1));
1294 thejob->next = NULL;
1295 /*seems to be wrong:*/
1296 /*thejob->running_progs = thejob->num_progs;*/
1297 /*thejob->stopped_progs = 0;*/
1298 thejob->text = xmalloc(BUFSIZ); /* cmdedit buffer size */
1299 //if (pi->progs[0] && pi->progs[0].argv && pi->progs[0].argv[0])
1301 // FIXME: overflow check? and also trim the size, BUFSIZ can be 4K!
1302 char *bar = thejob->text;
1303 char **foo = pi->progs[0].argv;
1306 bar += sprintf(bar, "%s ", *foo++);
1309 /* we don't wait for background thejobs to return -- append it
1310 to the list of backgrounded thejobs and leave it alone */
1311 printf("[%d] %d\n", thejob->jobid, thejob->progs[0].pid);
1312 last_bg_pid = thejob->progs[0].pid;
1313 last_jobid = thejob->jobid;
1316 static void remove_bg_job(struct pipe *pi)
1318 struct pipe *prev_pipe;
1320 if (pi == job_list) {
1321 job_list = pi->next;
1323 prev_pipe = job_list;
1324 while (prev_pipe->next != pi)
1325 prev_pipe = prev_pipe->next;
1326 prev_pipe->next = pi->next;
1329 last_jobid = job_list->jobid;
1334 /* remove a backgrounded job */
1335 static void delete_finished_bg_job(struct pipe *pi)
1338 pi->stopped_progs = 0;
1343 /* Checks to see if any processes have exited -- if they
1344 have, figure out why and see if a job has completed */
1345 static int checkjobs(struct pipe* fg_pipe)
1354 attributes = WUNTRACED;
1355 if (fg_pipe == NULL) {
1356 attributes |= WNOHANG;
1359 /* Do we do this right?
1360 * bash-3.00# sleep 20 | false
1362 * [3]+ Stopped sleep 20 | false
1363 * bash-3.00# echo $?
1364 * 1 <========== bg pipe is not fully done, but exitcode is already known!
1368 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
1369 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
1371 #ifdef DEBUG_SHELL_JOBS
1372 if (WIFSTOPPED(status))
1373 debug_jobs_printf("pid %d stopped by sig %d (exitcode %d)\n",
1374 childpid, WSTOPSIG(status), WEXITSTATUS(status));
1375 if (WIFSIGNALED(status))
1376 debug_jobs_printf("pid %d killed by sig %d (exitcode %d)\n",
1377 childpid, WTERMSIG(status), WEXITSTATUS(status));
1378 if (WIFEXITED(status))
1379 debug_jobs_printf("pid %d exited, exitcode %d\n",
1380 childpid, WEXITSTATUS(status));
1382 /* Were we asked to wait for fg pipe? */
1385 for (i = 0; i < fg_pipe->num_progs; i++) {
1386 debug_jobs_printf("check pid %d\n", fg_pipe->progs[i].pid);
1387 if (fg_pipe->progs[i].pid == childpid) {
1388 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
1390 fg_pipe->progs[i].pid = 0;
1391 fg_pipe->running_progs--;
1392 if (i == fg_pipe->num_progs-1)
1393 /* last process gives overall exitstatus */
1394 rcode = WEXITSTATUS(status);
1396 fg_pipe->progs[i].is_stopped = 1;
1397 fg_pipe->stopped_progs++;
1399 debug_jobs_printf("fg_pipe: running_progs %d stopped_progs %d\n",
1400 fg_pipe->running_progs, fg_pipe->stopped_progs);
1401 if (fg_pipe->running_progs - fg_pipe->stopped_progs <= 0) {
1402 /* All processes in fg pipe have exited/stopped */
1403 if (fg_pipe->running_progs)
1404 insert_bg_job(fg_pipe);
1407 /* There are still running processes in the fg pipe */
1411 /* fall through to searching process in bg pipes */
1414 /* We asked to wait for bg or orphaned children */
1415 /* No need to remember exitcode in this case */
1416 for (pi = job_list; pi; pi = pi->next) {
1418 while (prognum < pi->num_progs) {
1419 if (pi->progs[prognum].pid == childpid)
1420 goto found_pi_and_prognum;
1425 /* Happens when shell is used as init process (init=/bin/sh) */
1426 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
1429 found_pi_and_prognum:
1432 pi->progs[prognum].pid = 0;
1433 pi->running_progs--;
1434 if (!pi->running_progs) {
1435 printf(JOB_STATUS_FORMAT, pi->jobid,
1437 delete_finished_bg_job(pi);
1441 pi->stopped_progs++;
1442 pi->progs[prognum].is_stopped = 1;
1446 /* wait found no children or failed */
1448 if (childpid && errno != ECHILD)
1449 bb_perror_msg("waitpid");
1451 /* move the shell to the foreground */
1452 //if (interactive_fd && tcsetpgrp(interactive_fd, getpgid(0)))
1453 // bb_perror_msg("tcsetpgrp-2");
1457 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1460 int rcode = checkjobs(fg_pipe);
1461 /* Job finished, move the shell to the foreground */
1463 debug_printf("fg'ing ourself: getpgid(0)=%d\n", (int)p);
1464 if (tcsetpgrp(interactive_fd, p) && errno != ENOTTY)
1465 bb_perror_msg("tcsetpgrp-4a");
1469 /* run_pipe_real() starts all the jobs, but doesn't wait for anything
1470 * to finish. See checkjobs().
1472 * return code is normally -1, when the caller has to wait for children
1473 * to finish to determine the exit status of the pipe. If the pipe
1474 * is a simple builtin command, however, the action is done by the
1475 * time run_pipe_real returns, and the exit code is provided as the
1478 * The input of the pipe is always stdin, the output is always
1479 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1480 * because it tries to avoid running the command substitution in
1481 * subshell, when that is in fact necessary. The subshell process
1482 * now has its stdout directed to the input of the appropriate pipe,
1483 * so this routine is noticeably simpler.
1485 static int run_pipe_real(struct pipe *pi)
1488 int nextin, nextout;
1489 int pipefds[2]; /* pipefds[0] is for reading */
1490 struct child_prog *child;
1491 const struct built_in_command *x;
1493 /* it is not always needed, but we aim to smaller code */
1494 int squirrel[] = { -1, -1, -1 };
1496 const int single_fg = (pi->num_progs == 1 && pi->followup != PIPE_BG);
1500 pi->running_progs = 0;
1501 pi->stopped_progs = 0;
1503 /* Check if this is a simple builtin (not part of a pipe).
1504 * Builtins within pipes have to fork anyway, and are handled in
1505 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1507 child = &(pi->progs[0]);
1508 if (single_fg && child->group && child->subshell == 0) {
1509 debug_printf("non-subshell grouping\n");
1510 setup_redirects(child, squirrel);
1511 /* XXX could we merge code with following builtin case,
1512 * by creating a pseudo builtin that calls run_list_real? */
1513 rcode = run_list_real(child->group);
1514 restore_redirects(squirrel);
1518 if (single_fg && child->argv != NULL) {
1519 char **argv = child->argv;
1521 for (i = 0; is_assignment(argv[i]); i++)
1523 if (i != 0 && argv[i] == NULL) {
1524 /* assignments, but no command: set the local environment */
1525 for (i = 0; argv[i] != NULL; i++) {
1526 /* Ok, this case is tricky. We have to decide if this is a
1527 * local variable, or an already exported variable. If it is
1528 * already exported, we have to export the new value. If it is
1529 * not exported, we need only set this as a local variable.
1530 * This junk is all to decide whether or not to export this
1534 name = xstrdup(argv[i]);
1535 debug_printf("Local environment set: %s\n", name);
1536 value = strchr(name, '=');
1539 if (get_local_var(name)) {
1543 p = insert_var_value(argv[i]);
1544 set_local_var(p, export_me);
1548 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1550 for (i = 0; is_assignment(argv[i]); i++) {
1551 p = insert_var_value(argv[i]);
1561 str = make_string(argv + i);
1562 parse_string_outer(str, FLAG_EXIT_FROM_LOOP | FLAG_REPARSING);
1564 return last_return_code;
1566 for (x = bltins; x->cmd; x++) {
1567 if (strcmp(argv[i], x->cmd) == 0) {
1568 if (x->function == builtin_exec && argv[i+1] == NULL) {
1569 debug_printf("magic exec\n");
1570 setup_redirects(child, NULL);
1571 return EXIT_SUCCESS;
1573 debug_printf("builtin inline %s\n", argv[0]);
1574 /* XXX setup_redirects acts on file descriptors, not FILEs.
1575 * This is perfect for work that comes after exec().
1576 * Is it really safe for inline use? Experimentally,
1577 * things seem to work with glibc. */
1578 setup_redirects(child, squirrel);
1579 rcode = x->function(argv + i);
1580 restore_redirects(squirrel);
1584 #if ENABLE_FEATURE_SH_STANDALONE
1586 const struct bb_applet *a = find_applet_by_name(argv[i]);
1587 if (a && a->nofork) {
1588 setup_redirects(child, squirrel);
1589 /* TSTP handler will store pid etc in pi */
1591 save_nofork_data(&nofork_save);
1592 if (sigsetjmp(nofork_jb, 1) == 0) {
1593 signal_SA_RESTART(SIGTSTP, handler_ctrl_z);
1594 rcode = run_nofork_applet_prime(&nofork_save, a, argv + i);
1595 if (--nofork_save.saved != 0)
1596 /* Ctrl-Z! forked, we are child */
1598 restore_redirects(squirrel);
1601 /* Ctrl-Z, forked, we are parent.
1602 * Sighandler has longjmped us here */
1603 signal(SIGTSTP, SIG_IGN);
1604 debug_jobs_printf("Exiting nofork early\n");
1605 restore_nofork_data(&nofork_save);
1606 restore_redirects(squirrel);
1615 /* Disable job control signals for shell (parent) and
1616 * for initial child code after fork */
1617 set_jobctrl_sighandler(SIG_IGN);
1619 for (i = 0; i < pi->num_progs; i++) {
1620 child = &(pi->progs[i]);
1622 /* pipes are inserted between pairs of commands */
1623 if ((i + 1) < pi->num_progs) {
1624 if (pipe(pipefds) < 0)
1625 bb_perror_msg_and_die("pipe");
1626 nextout = pipefds[1];
1632 /* XXX test for failed fork()? */
1634 child->pid = fork();
1636 child->pid = vfork();
1638 if (!child->pid) { /* child */
1639 /* Every child adds itself to new process group
1640 * with pgid == pid of first child in pipe */
1641 if (interactive_fd) {
1642 if (pi->pgrp < 0) /* true for 1st process only */
1643 pi->pgrp = getpid();
1644 if (setpgid(0, pi->pgrp) == 0 && pi->followup != PIPE_BG) {
1645 /* We do it in *every* child, not just first,
1647 tcsetpgrp(interactive_fd, pi->pgrp);
1649 /* Don't do pgrp restore anymore on fatal signals */
1650 set_fatal_sighandler(SIG_DFL);
1652 // in non-interactive case fatal sigs are already SIG_DFL
1662 if (pipefds[0] != -1) {
1663 close(pipefds[0]); /* opposite end of our output pipe */
1665 /* Like bash, explicit redirects override pipes,
1666 * and the pipe fd is available for dup'ing. */
1667 setup_redirects(child, NULL);
1669 /* Restore default handlers just prior to exec */
1670 set_jobctrl_sighandler(SIG_DFL);
1671 set_misc_sighandler(SIG_DFL);
1672 signal(SIGCHLD, SIG_DFL);
1676 pi->running_progs++;
1678 /* Second and next children need to know pid of first one */
1680 pi->pgrp = child->pid;
1682 /* Don't check for errors. The child may be dead already,
1683 * in which case setpgid returns error code EACCES. */
1684 //why we do it at all?? child does it itself
1685 //if (interactive_fd)
1686 // setpgid(child->pid, pi->pgrp);
1693 /* If there isn't another process, nextin is garbage
1694 but it doesn't matter */
1695 nextin = pipefds[0];
1700 static int run_list_real(struct pipe *pi)
1702 char *save_name = NULL;
1704 char **save_list = NULL;
1708 int rcode = 0, flag_skip = 1;
1709 int flag_restore = 0;
1710 int if_code = 0, next_if_code = 0; /* need double-buffer to handle elif */
1711 reserved_style rmode, skip_more_in_this_rmode = RES_XXXX;
1712 /* check syntax for "for" */
1713 for (rpipe = pi; rpipe; rpipe = rpipe->next) {
1714 if ((rpipe->r_mode == RES_IN || rpipe->r_mode == RES_FOR)
1715 && (rpipe->next == NULL)
1720 if ((rpipe->r_mode == RES_IN && rpipe->next->r_mode == RES_IN && rpipe->next->progs->argv != NULL)
1721 || (rpipe->r_mode == RES_FOR && rpipe->next->r_mode != RES_IN)
1727 for (; pi; pi = (flag_restore != 0) ? rpipe : pi->next) {
1728 if (pi->r_mode == RES_WHILE || pi->r_mode == RES_UNTIL
1729 || pi->r_mode == RES_FOR
1738 debug_printf("rmode=%d if_code=%d next_if_code=%d skip_more=%d\n",
1739 rmode, if_code, next_if_code, skip_more_in_this_rmode);
1740 if (rmode == skip_more_in_this_rmode && flag_skip) {
1741 if (pi->followup == PIPE_SEQ)
1746 skip_more_in_this_rmode = RES_XXXX;
1747 if (rmode == RES_THEN || rmode == RES_ELSE)
1748 if_code = next_if_code;
1749 if (rmode == RES_THEN && if_code)
1751 if (rmode == RES_ELSE && !if_code)
1753 if (rmode == RES_ELIF && !if_code)
1755 if (rmode == RES_FOR && pi->num_progs) {
1757 /* if no variable values after "in" we skip "for" */
1758 if (!pi->next->progs->argv)
1760 /* create list of variable values */
1761 list = make_list_in(pi->next->progs->argv,
1762 pi->progs->argv[0]);
1764 save_name = pi->progs->argv[0];
1765 pi->progs->argv[0] = NULL;
1769 free(pi->progs->argv[0]);
1773 pi->progs->argv[0] = save_name;
1774 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
1777 /* insert new value from list for variable */
1778 if (pi->progs->argv[0])
1779 free(pi->progs->argv[0]);
1780 pi->progs->argv[0] = *list++;
1781 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
1783 if (rmode == RES_IN)
1785 if (rmode == RES_DO) {
1789 if (rmode == RES_DONE) {
1796 if (pi->num_progs == 0)
1798 save_num_progs = pi->num_progs; /* save number of programs */
1799 rcode = run_pipe_real(pi);
1800 debug_printf("run_pipe_real returned %d\n", rcode);
1802 /* We only ran a builtin: rcode was set by the return value
1803 * of run_pipe_real(), and we don't need to wait for anything. */
1804 } else if (pi->followup == PIPE_BG) {
1805 /* XXX check bash's behavior with nontrivial pipes */
1806 /* XXX compute jobid */
1807 /* XXX what does bash do with attempts to background builtins? */
1809 rcode = EXIT_SUCCESS;
1811 if (interactive_fd) {
1812 rcode = checkjobs_and_fg_shell(pi);
1814 rcode = checkjobs(pi);
1816 debug_printf("checkjobs returned %d\n", rcode);
1818 last_return_code = rcode;
1819 pi->num_progs = save_num_progs; /* restore number of programs */
1820 if (rmode == RES_IF || rmode == RES_ELIF)
1821 next_if_code = rcode; /* can be overwritten a number of times */
1822 if (rmode == RES_WHILE)
1823 flag_rep = !last_return_code;
1824 if (rmode == RES_UNTIL)
1825 flag_rep = last_return_code;
1826 if ((rcode == EXIT_SUCCESS && pi->followup == PIPE_OR)
1827 || (rcode != EXIT_SUCCESS && pi->followup == PIPE_AND)
1829 skip_more_in_this_rmode = rmode;
1836 /* return code is the exit status of the pipe */
1837 static int free_pipe(struct pipe *pi, int indent)
1840 struct child_prog *child;
1841 struct redir_struct *r, *rnext;
1842 int a, i, ret_code = 0;
1844 if (pi->stopped_progs > 0)
1846 final_printf("%s run pipe: (pid %d)\n", indenter(indent), getpid());
1847 for (i = 0; i < pi->num_progs; i++) {
1848 child = &pi->progs[i];
1849 final_printf("%s command %d:\n", indenter(indent), i);
1851 for (a = 0, p = child->argv; *p; a++, p++) {
1852 final_printf("%s argv[%d] = %s\n", indenter(indent), a, *p);
1854 globfree(&child->glob_result);
1856 } else if (child->group) {
1857 final_printf("%s begin group (subshell:%d)\n", indenter(indent), child->subshell);
1858 ret_code = free_pipe_list(child->group, indent+3);
1859 final_printf("%s end group\n", indenter(indent));
1861 final_printf("%s (nil)\n", indenter(indent));
1863 for (r = child->redirects; r; r = rnext) {
1864 final_printf("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->type].descrip);
1866 /* guard against the case >$FOO, where foo is unset or blank */
1867 if (r->word.gl_pathv) {
1868 final_printf(" %s\n", *r->word.gl_pathv);
1872 final_printf("&%d\n", r->dup);
1877 child->redirects = NULL;
1879 free(pi->progs); /* children are an array, they get freed all at once */
1884 static int free_pipe_list(struct pipe *head, int indent)
1886 int rcode = 0; /* if list has no members */
1887 struct pipe *pi, *next;
1888 for (pi = head; pi; pi = next) {
1889 final_printf("%s pipe reserved mode %d\n", indenter(indent), pi->r_mode);
1890 rcode = free_pipe(pi, indent);
1891 final_printf("%s pipe followup code %d\n", indenter(indent), pi->followup);
1893 /*pi->next = NULL;*/
1899 /* Select which version we will use */
1900 static int run_list(struct pipe *pi)
1903 if (fake_mode == 0) {
1904 rcode = run_list_real(pi);
1906 /* free_pipe_list has the side effect of clearing memory
1907 * In the long run that function can be merged with run_list_real,
1908 * but doing that now would hobble the debugging effort. */
1909 free_pipe_list(pi,0);
1913 /* The API for glob is arguably broken. This routine pushes a non-matching
1914 * string into the output structure, removing non-backslashed backslashes.
1915 * If someone can prove me wrong, by performing this function within the
1916 * original glob(3) api, feel free to rewrite this routine into oblivion.
1917 * Return code (0 vs. GLOB_NOSPACE) matches glob(3).
1918 * XXX broken if the last character is '\\', check that before calling.
1920 static int globhack(const char *src, int flags, glob_t *pglob)
1925 for (cnt = 1, s = src; s && *s; s++) {
1926 if (*s == '\\') s++;
1931 return GLOB_NOSPACE;
1932 if (!(flags & GLOB_APPEND)) {
1933 pglob->gl_pathv = NULL;
1934 pglob->gl_pathc = 0;
1938 pathc = ++pglob->gl_pathc;
1939 pglob->gl_pathv = realloc(pglob->gl_pathv, (pathc+1)*sizeof(*pglob->gl_pathv));
1940 if (pglob->gl_pathv == NULL)
1941 return GLOB_NOSPACE;
1942 pglob->gl_pathv[pathc-1] = dest;
1943 pglob->gl_pathv[pathc] = NULL;
1944 for (s = src; s && *s; s++, dest++) {
1945 if (*s == '\\') s++;
1952 /* XXX broken if the last character is '\\', check that before calling */
1953 static int glob_needed(const char *s)
1956 if (*s == '\\') s++;
1957 if (strchr("*[?", *s)) return 1;
1962 static int xglob(o_string *dest, int flags, glob_t *pglob)
1966 /* short-circuit for null word */
1967 /* we can code this better when the debug_printf's are gone */
1968 if (dest->length == 0) {
1969 if (dest->nonnull) {
1970 /* bash man page calls this an "explicit" null */
1971 gr = globhack(dest->data, flags, pglob);
1972 debug_printf("globhack returned %d\n", gr);
1976 } else if (glob_needed(dest->data)) {
1977 gr = glob(dest->data, flags, NULL, pglob);
1978 debug_printf("glob returned %d\n", gr);
1979 if (gr == GLOB_NOMATCH) {
1980 /* quote removal, or more accurately, backslash removal */
1981 gr = globhack(dest->data, flags, pglob);
1982 debug_printf("globhack returned %d\n", gr);
1985 gr = globhack(dest->data, flags, pglob);
1986 debug_printf("globhack returned %d\n", gr);
1988 if (gr == GLOB_NOSPACE)
1989 bb_error_msg_and_die("out of memory during glob");
1990 if (gr != 0) { /* GLOB_ABORTED ? */
1991 bb_error_msg("glob(3) error %d", gr);
1993 /* globprint(glob_target); */
1997 static char **make_list_in(char **inp, char *name)
2000 int name_len = strlen(name);
2005 /* create list of variable values */
2006 list = xmalloc(sizeof(*list));
2007 for (i = 0; inp[i]; i++) {
2008 p3 = insert_var_value(inp[i]);
2015 p2 = strchr(p1, ' ');
2022 /* we use n + 2 in realloc for list, because we add
2023 * new element and then we will add NULL element */
2024 list = xrealloc(list, sizeof(*list) * (n + 2));
2025 list[n] = xmalloc(2 + name_len + len);
2026 strcpy(list[n], name);
2027 strcat(list[n], "=");
2028 strncat(list[n], p1, len);
2029 list[n++][name_len + len + 1] = '\0';
2032 if (p3 != inp[i]) free(p3);
2038 static char *insert_var_value(char *inp)
2040 int res_str_len = 0;
2043 char *p, *res_str = NULL;
2046 while ((p = strchr(inp, SPECIAL_VAR_SYMBOL))) {
2049 res_str = xrealloc(res_str, (res_str_len + len));
2050 strncpy((res_str + res_str_len), inp, len);
2054 p = strchr(inp, SPECIAL_VAR_SYMBOL);
2056 p1 = lookup_param(inp);
2058 len = res_str_len + strlen(p1);
2059 res_str = xrealloc(res_str, (1 + len));
2060 strcpy((res_str + res_str_len), p1);
2063 *p = SPECIAL_VAR_SYMBOL;
2068 res_str = xrealloc(res_str, (1 + res_str_len + strlen(inp)));
2069 strcpy((res_str + res_str_len), inp);
2070 while ((p = strchr(res_str, '\n'))) {
2074 return (res_str == NULL) ? inp : res_str;
2077 /* This is used to get/check local shell variables */
2078 static const char *get_local_var(const char *s)
2080 struct variables *cur;
2084 for (cur = top_vars; cur; cur = cur->next)
2085 if (strcmp(cur->name, s) == 0)
2090 /* This is used to set local shell variables
2091 flg_export == 0 if only local (not exporting) variable
2092 flg_export == 1 if "new" exporting environ
2093 flg_export > 1 if current startup environ (not call putenv()) */
2094 static int set_local_var(const char *s, int flg_export)
2098 struct variables *cur;
2102 /* Assume when we enter this function that we are already in
2103 * NAME=VALUE format. So the first order of business is to
2104 * split 's' on the '=' into 'name' and 'value' */
2105 value = strchr(name, '=');
2106 /*if (value == 0 && ++value == 0) ??? -vda */
2107 if (value == NULL || value[1] == '\0') {
2113 for (cur = top_vars; cur; cur = cur->next) {
2114 if (strcmp(cur->name, name) == 0)
2119 if (strcmp(cur->value, value) == 0) {
2120 if (flg_export > 0 && cur->flg_export == 0)
2121 cur->flg_export = flg_export;
2124 } else if (cur->flg_read_only) {
2125 bb_error_msg("%s: readonly variable", name);
2128 if (flg_export > 0 || cur->flg_export > 1)
2129 cur->flg_export = 1;
2130 free((char*)cur->value);
2132 cur->value = strdup(value);
2135 cur = malloc(sizeof(struct variables));
2139 cur->name = strdup(name);
2144 struct variables *bottom = top_vars;
2145 cur->value = strdup(value);
2147 cur->flg_export = flg_export;
2148 cur->flg_read_only = 0;
2149 while (bottom->next)
2150 bottom = bottom->next;
2156 if (result == 0 && cur->flg_export == 1) {
2158 result = putenv(name);
2161 if (result > 0) /* equivalent to previous set */
2167 static void unset_local_var(const char *name)
2169 struct variables *cur, *next;
2173 for (cur = top_vars; cur; cur = cur->next) {
2174 if (strcmp(cur->name, name) == 0) {
2175 if (cur->flg_read_only) {
2176 bb_error_msg("%s: readonly variable", name);
2179 if (cur->flg_export)
2180 unsetenv(cur->name);
2181 free((char*)cur->name);
2182 free((char*)cur->value);
2184 while (next->next != cur)
2186 next->next = cur->next;
2193 static int is_assignment(const char *s)
2195 if (!s || !isalpha(*s))
2198 while (isalnum(*s) || *s == '_')
2203 /* the src parameter allows us to peek forward to a possible &n syntax
2204 * for file descriptor duplication, e.g., "2>&1".
2205 * Return code is 0 normally, 1 if a syntax error is detected in src.
2206 * Resource errors (in xmalloc) cause the process to exit */
2207 static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2208 struct in_str *input)
2210 struct child_prog *child = ctx->child;
2211 struct redir_struct *redir = child->redirects;
2212 struct redir_struct *last_redir = NULL;
2214 /* Create a new redir_struct and drop it onto the end of the linked list */
2217 redir = redir->next;
2219 redir = xmalloc(sizeof(struct redir_struct));
2221 redir->word.gl_pathv = NULL;
2223 last_redir->next = redir;
2225 child->redirects = redir;
2228 redir->type = style;
2229 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
2231 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2233 /* Check for a '2>&1' type redirect */
2234 redir->dup = redirect_dup_num(input);
2235 if (redir->dup == -2) return 1; /* syntax error */
2236 if (redir->dup != -1) {
2237 /* Erik had a check here that the file descriptor in question
2238 * is legit; I postpone that to "run time"
2239 * A "-" representation of "close me" shows up as a -3 here */
2240 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2242 /* We do _not_ try to open the file that src points to,
2243 * since we need to return and let src be expanded first.
2244 * Set ctx->pending_redirect, so we know what to do at the
2245 * end of the next parsed word.
2247 ctx->pending_redirect = redir;
2252 static struct pipe *new_pipe(void)
2255 pi = xmalloc(sizeof(struct pipe));
2259 pi->followup = 0; /* invalid */
2260 pi->r_mode = RES_NONE;
2264 static void initialize_context(struct p_context *ctx)
2267 ctx->pending_redirect = NULL;
2269 ctx->list_head = new_pipe();
2270 ctx->pipe = ctx->list_head;
2274 done_command(ctx); /* creates the memory for working child */
2277 /* normal return is 0
2278 * if a reserved word is found, and processed, return 1
2279 * should handle if, then, elif, else, fi, for, while, until, do, done.
2280 * case, function, and select are obnoxious, save those for later.
2282 static int reserved_word(o_string *dest, struct p_context *ctx)
2284 struct reserved_combo {
2289 /* Mostly a list of accepted follow-up reserved words.
2290 * FLAG_END means we are done with the sequence, and are ready
2291 * to turn the compound list into a command.
2292 * FLAG_START means the word must start a new compound list.
2294 static const struct reserved_combo reserved_list[] = {
2295 { "if", RES_IF, FLAG_THEN | FLAG_START },
2296 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2297 { "elif", RES_ELIF, FLAG_THEN },
2298 { "else", RES_ELSE, FLAG_FI },
2299 { "fi", RES_FI, FLAG_END },
2300 { "for", RES_FOR, FLAG_IN | FLAG_START },
2301 { "while", RES_WHILE, FLAG_DO | FLAG_START },
2302 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
2303 { "in", RES_IN, FLAG_DO },
2304 { "do", RES_DO, FLAG_DONE },
2305 { "done", RES_DONE, FLAG_END }
2307 enum { NRES = sizeof(reserved_list)/sizeof(reserved_list[0]) };
2308 const struct reserved_combo *r;
2310 for (r = reserved_list; r < reserved_list+NRES; r++) {
2311 if (strcmp(dest->data, r->literal) == 0) {
2312 debug_printf("found reserved word %s, code %d\n", r->literal, r->code);
2313 if (r->flag & FLAG_START) {
2314 struct p_context *new = xmalloc(sizeof(struct p_context));
2315 debug_printf("push stack\n");
2316 if (ctx->w == RES_IN || ctx->w == RES_FOR) {
2323 *new = *ctx; /* physical copy */
2324 initialize_context(ctx);
2326 } else if (ctx->w == RES_NONE || !(ctx->old_flag & (1 << r->code))) {
2333 ctx->old_flag = r->flag;
2334 if (ctx->old_flag & FLAG_END) {
2335 struct p_context *old;
2336 debug_printf("pop stack\n");
2337 done_pipe(ctx, PIPE_SEQ);
2339 old->child->group = ctx->list_head;
2340 old->child->subshell = 0;
2341 *ctx = *old; /* physical copy */
2351 /* normal return is 0.
2352 * Syntax or xglob errors return 1. */
2353 static int done_word(o_string *dest, struct p_context *ctx)
2355 struct child_prog *child = ctx->child;
2356 glob_t *glob_target;
2359 debug_printf("done_word: %s %p\n", dest->data, child);
2360 if (dest->length == 0 && !dest->nonnull) {
2361 debug_printf(" true null, ignored\n");
2364 if (ctx->pending_redirect) {
2365 glob_target = &ctx->pending_redirect->word;
2369 return 1; /* syntax error, groups and arglists don't mix */
2371 if (!child->argv && (ctx->type & FLAG_PARSE_SEMICOLON)) {
2372 debug_printf("checking %s for reserved-ness\n", dest->data);
2373 if (reserved_word(dest, ctx))
2374 return (ctx->w == RES_SNTX);
2376 glob_target = &child->glob_result;
2377 if (child->argv) flags |= GLOB_APPEND;
2379 gr = xglob(dest, flags, glob_target);
2380 if (gr != 0) return 1;
2383 if (ctx->pending_redirect) {
2384 ctx->pending_redirect = NULL;
2385 if (glob_target->gl_pathc != 1) {
2386 bb_error_msg("ambiguous redirect");
2390 child->argv = glob_target->gl_pathv;
2392 if (ctx->w == RES_FOR) {
2393 done_word(dest, ctx);
2394 done_pipe(ctx, PIPE_SEQ);
2399 /* The only possible error here is out of memory, in which case
2401 static int done_command(struct p_context *ctx)
2403 /* The child is really already in the pipe structure, so
2404 * advance the pipe counter and make a new, null child.
2405 * Only real trickiness here is that the uncommitted
2406 * child structure, to which ctx->child points, is not
2407 * counted in pi->num_progs. */
2408 struct pipe *pi = ctx->pipe;
2409 struct child_prog *prog = ctx->child;
2411 if (prog && prog->group == NULL
2412 && prog->argv == NULL
2413 && prog->redirects == NULL
2415 debug_printf("done_command: skipping null command\n");
2420 debug_printf("done_command: num_progs incremented to %d\n", pi->num_progs);
2422 debug_printf("done_command: initializing\n");
2424 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
2426 prog = pi->progs + pi->num_progs;
2427 prog->redirects = NULL;
2429 prog->is_stopped = 0;
2431 prog->glob_result.gl_pathv = NULL;
2435 prog->type = ctx->type;
2437 /* but ctx->pipe and ctx->list_head remain unchanged */
2441 static int done_pipe(struct p_context *ctx, pipe_style type)
2444 done_command(ctx); /* implicit closure of previous command */
2445 debug_printf("done_pipe, type %d\n", type);
2446 ctx->pipe->followup = type;
2447 ctx->pipe->r_mode = ctx->w;
2449 ctx->pipe->next = new_p;
2452 done_command(ctx); /* set up new pipe to accept commands */
2456 /* peek ahead in the in_str to find out if we have a "&n" construct,
2457 * as in "2>&1", that represents duplicating a file descriptor.
2458 * returns either -2 (syntax error), -1 (no &), or the number found.
2460 static int redirect_dup_num(struct in_str *input)
2462 int ch, d = 0, ok = 0;
2464 if (ch != '&') return -1;
2466 b_getch(input); /* get the & */
2470 return -3; /* "-" represents "close me" */
2472 while (isdigit(ch)) {
2473 d = d*10 + (ch-'0');
2480 bb_error_msg("ambiguous redirect");
2484 /* If a redirect is immediately preceded by a number, that number is
2485 * supposed to tell which file descriptor to redirect. This routine
2486 * looks for such preceding numbers. In an ideal world this routine
2487 * needs to handle all the following classes of redirects...
2488 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
2489 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
2490 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
2491 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
2492 * A -1 output from this program means no valid number was found, so the
2493 * caller should use the appropriate default for this redirection.
2495 static int redirect_opt_num(o_string *o)
2501 for (num = 0; num < o->length; num++) {
2502 if (!isdigit(*(o->data + num))) {
2506 /* reuse num (and save an int) */
2507 num = atoi(o->data);
2512 static FILE *generate_stream_from_list(struct pipe *head)
2515 int pid, channel[2];
2516 if (pipe(channel) < 0) bb_perror_msg_and_die("pipe");
2523 bb_perror_msg_and_die("fork");
2524 } else if (pid == 0) {
2526 if (channel[1] != 1) {
2527 dup2(channel[1], 1);
2530 _exit(run_list_real(head)); /* leaks memory */
2532 debug_printf("forked child %d\n", pid);
2534 pf = fdopen(channel[0], "r");
2535 debug_printf("pipe on FILE *%p\n", pf);
2539 /* this version hacked for testing purposes */
2540 /* return code is exit status of the process that is run. */
2541 static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end)
2544 o_string result = NULL_O_STRING;
2545 struct p_context inner;
2547 struct in_str pipe_str;
2548 initialize_context(&inner);
2550 /* recursion to generate command */
2551 retcode = parse_stream(&result, &inner, input, subst_end);
2552 if (retcode != 0) return retcode; /* syntax error or EOF */
2553 done_word(&result, &inner);
2554 done_pipe(&inner, PIPE_SEQ);
2557 p = generate_stream_from_list(inner.list_head);
2558 if (p == NULL) return 1;
2559 mark_open(fileno(p));
2560 setup_file_in_str(&pipe_str, p);
2562 /* now send results of command back into original context */
2563 retcode = parse_stream(dest, ctx, &pipe_str, '\0');
2564 /* XXX In case of a syntax error, should we try to kill the child?
2565 * That would be tough to do right, so just read until EOF. */
2567 while (b_getch(&pipe_str) != EOF)
2571 debug_printf("done reading from pipe, pclose()ing\n");
2572 /* This is the step that wait()s for the child. Should be pretty
2573 * safe, since we just read an EOF from its stdout. We could try
2574 * to better, by using wait(), and keeping track of background jobs
2575 * at the same time. That would be a lot of work, and contrary
2576 * to the KISS philosophy of this program. */
2577 mark_closed(fileno(p));
2578 retcode = pclose(p);
2579 free_pipe_list(inner.list_head, 0);
2580 debug_printf("pclosed, retcode=%d\n", retcode);
2581 /* XXX this process fails to trim a single trailing newline */
2585 static int parse_group(o_string *dest, struct p_context *ctx,
2586 struct in_str *input, int ch)
2588 int rcode, endch = 0;
2589 struct p_context sub;
2590 struct child_prog *child = ctx->child;
2593 return 1; /* syntax error, groups and arglists don't mix */
2595 initialize_context(&sub);
2599 child->subshell = 1;
2605 syntax(); /* really logic error */
2607 rcode = parse_stream(dest, &sub, input, endch);
2608 done_word(dest, &sub); /* finish off the final word in the subcontext */
2609 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
2610 child->group = sub.list_head;
2612 /* child remains "open", available for possible redirects */
2615 /* basically useful version until someone wants to get fancier,
2616 * see the bash man page under "Parameter Expansion" */
2617 static const char *lookup_param(const char *src)
2619 const char *p = NULL;
2623 p = get_local_var(src);
2628 /* Make new string for parser */
2629 static char* make_string(char ** inp)
2636 for (n = 0; inp[n]; n++) {
2637 p = insert_var_value(inp[n]);
2638 str = xrealloc(str, (len + strlen(p)));
2645 len = strlen(str) + 3;
2646 if (p != inp[n]) free(p);
2654 /* return code: 0 for OK, 1 for syntax error */
2655 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
2659 int ch = input->peek(input); /* first character after the $ */
2660 debug_printf("handle_dollar: ch=%c\n", ch);
2662 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2664 while (ch = b_peek(input), isalnum(ch) || ch == '_') {
2668 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2669 } else if (isdigit(ch)) {
2670 i = ch - '0'; /* XXX is $0 special? */
2671 if (i < global_argc) {
2672 parse_string(dest, ctx, global_argv[i]); /* recursion */
2675 } else switch (ch) {
2677 b_adduint(dest, getpid());
2681 if (last_bg_pid > 0) b_adduint(dest, last_bg_pid);
2685 b_adduint(dest, last_return_code);
2689 b_adduint(dest, global_argc ? global_argc-1 : 0);
2693 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2696 /* XXX maybe someone will try to escape the '}' */
2698 ch = b_getch(input);
2699 if (ch == EOF || ch == '}')
2707 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2711 process_command_subs(dest, ctx, input, ')');
2715 for (i = 1; i < global_argc; i++) {
2716 parse_string(dest, ctx, global_argv[i]);
2717 if (i+1 < global_argc)
2718 parse_string(dest, ctx, sep);
2724 /* still unhandled, but should be eventually */
2725 bb_error_msg("unhandled syntax: $%c", ch);
2729 b_addqchr(dest,'$', dest->quote);
2731 /* Eat the character if the flag was set. If the compiler
2732 * is smart enough, we could substitute "b_getch(input);"
2733 * for all the "advance = 1;" above, and also end up with
2734 * a nice size-optimized program. Hah! That'll be the day.
2736 if (advance) b_getch(input);
2740 static int parse_string(o_string *dest, struct p_context *ctx, const char *src)
2743 setup_string_in_str(&foo, src);
2744 return parse_stream(dest, ctx, &foo, '\0');
2747 /* return code is 0 for normal exit, 1 for syntax error */
2748 static int parse_stream(o_string *dest, struct p_context *ctx,
2749 struct in_str *input, int end_trigger)
2753 redir_type redir_style;
2756 /* Only double-quote state is handled in the state variable dest->quote.
2757 * A single-quote triggers a bypass of the main loop until its mate is
2758 * found. When recursing, quote state is passed in via dest->quote. */
2760 debug_printf("parse_stream, end_trigger=%d\n", end_trigger);
2761 while ((ch = b_getch(input)) != EOF) {
2763 next = (ch == '\n') ? 0 : b_peek(input);
2764 debug_printf("parse_stream: ch=%c (%d) m=%d quote=%d\n",
2765 ch, ch, m, dest->quote);
2766 if (m == 0 || ((m == 1 || m == 2) && dest->quote)) {
2767 b_addqchr(dest, ch, dest->quote);
2770 if (m == 2) { /* unquoted IFS */
2771 if (done_word(dest, ctx)) {
2774 /* If we aren't performing a substitution, treat a newline as a
2775 * command separator. */
2776 if (end_trigger != '\0' && ch == '\n')
2777 done_pipe(ctx, PIPE_SEQ);
2779 if (ch == end_trigger && !dest->quote && ctx->w == RES_NONE) {
2780 debug_printf("leaving parse_stream (triggered)\n");
2787 if (dest->length == 0 && !dest->quote) {
2790 if (ch == EOF || ch == '\n')
2795 b_addqchr(dest, ch, dest->quote);
2803 b_addqchr(dest, '\\', dest->quote);
2804 b_addqchr(dest, b_getch(input), dest->quote);
2807 if (handle_dollar(dest, ctx, input) != 0) return 1;
2812 ch = b_getch(input);
2813 if (ch == EOF || ch == '\'')
2824 dest->quote = !dest->quote;
2827 process_command_subs(dest, ctx, input, '`');
2830 redir_fd = redirect_opt_num(dest);
2831 done_word(dest, ctx);
2832 redir_style = REDIRECT_OVERWRITE;
2834 redir_style = REDIRECT_APPEND;
2836 } else if (next == '(') {
2837 syntax(); /* until we support >(list) Process Substitution */
2840 setup_redirect(ctx, redir_fd, redir_style, input);
2843 redir_fd = redirect_opt_num(dest);
2844 done_word(dest, ctx);
2845 redir_style = REDIRECT_INPUT;
2847 redir_style = REDIRECT_HEREIS;
2849 } else if (next == '>') {
2850 redir_style = REDIRECT_IO;
2852 } else if (next == '(') {
2853 syntax(); /* until we support <(list) Process Substitution */
2856 setup_redirect(ctx, redir_fd, redir_style, input);
2859 done_word(dest, ctx);
2860 done_pipe(ctx, PIPE_SEQ);
2863 done_word(dest, ctx);
2866 done_pipe(ctx, PIPE_AND);
2868 done_pipe(ctx, PIPE_BG);
2872 done_word(dest, ctx);
2875 done_pipe(ctx, PIPE_OR);
2877 /* we could pick up a file descriptor choice here
2878 * with redirect_opt_num(), but bash doesn't do it.
2879 * "echo foo 2| cat" yields "foo 2". */
2885 if (parse_group(dest, ctx, input, ch) != 0)
2890 syntax(); /* Proper use of this character caught by end_trigger */
2893 syntax(); /* this is really an internal logic error */
2897 /* complain if quote? No, maybe we just finished a command substitution
2898 * that was quoted. Example:
2899 * $ echo "`cat foo` plus more"
2900 * and we just got the EOF generated by the subshell that ran "cat foo"
2901 * The only real complaint is if we got an EOF when end_trigger != '\0',
2902 * that is, we were really supposed to get end_trigger, and never got
2903 * one before the EOF. Can't use the standard "syntax error" return code,
2904 * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
2905 debug_printf("leaving parse_stream (EOF)\n");
2906 if (end_trigger != '\0')
2911 static void mapset(const char *set, int code)
2914 map[(unsigned char)*set++] = code;
2917 static void update_ifs_map(void)
2919 /* char *ifs and char map[256] are both globals. */
2920 ifs = getenv("IFS");
2921 if (ifs == NULL) ifs = " \t\n";
2922 /* Precompute a list of 'flow through' behavior so it can be treated
2923 * quickly up front. Computation is necessary because of IFS.
2924 * Special case handling of IFS == " \t\n" is not implemented.
2925 * The map[] array only really needs two bits each, and on most machines
2926 * that would be faster because of the reduced L1 cache footprint.
2928 memset(map, 0, sizeof(map)); /* most characters flow through always */
2929 mapset("\\$'\"`", 3); /* never flow through */
2930 mapset("<>;&|(){}#", 1); /* flow through if quoted */
2931 mapset(ifs, 2); /* also flow through if quoted */
2934 /* most recursion does not come through here, the exception is
2935 * from builtin_source() */
2936 static int parse_stream_outer(struct in_str *inp, int flag)
2938 struct p_context ctx;
2939 o_string temp = NULL_O_STRING;
2943 initialize_context(&ctx);
2945 if (!(flag & FLAG_PARSE_SEMICOLON) || (flag & FLAG_REPARSING))
2947 inp->promptmode = 1;
2948 rcode = parse_stream(&temp, &ctx, inp, '\n');
2949 if (rcode != 1 && ctx.old_flag != 0) {
2952 if (rcode != 1 && ctx.old_flag == 0) {
2953 done_word(&temp, &ctx);
2954 done_pipe(&ctx, PIPE_SEQ);
2955 run_list(ctx.list_head);
2957 if (ctx.old_flag != 0) {
2964 free_pipe_list(ctx.list_head, 0);
2967 } while (rcode != -1 && !(flag & FLAG_EXIT_FROM_LOOP)); /* loop on syntax errors, return on EOF */
2971 static int parse_string_outer(const char *s, int flag)
2973 struct in_str input;
2974 setup_string_in_str(&input, s);
2975 return parse_stream_outer(&input, flag);
2978 static int parse_file_outer(FILE *f)
2981 struct in_str input;
2982 setup_file_in_str(&input, f);
2983 rcode = parse_stream_outer(&input, FLAG_PARSE_SEMICOLON);
2987 /* Make sure we have a controlling tty. If we get started under a job
2988 * aware app (like bash for example), make sure we are now in charge so
2989 * we don't fight over who gets the foreground */
2990 static void setup_job_control(void)
2994 saved_task_pgrp = shell_pgrp = getpgrp();
2995 debug_printf("saved_task_pgrp=%d\n", saved_task_pgrp);
2996 fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
2998 /* If we were ran as 'hush &',
2999 * sleep until we are in the foreground. */
3000 while (tcgetpgrp(interactive_fd) != shell_pgrp) {
3001 /* Send TTIN to ourself (will stop us) */
3002 kill(- shell_pgrp, SIGTTIN);
3003 shell_pgrp = getpgrp();
3006 /* Ignore job-control and misc signals. */
3007 set_jobctrl_sighandler(SIG_IGN);
3008 set_misc_sighandler(SIG_IGN);
3009 //huh? signal(SIGCHLD, SIG_IGN);
3011 /* We _must_ do cleanup on fatal signals */
3012 set_fatal_sighandler(sigexit);
3014 /* Put ourselves in our own process group. */
3015 shell_pgrp = getpid();
3016 setpgrp(); /* is the same as setpgid(shell_pgrp, shell_pgrp); */
3018 /* Grab control of the terminal. */
3019 tcsetpgrp(interactive_fd, shell_pgrp);
3022 int hush_main(int argc, char **argv);
3023 int hush_main(int argc, char **argv)
3029 #if ENABLE_FEATURE_EDITING
3030 line_input_state = new_line_input_t(FOR_SHELL);
3033 /* XXX what should these be while sourcing /etc/profile? */
3037 /* (re?) initialize globals. Sometimes hush_main() ends up calling
3038 * hush_main(), therefore we cannot rely on the BSS to zero out this
3039 * stuff. Reset these to 0 every time. */
3041 /* map[] is taken care of with call to update_ifs_map() */
3044 close_me_head = NULL;
3049 /* Initialize some more globals to non-zero values */
3051 if (ENABLE_FEATURE_EDITING)
3052 cmdedit_set_initial_prompt();
3056 /* initialize our shell local variables with the values
3057 * currently living in the environment */
3061 set_local_var(*e++, 2); /* without call putenv() */
3063 last_return_code = EXIT_SUCCESS;
3065 if (argv[0] && argv[0][0] == '-') {
3066 debug_printf("\nsourcing /etc/profile\n");
3067 input = fopen("/etc/profile", "r");
3068 if (input != NULL) {
3069 mark_open(fileno(input));
3070 parse_file_outer(input);
3071 mark_closed(fileno(input));
3077 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
3080 global_argv = argv + optind;
3081 global_argc = argc - optind;
3082 opt = parse_string_outer(optarg, FLAG_PARSE_SEMICOLON);
3085 // Well, we cannot just declare interactiveness,
3086 // we have to have some stuff (ctty, etc)
3087 /*interactive_fd++;*/
3094 fprintf(stderr, "Usage: sh [FILE]...\n"
3095 " or: sh -c command [args]...\n\n");
3102 /* A shell is interactive if the '-i' flag was given, or if all of
3103 * the following conditions are met:
3105 * no arguments remaining or the -s flag given
3106 * standard input is a terminal
3107 * standard output is a terminal
3108 * Refer to Posix.2, the description of the 'sh' utility. */
3109 if (argv[optind] == NULL && input == stdin
3110 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3112 saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
3113 debug_printf("saved_tty_pgrp=%d\n", saved_tty_pgrp);
3114 if (saved_tty_pgrp >= 0) {
3115 /* try to dup to high fd#, >= 255 */
3116 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3117 if (interactive_fd < 0) {
3118 /* try to dup to any fd */
3119 interactive_fd = dup(STDIN_FILENO);
3120 if (interactive_fd < 0)
3124 // TODO: track & disallow any attempts of user
3125 // to (inadvertently) close/redirect it
3129 debug_printf("\ninteractive_fd=%d\n", interactive_fd);
3130 if (interactive_fd) {
3131 /* Looks like they want an interactive shell */
3132 setup_job_control();
3133 /* Make xfuncs do cleanup on exit */
3134 die_sleep = -1; /* flag */
3135 if (setjmp(die_jmp)) {
3136 /* xfunc has failed! die die die */
3137 hush_exit(xfunc_error_retval);
3139 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
3140 printf("\n\n%s hush - the humble shell v0.02\n", BB_BANNER);
3141 printf("Enter 'help' for a list of built-in commands.\n\n");
3145 if (argv[optind] == NULL) {
3146 opt = parse_file_outer(stdin);
3150 debug_printf("\nrunning script '%s'\n", argv[optind]);
3151 global_argv = argv + optind;
3152 global_argc = argc - optind;
3153 input = xfopen(argv[optind], "r");
3154 opt = parse_file_outer(input);
3156 #if ENABLE_FEATURE_CLEAN_UP
3158 if (cwd != bb_msg_unknown)
3161 struct variables *cur, *tmp;
3162 for (cur = top_vars; cur; cur = tmp) {
3164 if (!cur->flg_read_only) {
3165 free((char*)cur->name);
3166 free((char*)cur->value);
3174 hush_exit(opt ? opt : last_return_code);