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
47 * Arithmetic Expansion
48 * <(list) and >(list) Process Substitution
49 * reserved words: case, esac, select, function
50 * Here Documents ( << word )
53 * job handling woefully incomplete and buggy
54 * reserved word execution woefully incomplete and buggy
56 * port selected bugfixes from post-0.49 busybox lash - done?
57 * finish implementing reserved words: for, while, until, do, done
58 * finish implementing local variable assignment
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 * This program is free software; you can redistribute it and/or modify
78 * it under the terms of the GNU General Public License as published by
79 * the Free Software Foundation; either version 2 of the License, or
80 * (at your option) any later version.
82 * This program is distributed in the hope that it will be useful,
83 * but WITHOUT ANY WARRANTY; without even the implied warranty of
84 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
85 * General Public License for more details.
87 * You should have received a copy of the GNU General Public License
88 * along with this program; if not, write to the Free Software
89 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
91 #include <ctype.h> /* isalpha, isdigit */
92 #include <unistd.h> /* getpid */
93 #include <stdlib.h> /* getenv, atoi */
94 #include <string.h> /* strchr */
95 #include <stdio.h> /* popen etc. */
96 #include <glob.h> /* glob, of course */
97 #include <stdarg.h> /* va_list */
100 #include <getopt.h> /* should be pretty obvious */
102 #include <sys/stat.h> /* ulimit */
103 #include <sys/types.h>
104 #include <sys/wait.h>
107 /* #include <dmalloc.h> */
108 /* #define DEBUG_SHELL */
114 #define applet_name "hush"
115 #include "standalone.h"
116 #define shell_main main
117 #define BB_FEATURE_SH_SIMPLE_PROMPT
122 REDIRECT_OVERWRITE = 2,
128 /* The descrip member of this structure is only used to make debugging
130 struct {int mode; int default_fd; char *descrip;} redir_table[] = {
132 { O_RDONLY, 0, "<" },
133 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
134 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
135 { O_RDONLY, -1, "<<" },
146 /* might eventually control execution */
162 #define FLAG_END (1<<RES_NONE)
163 #define FLAG_IF (1<<RES_IF)
164 #define FLAG_THEN (1<<RES_THEN)
165 #define FLAG_ELIF (1<<RES_ELIF)
166 #define FLAG_ELSE (1<<RES_ELSE)
167 #define FLAG_FI (1<<RES_FI)
168 #define FLAG_FOR (1<<RES_FOR)
169 #define FLAG_WHILE (1<<RES_WHILE)
170 #define FLAG_UNTIL (1<<RES_UNTIL)
171 #define FLAG_DO (1<<RES_DO)
172 #define FLAG_DONE (1<<RES_DONE)
173 #define FLAG_START (1<<RES_XXXX)
175 /* This holds pointers to the various results of parsing */
177 struct child_prog *child;
178 struct pipe *list_head;
180 struct redir_struct *pending_redirect;
182 int old_flag; /* for figuring out valid reserved words */
183 struct p_context *stack;
184 /* How about quoting status? */
187 struct redir_struct {
188 redir_type type; /* type of redirection */
189 int fd; /* file descriptor being redirected */
190 int dup; /* -1, or file descriptor being duplicated */
191 struct redir_struct *next; /* pointer to the next redirect in the list */
192 glob_t word; /* *word.gl_pathv is the filename */
196 pid_t pid; /* 0 if exited */
197 char **argv; /* program name and arguments */
198 struct pipe *group; /* if non-NULL, first in group or subshell */
199 int subshell; /* flag, non-zero if group must be forked */
200 struct redir_struct *redirects; /* I/O redirections */
201 glob_t glob_result; /* result of parameter globbing */
202 int is_stopped; /* is the program currently running? */
203 struct pipe *family; /* pointer back to the child's parent pipe */
207 int jobid; /* job number */
208 int num_progs; /* total number of programs in job */
209 int running_progs; /* number of programs running */
210 char *text; /* name of job */
211 char *cmdbuf; /* buffer various argv's point into */
212 pid_t pgrp; /* process group ID for the job */
213 struct child_prog *progs; /* array of commands in pipe */
214 struct pipe *next; /* to track background commands */
215 int stopped_progs; /* number of programs alive, but stopped */
216 int job_context; /* bitmask defining current context */
217 pipe_style followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
218 reserved_style r_mode; /* supports if, for, while, until */
222 struct pipe *head; /* head of list of running jobs */
223 struct pipe *fg; /* current foreground job */
228 struct close_me *next;
231 /* globals, connect us to the outside world
232 * the first three support $?, $#, and $1 */
234 unsigned int global_argc;
235 unsigned int last_return_code;
236 extern char **environ; /* This is in <unistd.h>, but protected with __USE_GNU */
238 /* Variables we export */
239 unsigned int shell_context; /* Used in cmdedit.c to reset the
240 * context when someone hits ^C */
242 /* "globals" within this file */
243 static char *ifs=NULL;
244 static char map[256];
245 static int fake_mode=0;
246 static int interactive=0;
247 static struct close_me *close_me_head = NULL;
248 static const char *cwd;
249 static struct jobset *job_list;
250 static unsigned int last_bg_pid=0;
252 static char *PS2 = "> ";
254 #define B_CHUNK (100)
256 #define MAX_LINE 256 /* for cwd */
257 #define MAX_READ 256 /* for builtin_read */
266 #define NULL_O_STRING {NULL,0,0,0,0}
267 /* used for initialization:
268 o_string foo = NULL_O_STRING; */
270 /* I can almost use ordinary FILE *. Is open_memstream() universally
271 * available? Where is it documented? */
277 int (*get) (struct in_str *);
278 int (*peek) (struct in_str *);
280 #define b_getch(input) ((input)->get(input))
281 #define b_peek(input) ((input)->peek(input))
283 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
285 struct built_in_command {
286 char *cmd; /* name */
287 char *descr; /* description */
288 int (*function) (struct child_prog *); /* function ptr */
291 /* belongs in busybox.h */
292 static inline int max(int a, int b) {
296 /* This should be in utility.c */
298 static void debug_printf(const char *format, ...)
301 va_start(args, format);
302 vfprintf(stderr, format, args);
306 static void debug_printf(const char *format, ...) { }
308 #define final_printf debug_printf
310 void __syntax(char *file, int line) {
311 fprintf(stderr,"syntax error %s:%d\n",file,line);
313 #define syntax() __syntax(__FILE__, __LINE__)
315 /* Index of subroutines: */
316 /* function prototypes for builtins */
317 static int builtin_cd(struct child_prog *child);
318 static int builtin_env(struct child_prog *child);
319 static int builtin_exec(struct child_prog *child);
320 static int builtin_exit(struct child_prog *child);
321 static int builtin_export(struct child_prog *child);
322 static int builtin_fg_bg(struct child_prog *child);
323 static int builtin_help(struct child_prog *child);
324 static int builtin_jobs(struct child_prog *child);
325 static int builtin_pwd(struct child_prog *child);
326 static int builtin_read(struct child_prog *child);
327 static int builtin_shift(struct child_prog *child);
328 static int builtin_source(struct child_prog *child);
329 static int builtin_umask(struct child_prog *child);
330 static int builtin_unset(struct child_prog *child);
331 static int builtin_not_written(struct child_prog *child);
332 /* o_string manipulation: */
333 static int b_check_space(o_string *o, int len);
334 static int b_addchr(o_string *o, int ch);
335 static void b_reset(o_string *o);
336 static int b_addqchr(o_string *o, int ch, int quote);
337 static int b_adduint(o_string *o, unsigned int i);
338 /* in_str manipulations: */
339 static int static_get(struct in_str *i);
340 static int static_peek(struct in_str *i);
341 static int file_get(struct in_str *i);
342 static int file_peek(struct in_str *i);
343 static void setup_file_in_str(struct in_str *i, FILE *f);
344 static void setup_string_in_str(struct in_str *i, const char *s);
345 /* close_me manipulations: */
346 static void mark_open(int fd);
347 static void mark_closed(int fd);
348 static void close_all();
349 /* "run" the final data structures: */
350 static char *indenter(int i);
351 static int run_list_test(struct pipe *head, int indent);
352 static int run_pipe_test(struct pipe *pi, int indent);
353 /* really run the final data structures: */
354 static int setup_redirects(struct child_prog *prog, int squirrel[]);
355 static int pipe_wait(struct pipe *pi);
356 static int run_list_real(struct pipe *pi);
357 static void pseudo_exec(struct child_prog *child) __attribute__ ((noreturn));
358 static int run_pipe_real(struct pipe *pi);
359 /* extended glob support: */
360 static int globhack(const char *src, int flags, glob_t *pglob);
361 static int glob_needed(const char *s);
362 static int xglob(o_string *dest, int flags, glob_t *pglob);
363 /* variable assignment: */
364 static int set_local_var(const char *s);
365 static int is_assignment(const char *s);
366 /* data structure manipulation: */
367 static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
368 static void initialize_context(struct p_context *ctx);
369 static int done_word(o_string *dest, struct p_context *ctx);
370 static int done_command(struct p_context *ctx);
371 static int done_pipe(struct p_context *ctx, pipe_style type);
372 /* primary string parsing: */
373 static int redirect_dup_num(struct in_str *input);
374 static int redirect_opt_num(o_string *o);
375 static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end);
376 static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
377 static void lookup_param(o_string *dest, struct p_context *ctx, o_string *src);
378 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
379 static int parse_string(o_string *dest, struct p_context *ctx, const char *src);
380 static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, int end_trigger);
382 static int parse_stream_outer(struct in_str *inp);
383 static int parse_string_outer(const char *s);
384 static int parse_file_outer(FILE *f);
385 /* job management: */
386 static void checkjobs();
387 static void insert_bg_job(struct pipe *pi);
388 static void remove_bg_job(struct pipe *pi);
389 static void free_pipe(struct pipe *pi);
391 /* Table of built-in functions. They can be forked or not, depending on
392 * context: within pipes, they fork. As simple commands, they do not.
393 * When used in non-forking context, they can change global variables
394 * in the parent shell process. If forked, of course they can not.
395 * For example, 'unset foo | whatever' will parse and run, but foo will
396 * still be set at the end. */
397 static struct built_in_command bltins[] = {
398 {"bg", "Resume a job in the background", builtin_fg_bg},
399 {"break", "Exit for, while or until loop", builtin_not_written},
400 {"cd", "Change working directory", builtin_cd},
401 {"continue", "Continue for, while or until loop", builtin_not_written},
402 {"env", "Print all environment variables", builtin_env},
403 {"eval", "Construct and run shell command", builtin_not_written},
404 {"exec", "Exec command, replacing this shell with the exec'd process", builtin_exec},
405 {"exit", "Exit from shell()", builtin_exit},
406 {"export", "Set environment variable", builtin_export},
407 {"fg", "Bring job into the foreground", builtin_fg_bg},
408 {"jobs", "Lists the active jobs", builtin_jobs},
409 {"pwd", "Print current directory", builtin_pwd},
410 {"read", "Input environment variable", builtin_read},
411 {"return", "Return from a function", builtin_not_written},
412 {"set", "Set/unset shell options", builtin_not_written},
413 {"shift", "Shift positional parameters", builtin_shift},
414 {"trap", "Trap signals", builtin_not_written},
415 {"ulimit","Controls resource limits", builtin_not_written},
416 {"umask","Sets file creation mask", builtin_umask},
417 {"unset", "Unset environment variable", builtin_unset},
418 {".", "Source-in and run commands in a file", builtin_source},
419 {"help", "List shell built-in commands", builtin_help},
423 /* built-in 'cd <path>' handler */
424 static int builtin_cd(struct child_prog *child)
427 if (child->argv[1] == NULL)
428 newdir = getenv("HOME");
430 newdir = child->argv[1];
432 printf("cd: %s: %s\n", newdir, strerror(errno));
435 cwd = xgetcwd((char *)cwd);
441 /* built-in 'env' handler */
442 static int builtin_env(struct child_prog *dummy)
445 if (e == NULL) return EXIT_FAILURE;
452 /* built-in 'exec' handler */
453 static int builtin_exec(struct child_prog *child)
455 if (child->argv[1] == NULL)
456 return EXIT_SUCCESS; /* Really? */
462 /* built-in 'exit' handler */
463 static int builtin_exit(struct child_prog *child)
465 if (child->argv[1] == NULL)
466 exit(last_return_code);
467 exit (atoi(child->argv[1]));
470 /* built-in 'export VAR=value' handler */
471 static int builtin_export(struct child_prog *child)
475 if (child->argv[1] == NULL) {
476 return (builtin_env(child));
478 /* FIXME -- I leak memory. This will be
479 * fixed up properly when we add local
480 * variable support -- I hope */
481 res = putenv(strdup(child->argv[1]));
483 fprintf(stderr, "export: %s\n", strerror(errno));
487 /* built-in 'fg' and 'bg' handler */
488 static int builtin_fg_bg(struct child_prog *child)
491 struct pipe *pi=NULL;
493 /* If they gave us no args, assume they want the last backgrounded task */
494 if (!child->argv[1]) {
495 for (pi = job_list->head; pi; pi = pi->next) {
496 if (pi->progs && pi->progs->pid == last_bg_pid) {
501 error_msg("%s: no current job", child->argv[0]);
505 if (sscanf(child->argv[1], "%%%d", &jobnum) != 1) {
506 error_msg("%s: bad argument '%s'", child->argv[0], child->argv[1]);
510 for (pi = job_list->head; pi; pi = pi->next) {
511 if (pi->jobid == jobnum) {
516 error_msg("%s: %d: no such job", child->argv[0], jobnum);
520 if (*child->argv[0] == 'f') {
521 /* Make this job the foreground job */
522 signal(SIGTTOU, SIG_IGN);
523 /* suppress messages when run from /linuxrc mag@sysgo.de */
524 if (tcsetpgrp(0, pi->pgrp) && errno != ENOTTY)
525 perror_msg("tcsetpgrp");
526 signal(SIGTTOU, SIG_DFL);
530 /* Restart the processes in the job */
531 for (i = 0; i < pi->num_progs; i++)
532 pi->progs[i].is_stopped = 0;
534 kill(-pi->pgrp, SIGCONT);
536 pi->stopped_progs = 0;
540 /* built-in 'help' handler */
541 static int builtin_help(struct child_prog *dummy)
543 struct built_in_command *x;
545 printf("\nBuilt-in commands:\n");
546 printf("-------------------\n");
547 for (x = bltins; x->cmd; x++) {
550 printf("%s\t%s\n", x->cmd, x->descr);
556 /* built-in 'jobs' handler */
557 static int builtin_jobs(struct child_prog *child)
562 for (job = job_list->head; job; job = job->next) {
563 if (job->running_progs == job->stopped_progs)
564 status_string = "Stopped";
566 status_string = "Running";
567 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->text);
573 /* built-in 'pwd' handler */
574 static int builtin_pwd(struct child_prog *dummy)
576 cwd = xgetcwd((char *)cwd);
583 /* built-in 'read VAR' handler */
584 static int builtin_read(struct child_prog *child)
586 int res = 0, len, newlen;
588 char string[MAX_READ];
590 if (child->argv[1]) {
591 /* argument (VAR) given: put "VAR=" into buffer */
592 strcpy(string, child->argv[1]);
593 len = strlen(string);
596 /* XXX would it be better to go through in_str? */
597 fgets(&string[len], sizeof(string) - len, stdin); /* read string */
598 newlen = strlen(string);
600 string[--newlen] = '\0'; /* chomp trailing newline */
602 ** string should now contain "VAR=<value>"
603 ** copy it (putenv() won't do that, so we must make sure
604 ** the string resides in a static buffer!)
607 if((s = strdup(string)))
610 fprintf(stderr, "read: %s\n", strerror(errno));
613 fgets(string, sizeof(string), stdin);
618 /* Built-in 'shift' handler */
619 static int builtin_shift(struct child_prog *child)
622 if (child->argv[1]) {
623 n=atoi(child->argv[1]);
625 if (n>=0 && n<global_argc) {
626 /* XXX This probably breaks $0 */
635 /* Built-in '.' handler (read-in and execute commands from file) */
636 static int builtin_source(struct child_prog *child)
641 if (child->argv[1] == NULL)
644 /* XXX search through $PATH is missing */
645 input = fopen(child->argv[1], "r");
647 fprintf(stderr, "Couldn't open file '%s'\n", child->argv[1]);
651 /* Now run the file */
652 /* XXX argv and argc are broken; need to save old global_argv
653 * (pointer only is OK!) on this stack frame,
654 * set global_argv=child->argv+1, recurse, and restore. */
655 mark_open(fileno(input));
656 status = parse_file_outer(input);
657 mark_closed(fileno(input));
662 static int builtin_umask(struct child_prog *child)
665 const char *arg = child->argv[1];
668 new_umask=strtoul(arg, &end, 8);
669 if (*end!='\0' || end == arg) {
673 printf("%.3o\n", (unsigned int) (new_umask=umask(0)));
679 /* built-in 'unset VAR' handler */
680 static int builtin_unset(struct child_prog *child)
682 if (child->argv[1] == NULL) {
683 fprintf(stderr, "unset: parameter required.\n");
686 unsetenv(child->argv[1]);
690 static int builtin_not_written(struct child_prog *child)
692 printf("builtin_%s not written\n",child->argv[0]);
696 static int b_check_space(o_string *o, int len)
698 /* It would be easy to drop a more restrictive policy
699 * in here, such as setting a maximum string length */
700 if (o->length + len > o->maxlen) {
701 char *old_data = o->data;
702 /* assert (data == NULL || o->maxlen != 0); */
703 o->maxlen += max(2*len, B_CHUNK);
704 o->data = realloc(o->data, 1 + o->maxlen);
705 if (o->data == NULL) {
709 return o->data == NULL;
712 static int b_addchr(o_string *o, int ch)
714 debug_printf("b_addchr: %c %d %p\n", ch, o->length, o);
715 if (b_check_space(o, 1)) return B_NOSPAC;
716 o->data[o->length] = ch;
718 o->data[o->length] = '\0';
722 static void b_reset(o_string *o)
726 if (o->data != NULL) *o->data = '\0';
729 static void b_free(o_string *o)
732 if (o->data != NULL) free(o->data);
737 /* My analysis of quoting semantics tells me that state information
738 * is associated with a destination, not a source.
740 static int b_addqchr(o_string *o, int ch, int quote)
742 if (quote && strchr("*?[\\",ch)) {
744 rc = b_addchr(o, '\\');
747 return b_addchr(o, ch);
750 /* belongs in utility.c */
751 char *simple_itoa(unsigned int i)
753 /* 21 digits plus null terminator, good for 64-bit or smaller ints */
754 static char local[22];
755 char *p = &local[21];
764 static int b_adduint(o_string *o, unsigned int i)
767 char *p = simple_itoa(i);
768 /* no escape checking necessary */
769 do r=b_addchr(o, *p++); while (r==0 && *p);
773 static int static_get(struct in_str *i)
776 if (ch=='\0') return EOF;
780 static int static_peek(struct in_str *i)
785 static inline void cmdedit_set_initial_prompt(void)
787 #ifdef BB_FEATURE_SH_SIMPLE_PROMPT
796 static inline void setup_prompt_string(int promptmode, char **prompt_str)
798 debug_printf("setup_prompt_string %d ",promptmode);
799 #ifdef BB_FEATURE_SH_SIMPLE_PROMPT
800 /* Set up the prompt */
801 if (promptmode == 1) {
804 PS1=xmalloc(strlen(cwd)+4);
805 sprintf(PS1, "%s %s", cwd, ( geteuid() != 0 ) ? "$ ":"# ");
811 *prompt_str = (promptmode==0)? PS1 : PS2;
813 debug_printf("result %s\n",*prompt_str);
816 static void get_user_input(struct in_str *i)
819 static char the_command[BUFSIZ];
821 setup_prompt_string(i->promptmode, &prompt_str);
822 #ifdef BB_FEATURE_COMMAND_EDITING
824 ** enable command line editing only while a command line
825 ** is actually being read; otherwise, we'll end up bequeathing
826 ** atexit() handlers and other unwanted stuff to our
827 ** child processes (rob@sysgo.de)
829 cmdedit_read_input(prompt_str, the_command);
832 fputs(prompt_str, stdout);
834 the_command[0]=fgetc(i->file);
840 /* This is the magic location that prints prompts
841 * and gets data back from the user */
842 static int file_get(struct in_str *i)
847 /* If there is data waiting, eat it up */
851 /* need to double check i->file because we might be doing something
852 * more complicated by now, like sourcing or substituting. */
853 if (i->__promptme && interactive && i->file == stdin) {
864 debug_printf("b_getch: got a %d\n", ch);
866 if (ch == '\n') i->__promptme=1;
870 /* All the callers guarantee this routine will never be
871 * used right after a newline, so prompting is not needed.
873 static int file_peek(struct in_str *i)
878 static char buffer[2];
879 buffer[0] = fgetc(i->file);
882 debug_printf("b_peek: got a %d\n", *i->p);
887 static void setup_file_in_str(struct in_str *i, FILE *f)
897 static void setup_string_in_str(struct in_str *i, const char *s)
899 i->peek = static_peek;
906 static void mark_open(int fd)
908 struct close_me *new = xmalloc(sizeof(struct close_me));
910 new->next = close_me_head;
914 static void mark_closed(int fd)
916 struct close_me *tmp;
917 if (close_me_head == NULL || close_me_head->fd != fd)
918 error_msg_and_die("corrupt close_me");
920 close_me_head = close_me_head->next;
924 static void close_all()
927 for (c=close_me_head; c; c=c->next) {
930 close_me_head = NULL;
933 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
934 * and stderr if they are redirected. */
935 static int setup_redirects(struct child_prog *prog, int squirrel[])
938 struct redir_struct *redir;
940 for (redir=prog->redirects; redir; redir=redir->next) {
941 if (redir->dup == -1) {
942 mode=redir_table[redir->type].mode;
943 openfd = open(redir->word.gl_pathv[0], mode, 0666);
945 /* this could get lost if stderr has been redirected, but
946 bash and ash both lose it as well (though zsh doesn't!) */
947 fprintf(stderr,"error opening %s: %s\n", redir->word.gl_pathv[0],
955 if (openfd != redir->fd) {
956 if (squirrel && redir->fd < 3) {
957 squirrel[redir->fd] = dup(redir->fd);
962 dup2(openfd, redir->fd);
970 static void restore_redirects(int squirrel[])
973 for (i=0; i<3; i++) {
976 /* No error checking. I sure wouldn't know what
977 * to do with an error if I found one! */
984 /* XXX this definitely needs some more thought, work, and
985 * cribbing from other shells */
986 static int pipe_wait(struct pipe *pi)
988 int rcode=0, i, pid, running, status;
989 running = pi->num_progs;
991 pid=waitpid(-1, &status, 0);
992 if (pid < 0) perror_msg_and_die("waitpid");
993 for (i=0; i < pi->num_progs; i++) {
994 if (pi->progs[i].pid == pid) {
995 if (i==pi->num_progs-1) rcode=WEXITSTATUS(status);
996 pi->progs[i].pid = 0;
1005 /* very simple version for testing */
1006 static void pseudo_exec(struct child_prog *child)
1009 struct built_in_command *x;
1011 for (i=0; is_assignment(child->argv[i]); i++) {
1012 putenv(strdup(child->argv[i]));
1014 child->argv+=i; /* XXX this hack isn't so horrible, since we are about
1015 to exit, and therefore don't need to keep data
1016 structures consistent for free() use. */
1017 /* If a variable is assigned in a forest, and nobody listens,
1018 * was it ever really set?
1020 if (child->argv[0] == NULL) exit(EXIT_SUCCESS);
1023 * Check if the command matches any of the builtins.
1024 * Depending on context, this might be redundant. But it's
1025 * easier to waste a few CPU cycles than it is to figure out
1026 * if this is one of those cases.
1028 for (x = bltins; x->cmd; x++) {
1029 if (strcmp(child->argv[0], x->cmd) == 0 ) {
1030 debug_printf("builtin exec %s\n", child->argv[0]);
1031 exit(x->function(child));
1035 /* Check if the command matches any busybox internal commands
1037 * FIXME: This feature is not 100% safe, since
1038 * BusyBox is not fully reentrant, so we have no guarantee the things
1039 * from the .bss are still zeroed, or that things from .data are still
1040 * at their defaults. We could exec ourself from /proc/self/exe, but I
1041 * really dislike relying on /proc for things. We could exec ourself
1042 * from global_argv[0], but if we are in a chroot, we may not be able
1043 * to find ourself... */
1044 #ifdef BB_FEATURE_SH_STANDALONE_SHELL
1047 char** argv_l=child->argv;
1048 char *name = child->argv[0];
1050 #ifdef BB_FEATURE_SH_APPLETS_ALWAYS_WIN
1051 /* Following discussions from November 2000 on the busybox mailing
1052 * list, the default configuration, (without
1053 * get_last_path_component()) lets the user force use of an
1054 * external command by specifying the full (with slashes) filename.
1055 * If you enable BB_FEATURE_SH_APPLETS_ALWAYS_WIN, then applets
1056 * _aways_ override external commands, so if you want to run
1057 * /bin/cat, it will use BusyBox cat even if /bin/cat exists on the
1058 * filesystem and is _not_ busybox. Some systems may want this,
1060 name = get_last_path_component(name);
1062 /* Count argc for use in a second... */
1063 for(argc_l=0;*argv_l!=NULL; argv_l++, argc_l++);
1065 debug_printf("running applet %s\n", name);
1066 run_applet_by_name(name, argc_l, child->argv);
1069 debug_printf("exec of %s\n",child->argv[0]);
1070 execvp(child->argv[0],child->argv);
1073 } else if (child->group) {
1074 debug_printf("runtime nesting to group\n");
1075 interactive=0; /* crucial!!!! */
1076 rcode = run_list_real(child->group);
1077 /* OK to leak memory by not calling run_list_test,
1078 * since this process is about to exit */
1081 /* Can happen. See what bash does with ">foo" by itself. */
1082 debug_printf("trying to pseudo_exec null command\n");
1087 static void insert_bg_job(struct pipe *pi)
1089 struct pipe *thejob;
1091 /* Linear search for the ID of the job to use */
1093 for (thejob = job_list->head; thejob; thejob = thejob->next)
1094 if (thejob->jobid >= pi->jobid)
1095 pi->jobid = thejob->jobid + 1;
1097 /* add thejob to the list of running jobs */
1098 if (!job_list->head) {
1099 thejob = job_list->head = xmalloc(sizeof(*thejob));
1101 for (thejob = job_list->head; thejob->next; thejob = thejob->next) /* nothing */;
1102 thejob->next = xmalloc(sizeof(*thejob));
1103 thejob = thejob->next;
1106 /* physically copy the struct job */
1107 memcpy(thejob, pi, sizeof(struct pipe));
1108 thejob->next = NULL;
1109 thejob->running_progs = thejob->num_progs;
1110 thejob->stopped_progs = 0;
1111 thejob->text = xmalloc(MAX_LINE);
1113 //if (pi->progs[0] && pi->progs[0].argv && pi->progs[0].argv[0])
1115 char *bar=thejob->text;
1116 char **foo=pi->progs[0].argv;
1117 while(foo && *foo) {
1118 bar += sprintf(bar, "%s ", *foo++);
1122 /* we don't wait for background thejobs to return -- append it
1123 to the list of backgrounded thejobs and leave it alone */
1124 printf("[%d] %d\n", thejob->jobid, thejob->progs[0].pid);
1125 last_bg_pid = thejob->progs[0].pid;
1128 /* remove a backgrounded job from a jobset */
1129 static void remove_bg_job(struct pipe *pi)
1131 struct pipe *prev_pipe;
1134 if (pi == job_list->head) {
1135 job_list->head = pi->next;
1137 prev_pipe = job_list->head;
1138 while (prev_pipe->next != pi)
1139 prev_pipe = prev_pipe->next;
1140 prev_pipe->next = pi->next;
1146 /* free up all memory from a pipe */
1147 static void free_pipe(struct pipe *pi)
1151 for (i = 0; i < pi->num_progs; i++) {
1152 free(pi->progs[i].argv);
1153 if (pi->progs[i].redirects)
1154 free(pi->progs[i].redirects);
1162 memset(pi, 0, sizeof(struct pipe));
1166 /* Checks to see if any background processes have exited -- if they
1167 have, figure out why and see if a job has completed */
1168 static void checkjobs()
1175 while ((childpid = waitpid(-1, &status, WNOHANG | WUNTRACED)) > 0) {
1176 for (pi = job_list->head; pi; pi = pi->next) {
1178 while (prognum < pi->num_progs &&
1179 pi->progs[prognum].pid != childpid) prognum++;
1180 if (prognum < pi->num_progs)
1184 if (WIFEXITED(status) || WIFSIGNALED(status)) {
1186 pi->running_progs--;
1187 pi->progs[prognum].pid = 0;
1189 if (!pi->running_progs) {
1190 printf(JOB_STATUS_FORMAT, pi->jobid, "Done", pi->text);
1197 pi->stopped_progs++;
1198 pi->progs[prognum].is_stopped = 1;
1200 if (pi->stopped_progs == pi->num_progs) {
1201 printf(JOB_STATUS_FORMAT, pi->jobid, "Stopped", pi->text);
1206 if (childpid == -1 && errno != ECHILD)
1207 perror_msg("waitpid");
1209 /* move the shell to the foreground */
1210 if (tcsetpgrp(0, getpgrp()) && errno != ENOTTY)
1211 perror_msg("tcsetpgrp");
1214 /* run_pipe_real() starts all the jobs, but doesn't wait for anything
1215 * to finish. See pipe_wait().
1217 * return code is normally -1, when the caller has to wait for children
1218 * to finish to determine the exit status of the pipe. If the pipe
1219 * is a simple builtin command, however, the action is done by the
1220 * time run_pipe_real returns, and the exit code is provided as the
1223 * The input of the pipe is always stdin, the output is always
1224 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1225 * because it tries to avoid running the command substitution in
1226 * subshell, when that is in fact necessary. The subshell process
1227 * now has its stdout directed to the input of the appropriate pipe,
1228 * so this routine is noticeably simpler.
1230 static int run_pipe_real(struct pipe *pi)
1234 int nextin, nextout;
1235 int pipefds[2]; /* pipefds[0] is for reading */
1236 struct child_prog *child;
1237 struct built_in_command *x;
1243 /* Check if we are supposed to run in the foreground */
1244 if (interactive && pi->followup!=PIPE_BG) {
1245 if ((pi->pgrp = tcgetpgrp(ctty = 2)) < 0
1246 && (pi->pgrp = tcgetpgrp(ctty = 0)) < 0
1247 && (pi->pgrp = tcgetpgrp(ctty = 1)) < 0)
1248 return errno = ENOTTY, -1;
1250 if (pi->pgrp < 0 && pi->pgrp != getpgrp())
1251 return errno = EPERM, -1;
1254 /* Check if this is a simple builtin (not part of a pipe).
1255 * Builtins within pipes have to fork anyway, and are handled in
1256 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1258 if (pi->num_progs == 1 && pi->progs[0].argv != NULL) {
1259 child = & (pi->progs[0]);
1260 if (child->group && ! child->subshell) {
1261 int squirrel[] = {-1, -1, -1};
1263 debug_printf("non-subshell grouping\n");
1264 setup_redirects(child, squirrel);
1265 /* XXX could we merge code with following builtin case,
1266 * by creating a pseudo builtin that calls run_list_real? */
1267 rcode = run_list_real(child->group);
1268 restore_redirects(squirrel);
1271 for (i=0; is_assignment(child->argv[i]); i++) { /* nothing */ }
1272 if (i!=0 && child->argv[i]==NULL) {
1273 /* assignments, but no command: set the local environment */
1274 for (i=0; child->argv[i]!=NULL; i++) {
1275 set_local_var(child->argv[i]);
1277 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1279 for (x = bltins; x->cmd; x++) {
1280 if (strcmp(child->argv[i], x->cmd) == 0 ) {
1281 int squirrel[] = {-1, -1, -1};
1283 if (x->function == builtin_exec && child->argv[i+1]==NULL) {
1284 debug_printf("magic exec\n");
1285 setup_redirects(child,NULL);
1286 return EXIT_SUCCESS;
1288 debug_printf("builtin inline %s\n", child->argv[0]);
1289 /* XXX setup_redirects acts on file descriptors, not FILEs.
1290 * This is perfect for work that comes after exec().
1291 * Is it really safe for inline use? Experimentally,
1292 * things seem to work with glibc. */
1293 setup_redirects(child, squirrel);
1294 for (i=0; is_assignment(child->argv[i]); i++) {
1295 putenv(strdup(child->argv[i]));
1297 child->argv+=i; /* XXX horrible hack */
1298 rcode = x->function(child);
1299 child->argv-=i; /* XXX restore hack so free() can work right */
1300 restore_redirects(squirrel);
1306 for (i = 0; i < pi->num_progs; i++) {
1307 child = & (pi->progs[i]);
1309 /* pipes are inserted between pairs of commands */
1310 if ((i + 1) < pi->num_progs) {
1311 if (pipe(pipefds)<0) perror_msg_and_die("pipe");
1312 nextout = pipefds[1];
1318 /* XXX test for failed fork()? */
1319 if (!(child->pid = fork())) {
1321 signal(SIGTTOU, SIG_DFL);
1333 if (pipefds[0]!=-1) {
1334 close(pipefds[0]); /* opposite end of our output pipe */
1337 /* Like bash, explicit redirects override pipes,
1338 * and the pipe fd is available for dup'ing. */
1339 setup_redirects(child,NULL);
1341 if (pi->followup!=PIPE_BG) {
1342 /* Put our child in the process group whose leader is the
1343 * first process in this pipe. */
1345 pi->pgrp = child->pid;
1347 /* Don't check for errors. The child may be dead already,
1348 * in which case setpgid returns error code EACCES. */
1349 if (setpgid(0, pi->pgrp) == 0) {
1350 signal(SIGTTOU, SIG_IGN);
1351 tcsetpgrp(ctty, pi->pgrp);
1352 signal(SIGTTOU, SIG_DFL);
1358 /* Put our child in the process group whose leader is the
1359 * first process in this pipe. */
1361 pi->pgrp = child->pid;
1363 /* Don't check for errors. The child may be dead already,
1364 * in which case setpgid returns error code EACCES. */
1365 setpgid(child->pid, pi->pgrp);
1372 /* If there isn't another process, nextin is garbage
1373 but it doesn't matter */
1374 nextin = pipefds[0];
1379 static int run_list_real(struct pipe *pi)
1382 int if_code=0, next_if_code=0; /* need double-buffer to handle elif */
1383 reserved_style rmode, skip_more_in_this_rmode=RES_XXXX;
1384 for (;pi;pi=pi->next) {
1386 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);
1387 if (rmode == skip_more_in_this_rmode) continue;
1388 skip_more_in_this_rmode = RES_XXXX;
1389 if (rmode == RES_THEN || rmode == RES_ELSE) if_code = next_if_code;
1390 if (rmode == RES_THEN && if_code) continue;
1391 if (rmode == RES_ELSE && !if_code) continue;
1392 if (rmode == RES_ELIF && !if_code) continue;
1393 if (pi->num_progs == 0) continue;
1394 rcode = run_pipe_real(pi);
1396 /* We only ran a builtin: rcode was set by the return value
1397 * of run_pipe_real(), and we don't need to wait for anything. */
1398 } else if (pi->followup==PIPE_BG) {
1399 /* XXX check bash's behavior with nontrivial pipes */
1400 /* XXX compute jobid */
1401 /* XXX what does bash do with attempts to background builtins? */
1403 rcode = EXIT_SUCCESS;
1407 /* move the new process group into the foreground */
1408 /* suppress messages when run from /linuxrc mag@sysgo.de */
1409 //signal(SIGTTIN, SIG_IGN);
1410 //signal(SIGTTOU, SIG_IGN);
1411 if (tcsetpgrp(0, pi->pgrp) && errno != ENOTTY)
1412 perror_msg("tcsetpgrp");
1413 rcode = pipe_wait(pi);
1414 if (tcsetpgrp(0, getpgrp()) && errno != ENOTTY)
1415 perror_msg("tcsetpgrp");
1416 //signal(SIGTTIN, SIG_DFL);
1417 //signal(SIGTTOU, SIG_DFL);
1419 rcode = pipe_wait(pi);
1422 last_return_code=rcode;
1423 if ( rmode == RES_IF || rmode == RES_ELIF )
1424 next_if_code=rcode; /* can be overwritten a number of times */
1425 if ( (rcode==EXIT_SUCCESS && pi->followup==PIPE_OR) ||
1426 (rcode!=EXIT_SUCCESS && pi->followup==PIPE_AND) )
1427 skip_more_in_this_rmode=rmode;
1428 /* return rcode; */ /* XXX broken if list is part of if/then/else */
1434 /* broken, of course, but OK for testing */
1435 static char *indenter(int i)
1437 static char blanks[]=" ";
1438 return &blanks[sizeof(blanks)-i-1];
1441 /* return code is the exit status of the pipe */
1442 static int run_pipe_test(struct pipe *pi, int indent)
1445 struct child_prog *child;
1446 struct redir_struct *r, *rnext;
1447 int a, i, ret_code=0;
1448 char *ind = indenter(indent);
1449 final_printf("%s run pipe: (pid %d)\n",ind,getpid());
1450 for (i=0; i<pi->num_progs; i++) {
1451 child = &pi->progs[i];
1452 final_printf("%s command %d:\n",ind,i);
1454 for (a=0,p=child->argv; *p; a++,p++) {
1455 final_printf("%s argv[%d] = %s\n",ind,a,*p);
1457 globfree(&child->glob_result);
1459 } else if (child->group) {
1460 final_printf("%s begin group (subshell:%d)\n",ind, child->subshell);
1461 ret_code = run_list_test(child->group,indent+3);
1462 final_printf("%s end group\n",ind);
1464 final_printf("%s (nil)\n",ind);
1466 for (r=child->redirects; r; r=rnext) {
1467 final_printf("%s redirect %d%s", ind, r->fd, redir_table[r->type].descrip);
1469 final_printf(" %s\n", *r->word.gl_pathv);
1472 final_printf("&%d\n", r->dup);
1477 child->redirects=NULL;
1479 free(pi->progs); /* children are an array, they get freed all at once */
1484 static int run_list_test(struct pipe *head, int indent)
1486 int rcode=0; /* if list has no members */
1487 struct pipe *pi, *next;
1488 char *ind = indenter(indent);
1489 for (pi=head; pi; pi=next) {
1490 if (pi->num_progs == 0) break;
1491 final_printf("%s pipe reserved mode %d\n", ind, pi->r_mode);
1492 rcode = run_pipe_test(pi, indent);
1493 final_printf("%s pipe followup code %d\n", ind, pi->followup);
1501 /* Select which version we will use */
1502 static int run_list(struct pipe *pi)
1506 rcode = run_list_real(pi);
1508 /* run_list_test has the side effect of clearing memory
1509 * In the long run that function can be merged with run_list_real,
1510 * but doing that now would hobble the debugging effort. */
1511 run_list_test(pi,0);
1515 /* The API for glob is arguably broken. This routine pushes a non-matching
1516 * string into the output structure, removing non-backslashed backslashes.
1517 * If someone can prove me wrong, by performing this function within the
1518 * original glob(3) api, feel free to rewrite this routine into oblivion.
1519 * Return code (0 vs. GLOB_NOSPACE) matches glob(3).
1520 * XXX broken if the last character is '\\', check that before calling.
1522 static int globhack(const char *src, int flags, glob_t *pglob)
1527 for (cnt=1, s=src; *s; s++) {
1528 if (*s == '\\') s++;
1532 if (!dest) return GLOB_NOSPACE;
1533 if (!(flags & GLOB_APPEND)) {
1534 pglob->gl_pathv=NULL;
1539 pathc = ++pglob->gl_pathc;
1540 pglob->gl_pathv = realloc(pglob->gl_pathv, (pathc+1)*sizeof(*pglob->gl_pathv));
1541 if (pglob->gl_pathv == NULL) return GLOB_NOSPACE;
1542 pglob->gl_pathv[pathc-1]=dest;
1543 pglob->gl_pathv[pathc]=NULL;
1544 for (s=src; *s; s++, dest++) {
1545 if (*s == '\\') s++;
1552 /* XXX broken if the last character is '\\', check that before calling */
1553 static int glob_needed(const char *s)
1556 if (*s == '\\') s++;
1557 if (strchr("*[?",*s)) return 1;
1563 static void globprint(glob_t *pglob)
1566 debug_printf("glob_t at %p:\n", pglob);
1567 debug_printf(" gl_pathc=%d gl_pathv=%p gl_offs=%d gl_flags=%d\n",
1568 pglob->gl_pathc, pglob->gl_pathv, pglob->gl_offs, pglob->gl_flags);
1569 for (i=0; i<pglob->gl_pathc; i++)
1570 debug_printf("pglob->gl_pathv[%d] = %p = %s\n", i,
1571 pglob->gl_pathv[i], pglob->gl_pathv[i]);
1575 static int xglob(o_string *dest, int flags, glob_t *pglob)
1579 /* short-circuit for null word */
1580 /* we can code this better when the debug_printf's are gone */
1581 if (dest->length == 0) {
1582 if (dest->nonnull) {
1583 /* bash man page calls this an "explicit" null */
1584 gr = globhack(dest->data, flags, pglob);
1585 debug_printf("globhack returned %d\n",gr);
1589 } else if (glob_needed(dest->data)) {
1590 gr = glob(dest->data, flags, NULL, pglob);
1591 debug_printf("glob returned %d\n",gr);
1592 if (gr == GLOB_NOMATCH) {
1593 /* quote removal, or more accurately, backslash removal */
1594 gr = globhack(dest->data, flags, pglob);
1595 debug_printf("globhack returned %d\n",gr);
1598 gr = globhack(dest->data, flags, pglob);
1599 debug_printf("globhack returned %d\n",gr);
1601 if (gr == GLOB_NOSPACE) {
1602 fprintf(stderr,"out of memory during glob\n");
1605 if (gr != 0) { /* GLOB_ABORTED ? */
1606 fprintf(stderr,"glob(3) error %d\n",gr);
1608 /* globprint(glob_target); */
1613 static int set_local_var(const char *s)
1615 /* when you write this, also need to update lookup_param() */
1616 printf("assignment %s not handled: write me!\n",s);
1620 static int is_assignment(const char *s)
1622 if (s==NULL || !isalpha(*s)) return 0;
1624 while(isalnum(*s) || *s=='_') ++s;
1628 /* the src parameter allows us to peek forward to a possible &n syntax
1629 * for file descriptor duplication, e.g., "2>&1".
1630 * Return code is 0 normally, 1 if a syntax error is detected in src.
1631 * Resource errors (in xmalloc) cause the process to exit */
1632 static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
1633 struct in_str *input)
1635 struct child_prog *child=ctx->child;
1636 struct redir_struct *redir = child->redirects;
1637 struct redir_struct *last_redir=NULL;
1639 /* Create a new redir_struct and drop it onto the end of the linked list */
1644 redir = xmalloc(sizeof(struct redir_struct));
1647 last_redir->next=redir;
1649 child->redirects=redir;
1653 redir->fd= (fd==-1) ? redir_table[style].default_fd : fd ;
1655 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
1657 /* Check for a '2>&1' type redirect */
1658 redir->dup = redirect_dup_num(input);
1659 if (redir->dup == -2) return 1; /* syntax error */
1660 if (redir->dup != -1) {
1661 /* Erik had a check here that the file descriptor in question
1662 * is legit; I postpone that to "run time"
1663 * A "-" representation of "close me" shows up as a -3 here */
1664 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
1666 /* We do _not_ try to open the file that src points to,
1667 * since we need to return and let src be expanded first.
1668 * Set ctx->pending_redirect, so we know what to do at the
1669 * end of the next parsed word.
1671 ctx->pending_redirect = redir;
1676 struct pipe *new_pipe(void) {
1678 pi = xmalloc(sizeof(struct pipe));
1682 pi->followup = 0; /* invalid */
1686 static void initialize_context(struct p_context *ctx)
1689 ctx->pending_redirect=NULL;
1691 ctx->list_head=new_pipe();
1692 ctx->pipe=ctx->list_head;
1695 done_command(ctx); /* creates the memory for working child */
1698 /* normal return is 0
1699 * if a reserved word is found, and processed, return 1
1700 * should handle if, then, elif, else, fi, for, while, until, do, done.
1701 * case, function, and select are obnoxious, save those for later.
1703 int reserved_word(o_string *dest, struct p_context *ctx)
1705 struct reserved_combo {
1710 /* Mostly a list of accepted follow-up reserved words.
1711 * FLAG_END means we are done with the sequence, and are ready
1712 * to turn the compound list into a command.
1713 * FLAG_START means the word must start a new compound list.
1715 static struct reserved_combo reserved_list[] = {
1716 { "if", RES_IF, FLAG_THEN | FLAG_START },
1717 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
1718 { "elif", RES_ELIF, FLAG_THEN },
1719 { "else", RES_ELSE, FLAG_FI },
1720 { "fi", RES_FI, FLAG_END },
1721 { "for", RES_FOR, FLAG_DO | FLAG_START },
1722 { "while", RES_WHILE, FLAG_DO | FLAG_START },
1723 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
1724 { "do", RES_DO, FLAG_DONE },
1725 { "done", RES_DONE, FLAG_END }
1727 struct reserved_combo *r;
1728 for (r=reserved_list;
1729 #define NRES sizeof(reserved_list)/sizeof(struct reserved_combo)
1730 r<reserved_list+NRES; r++) {
1731 if (strcmp(dest->data, r->literal) == 0) {
1732 debug_printf("found reserved word %s, code %d\n",r->literal,r->code);
1733 if (r->flag & FLAG_START) {
1734 struct p_context *new = xmalloc(sizeof(struct p_context));
1735 debug_printf("push stack\n");
1736 *new = *ctx; /* physical copy */
1737 initialize_context(ctx);
1739 } else if ( ctx->w == RES_NONE || ! (ctx->old_flag & (1<<r->code))) {
1746 ctx->old_flag = r->flag;
1747 if (ctx->old_flag & FLAG_END) {
1748 struct p_context *old;
1749 debug_printf("pop stack\n");
1751 old->child->group = ctx->list_head;
1752 *ctx = *old; /* physical copy */
1762 /* normal return is 0.
1763 * Syntax or xglob errors return 1. */
1764 static int done_word(o_string *dest, struct p_context *ctx)
1766 struct child_prog *child=ctx->child;
1767 glob_t *glob_target;
1770 debug_printf("done_word: %s %p\n", dest->data, child);
1771 if (dest->length == 0 && !dest->nonnull) {
1772 debug_printf(" true null, ignored\n");
1775 if (ctx->pending_redirect) {
1776 glob_target = &ctx->pending_redirect->word;
1780 return 1; /* syntax error, groups and arglists don't mix */
1783 debug_printf("checking %s for reserved-ness\n",dest->data);
1784 if (reserved_word(dest,ctx)) return ctx->w==RES_SNTX;
1786 glob_target = &child->glob_result;
1787 if (child->argv) flags |= GLOB_APPEND;
1789 gr = xglob(dest, flags, glob_target);
1790 if (gr != 0) return 1;
1793 if (ctx->pending_redirect) {
1794 ctx->pending_redirect=NULL;
1795 if (glob_target->gl_pathc != 1) {
1796 fprintf(stderr, "ambiguous redirect\n");
1800 child->argv = glob_target->gl_pathv;
1805 /* The only possible error here is out of memory, in which case
1807 static int done_command(struct p_context *ctx)
1809 /* The child is really already in the pipe structure, so
1810 * advance the pipe counter and make a new, null child.
1811 * Only real trickiness here is that the uncommitted
1812 * child structure, to which ctx->child points, is not
1813 * counted in pi->num_progs. */
1814 struct pipe *pi=ctx->pipe;
1815 struct child_prog *prog=ctx->child;
1817 if (prog && prog->group == NULL
1818 && prog->argv == NULL
1819 && prog->redirects == NULL) {
1820 debug_printf("done_command: skipping null command\n");
1824 debug_printf("done_command: num_progs incremented to %d\n",pi->num_progs);
1826 debug_printf("done_command: initializing\n");
1828 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
1830 prog = pi->progs + pi->num_progs;
1831 prog->redirects = NULL;
1833 prog->is_stopped = 0;
1835 prog->glob_result.gl_pathv = NULL;
1839 /* but ctx->pipe and ctx->list_head remain unchanged */
1843 static int done_pipe(struct p_context *ctx, pipe_style type)
1846 done_command(ctx); /* implicit closure of previous command */
1847 debug_printf("done_pipe, type %d\n", type);
1848 ctx->pipe->followup = type;
1849 ctx->pipe->r_mode = ctx->w;
1851 ctx->pipe->next = new_p;
1854 done_command(ctx); /* set up new pipe to accept commands */
1858 /* peek ahead in the in_str to find out if we have a "&n" construct,
1859 * as in "2>&1", that represents duplicating a file descriptor.
1860 * returns either -2 (syntax error), -1 (no &), or the number found.
1862 static int redirect_dup_num(struct in_str *input)
1866 if (ch != '&') return -1;
1868 b_getch(input); /* get the & */
1872 return -3; /* "-" represents "close me" */
1874 while (isdigit(ch)) {
1882 fprintf(stderr, "ambiguous redirect\n");
1886 /* If a redirect is immediately preceded by a number, that number is
1887 * supposed to tell which file descriptor to redirect. This routine
1888 * looks for such preceding numbers. In an ideal world this routine
1889 * needs to handle all the following classes of redirects...
1890 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
1891 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
1892 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
1893 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
1894 * A -1 output from this program means no valid number was found, so the
1895 * caller should use the appropriate default for this redirection.
1897 static int redirect_opt_num(o_string *o)
1901 if (o->length==0) return -1;
1902 for(num=0; num<o->length; num++) {
1903 if (!isdigit(*(o->data+num))) {
1907 /* reuse num (and save an int) */
1913 FILE *generate_stream_from_list(struct pipe *head)
1917 int pid, channel[2];
1918 if (pipe(channel)<0) perror_msg_and_die("pipe");
1921 perror_msg_and_die("fork");
1922 } else if (pid==0) {
1924 if (channel[1] != 1) {
1929 #define SURROGATE "surrogate response"
1930 write(1,SURROGATE,sizeof(SURROGATE));
1931 exit(run_list(head));
1933 exit(run_list_real(head)); /* leaks memory */
1936 debug_printf("forked child %d\n",pid);
1938 pf = fdopen(channel[0],"r");
1939 debug_printf("pipe on FILE *%p\n",pf);
1941 run_list_test(head,0);
1942 pf=popen("echo surrogate response","r");
1943 debug_printf("started fake pipe on FILE *%p\n",pf);
1948 /* this version hacked for testing purposes */
1949 /* return code is exit status of the process that is run. */
1950 static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end)
1953 o_string result=NULL_O_STRING;
1954 struct p_context inner;
1956 struct in_str pipe_str;
1957 initialize_context(&inner);
1959 /* recursion to generate command */
1960 retcode = parse_stream(&result, &inner, input, subst_end);
1961 if (retcode != 0) return retcode; /* syntax error or EOF */
1962 done_word(&result, &inner);
1963 done_pipe(&inner, PIPE_SEQ);
1966 p=generate_stream_from_list(inner.list_head);
1967 if (p==NULL) return 1;
1968 mark_open(fileno(p));
1969 setup_file_in_str(&pipe_str, p);
1971 /* now send results of command back into original context */
1972 retcode = parse_stream(dest, ctx, &pipe_str, '\0');
1973 /* XXX In case of a syntax error, should we try to kill the child?
1974 * That would be tough to do right, so just read until EOF. */
1976 while (b_getch(&pipe_str)!=EOF) { /* discard */ };
1979 debug_printf("done reading from pipe, pclose()ing\n");
1980 /* This is the step that wait()s for the child. Should be pretty
1981 * safe, since we just read an EOF from its stdout. We could try
1982 * to better, by using wait(), and keeping track of background jobs
1983 * at the same time. That would be a lot of work, and contrary
1984 * to the KISS philosophy of this program. */
1985 mark_closed(fileno(p));
1987 debug_printf("pclosed, retcode=%d\n",retcode);
1988 /* XXX this process fails to trim a single trailing newline */
1992 static int parse_group(o_string *dest, struct p_context *ctx,
1993 struct in_str *input, int ch)
1996 struct p_context sub;
1997 struct child_prog *child = ctx->child;
2000 return 1; /* syntax error, groups and arglists don't mix */
2002 initialize_context(&sub);
2004 case '(': endch=')'; child->subshell=1; break;
2005 case '{': endch='}'; break;
2006 default: syntax(); /* really logic error */
2008 rcode=parse_stream(dest,&sub,input,endch);
2009 done_word(dest,&sub); /* finish off the final word in the subcontext */
2010 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
2011 child->group = sub.list_head;
2013 /* child remains "open", available for possible redirects */
2016 /* basically useful version until someone wants to get fancier,
2017 * see the bash man page under "Parameter Expansion" */
2018 static void lookup_param(o_string *dest, struct p_context *ctx, o_string *src)
2021 if (src->data) p = getenv(src->data);
2022 if (p) parse_string(dest, ctx, p); /* recursion */
2026 /* return code: 0 for OK, 1 for syntax error */
2027 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
2030 o_string alt=NULL_O_STRING;
2032 int ch = input->peek(input); /* first character after the $ */
2033 debug_printf("handle_dollar: ch=%c\n",ch);
2035 while(ch=b_peek(input),isalnum(ch) || ch=='_') {
2039 lookup_param(dest, ctx, &alt);
2040 } else if (isdigit(ch)) {
2041 i = ch-'0'; /* XXX is $0 special? */
2042 if (i<global_argc) {
2043 parse_string(dest, ctx, global_argv[i]); /* recursion */
2046 } else switch (ch) {
2048 b_adduint(dest,getpid());
2052 if (last_bg_pid > 0) b_adduint(dest, last_bg_pid);
2056 b_adduint(dest,last_return_code);
2060 b_adduint(dest,global_argc ? global_argc-1 : 0);
2065 /* XXX maybe someone will try to escape the '}' */
2066 while(ch=b_getch(input),ch!=EOF && ch!='}') {
2073 lookup_param(dest, ctx, &alt);
2077 process_command_subs(dest, ctx, input, ')');
2081 for (i=1; i<global_argc; i++) {
2082 parse_string(dest, ctx, global_argv[i]);
2083 if (i+1 < global_argc) parse_string(dest, ctx, sep);
2089 /* still unhandled, but should be eventually */
2090 fprintf(stderr,"unhandled syntax: $%c\n",ch);
2094 b_addqchr(dest,'$',dest->quote);
2096 /* Eat the character if the flag was set. If the compiler
2097 * is smart enough, we could substitute "b_getch(input);"
2098 * for all the "advance = 1;" above, and also end up with
2099 * a nice size-optimized program. Hah! That'll be the day.
2101 if (advance) b_getch(input);
2105 int parse_string(o_string *dest, struct p_context *ctx, const char *src)
2108 setup_string_in_str(&foo, src);
2109 return parse_stream(dest, ctx, &foo, '\0');
2112 /* return code is 0 for normal exit, 1 for syntax error */
2113 int parse_stream(o_string *dest, struct p_context *ctx,
2114 struct in_str *input, int end_trigger)
2118 redir_type redir_style;
2121 /* Only double-quote state is handled in the state variable dest->quote.
2122 * A single-quote triggers a bypass of the main loop until its mate is
2123 * found. When recursing, quote state is passed in via dest->quote. */
2125 debug_printf("parse_stream, end_trigger=%d\n",end_trigger);
2126 while ((ch=b_getch(input))!=EOF) {
2128 next = (ch == '\n') ? 0 : b_peek(input);
2129 debug_printf("parse_stream: ch=%c (%d) m=%d quote=%d\n",
2130 ch,ch,m,dest->quote);
2131 if (m==0 || ((m==1 || m==2) && dest->quote)) {
2132 b_addqchr(dest, ch, dest->quote);
2134 if (m==2) { /* unquoted IFS */
2135 done_word(dest, ctx);
2136 /* If we aren't performing a substitution, treat a newline as a
2137 * command separator. */
2138 if (end_trigger != '\0' && ch=='\n')
2139 done_pipe(ctx,PIPE_SEQ);
2141 if (ch == end_trigger && !dest->quote && ctx->w==RES_NONE) {
2142 debug_printf("leaving parse_stream\n");
2147 /* Yahoo! Time to run with it! */
2148 done_pipe(ctx,PIPE_SEQ);
2149 run_list(ctx->list_head);
2150 initialize_context(ctx);
2153 if (m!=2) switch (ch) {
2155 if (dest->length == 0 && !dest->quote) {
2156 while(ch=b_peek(input),ch!=EOF && ch!='\n') { b_getch(input); }
2158 b_addqchr(dest, ch, dest->quote);
2166 b_addqchr(dest, '\\', dest->quote);
2167 b_addqchr(dest, b_getch(input), dest->quote);
2170 if (handle_dollar(dest, ctx, input)!=0) return 1;
2174 while(ch=b_getch(input),ch!=EOF && ch!='\'') {
2184 dest->quote = !dest->quote;
2187 process_command_subs(dest, ctx, input, '`');
2190 redir_fd = redirect_opt_num(dest);
2191 done_word(dest, ctx);
2192 redir_style=REDIRECT_OVERWRITE;
2194 redir_style=REDIRECT_APPEND;
2196 } else if (next == '(') {
2197 syntax(); /* until we support >(list) Process Substitution */
2200 setup_redirect(ctx, redir_fd, redir_style, input);
2203 redir_fd = redirect_opt_num(dest);
2204 done_word(dest, ctx);
2205 redir_style=REDIRECT_INPUT;
2207 redir_style=REDIRECT_HEREIS;
2209 } else if (next == '>') {
2210 redir_style=REDIRECT_IO;
2212 } else if (next == '(') {
2213 syntax(); /* until we support <(list) Process Substitution */
2216 setup_redirect(ctx, redir_fd, redir_style, input);
2219 done_word(dest, ctx);
2220 done_pipe(ctx,PIPE_SEQ);
2223 done_word(dest, ctx);
2226 done_pipe(ctx,PIPE_AND);
2228 done_pipe(ctx,PIPE_BG);
2232 done_word(dest, ctx);
2235 done_pipe(ctx,PIPE_OR);
2237 /* we could pick up a file descriptor choice here
2238 * with redirect_opt_num(), but bash doesn't do it.
2239 * "echo foo 2| cat" yields "foo 2". */
2245 if (parse_group(dest, ctx, input, ch)!=0) return 1;
2249 syntax(); /* Proper use of this character caught by end_trigger */
2253 syntax(); /* this is really an internal logic error */
2258 /* complain if quote? No, maybe we just finished a command substitution
2259 * that was quoted. Example:
2260 * $ echo "`cat foo` plus more"
2261 * and we just got the EOF generated by the subshell that ran "cat foo"
2262 * The only real complaint is if we got an EOF when end_trigger != '\0',
2263 * that is, we were really supposed to get end_trigger, and never got
2264 * one before the EOF. Can't use the standard "syntax error" return code,
2265 * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
2266 if (end_trigger != '\0') return -1;
2270 void mapset(const unsigned char *set, int code)
2272 const unsigned char *s;
2273 for (s=set; *s; s++) map[*s] = code;
2276 void update_ifs_map(void)
2278 /* char *ifs and char map[256] are both globals. */
2279 ifs = getenv("IFS");
2280 if (ifs == NULL) ifs=" \t\n";
2281 /* Precompute a list of 'flow through' behavior so it can be treated
2282 * quickly up front. Computation is necessary because of IFS.
2283 * Special case handling of IFS == " \t\n" is not implemented.
2284 * The map[] array only really needs two bits each, and on most machines
2285 * that would be faster because of the reduced L1 cache footprint.
2287 memset(map,0,256); /* most characters flow through always */
2288 mapset("\\$'\"`", 3); /* never flow through */
2289 mapset("<>;&|(){}#", 1); /* flow through if quoted */
2290 mapset(ifs, 2); /* also flow through if quoted */
2293 /* most recursion does not come through here, the exeception is
2294 * from builtin_source() */
2295 int parse_stream_outer(struct in_str *inp)
2298 struct p_context ctx;
2299 o_string temp=NULL_O_STRING;
2302 initialize_context(&ctx);
2305 rcode = parse_stream(&temp, &ctx, inp, '\n');
2306 done_word(&temp, &ctx);
2307 done_pipe(&ctx,PIPE_SEQ);
2308 run_list(ctx.list_head);
2309 } while (rcode != -1); /* loop on syntax errors, return on EOF */
2313 static int parse_string_outer(const char *s)
2315 struct in_str input;
2316 setup_string_in_str(&input, s);
2317 return parse_stream_outer(&input);
2320 static int parse_file_outer(FILE *f)
2323 struct in_str input;
2324 setup_file_in_str(&input, f);
2325 rcode = parse_stream_outer(&input);
2329 int shell_main(int argc, char **argv)
2333 struct jobset joblist_end = { NULL, NULL };
2334 job_list = &joblist_end;
2336 last_return_code=EXIT_SUCCESS;
2338 /* XXX what should these be while sourcing /etc/profile? */
2342 /* don't pay any attention to this signal; it just confuses
2343 things and isn't really meant for shells anyway */
2344 signal(SIGTTOU, SIG_IGN);
2346 if (argv[0] && argv[0][0] == '-') {
2347 debug_printf("\nsourcing /etc/profile\n");
2348 input = xfopen("/etc/profile", "r");
2349 mark_open(fileno(input));
2350 parse_file_outer(input);
2351 mark_closed(fileno(input));
2356 /* initialize the cwd -- this is never freed...*/
2360 #ifdef BB_FEATURE_COMMAND_EDITING
2361 cmdedit_set_initial_prompt();
2366 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
2370 global_argv = argv+optind;
2371 global_argc = argc-optind;
2372 opt = parse_string_outer(optarg);
2383 fprintf(stderr, "Usage: sh [FILE]...\n"
2384 " or: sh -c command [args]...\n\n");
2388 /* A shell is interactive if the `-i' flag was given, or if all of
2389 * the following conditions are met:
2391 * no arguments remaining or the -s flag given
2392 * standard input is a terminal
2393 * standard output is a terminal
2394 * Refer to Posix.2, the description of the `sh' utility. */
2395 if (argv[optind]==NULL && input==stdin &&
2396 isatty(fileno(stdin)) && isatty(fileno(stdout))) {
2400 debug_printf("\ninteractive=%d\n", interactive);
2402 /* Looks like they want an interactive shell */
2403 fprintf(stdout, "\nhush -- the humble shell v0.01 (testing)\n\n");
2404 opt=parse_file_outer(stdin);
2408 debug_printf("\nrunning script '%s'\n", argv[optind]);
2409 global_argv = argv+optind;
2410 global_argc = argc-optind;
2411 input = xfopen(argv[optind], "r");
2412 opt = parse_file_outer(input);
2414 #ifdef BB_FEATURE_CLEAN_UP
2419 return(opt?opt:last_return_code);