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.
13 * The execution engine, the builtins, and much of the underlying
14 * support has been adapted from busybox-0.49pre's lash,
15 * which is Copyright (C) 2000 by Lineo, Inc., and
16 * written by Erik Andersen <andersen@lineo.com>, <andersee@debian.org>.
17 * That, in turn, is based in part on ladsh.c, by Michael K. Johnson and
18 * Erik W. Troan, which they placed in the public domain. I don't know
19 * how much of the Johnson/Troan code has survived the repeated rewrites.
21 * simple_itoa() was lifted from boa-0.93.15
22 * b_addchr() derived from similar w_addchar function in glibc-2.2
23 * setup_redirect(), redirect_opt_num(), and big chunks of main()
24 * and many builtins derived from contributions by Erik Andersen
25 * miscellaneous bugfixes from Matt Kraai
27 * There are two big (and related) architecture differences between
28 * this parser and the lash parser. One is that this version is
29 * actually designed from the ground up to understand nearly all
30 * of the Bourne grammar. The second, consequential change is that
31 * the parser and input reader have been turned inside out. Now,
32 * the parser is in control, and asks for input as needed. The old
33 * way had the input reader in control, and it asked for parsing to
34 * take place as needed. The new way makes it much easier to properly
35 * handle the recursion implicit in the various substitutions, especially
36 * across continuation lines.
38 * Bash grammar not implemented: (how many of these were in original sh?)
39 * $@ (those sure look like weird quoting rules)
41 * ! negation operator for pipes
42 * &> and >& redirection of stdout+stderr
45 * fancy forms of Parameter Expansion
46 * Arithmetic Expansion
47 * <(list) and >(list) Process Substitution
48 * reserved words: case, esac, function
49 * Here Documents ( << word )
52 * job handling woefully incomplete and buggy
53 * reserved word execution woefully incomplete and buggy
55 * port selected bugfixes from post-0.49 busybox lash
56 * finish implementing reserved words
57 * handle children going into background
58 * clean up recognition of null pipes
59 * have builtin_exec set flag to avoid restore_redirects
60 * figure out if "echo foo}" is fixable
61 * check setting of global_argc and global_argv
62 * control-C handling, probably with longjmp
63 * VAR=value prefix for simple commands
64 * follow IFS rules more precisely, including update semantics
65 * write builtin_eval, builtin_ulimit, builtin_umask
66 * figure out what to do with backslash-newline
67 * explain why we use signal instead of sigaction
68 * propagate syntax errors, die on resource errors?
69 * continuation lines, both explicit and implicit - done?
70 * memory leak finding and plugging - done?
71 * more testing, especially quoting rules and redirection
72 * maybe change map[] to use 2-bit entries
73 * (eventually) remove all the printf's
75 * This program is free software; you can redistribute it and/or modify
76 * it under the terms of the GNU General Public License as published by
77 * the Free Software Foundation; either version 2 of the License, or
78 * (at your option) any later version.
80 * This program is distributed in the hope that it will be useful,
81 * but WITHOUT ANY WARRANTY; without even the implied warranty of
82 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
83 * General Public License for more details.
85 * You should have received a copy of the GNU General Public License
86 * along with this program; if not, write to the Free Software
87 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
89 #include <ctype.h> /* isalpha, isdigit */
90 #include <unistd.h> /* getpid */
91 #include <stdlib.h> /* getenv, atoi */
92 #include <string.h> /* strchr */
93 #include <stdio.h> /* popen etc. */
94 #include <glob.h> /* glob, of course */
95 #include <stdarg.h> /* va_list */
98 #include <getopt.h> /* should be pretty obvious */
100 #include <sys/types.h>
101 #include <sys/wait.h>
104 /* #include <dmalloc.h> */
105 /* #define DEBUG_SHELL */
111 #define applet_name "hush"
112 #include "standalone.h"
113 #define shell_main main
114 #define BB_FEATURE_SH_SIMPLE_PROMPT
119 REDIRECT_OVERWRITE = 2,
125 /* The descrip member of this structure is only used to make debugging
127 struct {int mode; int default_fd; char *descrip;} redir_table[] = {
129 { O_RDONLY, 0, "<" },
130 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
131 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
132 { O_RDONLY, -1, "<<" },
143 /* might eventually control execution */
159 #define FLAG_END (1<<RES_NONE)
160 #define FLAG_IF (1<<RES_IF)
161 #define FLAG_THEN (1<<RES_THEN)
162 #define FLAG_ELIF (1<<RES_ELIF)
163 #define FLAG_ELSE (1<<RES_ELSE)
164 #define FLAG_FI (1<<RES_FI)
165 #define FLAG_FOR (1<<RES_FOR)
166 #define FLAG_WHILE (1<<RES_WHILE)
167 #define FLAG_UNTIL (1<<RES_UNTIL)
168 #define FLAG_DO (1<<RES_DO)
169 #define FLAG_DONE (1<<RES_DONE)
170 #define FLAG_START (1<<RES_XXXX)
172 /* This holds pointers to the various results of parsing */
174 struct child_prog *child;
175 struct pipe *list_head;
177 struct redir_struct *pending_redirect;
179 int old_flag; /* for figuring out valid reserved words */
180 struct p_context *stack;
181 /* How about quoting status? */
184 struct redir_struct {
185 redir_type type; /* type of redirection */
186 int fd; /* file descriptor being redirected */
187 int dup; /* -1, or file descriptor being duplicated */
188 struct redir_struct *next; /* pointer to the next redirect in the list */
189 glob_t word; /* *word.gl_pathv is the filename */
193 pid_t pid; /* 0 if exited */
194 char **argv; /* program name and arguments */
195 struct pipe *group; /* if non-NULL, first in group or subshell */
196 int subshell; /* flag, non-zero if group must be forked */
197 struct redir_struct *redirects; /* I/O redirections */
198 glob_t glob_result; /* result of parameter globbing */
199 int is_stopped; /* is the program currently running? */
200 struct pipe *family; /* pointer back to the child's parent pipe */
204 int jobid; /* job number */
205 int num_progs; /* total number of programs in job */
206 int running_progs; /* number of programs running */
207 char *text; /* name of job */
208 char *cmdbuf; /* buffer various argv's point into */
209 pid_t pgrp; /* process group ID for the job */
210 struct child_prog *progs; /* array of commands in pipe */
211 struct pipe *next; /* to track background commands */
212 int stopped_progs; /* number of programs alive, but stopped */
213 int job_context; /* bitmask defining current context */
214 pipe_style followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
215 reserved_style r_mode; /* supports if, for, while, until */
216 struct jobset *job_list;
220 struct pipe *head; /* head of list of running jobs */
221 struct pipe *fg; /* current foreground job */
226 struct close_me *next;
229 /* globals, connect us to the outside world
230 * the first three support $?, $#, and $1 */
232 unsigned int global_argc;
233 unsigned int last_return_code;
234 extern char **environ; /* This is in <unistd.h>, but protected with __USE_GNU */
236 /* Variables we export */
237 unsigned int shell_context; /* Used in cmdedit.c to reset the
238 * context when someone hits ^C */
240 /* "globals" within this file */
241 static char *ifs=NULL;
242 static char map[256];
243 static int fake_mode=0;
244 static int interactive=0;
245 static struct close_me *close_me_head = NULL;
247 /* static struct jobset job_list = { NULL, NULL }; */
248 static unsigned int last_bg_pid=0;
250 static char *PS2 = "> ";
252 #define B_CHUNK (100)
254 #define MAX_LINE 256 /* for cwd */
255 #define MAX_READ 256 /* for builtin_read */
264 #define NULL_O_STRING {NULL,0,0,0,0}
265 /* used for initialization:
266 o_string foo = NULL_O_STRING; */
268 /* I can almost use ordinary FILE *. Is open_memstream() universally
269 * available? Where is it documented? */
275 int (*get) (struct in_str *);
276 int (*peek) (struct in_str *);
278 #define b_getch(input) ((input)->get(input))
279 #define b_peek(input) ((input)->peek(input))
281 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
283 struct built_in_command {
284 char *cmd; /* name */
285 char *descr; /* description */
286 int (*function) (struct child_prog *); /* function ptr */
289 /* belongs in busybox.h */
290 static inline int max(int a, int b) {
294 /* This should be in utility.c */
296 static void debug_printf(const char *format, ...)
299 va_start(args, format);
300 vfprintf(stderr, format, args);
304 static void debug_printf(const char *format, ...) { }
306 #define final_printf debug_printf
308 void __syntax(char *file, int line) {
309 fprintf(stderr,"syntax error %s:%d\n",file,line);
311 #define syntax() __syntax(__FILE__, __LINE__)
313 /* Index of subroutines: */
314 /* function prototypes for builtins */
315 static int builtin_cd(struct child_prog *child);
316 static int builtin_env(struct child_prog *child);
317 static int builtin_exec(struct child_prog *child);
318 static int builtin_exit(struct child_prog *child);
319 static int builtin_export(struct child_prog *child);
320 static int builtin_fg_bg(struct child_prog *child);
321 static int builtin_help(struct child_prog *child);
322 static int builtin_jobs(struct child_prog *child);
323 static int builtin_pwd(struct child_prog *child);
324 static int builtin_read(struct child_prog *child);
325 static int builtin_shift(struct child_prog *child);
326 static int builtin_source(struct child_prog *child);
327 static int builtin_ulimit(struct child_prog *child);
328 static int builtin_umask(struct child_prog *child);
329 static int builtin_unset(struct child_prog *child);
330 /* o_string manipulation: */
331 static int b_check_space(o_string *o, int len);
332 static int b_addchr(o_string *o, int ch);
333 static void b_reset(o_string *o);
334 static int b_addqchr(o_string *o, int ch, int quote);
335 static int b_adduint(o_string *o, unsigned int i);
336 /* in_str manipulations: */
337 static int static_get(struct in_str *i);
338 static int static_peek(struct in_str *i);
339 static int file_get(struct in_str *i);
340 static int file_peek(struct in_str *i);
341 static void setup_file_in_str(struct in_str *i, FILE *f);
342 static void setup_string_in_str(struct in_str *i, const char *s);
343 /* close_me manipulations: */
344 static void mark_open(int fd);
345 static void mark_closed(int fd);
346 static void close_all();
347 /* "run" the final data structures: */
348 static char *indenter(int i);
349 static int run_list_test(struct pipe *head, int indent);
350 static int run_pipe_test(struct pipe *pi, int indent);
351 /* really run the final data structures: */
352 static int setup_redirects(struct child_prog *prog, int squirrel[]);
353 static int pipe_wait(struct pipe *pi);
354 static int run_list_real(struct pipe *pi);
355 static void pseudo_exec(struct child_prog *child) __attribute__ ((noreturn));
356 static int run_pipe_real(struct pipe *pi);
357 /* extended glob support: */
358 static int globhack(const char *src, int flags, glob_t *pglob);
359 static int glob_needed(const char *s);
360 static int xglob(o_string *dest, int flags, glob_t *pglob);
361 /* data structure manipulation: */
362 static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
363 static void initialize_context(struct p_context *ctx);
364 static int done_word(o_string *dest, struct p_context *ctx);
365 static int done_command(struct p_context *ctx);
366 static int done_pipe(struct p_context *ctx, pipe_style type);
367 /* primary string parsing: */
368 static int redirect_dup_num(struct in_str *input);
369 static int redirect_opt_num(o_string *o);
370 static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end);
371 static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
372 static void lookup_param(o_string *dest, struct p_context *ctx, o_string *src);
373 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
374 static int parse_string(o_string *dest, struct p_context *ctx, const char *src);
375 static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, int end_trigger);
377 static int parse_stream_outer(struct in_str *inp);
378 static int parse_string_outer(const char *s);
379 static int parse_file_outer(FILE *f);
381 /* Table of built-in functions. They can be forked or not, depending on
382 * context: within pipes, they fork. As simple commands, they do not.
383 * When used in non-forking context, they can change global variables
384 * in the parent shell process. If forked, of course they can not.
385 * For example, 'unset foo | whatever' will parse and run, but foo will
386 * still be set at the end. */
387 static struct built_in_command bltins[] = {
388 {"bg", "Resume a job in the background", builtin_fg_bg},
389 {"cd", "Change working directory", builtin_cd},
390 {"env", "Print all environment variables", builtin_env},
391 {"exec", "Exec command, replacing this shell with the exec'd process", builtin_exec},
392 {"exit", "Exit from shell()", builtin_exit},
393 {"export", "Set environment variable", builtin_export},
394 {"fg", "Bring job into the foreground", builtin_fg_bg},
395 {"jobs", "Lists the active jobs", builtin_jobs},
396 {"pwd", "Print current directory", builtin_pwd},
397 {"read", "Input environment variable", builtin_read},
398 {"shift", "Shift positional parameters", builtin_shift},
399 {"ulimit","Controls resource limits", builtin_ulimit},
400 {"umask","Sets file creation mask", builtin_umask},
401 {"unset", "Unset environment variable", builtin_unset},
402 {".", "Source-in and run commands in a file", builtin_source},
403 {"help", "List shell built-in commands", builtin_help},
407 /* built-in 'cd <path>' handler */
408 static int builtin_cd(struct child_prog *child)
411 if (child->argv[1] == NULL)
412 newdir = getenv("HOME");
414 newdir = child->argv[1];
416 printf("cd: %s: %s\n", newdir, strerror(errno));
419 getcwd(cwd, sizeof(char)*MAX_LINE);
423 /* built-in 'env' handler */
424 static int builtin_env(struct child_prog *dummy)
427 if (e == NULL) return EXIT_FAILURE;
434 /* built-in 'exec' handler */
435 static int builtin_exec(struct child_prog *child)
437 if (child->argv[1] == NULL)
438 return EXIT_SUCCESS; /* Really? */
444 /* built-in 'exit' handler */
445 static int builtin_exit(struct child_prog *child)
447 if (child->argv[1] == NULL)
449 exit (atoi(child->argv[1]));
452 /* built-in 'export VAR=value' handler */
453 static int builtin_export(struct child_prog *child)
457 if (child->argv[1] == NULL) {
458 return (builtin_env(child));
460 res = putenv(child->argv[1]);
462 fprintf(stderr, "export: %s\n", strerror(errno));
466 /* built-in 'fg' and 'bg' handler */
467 static int builtin_fg_bg(struct child_prog *child)
470 struct pipe *job=NULL;
472 if (!child->argv[1] || child->argv[2]) {
473 error_msg("%s: exactly one argument is expected\n",
478 if (sscanf(child->argv[1], "%%%d", &jobNum) != 1) {
479 error_msg("%s: bad argument '%s'\n",
480 child->argv[0], child->argv[1]);
484 for (job = child->family->job_list->head; job; job = job->next) {
485 if (job->jobid == jobNum) {
491 error_msg("%s: unknown job %d\n",
492 child->argv[0], jobNum);
496 if (*child->argv[0] == 'f') {
497 /* Make this job the foreground job */
498 /* suppress messages when run from /linuxrc mag@sysgo.de */
499 if (tcsetpgrp(0, job->pgrp) && errno != ENOTTY)
500 perror_msg("tcsetpgrp");
501 child->family->job_list->fg = job;
504 /* Restart the processes in the job */
505 for (i = 0; i < job->num_progs; i++)
506 job->progs[i].is_stopped = 0;
508 kill(-job->pgrp, SIGCONT);
510 job->stopped_progs = 0;
514 /* built-in 'help' handler */
515 static int builtin_help(struct child_prog *dummy)
517 struct built_in_command *x;
519 printf("\nBuilt-in commands:\n");
520 printf("-------------------\n");
521 for (x = bltins; x->cmd; x++) {
524 printf("%s\t%s\n", x->cmd, x->descr);
530 /* built-in 'jobs' handler */
531 static int builtin_jobs(struct child_prog *child)
536 for (job = child->family->job_list->head; job; job = job->next) {
537 if (job->running_progs == job->stopped_progs)
538 status_string = "Stopped";
540 status_string = "Running";
541 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->text);
547 /* built-in 'pwd' handler */
548 static int builtin_pwd(struct child_prog *dummy)
550 getcwd(cwd, MAX_LINE);
555 /* built-in 'read VAR' handler */
556 static int builtin_read(struct child_prog *child)
558 int res = 0, len, newlen;
560 char string[MAX_READ];
562 if (child->argv[1]) {
563 /* argument (VAR) given: put "VAR=" into buffer */
564 strcpy(string, child->argv[1]);
565 len = strlen(string);
568 /* XXX would it be better to go through in_str? */
569 fgets(&string[len], sizeof(string) - len, stdin); /* read string */
570 newlen = strlen(string);
572 string[--newlen] = '\0'; /* chomp trailing newline */
574 ** string should now contain "VAR=<value>"
575 ** copy it (putenv() won't do that, so we must make sure
576 ** the string resides in a static buffer!)
579 if((s = strdup(string)))
582 fprintf(stderr, "read: %s\n", strerror(errno));
585 fgets(string, sizeof(string), stdin);
590 /* Built-in 'shift' handler */
591 static int builtin_shift(struct child_prog *child)
594 if (child->argv[1]) {
595 n=atoi(child->argv[1]);
597 if (n>=0 && n<global_argc) {
598 /* XXX This probably breaks $0 */
607 /* Built-in '.' handler (read-in and execute commands from file) */
608 static int builtin_source(struct child_prog *child)
613 if (child->argv[1] == NULL)
616 /* XXX search through $PATH is missing */
617 input = fopen(child->argv[1], "r");
619 fprintf(stderr, "Couldn't open file '%s'\n", child->argv[1]);
623 /* Now run the file */
624 /* XXX argv and argc are broken; need to save old global_argv
625 * (pointer only is OK!) on this stack frame,
626 * set global_argv=child->argv+1, recurse, and restore. */
627 mark_open(fileno(input));
628 status = parse_file_outer(input);
629 mark_closed(fileno(input));
634 static int builtin_ulimit(struct child_prog *child)
636 printf("builtin_ulimit not written\n");
640 static int builtin_umask(struct child_prog *child)
642 printf("builtin_umask not written\n");
646 /* built-in 'unset VAR' handler */
647 static int builtin_unset(struct child_prog *child)
649 if (child->argv[1] == NULL) {
650 fprintf(stderr, "unset: parameter required.\n");
653 unsetenv(child->argv[1]);
657 static int b_check_space(o_string *o, int len)
659 /* It would be easy to drop a more restrictive policy
660 * in here, such as setting a maximum string length */
661 if (o->length + len > o->maxlen) {
662 char *old_data = o->data;
663 /* assert (data == NULL || o->maxlen != 0); */
664 o->maxlen += max(2*len, B_CHUNK);
665 o->data = realloc(o->data, 1 + o->maxlen);
666 if (o->data == NULL) {
670 return o->data == NULL;
673 static int b_addchr(o_string *o, int ch)
675 debug_printf("b_addchr: %c %d %p\n", ch, o->length, o);
676 if (b_check_space(o, 1)) return B_NOSPAC;
677 o->data[o->length] = ch;
679 o->data[o->length] = '\0';
683 static void b_reset(o_string *o)
687 if (o->data != NULL) *o->data = '\0';
690 static void b_free(o_string *o)
693 if (o->data != NULL) free(o->data);
698 /* My analysis of quoting semantics tells me that state information
699 * is associated with a destination, not a source.
701 static int b_addqchr(o_string *o, int ch, int quote)
703 if (quote && strchr("*?[\\",ch)) {
705 rc = b_addchr(o, '\\');
708 return b_addchr(o, ch);
711 /* belongs in utility.c */
712 char *simple_itoa(unsigned int i)
714 /* 21 digits plus null terminator, good for 64-bit or smaller ints */
715 static char local[22];
716 char *p = &local[21];
725 static int b_adduint(o_string *o, unsigned int i)
728 char *p = simple_itoa(i);
729 /* no escape checking necessary */
730 do r=b_addchr(o, *p++); while (r==0 && *p);
734 static int static_get(struct in_str *i)
737 if (ch=='\0') return EOF;
741 static int static_peek(struct in_str *i)
746 static inline void cmdedit_set_initial_prompt(void)
748 #ifdef BB_FEATURE_SH_SIMPLE_PROMPT
757 static inline void setup_prompt_string(int promptmode, char **prompt_str)
759 debug_printf("setup_prompt_string %d ",promptmode);
760 #ifdef BB_FEATURE_SH_SIMPLE_PROMPT
761 /* Set up the prompt */
762 if (promptmode == 1) {
765 PS1=xmalloc(strlen(cwd)+4);
766 sprintf(PS1, "%s %s", cwd, ( geteuid() != 0 ) ? "$ ":"# ");
772 *prompt_str = (promptmode==0)? PS1 : PS2;
774 debug_printf("result %s\n",*prompt_str);
777 static void get_user_input(struct in_str *i)
780 static char the_command[BUFSIZ];
782 setup_prompt_string(i->promptmode, &prompt_str);
783 #ifdef BB_FEATURE_COMMAND_EDITING
785 ** enable command line editing only while a command line
786 ** is actually being read; otherwise, we'll end up bequeathing
787 ** atexit() handlers and other unwanted stuff to our
788 ** child processes (rob@sysgo.de)
790 cmdedit_read_input(prompt_str, the_command);
793 fputs(prompt_str, stdout);
795 the_command[0]=fgetc(i->file);
801 /* This is the magic location that prints prompts
802 * and gets data back from the user */
803 static int file_get(struct in_str *i)
808 /* If there is data waiting, eat it up */
812 /* need to double check i->file because we might be doing something
813 * more complicated by now, like sourcing or substituting. */
814 if (i->__promptme && interactive && i->file == stdin) {
819 buffer = fgetc(i->file);
828 debug_printf("b_getch: got a %d\n", ch);
830 if (ch == '\n') i->__promptme=1;
834 /* All the callers guarantee this routine will never be
835 * used right after a newline, so prompting is not needed.
837 static int file_peek(struct in_str *i)
843 buffer = fgetc(i->file);
845 debug_printf("b_peek: got a %d\n", *i->p);
850 static void setup_file_in_str(struct in_str *i, FILE *f)
860 static void setup_string_in_str(struct in_str *i, const char *s)
862 i->peek = static_peek;
869 static void mark_open(int fd)
871 struct close_me *new = xmalloc(sizeof(struct close_me));
873 new->next = close_me_head;
877 static void mark_closed(int fd)
879 struct close_me *tmp;
880 if (close_me_head == NULL || close_me_head->fd != fd)
881 error_msg_and_die("corrupt close_me");
883 close_me_head = close_me_head->next;
887 static void close_all()
890 for (c=close_me_head; c; c=c->next) {
893 close_me_head = NULL;
896 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
897 * and stderr if they are redirected. */
898 static int setup_redirects(struct child_prog *prog, int squirrel[])
901 struct redir_struct *redir;
903 for (redir=prog->redirects; redir; redir=redir->next) {
904 if (redir->dup == -1) {
905 mode=redir_table[redir->type].mode;
906 openfd = open(redir->word.gl_pathv[0], mode, 0666);
908 /* this could get lost if stderr has been redirected, but
909 bash and ash both lose it as well (though zsh doesn't!) */
910 fprintf(stderr,"error opening %s: %s\n", redir->word.gl_pathv[0],
918 if (openfd != redir->fd) {
919 if (squirrel && redir->fd < 3) {
920 squirrel[redir->fd] = dup(redir->fd);
922 dup2(openfd, redir->fd);
929 static void restore_redirects(int squirrel[])
932 for (i=0; i<3; i++) {
935 /* No error checking. I sure wouldn't know what
936 * to do with an error if I found one! */
943 /* XXX this definitely needs some more thought, work, and
944 * cribbing from other shells */
945 static int pipe_wait(struct pipe *pi)
947 int rcode=0, i, pid, running, status;
948 running = pi->num_progs;
950 pid=waitpid(-1, &status, 0);
951 if (pid < 0) perror_msg_and_die("waitpid");
952 for (i=0; i < pi->num_progs; i++) {
953 if (pi->progs[i].pid == pid) {
954 if (i==pi->num_progs-1) rcode=WEXITSTATUS(status);
955 pi->progs[i].pid = 0;
964 /* very simple version for testing */
965 static void pseudo_exec(struct child_prog *child)
968 struct built_in_command *x;
971 * Check if the command matches any of the builtins.
972 * Depending on context, this might be redundant. But it's
973 * easier to waste a few CPU cycles than it is to figure out
974 * if this is one of those cases.
976 for (x = bltins; x->cmd; x++) {
977 if (strcmp(child->argv[0], x->cmd) == 0 ) {
978 debug_printf("builtin exec %s\n", child->argv[0]);
979 exit(x->function(child));
983 /* Check if the command matches any busybox internal commands
985 * FIXME: This feature is not 100% safe, since
986 * BusyBox is not fully reentrant, so we have no guarantee the things
987 * from the .bss are still zeroed, or that things from .data are still
988 * at their defaults. We could exec ourself from /proc/self/exe, but I
989 * really dislike relying on /proc for things. We could exec ourself
990 * from global_argv[0], but if we are in a chroot, we may not be able
991 * to find ourself... */
992 #ifdef BB_FEATURE_SH_STANDALONE_SHELL
995 char** argv_l=child->argv;
996 char *name = child->argv[0];
998 #ifdef BB_FEATURE_SH_APPLETS_ALWAYS_WIN
999 /* Following discussions from November 2000 on the busybox mailing
1000 * list, the default configuration, (without
1001 * get_last_path_component()) lets the user force use of an
1002 * external command by specifying the full (with slashes) filename.
1003 * If you enable BB_FEATURE_SH_APPLETS_ALWAYS_WIN, then applets
1004 * _aways_ override external commands, so if you want to run
1005 * /bin/cat, it will use BusyBox cat even if /bin/cat exists on the
1006 * filesystem and is _not_ busybox. Some systems may want this,
1008 name = get_last_path_component(name);
1010 /* Count argc for use in a second... */
1011 for(argc_l=0;*argv_l!=NULL; argv_l++, argc_l++);
1013 debug_printf("running applet %s\n", name);
1014 run_applet_by_name(name, argc_l, child->argv);
1018 debug_printf("exec of %s\n",child->argv[0]);
1019 execvp(child->argv[0],child->argv);
1022 } else if (child->group) {
1023 debug_printf("runtime nesting to group\n");
1024 interactive=0; /* crucial!!!! */
1025 rcode = run_list_real(child->group);
1026 /* OK to leak memory by not calling run_list_test,
1027 * since this process is about to exit */
1030 /* Can happen. See what bash does with ">foo" by itself. */
1031 debug_printf("trying to pseudo_exec null command\n");
1036 /* run_pipe_real() starts all the jobs, but doesn't wait for anything
1037 * to finish. See pipe_wait().
1039 * return code is normally -1, when the caller has to wait for children
1040 * to finish to determine the exit status of the pipe. If the pipe
1041 * is a simple builtin command, however, the action is done by the
1042 * time run_pipe_real returns, and the exit code is provided as the
1045 * The input of the pipe is always stdin, the output is always
1046 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1047 * because it tries to avoid running the command substitution in
1048 * subshell, when that is in fact necessary. The subshell process
1049 * now has its stdout directed to the input of the appropriate pipe,
1050 * so this routine is noticeably simpler.
1052 static int run_pipe_real(struct pipe *pi)
1055 int nextin, nextout;
1056 int pipefds[2]; /* pipefds[0] is for reading */
1057 struct child_prog *child;
1058 struct built_in_command *x;
1063 /* Check if this is a simple builtin (not part of a pipe).
1064 * Builtins within pipes have to fork anyway, and are handled in
1065 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1067 if (pi->num_progs == 1 && pi->progs[0].argv != NULL) {
1068 child = & (pi->progs[0]);
1069 if (child->group && ! child->subshell) {
1070 int squirrel[] = {-1, -1, -1};
1072 debug_printf("non-subshell grouping\n");
1073 setup_redirects(child, squirrel);
1074 /* XXX could we merge code with following builtin case,
1075 * by creating a pseudo builtin that calls run_list_real? */
1076 rcode = run_list_real(child->group);
1077 restore_redirects(squirrel);
1080 for (x = bltins; x->cmd; x++) {
1081 if (strcmp(child->argv[0], x->cmd) == 0 ) {
1082 int squirrel[] = {-1, -1, -1};
1084 debug_printf("builtin inline %s\n", child->argv[0]);
1085 /* XXX setup_redirects acts on file descriptors, not FILEs.
1086 * This is perfect for work that comes after exec().
1087 * Is it really safe for inline use? Experimentally,
1088 * things seem to work with glibc. */
1089 setup_redirects(child, squirrel);
1090 rcode = x->function(child);
1091 restore_redirects(squirrel);
1097 for (i = 0; i < pi->num_progs; i++) {
1098 child = & (pi->progs[i]);
1100 /* pipes are inserted between pairs of commands */
1101 if ((i + 1) < pi->num_progs) {
1102 if (pipe(pipefds)<0) perror_msg_and_die("pipe");
1103 nextout = pipefds[1];
1109 /* XXX test for failed fork()? */
1110 if (!(child->pid = fork())) {
1121 if (pipefds[0]!=-1) {
1122 close(pipefds[0]); /* opposite end of our output pipe */
1125 /* Like bash, explicit redirects override pipes,
1126 * and the pipe fd is available for dup'ing. */
1127 setup_redirects(child,NULL);
1132 /* Put our child in the process group whose leader is the
1133 * first process in this pipe. */
1135 pi->pgrp = child->pid;
1137 /* Don't check for errors. The child may be dead already,
1138 * in which case setpgid returns error code EACCES. */
1139 setpgid(child->pid, pi->pgrp);
1141 /* In the non-interactive case, do nothing. Leave the children
1142 * with the process group that they inherited from us. */
1149 /* If there isn't another process, nextin is garbage
1150 but it doesn't matter */
1151 nextin = pipefds[0];
1156 static int run_list_real(struct pipe *pi)
1159 int if_code=0, next_if_code=0; /* need double-buffer to handle elif */
1160 reserved_style rmode, skip_more_in_this_rmode=RES_XXXX;
1161 for (;pi;pi=pi->next) {
1163 debug_printf("rmode=%d if_code=%d next_if_code=%d skip_more=%d\n", rmode, if_code, next_if_code, skip_more_in_this_rmode);
1164 if (rmode == skip_more_in_this_rmode) continue;
1165 skip_more_in_this_rmode = RES_XXXX;
1166 if (rmode == RES_THEN || rmode == RES_ELSE) if_code = next_if_code;
1167 if (rmode == RES_THEN && if_code) continue;
1168 if (rmode == RES_ELSE && !if_code) continue;
1169 if (rmode == RES_ELIF && !if_code) continue;
1170 if (pi->num_progs == 0) continue;
1171 rcode = run_pipe_real(pi);
1173 /* We only ran a builtin: rcode was set by the return value
1174 * of run_pipe_real(), and we don't need to wait for anything. */
1175 } else if (pi->followup==PIPE_BG) {
1176 /* XXX check bash's behavior with nontrivial pipes */
1177 /* XXX compute jobid */
1178 /* XXX what does bash do with attempts to background builtins? */
1179 printf("[%d] %d\n", pi->jobid, pi->pgrp);
1180 last_bg_pid = pi->pgrp;
1181 rcode = EXIT_SUCCESS;
1184 /* move the new process group into the foreground */
1185 /* suppress messages when run from /linuxrc mag@sysgo.de */
1186 signal(SIGTTIN, SIG_IGN);
1187 signal(SIGTTOU, SIG_IGN);
1188 if (tcsetpgrp(0, pi->pgrp) && errno != ENOTTY)
1189 perror_msg("tcsetpgrp");
1190 rcode = pipe_wait(pi);
1191 if (tcsetpgrp(0, getpid()) && errno != ENOTTY)
1192 perror_msg("tcsetpgrp");
1193 signal(SIGTTIN, SIG_DFL);
1194 signal(SIGTTOU, SIG_DFL);
1196 rcode = pipe_wait(pi);
1199 last_return_code=rcode;
1200 if ( rmode == RES_IF || rmode == RES_ELIF )
1201 next_if_code=rcode; /* can be overwritten a number of times */
1202 if ( (rcode==EXIT_SUCCESS && pi->followup==PIPE_OR) ||
1203 (rcode!=EXIT_SUCCESS && pi->followup==PIPE_AND) )
1204 skip_more_in_this_rmode=rmode;
1205 /* return rcode; */ /* XXX broken if list is part of if/then/else */
1210 /* broken, of course, but OK for testing */
1211 static char *indenter(int i)
1213 static char blanks[]=" ";
1214 return &blanks[sizeof(blanks)-i-1];
1217 /* return code is the exit status of the pipe */
1218 static int run_pipe_test(struct pipe *pi, int indent)
1221 struct child_prog *child;
1222 struct redir_struct *r, *rnext;
1223 int a, i, ret_code=0;
1224 char *ind = indenter(indent);
1225 final_printf("%s run pipe: (pid %d)\n",ind,getpid());
1226 for (i=0; i<pi->num_progs; i++) {
1227 child = &pi->progs[i];
1228 final_printf("%s command %d:\n",ind,i);
1230 for (a=0,p=child->argv; *p; a++,p++) {
1231 final_printf("%s argv[%d] = %s\n",ind,a,*p);
1233 globfree(&child->glob_result);
1235 } else if (child->group) {
1236 final_printf("%s begin group (subshell:%d)\n",ind, child->subshell);
1237 ret_code = run_list_test(child->group,indent+3);
1238 final_printf("%s end group\n",ind);
1240 final_printf("%s (nil)\n",ind);
1242 for (r=child->redirects; r; r=rnext) {
1243 final_printf("%s redirect %d%s", ind, r->fd, redir_table[r->type].descrip);
1245 final_printf(" %s\n", *r->word.gl_pathv);
1248 final_printf("&%d\n", r->dup);
1253 child->redirects=NULL;
1255 free(pi->progs); /* children are an array, they get freed all at once */
1260 static int run_list_test(struct pipe *head, int indent)
1262 int rcode=0; /* if list has no members */
1263 struct pipe *pi, *next;
1264 char *ind = indenter(indent);
1265 for (pi=head; pi; pi=next) {
1266 if (pi->num_progs == 0) break;
1267 final_printf("%s pipe reserved mode %d\n", ind, pi->r_mode);
1268 rcode = run_pipe_test(pi, indent);
1269 final_printf("%s pipe followup code %d\n", ind, pi->followup);
1277 /* Select which version we will use */
1278 static int run_list(struct pipe *pi)
1282 rcode = run_list_real(pi);
1284 /* run_list_test has the side effect of clearing memory
1285 * In the long run that function can be merged with run_list_real,
1286 * but doing that now would hobble the debugging effort. */
1287 run_list_test(pi,0);
1291 /* The API for glob is arguably broken. This routine pushes a non-matching
1292 * string into the output structure, removing non-backslashed backslashes.
1293 * If someone can prove me wrong, by performing this function within the
1294 * original glob(3) api, feel free to rewrite this routine into oblivion.
1295 * Return code (0 vs. GLOB_NOSPACE) matches glob(3).
1296 * XXX broken if the last character is '\\', check that before calling.
1298 static int globhack(const char *src, int flags, glob_t *pglob)
1303 for (cnt=1, s=src; *s; s++) {
1304 if (*s == '\\') s++;
1308 if (!dest) return GLOB_NOSPACE;
1309 if (!(flags & GLOB_APPEND)) {
1310 pglob->gl_pathv=NULL;
1315 pathc = ++pglob->gl_pathc;
1316 pglob->gl_pathv = realloc(pglob->gl_pathv, (pathc+1)*sizeof(*pglob->gl_pathv));
1317 if (pglob->gl_pathv == NULL) return GLOB_NOSPACE;
1318 pglob->gl_pathv[pathc-1]=dest;
1319 pglob->gl_pathv[pathc]=NULL;
1320 for (s=src; *s; s++, dest++) {
1321 if (*s == '\\') s++;
1328 /* XXX broken if the last character is '\\', check that before calling */
1329 static int glob_needed(const char *s)
1332 if (*s == '\\') s++;
1333 if (strchr("*[?",*s)) return 1;
1339 static void globprint(glob_t *pglob)
1342 debug_printf("glob_t at %p:\n", pglob);
1343 debug_printf(" gl_pathc=%d gl_pathv=%p gl_offs=%d gl_flags=%d\n",
1344 pglob->gl_pathc, pglob->gl_pathv, pglob->gl_offs, pglob->gl_flags);
1345 for (i=0; i<pglob->gl_pathc; i++)
1346 debug_printf("pglob->gl_pathv[%d] = %p = %s\n", i,
1347 pglob->gl_pathv[i], pglob->gl_pathv[i]);
1351 static int xglob(o_string *dest, int flags, glob_t *pglob)
1355 /* short-circuit for null word */
1356 /* we can code this better when the debug_printf's are gone */
1357 if (dest->length == 0) {
1358 if (dest->nonnull) {
1359 /* bash man page calls this an "explicit" null */
1360 gr = globhack(dest->data, flags, pglob);
1361 debug_printf("globhack returned %d\n",gr);
1365 } else if (glob_needed(dest->data)) {
1366 gr = glob(dest->data, flags, NULL, pglob);
1367 debug_printf("glob returned %d\n",gr);
1368 if (gr == GLOB_NOMATCH) {
1369 /* quote removal, or more accurately, backslash removal */
1370 gr = globhack(dest->data, flags, pglob);
1371 debug_printf("globhack returned %d\n",gr);
1374 gr = globhack(dest->data, flags, pglob);
1375 debug_printf("globhack returned %d\n",gr);
1377 if (gr == GLOB_NOSPACE) {
1378 fprintf(stderr,"out of memory during glob\n");
1381 if (gr != 0) { /* GLOB_ABORTED ? */
1382 fprintf(stderr,"glob(3) error %d\n",gr);
1384 /* globprint(glob_target); */
1388 /* the src parameter allows us to peek forward to a possible &n syntax
1389 * for file descriptor duplication, e.g., "2>&1".
1390 * Return code is 0 normally, 1 if a syntax error is detected in src.
1391 * Resource errors (in xmalloc) cause the process to exit */
1392 static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
1393 struct in_str *input)
1395 struct child_prog *child=ctx->child;
1396 struct redir_struct *redir = child->redirects;
1397 struct redir_struct *last_redir=NULL;
1399 /* Create a new redir_struct and drop it onto the end of the linked list */
1404 redir = xmalloc(sizeof(struct redir_struct));
1407 last_redir->next=redir;
1409 child->redirects=redir;
1413 redir->fd= (fd==-1) ? redir_table[style].default_fd : fd ;
1415 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
1417 /* Check for a '2>&1' type redirect */
1418 redir->dup = redirect_dup_num(input);
1419 if (redir->dup == -2) return 1; /* syntax error */
1420 if (redir->dup != -1) {
1421 /* Erik had a check here that the file descriptor in question
1422 * is legit; I postpone that to "run time" */
1423 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
1425 /* We do _not_ try to open the file that src points to,
1426 * since we need to return and let src be expanded first.
1427 * Set ctx->pending_redirect, so we know what to do at the
1428 * end of the next parsed word.
1430 ctx->pending_redirect = redir;
1435 struct pipe *new_pipe(void) {
1437 pi = xmalloc(sizeof(struct pipe));
1441 pi->followup = 0; /* invalid */
1445 static void initialize_context(struct p_context *ctx)
1448 ctx->pending_redirect=NULL;
1450 ctx->list_head=new_pipe();
1451 ctx->pipe=ctx->list_head;
1454 done_command(ctx); /* creates the memory for working child */
1457 /* normal return is 0
1458 * if a reserved word is found, and processed, return 1
1459 * should handle if, then, elif, else, fi, for, while, until, do, done.
1460 * case, function, and select are obnoxious, save those for later.
1462 int reserved_word(o_string *dest, struct p_context *ctx)
1464 struct reserved_combo {
1469 /* Mostly a list of accepted follow-up reserved words.
1470 * FLAG_END means we are done with the sequence, and are ready
1471 * to turn the compound list into a command.
1472 * FLAG_START means the word must start a new compound list.
1474 static struct reserved_combo reserved_list[] = {
1475 { "if", RES_IF, FLAG_THEN | FLAG_START },
1476 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
1477 { "elif", RES_ELIF, FLAG_THEN },
1478 { "else", RES_ELSE, FLAG_FI },
1479 { "fi", RES_FI, FLAG_END },
1480 { "for", RES_FOR, FLAG_DO | FLAG_START },
1481 { "while", RES_WHILE, FLAG_DO | FLAG_START },
1482 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
1483 { "do", RES_DO, FLAG_DONE },
1484 { "done", RES_DONE, FLAG_END }
1486 struct reserved_combo *r;
1487 for (r=reserved_list;
1488 #define NRES sizeof(reserved_list)/sizeof(struct reserved_combo)
1489 r<reserved_list+NRES; r++) {
1490 if (strcmp(dest->data, r->literal) == 0) {
1491 debug_printf("found reserved word %s, code %d\n",r->literal,r->code);
1492 if (r->flag & FLAG_START) {
1493 struct p_context *new = xmalloc(sizeof(struct p_context));
1494 debug_printf("push stack\n");
1495 *new = *ctx; /* physical copy */
1496 initialize_context(ctx);
1498 } else if ( ctx->w == RES_NONE || ! (ctx->old_flag & (1<<r->code))) {
1505 ctx->old_flag = r->flag;
1506 if (ctx->old_flag & FLAG_END) {
1507 struct p_context *old;
1508 debug_printf("pop stack\n");
1510 old->child->group = ctx->list_head;
1511 *ctx = *old; /* physical copy */
1522 /* normal return is 0.
1523 * Syntax or xglob errors return 1. */
1524 static int done_word(o_string *dest, struct p_context *ctx)
1526 struct child_prog *child=ctx->child;
1527 glob_t *glob_target;
1530 debug_printf("done_word: %s %p\n", dest->data, child);
1531 if (dest->length == 0 && !dest->nonnull) {
1532 debug_printf(" true null, ignored\n");
1535 if (ctx->pending_redirect) {
1536 glob_target = &ctx->pending_redirect->word;
1540 return 1; /* syntax error, groups and arglists don't mix */
1543 debug_printf("checking %s for reserved-ness\n",dest->data);
1544 if (reserved_word(dest,ctx)) return ctx->w==RES_SNTX;
1546 glob_target = &child->glob_result;
1547 if (child->argv) flags |= GLOB_APPEND;
1549 gr = xglob(dest, flags, glob_target);
1550 if (gr != 0) return 1;
1553 if (ctx->pending_redirect) {
1554 ctx->pending_redirect=NULL;
1555 if (glob_target->gl_pathc != 1) {
1556 fprintf(stderr, "ambiguous redirect\n");
1560 child->argv = glob_target->gl_pathv;
1565 /* The only possible error here is out of memory, in which case
1567 static int done_command(struct p_context *ctx)
1569 /* The child is really already in the pipe structure, so
1570 * advance the pipe counter and make a new, null child.
1571 * Only real trickiness here is that the uncommitted
1572 * child structure, to which ctx->child points, is not
1573 * counted in pi->num_progs. */
1574 struct pipe *pi=ctx->pipe;
1575 struct child_prog *prog=ctx->child;
1577 if (prog && prog->group == NULL
1578 && prog->argv == NULL
1579 && prog->redirects == NULL) {
1580 debug_printf("done_command: skipping null command\n");
1584 debug_printf("done_command: num_progs incremented to %d\n",pi->num_progs);
1586 debug_printf("done_command: initializing\n");
1588 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
1590 prog = pi->progs + pi->num_progs;
1591 prog->redirects = NULL;
1593 prog->is_stopped = 0;
1595 prog->glob_result.gl_pathv = NULL;
1599 /* but ctx->pipe and ctx->list_head remain unchanged */
1603 static int done_pipe(struct p_context *ctx, pipe_style type)
1606 done_command(ctx); /* implicit closure of previous command */
1607 debug_printf("done_pipe, type %d\n", type);
1608 ctx->pipe->followup = type;
1609 ctx->pipe->r_mode = ctx->w;
1611 ctx->pipe->next = new_p;
1614 done_command(ctx); /* set up new pipe to accept commands */
1618 /* peek ahead in the in_str to find out if we have a "&n" construct,
1619 * as in "2>&1", that represents duplicating a file descriptor.
1620 * returns either -2 (syntax error), -1 (no &), or the number found.
1622 static int redirect_dup_num(struct in_str *input)
1626 if (ch != '&') return -1;
1628 b_getch(input); /* get the & */
1629 while (ch=b_peek(input),isdigit(ch)) {
1636 fprintf(stderr, "ambiguous redirect\n");
1640 /* If a redirect is immediately preceded by a number, that number is
1641 * supposed to tell which file descriptor to redirect. This routine
1642 * looks for such preceding numbers. In an ideal world this routine
1643 * needs to handle all the following classes of redirects...
1644 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
1645 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
1646 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
1647 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
1648 * A -1 output from this program means no valid number was found, so the
1649 * caller should use the appropriate default for this redirection.
1651 static int redirect_opt_num(o_string *o)
1655 if (o->length==0) return -1;
1656 for(num=0; num<o->length; num++) {
1657 if (!isdigit(*(o->data+num))) {
1661 /* reuse num (and save an int) */
1667 FILE *generate_stream_from_list(struct pipe *head)
1671 int pid, channel[2];
1672 if (pipe(channel)<0) perror_msg_and_die("pipe");
1675 perror_msg_and_die("fork");
1676 } else if (pid==0) {
1678 if (channel[1] != 1) {
1683 #define SURROGATE "surrogate response"
1684 write(1,SURROGATE,sizeof(SURROGATE));
1685 exit(run_list(head));
1687 exit(run_list_real(head)); /* leaks memory */
1690 debug_printf("forked child %d\n",pid);
1692 pf = fdopen(channel[0],"r");
1693 debug_printf("pipe on FILE *%p\n",pf);
1695 run_list_test(head,0);
1696 pf=popen("echo surrogate response","r");
1697 debug_printf("started fake pipe on FILE *%p\n",pf);
1702 /* this version hacked for testing purposes */
1703 /* return code is exit status of the process that is run. */
1704 static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end)
1707 o_string result=NULL_O_STRING;
1708 struct p_context inner;
1710 struct in_str pipe_str;
1711 initialize_context(&inner);
1713 /* recursion to generate command */
1714 retcode = parse_stream(&result, &inner, input, subst_end);
1715 if (retcode != 0) return retcode; /* syntax error or EOF */
1716 done_word(&result, &inner);
1717 done_pipe(&inner, PIPE_SEQ);
1720 p=generate_stream_from_list(inner.list_head);
1721 if (p==NULL) return 1;
1722 mark_open(fileno(p));
1723 setup_file_in_str(&pipe_str, p);
1725 /* now send results of command back into original context */
1726 retcode = parse_stream(dest, ctx, &pipe_str, '\0');
1727 /* XXX In case of a syntax error, should we try to kill the child?
1728 * That would be tough to do right, so just read until EOF. */
1730 while (b_getch(&pipe_str)!=EOF) { /* discard */ };
1733 debug_printf("done reading from pipe, pclose()ing\n");
1734 /* This is the step that wait()s for the child. Should be pretty
1735 * safe, since we just read an EOF from its stdout. We could try
1736 * to better, by using wait(), and keeping track of background jobs
1737 * at the same time. That would be a lot of work, and contrary
1738 * to the KISS philosophy of this program. */
1739 mark_closed(fileno(p));
1741 debug_printf("pclosed, retcode=%d\n",retcode);
1742 /* XXX this process fails to trim a single trailing newline */
1746 static int parse_group(o_string *dest, struct p_context *ctx,
1747 struct in_str *input, int ch)
1750 struct p_context sub;
1751 struct child_prog *child = ctx->child;
1754 return 1; /* syntax error, groups and arglists don't mix */
1756 initialize_context(&sub);
1758 case '(': endch=')'; child->subshell=1; break;
1759 case '{': endch='}'; break;
1760 default: syntax(); /* really logic error */
1762 rcode=parse_stream(dest,&sub,input,endch);
1763 done_word(dest,&sub); /* finish off the final word in the subcontext */
1764 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
1765 child->group = sub.list_head;
1767 /* child remains "open", available for possible redirects */
1770 /* basically useful version until someone wants to get fancier,
1771 * see the bash man page under "Parameter Expansion" */
1772 static void lookup_param(o_string *dest, struct p_context *ctx, o_string *src)
1775 if (src->data) p = getenv(src->data);
1776 if (p) parse_string(dest, ctx, p); /* recursion */
1780 /* return code: 0 for OK, 1 for syntax error */
1781 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
1784 o_string alt=NULL_O_STRING;
1786 int ch = input->peek(input); /* first character after the $ */
1787 debug_printf("handle_dollar: ch=%c\n",ch);
1789 while(ch=b_peek(input),isalnum(ch) || ch=='_') {
1793 lookup_param(dest, ctx, &alt);
1794 } else if (isdigit(ch)) {
1795 i = ch-'0'; /* XXX is $0 special? */
1796 if (i<global_argc) {
1797 parse_string(dest, ctx, global_argv[i]); /* recursion */
1800 } else switch (ch) {
1802 b_adduint(dest,getpid());
1806 if (last_bg_pid > 0) b_adduint(dest, last_bg_pid);
1810 b_adduint(dest,last_return_code);
1814 b_adduint(dest,global_argc ? global_argc-1 : 0);
1819 /* XXX maybe someone will try to escape the '}' */
1820 while(ch=b_getch(input),ch!=EOF && ch!='}') {
1827 lookup_param(dest, ctx, &alt);
1830 process_command_subs(dest, ctx, input, ')');
1834 for (i=1; i<global_argc; i++) {
1835 parse_string(dest, ctx, global_argv[i]);
1836 if (i+1 < global_argc) parse_string(dest, ctx, sep);
1842 /* still unhandled, but should be eventually */
1843 fprintf(stderr,"unhandled syntax: $%c\n",ch);
1847 b_addqchr(dest,'$',dest->quote);
1849 /* Eat the character if the flag was set. If the compiler
1850 * is smart enough, we could substitute "b_getch(input);"
1851 * for all the "advance = 1;" above, and also end up with
1852 * a nice size-optimized program. Hah! That'll be the day.
1854 if (advance) b_getch(input);
1858 int parse_string(o_string *dest, struct p_context *ctx, const char *src)
1861 setup_string_in_str(&foo, src);
1862 return parse_stream(dest, ctx, &foo, '\0');
1865 /* return code is 0 for normal exit, 1 for syntax error */
1866 int parse_stream(o_string *dest, struct p_context *ctx,
1867 struct in_str *input, int end_trigger)
1871 redir_type redir_style;
1874 /* Only double-quote state is handled in the state variable dest->quote.
1875 * A single-quote triggers a bypass of the main loop until its mate is
1876 * found. When recursing, quote state is passed in via dest->quote. */
1878 debug_printf("parse_stream, end_trigger=%d\n",end_trigger);
1879 while ((ch=b_getch(input))!=EOF) {
1881 next = (ch == '\n') ? 0 : b_peek(input);
1882 debug_printf("parse_stream: ch=%c (%d) m=%d quote=%d\n",
1883 ch,ch,m,dest->quote);
1884 if (m==0 || ((m==1 || m==2) && dest->quote)) {
1885 b_addqchr(dest, ch, dest->quote);
1887 if (m==2) { /* unquoted IFS */
1888 done_word(dest, ctx);
1889 if (ch=='\n') done_pipe(ctx,PIPE_SEQ);
1891 if (ch == end_trigger && !dest->quote && ctx->w==RES_NONE) {
1892 debug_printf("leaving parse_stream\n");
1897 /* Yahoo! Time to run with it! */
1898 done_pipe(ctx,PIPE_SEQ);
1899 run_list(ctx->list_head);
1900 initialize_context(ctx);
1903 if (m!=2) switch (ch) {
1905 if (dest->length == 0 && !dest->quote) {
1906 while(ch=b_peek(input),ch!=EOF && ch!='\n') { b_getch(input); }
1908 b_addqchr(dest, ch, dest->quote);
1916 b_addqchr(dest, '\\', dest->quote);
1917 b_addqchr(dest, b_getch(input), dest->quote);
1920 if (handle_dollar(dest, ctx, input)!=0) return 1;
1924 while(ch=b_getch(input),ch!=EOF && ch!='\'') {
1934 dest->quote = !dest->quote;
1937 process_command_subs(dest, ctx, input, '`');
1940 redir_fd = redirect_opt_num(dest);
1941 done_word(dest, ctx);
1942 redir_style=REDIRECT_OVERWRITE;
1944 redir_style=REDIRECT_APPEND;
1946 } else if (next == '(') {
1947 syntax(); /* until we support >(list) Process Substitution */
1950 setup_redirect(ctx, redir_fd, redir_style, input);
1953 redir_fd = redirect_opt_num(dest);
1954 done_word(dest, ctx);
1955 redir_style=REDIRECT_INPUT;
1957 redir_style=REDIRECT_HEREIS;
1959 } else if (next == '>') {
1960 redir_style=REDIRECT_IO;
1962 } else if (next == '(') {
1963 syntax(); /* until we support <(list) Process Substitution */
1966 setup_redirect(ctx, redir_fd, redir_style, input);
1969 done_word(dest, ctx);
1970 done_pipe(ctx,PIPE_SEQ);
1973 done_word(dest, ctx);
1976 done_pipe(ctx,PIPE_AND);
1978 done_pipe(ctx,PIPE_BG);
1982 done_word(dest, ctx);
1985 done_pipe(ctx,PIPE_OR);
1987 /* we could pick up a file descriptor choice here
1988 * with redirect_opt_num(), but bash doesn't do it.
1989 * "echo foo 2| cat" yields "foo 2". */
1995 if (parse_group(dest, ctx, input, ch)!=0) return 1;
1999 syntax(); /* Proper use of this character caught by end_trigger */
2003 syntax(); /* this is really an internal logic error */
2008 /* complain if quote? No, maybe we just finished a command substitution
2009 * that was quoted. Example:
2010 * $ echo "`cat foo` plus more"
2011 * and we just got the EOF generated by the subshell that ran "cat foo"
2012 * The only real complaint is if we got an EOF when end_trigger != '\0',
2013 * that is, we were really supposed to get end_trigger, and never got
2014 * one before the EOF. Can't use the standard "syntax error" return code,
2015 * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
2016 if (end_trigger != '\0') return -1;
2020 void mapset(const unsigned char *set, int code)
2022 const unsigned char *s;
2023 for (s=set; *s; s++) map[*s] = code;
2026 void update_ifs_map(void)
2028 /* char *ifs and char map[256] are both globals. */
2029 ifs = getenv("IFS");
2030 if (ifs == NULL) ifs=" \t\n";
2031 /* Precompute a list of 'flow through' behavior so it can be treated
2032 * quickly up front. Computation is necessary because of IFS.
2033 * Special case handling of IFS == " \t\n" is not implemented.
2034 * The map[] array only really needs two bits each, and on most machines
2035 * that would be faster because of the reduced L1 cache footprint.
2037 memset(map,0,256); /* most characters flow through always */
2038 mapset("\\$'\"`", 3); /* never flow through */
2039 mapset("<>;&|(){}#", 1); /* flow through if quoted */
2040 mapset(ifs, 2); /* also flow through if quoted */
2043 /* most recursion does not come through here, the exeception is
2044 * from builtin_source() */
2045 int parse_stream_outer(struct in_str *inp)
2048 struct p_context ctx;
2049 o_string temp=NULL_O_STRING;
2052 initialize_context(&ctx);
2055 rcode = parse_stream(&temp, &ctx, inp, '\n');
2056 done_word(&temp, &ctx);
2057 done_pipe(&ctx,PIPE_SEQ);
2058 run_list(ctx.list_head);
2059 } while (rcode != -1); /* loop on syntax errors, return on EOF */
2063 static int parse_string_outer(const char *s)
2065 struct in_str input;
2066 setup_string_in_str(&input, s);
2067 return parse_stream_outer(&input);
2070 static int parse_file_outer(FILE *f)
2073 struct in_str input;
2074 setup_file_in_str(&input, f);
2075 rcode = parse_stream_outer(&input);
2079 int shell_main(int argc, char **argv)
2084 /* XXX what should these be while sourcing /etc/profile? */
2088 if (argv[0] && argv[0][0] == '-') {
2089 debug_printf("\nsourcing /etc/profile\n");
2090 input = xfopen("/etc/profile", "r");
2091 mark_open(fileno(input));
2092 parse_file_outer(input);
2093 mark_closed(fileno(input));
2098 /* initialize the cwd -- this is never freed...*/
2100 #ifdef BB_FEATURE_COMMAND_EDITING
2101 cmdedit_set_initial_prompt();
2106 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
2110 global_argv = argv+optind;
2111 global_argc = argc-optind;
2112 opt = parse_string_outer(optarg);
2123 fprintf(stderr, "Usage: sh [FILE]...\n"
2124 " or: sh -c command [args]...\n\n");
2128 /* A shell is interactive if the `-i' flag was given, or if all of
2129 * the following conditions are met:
2131 * no arguments remaining or the -s flag given
2132 * standard input is a terminal
2133 * standard output is a terminal
2134 * Refer to Posix.2, the description of the `sh' utility. */
2135 if (argv[optind]==NULL && input==stdin &&
2136 isatty(fileno(stdin)) && isatty(fileno(stdout))) {
2141 /* Looks like they want an interactive shell */
2142 fprintf(stdout, "\nhush -- the humble shell v0.01 (testing)\n\n");
2143 exit(parse_file_outer(stdin));
2145 debug_printf("\ninteractive=%d\n", interactive);
2147 debug_printf("\nrunning script '%s'\n", argv[optind]);
2148 global_argv = argv+optind;
2149 global_argc = argc-optind;
2150 input = xfopen(argv[optind], "r");
2151 opt = parse_file_outer(input);
2153 #ifdef BB_FEATURE_CLEAN_UP