1 /* vi: set sw=4 ts=4: */
3 * sh.c -- a prototype Bourne shell grammar parser
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
11 * The parser routines proper are all original material, first
12 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
13 * execution engine, the builtins, and much of the underlying
14 * support has been adapted from busybox-0.49pre's lash, which is
15 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
16 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
17 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
18 * Troan, which they placed in the public domain. I don't know
19 * how much of the Johnson/Troan code has survived the repeated
23 * b_addchr() derived from similar w_addchar function in glibc-2.2
24 * setup_redirect(), redirect_opt_num(), and big chunks of main()
25 * and many builtins derived from contributions by Erik Andersen
26 * miscellaneous bugfixes from Matt Kraai
28 * There are two big (and related) architecture differences between
29 * this parser and the lash parser. One is that this version is
30 * actually designed from the ground up to understand nearly all
31 * of the Bourne grammar. The second, consequential change is that
32 * the parser and input reader have been turned inside out. Now,
33 * the parser is in control, and asks for input as needed. The old
34 * way had the input reader in control, and it asked for parsing to
35 * take place as needed. The new way makes it much easier to properly
36 * handle the recursion implicit in the various substitutions, especially
37 * across continuation lines.
39 * Bash grammar not implemented: (how many of these were in original sh?)
40 * $@ (those sure look like weird quoting rules)
42 * ! negation operator for pipes
43 * &> and >& redirection of stdout+stderr
46 * fancy forms of Parameter Expansion
48 * Arithmetic Expansion
49 * <(list) and >(list) Process Substitution
50 * reserved words: case, esac, select, function
51 * Here Documents ( << word )
54 * job handling woefully incomplete and buggy
55 * reserved word execution woefully incomplete and buggy
57 * port selected bugfixes from post-0.49 busybox lash - done?
58 * finish implementing reserved words: for, while, until, do, done
59 * change { and } from special chars to reserved words
60 * builtins: break, continue, eval, return, set, trap, ulimit
62 * handle children going into background
63 * clean up recognition of null pipes
64 * check setting of global_argc and global_argv
65 * control-C handling, probably with longjmp
66 * follow IFS rules more precisely, including update semantics
67 * figure out what to do with backslash-newline
68 * explain why we use signal instead of sigaction
69 * propagate syntax errors, die on resource errors?
70 * continuation lines, both explicit and implicit - done?
71 * memory leak finding and plugging - done?
72 * more testing, especially quoting rules and redirection
73 * document how quoting rules not precisely followed for variable assignments
74 * maybe change map[] to use 2-bit entries
75 * (eventually) remove all the printf's
77 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
81 #include <glob.h> /* glob, of course */
82 #include <getopt.h> /* should be pretty obvious */
84 /* #include <dmalloc.h> */
85 /* #define DEBUG_SHELL */
88 #define SPECIAL_VAR_SYMBOL 03
89 #define FLAG_EXIT_FROM_LOOP 1
90 #define FLAG_PARSE_SEMICOLON (1 << 1) /* symbol ';' is special for parser */
91 #define FLAG_REPARSING (1 << 2) /* >=2nd pass */
95 REDIRECT_OVERWRITE = 2,
101 /* The descrip member of this structure is only used to make debugging
103 static const struct {
109 { O_RDONLY, 0, "<" },
110 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
111 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
112 { O_RDONLY, -1, "<<" },
123 /* might eventually control execution */
141 FLAG_END = (1 << RES_NONE ),
142 FLAG_IF = (1 << RES_IF ),
143 FLAG_THEN = (1 << RES_THEN ),
144 FLAG_ELIF = (1 << RES_ELIF ),
145 FLAG_ELSE = (1 << RES_ELSE ),
146 FLAG_FI = (1 << RES_FI ),
147 FLAG_FOR = (1 << RES_FOR ),
148 FLAG_WHILE = (1 << RES_WHILE),
149 FLAG_UNTIL = (1 << RES_UNTIL),
150 FLAG_DO = (1 << RES_DO ),
151 FLAG_DONE = (1 << RES_DONE ),
152 FLAG_IN = (1 << RES_IN ),
153 FLAG_START = (1 << RES_XXXX ),
156 /* This holds pointers to the various results of parsing */
158 struct child_prog *child;
159 struct pipe *list_head;
161 struct redir_struct *pending_redirect;
163 int old_flag; /* for figuring out valid reserved words */
164 struct p_context *stack;
165 int type; /* define type of parser : ";$" common or special symbol */
166 /* How about quoting status? */
169 struct redir_struct {
170 redir_type type; /* type of redirection */
171 int fd; /* file descriptor being redirected */
172 int dup; /* -1, or file descriptor being duplicated */
173 struct redir_struct *next; /* pointer to the next redirect in the list */
174 glob_t word; /* *word.gl_pathv is the filename */
178 pid_t pid; /* 0 if exited */
179 char **argv; /* program name and arguments */
180 struct pipe *group; /* if non-NULL, first in group or subshell */
181 int subshell; /* flag, non-zero if group must be forked */
182 struct redir_struct *redirects; /* I/O redirections */
183 glob_t glob_result; /* result of parameter globbing */
184 int is_stopped; /* is the program currently running? */
185 struct pipe *family; /* pointer back to the child's parent pipe */
186 int sp; /* number of SPECIAL_VAR_SYMBOL */
191 int jobid; /* job number */
192 int num_progs; /* total number of programs in job */
193 int running_progs; /* number of programs running (not exited) */
194 char *text; /* name of job */
195 char *cmdbuf; /* buffer various argv's point into */
196 pid_t pgrp; /* process group ID for the job */
197 struct child_prog *progs; /* array of commands in pipe */
198 struct pipe *next; /* to track background commands */
199 int stopped_progs; /* number of programs alive, but stopped */
200 int job_context; /* bitmask defining current context */
201 pipe_style followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
202 reserved_style r_mode; /* supports if, for, while, until */
207 struct close_me *next;
215 struct variables *next;
218 /* globals, connect us to the outside world
219 * the first three support $?, $#, and $1 */
220 static char **global_argv;
221 static int global_argc;
222 static int last_return_code;
223 extern char **environ; /* This is in <unistd.h>, but protected with __USE_GNU */
225 /* "globals" within this file */
226 static const char *ifs;
227 static unsigned char map[256];
228 static int fake_mode;
229 static struct close_me *close_me_head;
230 static const char *cwd;
231 static struct pipe *job_list;
232 static unsigned last_bg_pid;
233 static int last_jobid;
234 /* 'interactive_fd' is a fd# open to ctty, if we have one
235 * _AND_ if we decided to mess with job control */
236 static int interactive_fd;
237 static pid_t saved_task_pgrp;
238 static pid_t saved_tty_pgrp;
240 static const char *PS1;
241 static const char *PS2;
242 static struct variables shell_ver = { "HUSH_VERSION", "0.01", 1, 1, 0 };
243 static struct variables *top_vars = &shell_ver;
246 #define B_CHUNK (100)
256 #define NULL_O_STRING {NULL,0,0,0,0}
257 /* used for initialization:
258 o_string foo = NULL_O_STRING; */
260 /* I can almost use ordinary FILE *. Is open_memstream() universally
261 * available? Where is it documented? */
268 int (*get) (struct in_str *);
269 int (*peek) (struct in_str *);
271 #define b_getch(input) ((input)->get(input))
272 #define b_peek(input) ((input)->peek(input))
274 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
276 struct built_in_command {
277 const char *cmd; /* name */
278 const char *descr; /* description */
279 int (*function) (struct child_prog *); /* function ptr */
282 /* belongs in busybox.h */
283 static int max(int a, int b)
285 return (a > b) ? a : b;
288 /* This should be in utility.c */
290 static void debug_printf(const char *format, ...)
293 va_start(args, format);
294 vfprintf(stderr, format, args);
297 /* broken, of course, but OK for testing */
298 static char *indenter(int i)
300 static char blanks[] = " ";
301 return &blanks[sizeof(blanks)-i-1];
304 #define debug_printf(...) do {} while (0)
306 #define final_printf debug_printf
308 static void __syntax(const char *file, int line)
310 bb_error_msg("syntax error %s:%d", file, line);
312 /* NB: was __FILE__, but that produces full path sometimes, so... */
313 #define syntax() __syntax("hush.c", __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_eval(struct child_prog *child);
320 static int builtin_exec(struct child_prog *child);
321 static int builtin_exit(struct child_prog *child);
322 static int builtin_export(struct child_prog *child);
323 static int builtin_fg_bg(struct child_prog *child);
324 static int builtin_help(struct child_prog *child);
325 static int builtin_jobs(struct child_prog *child);
326 static int builtin_pwd(struct child_prog *child);
327 static int builtin_read(struct child_prog *child);
328 static int builtin_set(struct child_prog *child);
329 static int builtin_shift(struct child_prog *child);
330 static int builtin_source(struct child_prog *child);
331 static int builtin_umask(struct child_prog *child);
332 static int builtin_unset(struct child_prog *child);
333 static int builtin_not_written(struct child_prog *child);
334 /* o_string manipulation: */
335 static int b_check_space(o_string *o, int len);
336 static int b_addchr(o_string *o, int ch);
337 static void b_reset(o_string *o);
338 static int b_addqchr(o_string *o, int ch, int quote);
339 static int b_adduint(o_string *o, unsigned i);
340 /* in_str manipulations: */
341 static int static_get(struct in_str *i);
342 static int static_peek(struct in_str *i);
343 static int file_get(struct in_str *i);
344 static int file_peek(struct in_str *i);
345 static void setup_file_in_str(struct in_str *i, FILE *f);
346 static void setup_string_in_str(struct in_str *i, const char *s);
347 /* close_me manipulations: */
348 static void mark_open(int fd);
349 static void mark_closed(int fd);
350 static void close_all(void);
351 /* "run" the final data structures: */
352 static int free_pipe_list(struct pipe *head, int indent);
353 static int free_pipe(struct pipe *pi, int indent);
354 /* really run the final data structures: */
355 static int setup_redirects(struct child_prog *prog, int squirrel[]);
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 is_assignment(const char *s);
365 /* data structure manipulation: */
366 static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
367 static void initialize_context(struct p_context *ctx);
368 static int done_word(o_string *dest, struct p_context *ctx);
369 static int done_command(struct p_context *ctx);
370 static int done_pipe(struct p_context *ctx, pipe_style type);
371 /* primary string parsing: */
372 static int redirect_dup_num(struct in_str *input);
373 static int redirect_opt_num(o_string *o);
374 static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end);
375 static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
376 static const char *lookup_param(const char *src);
377 static char *make_string(char **inp);
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, int flag);
383 static int parse_string_outer(const char *s, int flag);
384 static int parse_file_outer(FILE *f);
385 /* job management: */
386 static int checkjobs(struct pipe* fg_pipe);
387 static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
388 static void insert_bg_job(struct pipe *pi);
389 static void remove_bg_job(struct pipe *pi);
390 /* local variable support */
391 static char **make_list_in(char **inp, char *name);
392 static char *insert_var_value(char *inp);
393 static const char *get_local_var(const char *var);
394 static int set_local_var(const char *s, int flg_export);
395 static void unset_local_var(const char *name);
397 /* Table of built-in functions. They can be forked or not, depending on
398 * context: within pipes, they fork. As simple commands, they do not.
399 * When used in non-forking context, they can change global variables
400 * in the parent shell process. If forked, of course they cannot.
401 * For example, 'unset foo | whatever' will parse and run, but foo will
402 * still be set at the end. */
403 static const struct built_in_command bltins[] = {
404 { "bg", "Resume a job in the background", builtin_fg_bg },
405 { "break", "Exit for, while or until loop", builtin_not_written },
406 { "cd", "Change working directory", builtin_cd },
407 { "continue", "Continue for, while or until loop", builtin_not_written },
408 { "env", "Print all environment variables", builtin_env },
409 { "eval", "Construct and run shell command", builtin_eval },
410 { "exec", "Exec command, replacing this shell with the exec'd process",
412 { "exit", "Exit from shell()", builtin_exit },
413 { "export", "Set environment variable", builtin_export },
414 { "fg", "Bring job into the foreground", builtin_fg_bg },
415 { "jobs", "Lists the active jobs", builtin_jobs },
416 { "pwd", "Print current directory", builtin_pwd },
417 { "read", "Input environment variable", builtin_read },
418 { "return", "Return from a function", builtin_not_written },
419 { "set", "Set/unset shell local variables", builtin_set },
420 { "shift", "Shift positional parameters", builtin_shift },
421 { "trap", "Trap signals", builtin_not_written },
422 { "ulimit","Controls resource limits", builtin_not_written },
423 { "umask","Sets file creation mask", builtin_umask },
424 { "unset", "Unset environment variable", builtin_unset },
425 { ".", "Source-in and run commands in a file", builtin_source },
426 { "help", "List shell built-in commands", builtin_help },
430 /* Restores tty foreground process group, and exits.
431 * May be called as signal handler for fatal signal
432 * (will faithfully resend signal to itself, producing correct exit state)
433 * or called directly with -EXITCODE.
434 * We also call it if xfunc is exiting. */
435 static void sigexit(int sig) ATTRIBUTE_NORETURN;
436 static void sigexit(int sig)
440 /* Disable all signals: job control, SIGPIPE, etc. */
441 sigfillset(&block_all);
442 sigprocmask(SIG_SETMASK, &block_all, NULL);
445 tcsetpgrp(interactive_fd, saved_tty_pgrp);
447 /* Not a signal, just exit */
451 /* Enable only this sig and kill ourself with it */
452 signal(sig, SIG_DFL);
453 sigdelset(&block_all, sig);
454 sigprocmask(SIG_SETMASK, &block_all, NULL);
456 _exit(1); /* Should not reach it */
459 /* Restores tty foreground process group, and exits. */
460 static void hush_exit(int exitcode) ATTRIBUTE_NORETURN;
461 static void hush_exit(int exitcode)
463 fflush(NULL); /* flush all streams */
464 sigexit(- (exitcode & 0xff));
467 /* Signals are grouped, we handle them in batches */
468 static void set_fatal_sighandler(void (*handler)(int))
470 signal(SIGILL , handler);
471 signal(SIGTRAP, handler);
472 signal(SIGABRT, handler);
473 signal(SIGFPE , handler);
474 signal(SIGBUS , handler);
475 signal(SIGSEGV, handler);
476 /* bash 3.2 seems to handle these just like 'fatal' ones,
477 * but _without_ printing signal name. TODO: mimic this too? */
478 signal(SIGHUP , handler);
479 signal(SIGPIPE, handler);
480 signal(SIGALRM, handler);
482 static void set_jobctrl_sighandler(void (*handler)(int))
484 signal(SIGTSTP, handler);
485 signal(SIGTTIN, handler);
486 signal(SIGTTOU, handler);
488 static void set_misc_sighandler(void (*handler)(int))
490 signal(SIGINT , handler);
491 signal(SIGQUIT, handler);
492 signal(SIGTERM, handler);
494 /* SIGCHLD is special and handled separately */
496 static const char *set_cwd(void)
498 if (cwd == bb_msg_unknown)
499 cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
500 cwd = xrealloc_getcwd_or_warn((char *)cwd);
502 cwd = bb_msg_unknown;
506 // It seems ALL built-ins ever use *only* child->argv in child param.
507 // Passing argv directly may make 'child->argv += n' modifications
508 // unneeded on vfork codepaths.
510 /* built-in 'eval' handler */
511 static int builtin_eval(struct child_prog *child)
514 int rcode = EXIT_SUCCESS;
516 if (child->argv[1]) {
517 str = make_string(child->argv + 1);
518 parse_string_outer(str, FLAG_EXIT_FROM_LOOP |
519 FLAG_PARSE_SEMICOLON);
521 rcode = last_return_code;
526 /* built-in 'cd <path>' handler */
527 static int builtin_cd(struct child_prog *child)
530 if (child->argv[1] == NULL)
531 newdir = getenv("HOME");
533 newdir = child->argv[1];
535 printf("cd: %s: %s\n", newdir, strerror(errno));
542 /* built-in 'env' handler */
543 static int builtin_env(struct child_prog *dummy ATTRIBUTE_UNUSED)
545 /* TODO: call env applet's code instead */
555 /* built-in 'exec' handler */
556 static int builtin_exec(struct child_prog *child)
558 if (child->argv[1] == NULL)
559 return EXIT_SUCCESS; /* Really? */
565 /* built-in 'exit' handler */
566 static int builtin_exit(struct child_prog *child)
568 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
569 //puts("exit"); /* bash does it */
571 if (child->argv[1] == NULL)
572 hush_exit(last_return_code);
573 /* mimic bash: exit 123abc == exit 255 + error msg */
574 xfunc_error_retval = 255;
575 /* bash: exit -2 == exit 254, no error msg */
576 hush_exit(xatoi(child->argv[1]));
579 /* built-in 'export VAR=value' handler */
580 static int builtin_export(struct child_prog *child)
583 char *name = child->argv[1];
586 return builtin_env(child);
592 const char *value = strchr(name, '=');
596 /* They are exporting something without an =VALUE */
598 value = get_local_var(name);
600 size_t ln = strlen(name);
602 tmp = realloc(name, ln+strlen(value)+2);
606 sprintf(tmp+ln, "=%s", value);
610 /* bash does not return an error when trying to export
611 * an undefined variable. Do likewise. */
617 bb_perror_msg("export");
619 res = set_local_var(name, 1);
626 /* built-in 'fg' and 'bg' handler */
627 static int builtin_fg_bg(struct child_prog *child)
634 /* If they gave us no args, assume they want the last backgrounded task */
635 if (!child->argv[1]) {
636 for (pi = job_list; pi; pi = pi->next) {
637 if (pi->jobid == last_jobid) {
641 bb_error_msg("%s: no current job", child->argv[0]);
644 if (sscanf(child->argv[1], "%%%d", &jobnum) != 1) {
645 bb_error_msg("%s: bad argument '%s'", child->argv[0], child->argv[1]);
648 for (pi = job_list; pi; pi = pi->next) {
649 if (pi->jobid == jobnum) {
653 bb_error_msg("%s: %d: no such job", child->argv[0], jobnum);
656 // TODO: bash prints a string representation
657 // of job being foregrounded (like "sleep 1 | cat")
658 if (*child->argv[0] == 'f') {
659 /* Put the job into the foreground. */
660 tcsetpgrp(interactive_fd, pi->pgrp);
663 /* Restart the processes in the job */
664 for (i = 0; i < pi->num_progs; i++)
665 pi->progs[i].is_stopped = 0;
667 i = kill(- pi->pgrp, SIGCONT);
668 pi->stopped_progs = 0;
670 if (errno == ESRCH) {
673 bb_perror_msg("kill (SIGCONT)");
677 if (*child->argv[0] == 'f')
678 return checkjobs_and_fg_shell(pi);
682 /* built-in 'help' handler */
683 static int builtin_help(struct child_prog *dummy ATTRIBUTE_UNUSED)
685 const struct built_in_command *x;
687 printf("\nBuilt-in commands:\n");
688 printf("-------------------\n");
689 for (x = bltins; x->cmd; x++) {
690 if (x->descr == NULL)
692 printf("%s\t%s\n", x->cmd, x->descr);
698 /* built-in 'jobs' handler */
699 static int builtin_jobs(struct child_prog *child ATTRIBUTE_UNUSED)
702 const char *status_string;
704 for (job = job_list; job; job = job->next) {
705 if (job->running_progs == job->stopped_progs)
706 status_string = "Stopped";
708 status_string = "Running";
710 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->text);
715 /* built-in 'pwd' handler */
716 static int builtin_pwd(struct child_prog *dummy ATTRIBUTE_UNUSED)
722 /* built-in 'read VAR' handler */
723 static int builtin_read(struct child_prog *child)
727 if (child->argv[1]) {
731 string[0] = '\0'; /* In case stdin has only EOF */
733 fgets(string, sizeof(string), stdin);
735 var = malloc(strlen(child->argv[1]) + strlen(string) + 2);
737 sprintf(var, "%s=%s", child->argv[1], string);
738 res = set_local_var(var, 0);
742 bb_perror_msg("read");
743 free(var); /* So not move up to avoid breaking errno */
746 do res = getchar(); while (res != '\n' && res != EOF);
750 /* built-in 'set VAR=value' handler */
751 static int builtin_set(struct child_prog *child)
753 char *temp = child->argv[1];
757 for (e = top_vars; e; e = e->next)
758 printf("%s=%s\n", e->name, e->value);
760 set_local_var(temp, 0);
766 /* Built-in 'shift' handler */
767 static int builtin_shift(struct child_prog *child)
770 if (child->argv[1]) {
771 n = atoi(child->argv[1]);
773 if (n >= 0 && n < global_argc) {
774 /* XXX This probably breaks $0 */
782 /* Built-in '.' handler (read-in and execute commands from file) */
783 static int builtin_source(struct child_prog *child)
788 if (child->argv[1] == NULL)
791 /* XXX search through $PATH is missing */
792 input = fopen(child->argv[1], "r");
794 bb_error_msg("cannot open '%s'", child->argv[1]);
798 /* Now run the file */
799 /* XXX argv and argc are broken; need to save old global_argv
800 * (pointer only is OK!) on this stack frame,
801 * set global_argv=child->argv+1, recurse, and restore. */
802 mark_open(fileno(input));
803 status = parse_file_outer(input);
804 mark_closed(fileno(input));
809 static int builtin_umask(struct child_prog *child)
812 const char *arg = child->argv[1];
815 new_umask = strtoul(arg, &end, 8);
816 if (*end != '\0' || end == arg) {
820 new_umask = umask(0);
821 printf("%.3o\n", (unsigned) new_umask);
827 /* built-in 'unset VAR' handler */
828 static int builtin_unset(struct child_prog *child)
830 /* bash returned already true */
831 unset_local_var(child->argv[1]);
835 static int builtin_not_written(struct child_prog *child)
837 printf("builtin_%s not written\n", child->argv[0]);
841 static int b_check_space(o_string *o, int len)
843 /* It would be easy to drop a more restrictive policy
844 * in here, such as setting a maximum string length */
845 if (o->length + len > o->maxlen) {
846 char *old_data = o->data;
847 /* assert(data == NULL || o->maxlen != 0); */
848 o->maxlen += max(2*len, B_CHUNK);
849 o->data = realloc(o->data, 1 + o->maxlen);
850 if (o->data == NULL) {
854 return o->data == NULL;
857 static int b_addchr(o_string *o, int ch)
859 debug_printf("b_addchr: %c %d %p\n", ch, o->length, o);
860 if (b_check_space(o, 1))
862 o->data[o->length] = ch;
864 o->data[o->length] = '\0';
868 static void b_reset(o_string *o)
876 static void b_free(o_string *o)
884 /* My analysis of quoting semantics tells me that state information
885 * is associated with a destination, not a source.
887 static int b_addqchr(o_string *o, int ch, int quote)
889 if (quote && strchr("*?[\\", ch)) {
891 rc = b_addchr(o, '\\');
895 return b_addchr(o, ch);
898 static int b_adduint(o_string *o, unsigned i)
901 char buf[sizeof(unsigned)*3 + 1];
903 *(utoa_to_buf(i, buf, sizeof(buf))) = '\0';
904 /* no escape checking necessary */
905 do r = b_addchr(o, *p++); while (r == 0 && *p);
909 static int static_get(struct in_str *i)
912 if (ch == '\0') return EOF;
916 static int static_peek(struct in_str *i)
921 static void cmdedit_set_initial_prompt(void)
923 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
932 static const char* setup_prompt_string(int promptmode)
934 const char *prompt_str;
935 debug_printf("setup_prompt_string %d ", promptmode);
936 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
937 /* Set up the prompt */
938 if (promptmode == 1) {
941 ns = xmalloc(strlen(cwd)+4);
942 sprintf(ns, "%s %s", cwd, (geteuid() != 0) ? "$ " : "# ");
949 prompt_str = (promptmode == 1) ? PS1 : PS2;
951 debug_printf("result %s\n", prompt_str);
955 #if ENABLE_FEATURE_EDITING
956 static line_input_t *line_input_state;
959 static void get_user_input(struct in_str *i)
961 const char *prompt_str;
962 static char the_command[BUFSIZ];
964 prompt_str = setup_prompt_string(i->promptmode);
965 #if ENABLE_FEATURE_EDITING
967 ** enable command line editing only while a command line
968 ** is actually being read; otherwise, we'll end up bequeathing
969 ** atexit() handlers and other unwanted stuff to our
970 ** child processes (rob@sysgo.de)
972 read_line_input(prompt_str, the_command, BUFSIZ, line_input_state);
974 fputs(prompt_str, stdout);
976 the_command[0] = fgetc(i->file);
977 the_command[1] = '\0';
983 /* This is the magic location that prints prompts
984 * and gets data back from the user */
985 static int file_get(struct in_str *i)
990 /* If there is data waiting, eat it up */
994 /* need to double check i->file because we might be doing something
995 * more complicated by now, like sourcing or substituting. */
996 if (i->__promptme && interactive_fd && i->file == stdin) {
997 while (!i->p || !(interactive_fd && strlen(i->p))) {
1002 if (i->p && *i->p) {
1006 ch = fgetc(i->file);
1009 debug_printf("b_getch: got a %d\n", ch);
1016 /* All the callers guarantee this routine will never be
1017 * used right after a newline, so prompting is not needed.
1019 static int file_peek(struct in_str *i)
1021 if (i->p && *i->p) {
1024 i->peek_buf[0] = fgetc(i->file);
1025 i->peek_buf[1] = '\0';
1027 debug_printf("b_peek: got a %d\n", *i->p);
1031 static void setup_file_in_str(struct in_str *i, FILE *f)
1033 i->peek = file_peek;
1041 static void setup_string_in_str(struct in_str *i, const char *s)
1043 i->peek = static_peek;
1044 i->get = static_get;
1050 static void mark_open(int fd)
1052 struct close_me *new = xmalloc(sizeof(struct close_me));
1054 new->next = close_me_head;
1055 close_me_head = new;
1058 static void mark_closed(int fd)
1060 struct close_me *tmp;
1061 if (close_me_head == NULL || close_me_head->fd != fd)
1062 bb_error_msg_and_die("corrupt close_me");
1063 tmp = close_me_head;
1064 close_me_head = close_me_head->next;
1068 static void close_all(void)
1071 for (c = close_me_head; c; c = c->next) {
1074 close_me_head = NULL;
1077 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
1078 * and stderr if they are redirected. */
1079 static int setup_redirects(struct child_prog *prog, int squirrel[])
1082 struct redir_struct *redir;
1084 for (redir = prog->redirects; redir; redir = redir->next) {
1085 if (redir->dup == -1 && redir->word.gl_pathv == NULL) {
1086 /* something went wrong in the parse. Pretend it didn't happen */
1089 if (redir->dup == -1) {
1090 mode = redir_table[redir->type].mode;
1091 openfd = open_or_warn(redir->word.gl_pathv[0], mode);
1093 /* this could get lost if stderr has been redirected, but
1094 bash and ash both lose it as well (though zsh doesn't!) */
1098 openfd = redir->dup;
1101 if (openfd != redir->fd) {
1102 if (squirrel && redir->fd < 3) {
1103 squirrel[redir->fd] = dup(redir->fd);
1108 dup2(openfd, redir->fd);
1109 if (redir->dup == -1)
1117 static void restore_redirects(int squirrel[])
1120 for (i = 0; i < 3; i++) {
1123 /* No error checking. I sure wouldn't know what
1124 * to do with an error if I found one! */
1132 /* XXX no exit() here. If you don't exec, use _exit instead.
1133 * The at_exit handlers apparently confuse the calling process,
1134 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
1135 static void pseudo_exec(struct child_prog *child)
1139 const struct built_in_command *x;
1142 for (i = 0; is_assignment(child->argv[i]); i++) {
1143 debug_printf("pid %d environment modification: %s\n",
1144 getpid(), child->argv[i]);
1145 // FIXME: vfork case??
1146 p = insert_var_value(child->argv[i]);
1148 if (p != child->argv[i])
1151 child->argv += i; /* XXX this hack isn't so horrible, since we are about
1152 to exit, and therefore don't need to keep data
1153 structures consistent for free() use. */
1154 // FIXME: ...unless we have _vforked_! Think NOMMU!
1156 /* If a variable is assigned in a forest, and nobody listens,
1157 * was it ever really set?
1159 if (child->argv[0] == NULL) {
1160 _exit(EXIT_SUCCESS);
1164 * Check if the command matches any of the builtins.
1165 * Depending on context, this might be redundant. But it's
1166 * easier to waste a few CPU cycles than it is to figure out
1167 * if this is one of those cases.
1169 for (x = bltins; x->cmd; x++) {
1170 if (strcmp(child->argv[0], x->cmd) == 0) {
1171 debug_printf("builtin exec %s\n", child->argv[0]);
1172 rcode = x->function(child);
1178 /* Check if the command matches any busybox internal commands
1180 * FIXME: This feature is not 100% safe, since
1181 * BusyBox is not fully reentrant, so we have no guarantee the things
1182 * from the .bss are still zeroed, or that things from .data are still
1183 * at their defaults. We could exec ourself from /proc/self/exe, but I
1184 * really dislike relying on /proc for things. We could exec ourself
1185 * from global_argv[0], but if we are in a chroot, we may not be able
1186 * to find ourself... */
1187 #if ENABLE_FEATURE_SH_STANDALONE
1188 debug_printf("running applet %s\n", child->argv[0]);
1189 run_applet_and_exit(child->argv[0], child->argv);
1190 // is it ok that run_applet_and_exit() does exit(), not _exit()?
1191 // NB: IIRC on NOMMU we are after _vfork_, not fork!
1193 debug_printf("exec of %s\n", child->argv[0]);
1194 execvp(child->argv[0], child->argv);
1195 bb_perror_msg("cannot exec '%s'", child->argv[0]);
1200 debug_printf("runtime nesting to group\n");
1201 // FIXME: do not modify globals! Think vfork!
1202 interactive_fd = 0; /* crucial!!!! */
1203 rcode = run_list_real(child->group);
1204 /* OK to leak memory by not calling free_pipe_list,
1205 * since this process is about to exit */
1209 /* Can happen. See what bash does with ">foo" by itself. */
1210 debug_printf("trying to pseudo_exec null command\n");
1211 _exit(EXIT_SUCCESS);
1214 static void insert_bg_job(struct pipe *pi)
1216 struct pipe *thejob;
1218 /* Linear search for the ID of the job to use */
1220 for (thejob = job_list; thejob; thejob = thejob->next)
1221 if (thejob->jobid >= pi->jobid)
1222 pi->jobid = thejob->jobid + 1;
1224 /* add thejob to the list of running jobs */
1226 thejob = job_list = xmalloc(sizeof(*thejob));
1228 for (thejob = job_list; thejob->next; thejob = thejob->next)
1230 thejob->next = xmalloc(sizeof(*thejob));
1231 thejob = thejob->next;
1234 /* physically copy the struct job */
1235 memcpy(thejob, pi, sizeof(struct pipe));
1236 thejob->next = NULL;
1237 thejob->running_progs = thejob->num_progs;
1238 thejob->stopped_progs = 0;
1239 thejob->text = xmalloc(BUFSIZ); /* cmdedit buffer size */
1241 //if (pi->progs[0] && pi->progs[0].argv && pi->progs[0].argv[0])
1243 char *bar = thejob->text;
1244 char **foo = pi->progs[0].argv;
1247 bar += sprintf(bar, "%s ", *foo++);
1250 /* we don't wait for background thejobs to return -- append it
1251 to the list of backgrounded thejobs and leave it alone */
1252 printf("[%d] %d\n", thejob->jobid, thejob->progs[0].pid);
1253 last_bg_pid = thejob->progs[0].pid;
1254 last_jobid = thejob->jobid;
1257 /* remove a backgrounded job */
1258 static void remove_bg_job(struct pipe *pi)
1260 struct pipe *prev_pipe;
1262 if (pi == job_list) {
1263 job_list = pi->next;
1265 prev_pipe = job_list;
1266 while (prev_pipe->next != pi)
1267 prev_pipe = prev_pipe->next;
1268 prev_pipe->next = pi->next;
1271 last_jobid = job_list->jobid;
1275 pi->stopped_progs = 0;
1280 /* Checks to see if any processes have exited -- if they
1281 have, figure out why and see if a job has completed */
1282 static int checkjobs(struct pipe* fg_pipe)
1291 attributes = WUNTRACED;
1292 //WUNTRACED?? huh, what will happed on Ctrl-Z? fg waiting code
1293 //doesn't seem to be ready for stopped children! (only exiting ones)...
1294 if (fg_pipe == NULL) {
1295 attributes |= WNOHANG;
1299 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
1300 /* Were we asked to wait for fg pipe? */
1303 for (i = 0; i < fg_pipe->num_progs; i++) {
1304 if (fg_pipe->progs[i].pid == childpid) {
1305 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
1306 fg_pipe->progs[i].pid = 0;
1307 if (i == fg_pipe->num_progs-1)
1308 /* last process gives overall exitstatus */
1309 rcode = WEXITSTATUS(status);
1310 if (--fg_pipe->running_progs <= 0)
1311 /* All processes in fg pipe have exited */
1313 /* There are still running processes in the fg pipe */
1319 /* We asked to wait for bg or orphaned children */
1320 /* No need to remember exitcode in this case */
1322 for (pi = job_list; pi; pi = pi->next) {
1324 while (prognum < pi->num_progs) {
1325 if (pi->progs[prognum].pid == childpid)
1326 goto found_pi_and_prognum;
1331 /* Happens when shell is used as init process (init=/bin/sh) */
1332 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
1335 found_pi_and_prognum:
1336 if (WIFEXITED(status) || WIFSIGNALED(status)) {
1338 pi->running_progs--;
1339 pi->progs[prognum].pid = 0;
1341 if (!pi->running_progs) {
1342 printf(JOB_STATUS_FORMAT, pi->jobid,
1348 pi->stopped_progs++;
1349 pi->progs[prognum].is_stopped = 1;
1353 if (childpid == -1 && errno != ECHILD)
1354 bb_perror_msg("waitpid");
1356 /* move the shell to the foreground */
1357 //if (interactive_fd && tcsetpgrp(interactive_fd, getpgid(0)))
1358 // bb_perror_msg("tcsetpgrp-2");
1362 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1365 int rcode = checkjobs(fg_pipe);
1366 /* Job finished, move the shell to the foreground */
1368 debug_printf("fg'ing ourself: getpgid(0)=%d\n", (int)p);
1369 if (tcsetpgrp(interactive_fd, p) && errno != ENOTTY)
1370 bb_perror_msg("tcsetpgrp-4a");
1374 /* run_pipe_real() starts all the jobs, but doesn't wait for anything
1375 * to finish. See checkjobs().
1377 * return code is normally -1, when the caller has to wait for children
1378 * to finish to determine the exit status of the pipe. If the pipe
1379 * is a simple builtin command, however, the action is done by the
1380 * time run_pipe_real returns, and the exit code is provided as the
1383 * The input of the pipe is always stdin, the output is always
1384 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1385 * because it tries to avoid running the command substitution in
1386 * subshell, when that is in fact necessary. The subshell process
1387 * now has its stdout directed to the input of the appropriate pipe,
1388 * so this routine is noticeably simpler.
1390 static int run_pipe_real(struct pipe *pi)
1393 int nextin, nextout;
1394 int pipefds[2]; /* pipefds[0] is for reading */
1395 struct child_prog *child;
1396 const struct built_in_command *x;
1398 /* it is not always needed, but we aim to smaller code */
1399 int squirrel[] = { -1, -1, -1 };
1401 const int single_fg = (pi->num_progs == 1 && pi->followup != PIPE_BG);
1406 /* Check if this is a simple builtin (not part of a pipe).
1407 * Builtins within pipes have to fork anyway, and are handled in
1408 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1410 child = &(pi->progs[0]);
1411 if (single_fg && child->group && child->subshell == 0) {
1412 debug_printf("non-subshell grouping\n");
1413 setup_redirects(child, squirrel);
1414 /* XXX could we merge code with following builtin case,
1415 * by creating a pseudo builtin that calls run_list_real? */
1416 rcode = run_list_real(child->group);
1417 restore_redirects(squirrel);
1421 if (single_fg && pi->progs[0].argv != NULL) {
1422 for (i = 0; is_assignment(child->argv[i]); i++)
1424 if (i != 0 && child->argv[i] == NULL) {
1425 /* assignments, but no command: set the local environment */
1426 for (i = 0; child->argv[i] != NULL; i++) {
1427 /* Ok, this case is tricky. We have to decide if this is a
1428 * local variable, or an already exported variable. If it is
1429 * already exported, we have to export the new value. If it is
1430 * not exported, we need only set this as a local variable.
1431 * This junk is all to decide whether or not to export this
1435 name = xstrdup(child->argv[i]);
1436 debug_printf("Local environment set: %s\n", name);
1437 value = strchr(name, '=');
1440 if (get_local_var(name)) {
1444 p = insert_var_value(child->argv[i]);
1445 set_local_var(p, export_me);
1446 if (p != child->argv[i])
1449 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1451 for (i = 0; is_assignment(child->argv[i]); i++) {
1452 p = insert_var_value(child->argv[i]);
1454 if (p != child->argv[i]) {
1462 str = make_string(child->argv + i);
1463 parse_string_outer(str, FLAG_EXIT_FROM_LOOP | FLAG_REPARSING);
1465 return last_return_code;
1467 for (x = bltins; x->cmd; x++) {
1468 if (strcmp(child->argv[i], x->cmd) == 0) {
1469 if (x->function == builtin_exec && child->argv[i+1] == NULL) {
1470 debug_printf("magic exec\n");
1471 setup_redirects(child, NULL);
1472 return EXIT_SUCCESS;
1474 debug_printf("builtin inline %s\n", child->argv[0]);
1475 /* XXX setup_redirects acts on file descriptors, not FILEs.
1476 * This is perfect for work that comes after exec().
1477 * Is it really safe for inline use? Experimentally,
1478 * things seem to work with glibc. */
1479 setup_redirects(child, squirrel);
1480 child->argv += i; /* XXX horrible hack */
1481 rcode = x->function(child);
1482 child->argv -= i; /* XXX restore hack so free() can work right */
1483 restore_redirects(squirrel);
1487 #if ENABLE_FEATURE_SH_STANDALONE
1489 // FIXME: applet runs like part of shell - for example, it ignores
1490 // SIGINT! Try to Ctrl-C out of "rm -i"... doesn't work
1491 const struct bb_applet *a = find_applet_by_name(child->argv[i]);
1492 if (a && a->nofork) {
1493 setup_redirects(child, squirrel);
1494 rcode = run_nofork_applet(a, child->argv + i);
1495 restore_redirects(squirrel);
1502 /* Disable job control signals for shell (parent) and
1503 * for initial child code after fork */
1504 set_jobctrl_sighandler(SIG_IGN);
1506 pi->running_progs = 0;
1507 for (i = 0; i < pi->num_progs; i++) {
1508 child = &(pi->progs[i]);
1510 /* pipes are inserted between pairs of commands */
1511 if ((i + 1) < pi->num_progs) {
1512 if (pipe(pipefds) < 0)
1513 bb_perror_msg_and_die("pipe");
1514 nextout = pipefds[1];
1520 /* XXX test for failed fork()? */
1522 child->pid = fork();
1524 child->pid = vfork();
1526 if (!child->pid) { /* child */
1527 /* Every child adds itself to new process group
1528 * with pgid == pid of first child in pipe */
1529 if (interactive_fd) {
1530 if (pi->pgrp < 0) /* true for 1st process only */
1531 pi->pgrp = getpid();
1532 if (setpgid(0, pi->pgrp) == 0 && pi->followup != PIPE_BG) {
1533 /* We do it in *every* child, not just first,
1535 tcsetpgrp(interactive_fd, pi->pgrp);
1537 /* Don't do pgrp restore anymore on fatal signals */
1538 set_fatal_sighandler(SIG_DFL);
1550 if (pipefds[0] != -1) {
1551 close(pipefds[0]); /* opposite end of our output pipe */
1553 /* Like bash, explicit redirects override pipes,
1554 * and the pipe fd is available for dup'ing. */
1555 setup_redirects(child, NULL);
1557 /* Restore default handlers just prior to exec */
1558 set_jobctrl_sighandler(SIG_DFL);
1559 set_misc_sighandler(SIG_DFL);
1560 signal(SIGCHLD, SIG_DFL);
1564 pi->running_progs++;
1566 /* Second and next children need to know pid of first one */
1568 pi->pgrp = child->pid;
1570 /* Don't check for errors. The child may be dead already,
1571 * in which case setpgid returns error code EACCES. */
1572 //why we do it at all?? child does it itself
1573 //if (interactive_fd)
1574 // setpgid(child->pid, pi->pgrp);
1581 /* If there isn't another process, nextin is garbage
1582 but it doesn't matter */
1583 nextin = pipefds[0];
1588 static int run_list_real(struct pipe *pi)
1590 char *save_name = NULL;
1592 char **save_list = NULL;
1596 int rcode = 0, flag_skip = 1;
1597 int flag_restore = 0;
1598 int if_code = 0, next_if_code = 0; /* need double-buffer to handle elif */
1599 reserved_style rmode, skip_more_in_this_rmode = RES_XXXX;
1600 /* check syntax for "for" */
1601 for (rpipe = pi; rpipe; rpipe = rpipe->next) {
1602 if ((rpipe->r_mode == RES_IN || rpipe->r_mode == RES_FOR)
1603 && (rpipe->next == NULL)
1608 if ((rpipe->r_mode == RES_IN && rpipe->next->r_mode == RES_IN && rpipe->next->progs->argv != NULL)
1609 || (rpipe->r_mode == RES_FOR && rpipe->next->r_mode != RES_IN)
1615 for (; pi; pi = (flag_restore != 0) ? rpipe : pi->next) {
1616 if (pi->r_mode == RES_WHILE || pi->r_mode == RES_UNTIL
1617 || pi->r_mode == RES_FOR
1626 debug_printf("rmode=%d if_code=%d next_if_code=%d skip_more=%d\n",
1627 rmode, if_code, next_if_code, skip_more_in_this_rmode);
1628 if (rmode == skip_more_in_this_rmode && flag_skip) {
1629 if (pi->followup == PIPE_SEQ)
1634 skip_more_in_this_rmode = RES_XXXX;
1635 if (rmode == RES_THEN || rmode == RES_ELSE)
1636 if_code = next_if_code;
1637 if (rmode == RES_THEN && if_code)
1639 if (rmode == RES_ELSE && !if_code)
1641 if (rmode == RES_ELIF && !if_code)
1643 if (rmode == RES_FOR && pi->num_progs) {
1645 /* if no variable values after "in" we skip "for" */
1646 if (!pi->next->progs->argv)
1648 /* create list of variable values */
1649 list = make_list_in(pi->next->progs->argv,
1650 pi->progs->argv[0]);
1652 save_name = pi->progs->argv[0];
1653 pi->progs->argv[0] = NULL;
1657 free(pi->progs->argv[0]);
1661 pi->progs->argv[0] = save_name;
1662 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
1665 /* insert new value from list for variable */
1666 if (pi->progs->argv[0])
1667 free(pi->progs->argv[0]);
1668 pi->progs->argv[0] = *list++;
1669 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
1671 if (rmode == RES_IN)
1673 if (rmode == RES_DO) {
1677 if (rmode == RES_DONE) {
1684 if (pi->num_progs == 0)
1686 save_num_progs = pi->num_progs; /* save number of programs */
1687 rcode = run_pipe_real(pi);
1688 debug_printf("run_pipe_real returned %d\n", rcode);
1690 /* We only ran a builtin: rcode was set by the return value
1691 * of run_pipe_real(), and we don't need to wait for anything. */
1692 } else if (pi->followup == PIPE_BG) {
1693 /* XXX check bash's behavior with nontrivial pipes */
1694 /* XXX compute jobid */
1695 /* XXX what does bash do with attempts to background builtins? */
1697 rcode = EXIT_SUCCESS;
1699 if (interactive_fd) {
1700 rcode = checkjobs_and_fg_shell(pi);
1702 rcode = checkjobs(pi);
1704 debug_printf("checkjobs returned %d\n", rcode);
1706 last_return_code = rcode;
1707 pi->num_progs = save_num_progs; /* restore number of programs */
1708 if (rmode == RES_IF || rmode == RES_ELIF)
1709 next_if_code = rcode; /* can be overwritten a number of times */
1710 if (rmode == RES_WHILE)
1711 flag_rep = !last_return_code;
1712 if (rmode == RES_UNTIL)
1713 flag_rep = last_return_code;
1714 if ((rcode == EXIT_SUCCESS && pi->followup == PIPE_OR)
1715 || (rcode != EXIT_SUCCESS && pi->followup == PIPE_AND)
1717 skip_more_in_this_rmode = rmode;
1724 /* return code is the exit status of the pipe */
1725 static int free_pipe(struct pipe *pi, int indent)
1728 struct child_prog *child;
1729 struct redir_struct *r, *rnext;
1730 int a, i, ret_code = 0;
1732 if (pi->stopped_progs > 0)
1734 final_printf("%s run pipe: (pid %d)\n", indenter(indent), getpid());
1735 for (i = 0; i < pi->num_progs; i++) {
1736 child = &pi->progs[i];
1737 final_printf("%s command %d:\n", indenter(indent), i);
1739 for (a = 0, p = child->argv; *p; a++, p++) {
1740 final_printf("%s argv[%d] = %s\n", indenter(indent), a, *p);
1742 globfree(&child->glob_result);
1744 } else if (child->group) {
1745 final_printf("%s begin group (subshell:%d)\n", indenter(indent), child->subshell);
1746 ret_code = free_pipe_list(child->group, indent+3);
1747 final_printf("%s end group\n", indenter(indent));
1749 final_printf("%s (nil)\n", indenter(indent));
1751 for (r = child->redirects; r; r = rnext) {
1752 final_printf("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->type].descrip);
1754 /* guard against the case >$FOO, where foo is unset or blank */
1755 if (r->word.gl_pathv) {
1756 final_printf(" %s\n", *r->word.gl_pathv);
1760 final_printf("&%d\n", r->dup);
1765 child->redirects = NULL;
1767 free(pi->progs); /* children are an array, they get freed all at once */
1772 static int free_pipe_list(struct pipe *head, int indent)
1774 int rcode = 0; /* if list has no members */
1775 struct pipe *pi, *next;
1776 for (pi = head; pi; pi = next) {
1777 final_printf("%s pipe reserved mode %d\n", indenter(indent), pi->r_mode);
1778 rcode = free_pipe(pi, indent);
1779 final_printf("%s pipe followup code %d\n", indenter(indent), pi->followup);
1781 /*pi->next = NULL;*/
1787 /* Select which version we will use */
1788 static int run_list(struct pipe *pi)
1791 if (fake_mode == 0) {
1792 rcode = run_list_real(pi);
1794 /* free_pipe_list has the side effect of clearing memory
1795 * In the long run that function can be merged with run_list_real,
1796 * but doing that now would hobble the debugging effort. */
1797 free_pipe_list(pi,0);
1801 /* The API for glob is arguably broken. This routine pushes a non-matching
1802 * string into the output structure, removing non-backslashed backslashes.
1803 * If someone can prove me wrong, by performing this function within the
1804 * original glob(3) api, feel free to rewrite this routine into oblivion.
1805 * Return code (0 vs. GLOB_NOSPACE) matches glob(3).
1806 * XXX broken if the last character is '\\', check that before calling.
1808 static int globhack(const char *src, int flags, glob_t *pglob)
1813 for (cnt = 1, s = src; s && *s; s++) {
1814 if (*s == '\\') s++;
1819 return GLOB_NOSPACE;
1820 if (!(flags & GLOB_APPEND)) {
1821 pglob->gl_pathv = NULL;
1822 pglob->gl_pathc = 0;
1826 pathc = ++pglob->gl_pathc;
1827 pglob->gl_pathv = realloc(pglob->gl_pathv, (pathc+1)*sizeof(*pglob->gl_pathv));
1828 if (pglob->gl_pathv == NULL)
1829 return GLOB_NOSPACE;
1830 pglob->gl_pathv[pathc-1] = dest;
1831 pglob->gl_pathv[pathc] = NULL;
1832 for (s = src; s && *s; s++, dest++) {
1833 if (*s == '\\') s++;
1840 /* XXX broken if the last character is '\\', check that before calling */
1841 static int glob_needed(const char *s)
1844 if (*s == '\\') s++;
1845 if (strchr("*[?", *s)) return 1;
1850 static int xglob(o_string *dest, int flags, glob_t *pglob)
1854 /* short-circuit for null word */
1855 /* we can code this better when the debug_printf's are gone */
1856 if (dest->length == 0) {
1857 if (dest->nonnull) {
1858 /* bash man page calls this an "explicit" null */
1859 gr = globhack(dest->data, flags, pglob);
1860 debug_printf("globhack returned %d\n", gr);
1864 } else if (glob_needed(dest->data)) {
1865 gr = glob(dest->data, flags, NULL, pglob);
1866 debug_printf("glob returned %d\n", gr);
1867 if (gr == GLOB_NOMATCH) {
1868 /* quote removal, or more accurately, backslash removal */
1869 gr = globhack(dest->data, flags, pglob);
1870 debug_printf("globhack returned %d\n", gr);
1873 gr = globhack(dest->data, flags, pglob);
1874 debug_printf("globhack returned %d\n", gr);
1876 if (gr == GLOB_NOSPACE)
1877 bb_error_msg_and_die("out of memory during glob");
1878 if (gr != 0) { /* GLOB_ABORTED ? */
1879 bb_error_msg("glob(3) error %d", gr);
1881 /* globprint(glob_target); */
1885 static char **make_list_in(char **inp, char *name)
1888 int name_len = strlen(name);
1893 /* create list of variable values */
1894 list = xmalloc(sizeof(*list));
1895 for (i = 0; inp[i]; i++) {
1896 p3 = insert_var_value(inp[i]);
1903 p2 = strchr(p1, ' ');
1910 /* we use n + 2 in realloc for list, because we add
1911 * new element and then we will add NULL element */
1912 list = xrealloc(list, sizeof(*list) * (n + 2));
1913 list[n] = xmalloc(2 + name_len + len);
1914 strcpy(list[n], name);
1915 strcat(list[n], "=");
1916 strncat(list[n], p1, len);
1917 list[n++][name_len + len + 1] = '\0';
1920 if (p3 != inp[i]) free(p3);
1926 static char *insert_var_value(char *inp)
1928 int res_str_len = 0;
1931 char *p, *res_str = NULL;
1934 while ((p = strchr(inp, SPECIAL_VAR_SYMBOL))) {
1937 res_str = xrealloc(res_str, (res_str_len + len));
1938 strncpy((res_str + res_str_len), inp, len);
1942 p = strchr(inp, SPECIAL_VAR_SYMBOL);
1944 p1 = lookup_param(inp);
1946 len = res_str_len + strlen(p1);
1947 res_str = xrealloc(res_str, (1 + len));
1948 strcpy((res_str + res_str_len), p1);
1951 *p = SPECIAL_VAR_SYMBOL;
1956 res_str = xrealloc(res_str, (1 + res_str_len + strlen(inp)));
1957 strcpy((res_str + res_str_len), inp);
1958 while ((p = strchr(res_str, '\n'))) {
1962 return (res_str == NULL) ? inp : res_str;
1965 /* This is used to get/check local shell variables */
1966 static const char *get_local_var(const char *s)
1968 struct variables *cur;
1972 for (cur = top_vars; cur; cur = cur->next)
1973 if (strcmp(cur->name, s) == 0)
1978 /* This is used to set local shell variables
1979 flg_export == 0 if only local (not exporting) variable
1980 flg_export == 1 if "new" exporting environ
1981 flg_export > 1 if current startup environ (not call putenv()) */
1982 static int set_local_var(const char *s, int flg_export)
1986 struct variables *cur;
1990 /* Assume when we enter this function that we are already in
1991 * NAME=VALUE format. So the first order of business is to
1992 * split 's' on the '=' into 'name' and 'value' */
1993 value = strchr(name, '=');
1994 /*if (value == 0 && ++value == 0) ??? -vda */
1995 if (value == NULL || value[1] == '\0') {
2001 for (cur = top_vars; cur; cur = cur->next) {
2002 if (strcmp(cur->name, name) == 0)
2007 if (strcmp(cur->value, value) == 0) {
2008 if (flg_export > 0 && cur->flg_export == 0)
2009 cur->flg_export = flg_export;
2012 } else if (cur->flg_read_only) {
2013 bb_error_msg("%s: readonly variable", name);
2016 if (flg_export > 0 || cur->flg_export > 1)
2017 cur->flg_export = 1;
2018 free((char*)cur->value);
2020 cur->value = strdup(value);
2023 cur = malloc(sizeof(struct variables));
2027 cur->name = strdup(name);
2032 struct variables *bottom = top_vars;
2033 cur->value = strdup(value);
2035 cur->flg_export = flg_export;
2036 cur->flg_read_only = 0;
2037 while (bottom->next)
2038 bottom = bottom->next;
2044 if (result == 0 && cur->flg_export == 1) {
2046 result = putenv(name);
2049 if (result > 0) /* equivalent to previous set */
2055 static void unset_local_var(const char *name)
2057 struct variables *cur, *next;
2061 for (cur = top_vars; cur; cur = cur->next) {
2062 if (strcmp(cur->name, name) == 0) {
2063 if (cur->flg_read_only) {
2064 bb_error_msg("%s: readonly variable", name);
2067 if (cur->flg_export)
2068 unsetenv(cur->name);
2069 free((char*)cur->name);
2070 free((char*)cur->value);
2072 while (next->next != cur)
2074 next->next = cur->next;
2081 static int is_assignment(const char *s)
2083 if (!s || !isalpha(*s))
2086 while (isalnum(*s) || *s == '_')
2091 /* the src parameter allows us to peek forward to a possible &n syntax
2092 * for file descriptor duplication, e.g., "2>&1".
2093 * Return code is 0 normally, 1 if a syntax error is detected in src.
2094 * Resource errors (in xmalloc) cause the process to exit */
2095 static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2096 struct in_str *input)
2098 struct child_prog *child = ctx->child;
2099 struct redir_struct *redir = child->redirects;
2100 struct redir_struct *last_redir = NULL;
2102 /* Create a new redir_struct and drop it onto the end of the linked list */
2105 redir = redir->next;
2107 redir = xmalloc(sizeof(struct redir_struct));
2109 redir->word.gl_pathv = NULL;
2111 last_redir->next = redir;
2113 child->redirects = redir;
2116 redir->type = style;
2117 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
2119 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2121 /* Check for a '2>&1' type redirect */
2122 redir->dup = redirect_dup_num(input);
2123 if (redir->dup == -2) return 1; /* syntax error */
2124 if (redir->dup != -1) {
2125 /* Erik had a check here that the file descriptor in question
2126 * is legit; I postpone that to "run time"
2127 * A "-" representation of "close me" shows up as a -3 here */
2128 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2130 /* We do _not_ try to open the file that src points to,
2131 * since we need to return and let src be expanded first.
2132 * Set ctx->pending_redirect, so we know what to do at the
2133 * end of the next parsed word.
2135 ctx->pending_redirect = redir;
2140 static struct pipe *new_pipe(void)
2143 pi = xmalloc(sizeof(struct pipe));
2147 pi->followup = 0; /* invalid */
2148 pi->r_mode = RES_NONE;
2152 static void initialize_context(struct p_context *ctx)
2155 ctx->pending_redirect = NULL;
2157 ctx->list_head = new_pipe();
2158 ctx->pipe = ctx->list_head;
2162 done_command(ctx); /* creates the memory for working child */
2165 /* normal return is 0
2166 * if a reserved word is found, and processed, return 1
2167 * should handle if, then, elif, else, fi, for, while, until, do, done.
2168 * case, function, and select are obnoxious, save those for later.
2170 static int reserved_word(o_string *dest, struct p_context *ctx)
2172 struct reserved_combo {
2177 /* Mostly a list of accepted follow-up reserved words.
2178 * FLAG_END means we are done with the sequence, and are ready
2179 * to turn the compound list into a command.
2180 * FLAG_START means the word must start a new compound list.
2182 static const struct reserved_combo reserved_list[] = {
2183 { "if", RES_IF, FLAG_THEN | FLAG_START },
2184 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2185 { "elif", RES_ELIF, FLAG_THEN },
2186 { "else", RES_ELSE, FLAG_FI },
2187 { "fi", RES_FI, FLAG_END },
2188 { "for", RES_FOR, FLAG_IN | FLAG_START },
2189 { "while", RES_WHILE, FLAG_DO | FLAG_START },
2190 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
2191 { "in", RES_IN, FLAG_DO },
2192 { "do", RES_DO, FLAG_DONE },
2193 { "done", RES_DONE, FLAG_END }
2195 enum { NRES = sizeof(reserved_list)/sizeof(reserved_list[0]) };
2196 const struct reserved_combo *r;
2198 for (r = reserved_list; r < reserved_list+NRES; r++) {
2199 if (strcmp(dest->data, r->literal) == 0) {
2200 debug_printf("found reserved word %s, code %d\n", r->literal, r->code);
2201 if (r->flag & FLAG_START) {
2202 struct p_context *new = xmalloc(sizeof(struct p_context));
2203 debug_printf("push stack\n");
2204 if (ctx->w == RES_IN || ctx->w == RES_FOR) {
2211 *new = *ctx; /* physical copy */
2212 initialize_context(ctx);
2214 } else if (ctx->w == RES_NONE || !(ctx->old_flag & (1 << r->code))) {
2221 ctx->old_flag = r->flag;
2222 if (ctx->old_flag & FLAG_END) {
2223 struct p_context *old;
2224 debug_printf("pop stack\n");
2225 done_pipe(ctx, PIPE_SEQ);
2227 old->child->group = ctx->list_head;
2228 old->child->subshell = 0;
2229 *ctx = *old; /* physical copy */
2239 /* normal return is 0.
2240 * Syntax or xglob errors return 1. */
2241 static int done_word(o_string *dest, struct p_context *ctx)
2243 struct child_prog *child = ctx->child;
2244 glob_t *glob_target;
2247 debug_printf("done_word: %s %p\n", dest->data, child);
2248 if (dest->length == 0 && !dest->nonnull) {
2249 debug_printf(" true null, ignored\n");
2252 if (ctx->pending_redirect) {
2253 glob_target = &ctx->pending_redirect->word;
2257 return 1; /* syntax error, groups and arglists don't mix */
2259 if (!child->argv && (ctx->type & FLAG_PARSE_SEMICOLON)) {
2260 debug_printf("checking %s for reserved-ness\n", dest->data);
2261 if (reserved_word(dest, ctx))
2262 return (ctx->w == RES_SNTX);
2264 glob_target = &child->glob_result;
2265 if (child->argv) flags |= GLOB_APPEND;
2267 gr = xglob(dest, flags, glob_target);
2268 if (gr != 0) return 1;
2271 if (ctx->pending_redirect) {
2272 ctx->pending_redirect = NULL;
2273 if (glob_target->gl_pathc != 1) {
2274 bb_error_msg("ambiguous redirect");
2278 child->argv = glob_target->gl_pathv;
2280 if (ctx->w == RES_FOR) {
2281 done_word(dest, ctx);
2282 done_pipe(ctx, PIPE_SEQ);
2287 /* The only possible error here is out of memory, in which case
2289 static int done_command(struct p_context *ctx)
2291 /* The child is really already in the pipe structure, so
2292 * advance the pipe counter and make a new, null child.
2293 * Only real trickiness here is that the uncommitted
2294 * child structure, to which ctx->child points, is not
2295 * counted in pi->num_progs. */
2296 struct pipe *pi = ctx->pipe;
2297 struct child_prog *prog = ctx->child;
2299 if (prog && prog->group == NULL
2300 && prog->argv == NULL
2301 && prog->redirects == NULL
2303 debug_printf("done_command: skipping null command\n");
2308 debug_printf("done_command: num_progs incremented to %d\n", pi->num_progs);
2310 debug_printf("done_command: initializing\n");
2312 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
2314 prog = pi->progs + pi->num_progs;
2315 prog->redirects = NULL;
2317 prog->is_stopped = 0;
2319 prog->glob_result.gl_pathv = NULL;
2323 prog->type = ctx->type;
2325 /* but ctx->pipe and ctx->list_head remain unchanged */
2329 static int done_pipe(struct p_context *ctx, pipe_style type)
2332 done_command(ctx); /* implicit closure of previous command */
2333 debug_printf("done_pipe, type %d\n", type);
2334 ctx->pipe->followup = type;
2335 ctx->pipe->r_mode = ctx->w;
2337 ctx->pipe->next = new_p;
2340 done_command(ctx); /* set up new pipe to accept commands */
2344 /* peek ahead in the in_str to find out if we have a "&n" construct,
2345 * as in "2>&1", that represents duplicating a file descriptor.
2346 * returns either -2 (syntax error), -1 (no &), or the number found.
2348 static int redirect_dup_num(struct in_str *input)
2350 int ch, d = 0, ok = 0;
2352 if (ch != '&') return -1;
2354 b_getch(input); /* get the & */
2358 return -3; /* "-" represents "close me" */
2360 while (isdigit(ch)) {
2361 d = d*10 + (ch-'0');
2368 bb_error_msg("ambiguous redirect");
2372 /* If a redirect is immediately preceded by a number, that number is
2373 * supposed to tell which file descriptor to redirect. This routine
2374 * looks for such preceding numbers. In an ideal world this routine
2375 * needs to handle all the following classes of redirects...
2376 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
2377 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
2378 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
2379 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
2380 * A -1 output from this program means no valid number was found, so the
2381 * caller should use the appropriate default for this redirection.
2383 static int redirect_opt_num(o_string *o)
2389 for (num = 0; num < o->length; num++) {
2390 if (!isdigit(*(o->data + num))) {
2394 /* reuse num (and save an int) */
2395 num = atoi(o->data);
2400 static FILE *generate_stream_from_list(struct pipe *head)
2403 int pid, channel[2];
2404 if (pipe(channel) < 0) bb_perror_msg_and_die("pipe");
2411 bb_perror_msg_and_die("fork");
2412 } else if (pid == 0) {
2414 if (channel[1] != 1) {
2415 dup2(channel[1], 1);
2418 _exit(run_list_real(head)); /* leaks memory */
2420 debug_printf("forked child %d\n", pid);
2422 pf = fdopen(channel[0], "r");
2423 debug_printf("pipe on FILE *%p\n", pf);
2427 /* this version hacked for testing purposes */
2428 /* return code is exit status of the process that is run. */
2429 static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end)
2432 o_string result = NULL_O_STRING;
2433 struct p_context inner;
2435 struct in_str pipe_str;
2436 initialize_context(&inner);
2438 /* recursion to generate command */
2439 retcode = parse_stream(&result, &inner, input, subst_end);
2440 if (retcode != 0) return retcode; /* syntax error or EOF */
2441 done_word(&result, &inner);
2442 done_pipe(&inner, PIPE_SEQ);
2445 p = generate_stream_from_list(inner.list_head);
2446 if (p == NULL) return 1;
2447 mark_open(fileno(p));
2448 setup_file_in_str(&pipe_str, p);
2450 /* now send results of command back into original context */
2451 retcode = parse_stream(dest, ctx, &pipe_str, '\0');
2452 /* XXX In case of a syntax error, should we try to kill the child?
2453 * That would be tough to do right, so just read until EOF. */
2455 while (b_getch(&pipe_str) != EOF)
2459 debug_printf("done reading from pipe, pclose()ing\n");
2460 /* This is the step that wait()s for the child. Should be pretty
2461 * safe, since we just read an EOF from its stdout. We could try
2462 * to better, by using wait(), and keeping track of background jobs
2463 * at the same time. That would be a lot of work, and contrary
2464 * to the KISS philosophy of this program. */
2465 mark_closed(fileno(p));
2466 retcode = pclose(p);
2467 free_pipe_list(inner.list_head, 0);
2468 debug_printf("pclosed, retcode=%d\n", retcode);
2469 /* XXX this process fails to trim a single trailing newline */
2473 static int parse_group(o_string *dest, struct p_context *ctx,
2474 struct in_str *input, int ch)
2476 int rcode, endch = 0;
2477 struct p_context sub;
2478 struct child_prog *child = ctx->child;
2481 return 1; /* syntax error, groups and arglists don't mix */
2483 initialize_context(&sub);
2487 child->subshell = 1;
2493 syntax(); /* really logic error */
2495 rcode = parse_stream(dest, &sub, input, endch);
2496 done_word(dest, &sub); /* finish off the final word in the subcontext */
2497 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
2498 child->group = sub.list_head;
2500 /* child remains "open", available for possible redirects */
2503 /* basically useful version until someone wants to get fancier,
2504 * see the bash man page under "Parameter Expansion" */
2505 static const char *lookup_param(const char *src)
2507 const char *p = NULL;
2511 p = get_local_var(src);
2516 /* Make new string for parser */
2517 static char* make_string(char ** inp)
2524 for (n = 0; inp[n]; n++) {
2525 p = insert_var_value(inp[n]);
2526 str = xrealloc(str, (len + strlen(p)));
2533 len = strlen(str) + 3;
2534 if (p != inp[n]) free(p);
2542 /* return code: 0 for OK, 1 for syntax error */
2543 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
2547 int ch = input->peek(input); /* first character after the $ */
2548 debug_printf("handle_dollar: ch=%c\n", ch);
2550 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2552 while (ch = b_peek(input), isalnum(ch) || ch == '_') {
2556 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2557 } else if (isdigit(ch)) {
2558 i = ch - '0'; /* XXX is $0 special? */
2559 if (i < global_argc) {
2560 parse_string(dest, ctx, global_argv[i]); /* recursion */
2563 } else switch (ch) {
2565 b_adduint(dest, getpid());
2569 if (last_bg_pid > 0) b_adduint(dest, last_bg_pid);
2573 b_adduint(dest, last_return_code);
2577 b_adduint(dest, global_argc ? global_argc-1 : 0);
2581 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2584 /* XXX maybe someone will try to escape the '}' */
2586 ch = b_getch(input);
2587 if (ch == EOF || ch == '}')
2595 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2599 process_command_subs(dest, ctx, input, ')');
2603 for (i = 1; i < global_argc; i++) {
2604 parse_string(dest, ctx, global_argv[i]);
2605 if (i+1 < global_argc)
2606 parse_string(dest, ctx, sep);
2612 /* still unhandled, but should be eventually */
2613 bb_error_msg("unhandled syntax: $%c", ch);
2617 b_addqchr(dest,'$', dest->quote);
2619 /* Eat the character if the flag was set. If the compiler
2620 * is smart enough, we could substitute "b_getch(input);"
2621 * for all the "advance = 1;" above, and also end up with
2622 * a nice size-optimized program. Hah! That'll be the day.
2624 if (advance) b_getch(input);
2628 static int parse_string(o_string *dest, struct p_context *ctx, const char *src)
2631 setup_string_in_str(&foo, src);
2632 return parse_stream(dest, ctx, &foo, '\0');
2635 /* return code is 0 for normal exit, 1 for syntax error */
2636 static int parse_stream(o_string *dest, struct p_context *ctx,
2637 struct in_str *input, int end_trigger)
2641 redir_type redir_style;
2644 /* Only double-quote state is handled in the state variable dest->quote.
2645 * A single-quote triggers a bypass of the main loop until its mate is
2646 * found. When recursing, quote state is passed in via dest->quote. */
2648 debug_printf("parse_stream, end_trigger=%d\n", end_trigger);
2649 while ((ch = b_getch(input)) != EOF) {
2651 next = (ch == '\n') ? 0 : b_peek(input);
2652 debug_printf("parse_stream: ch=%c (%d) m=%d quote=%d\n",
2653 ch, ch, m, dest->quote);
2654 if (m == 0 || ((m == 1 || m == 2) && dest->quote)) {
2655 b_addqchr(dest, ch, dest->quote);
2658 if (m == 2) { /* unquoted IFS */
2659 if (done_word(dest, ctx)) {
2662 /* If we aren't performing a substitution, treat a newline as a
2663 * command separator. */
2664 if (end_trigger != '\0' && ch == '\n')
2665 done_pipe(ctx, PIPE_SEQ);
2667 if (ch == end_trigger && !dest->quote && ctx->w == RES_NONE) {
2668 debug_printf("leaving parse_stream (triggered)\n");
2675 if (dest->length == 0 && !dest->quote) {
2678 if (ch == EOF || ch == '\n')
2683 b_addqchr(dest, ch, dest->quote);
2691 b_addqchr(dest, '\\', dest->quote);
2692 b_addqchr(dest, b_getch(input), dest->quote);
2695 if (handle_dollar(dest, ctx, input) != 0) return 1;
2700 ch = b_getch(input);
2701 if (ch == EOF || ch == '\'')
2712 dest->quote = !dest->quote;
2715 process_command_subs(dest, ctx, input, '`');
2718 redir_fd = redirect_opt_num(dest);
2719 done_word(dest, ctx);
2720 redir_style = REDIRECT_OVERWRITE;
2722 redir_style = REDIRECT_APPEND;
2724 } else if (next == '(') {
2725 syntax(); /* until we support >(list) Process Substitution */
2728 setup_redirect(ctx, redir_fd, redir_style, input);
2731 redir_fd = redirect_opt_num(dest);
2732 done_word(dest, ctx);
2733 redir_style = REDIRECT_INPUT;
2735 redir_style = REDIRECT_HEREIS;
2737 } else if (next == '>') {
2738 redir_style = REDIRECT_IO;
2740 } else if (next == '(') {
2741 syntax(); /* until we support <(list) Process Substitution */
2744 setup_redirect(ctx, redir_fd, redir_style, input);
2747 done_word(dest, ctx);
2748 done_pipe(ctx, PIPE_SEQ);
2751 done_word(dest, ctx);
2754 done_pipe(ctx, PIPE_AND);
2756 done_pipe(ctx, PIPE_BG);
2760 done_word(dest, ctx);
2763 done_pipe(ctx, PIPE_OR);
2765 /* we could pick up a file descriptor choice here
2766 * with redirect_opt_num(), but bash doesn't do it.
2767 * "echo foo 2| cat" yields "foo 2". */
2773 if (parse_group(dest, ctx, input, ch) != 0)
2778 syntax(); /* Proper use of this character caught by end_trigger */
2781 syntax(); /* this is really an internal logic error */
2785 /* complain if quote? No, maybe we just finished a command substitution
2786 * that was quoted. Example:
2787 * $ echo "`cat foo` plus more"
2788 * and we just got the EOF generated by the subshell that ran "cat foo"
2789 * The only real complaint is if we got an EOF when end_trigger != '\0',
2790 * that is, we were really supposed to get end_trigger, and never got
2791 * one before the EOF. Can't use the standard "syntax error" return code,
2792 * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
2793 debug_printf("leaving parse_stream (EOF)\n");
2794 if (end_trigger != '\0')
2799 static void mapset(const char *set, int code)
2802 map[(unsigned char)*set++] = code;
2805 static void update_ifs_map(void)
2807 /* char *ifs and char map[256] are both globals. */
2808 ifs = getenv("IFS");
2809 if (ifs == NULL) ifs = " \t\n";
2810 /* Precompute a list of 'flow through' behavior so it can be treated
2811 * quickly up front. Computation is necessary because of IFS.
2812 * Special case handling of IFS == " \t\n" is not implemented.
2813 * The map[] array only really needs two bits each, and on most machines
2814 * that would be faster because of the reduced L1 cache footprint.
2816 memset(map, 0, sizeof(map)); /* most characters flow through always */
2817 mapset("\\$'\"`", 3); /* never flow through */
2818 mapset("<>;&|(){}#", 1); /* flow through if quoted */
2819 mapset(ifs, 2); /* also flow through if quoted */
2822 /* most recursion does not come through here, the exception is
2823 * from builtin_source() */
2824 static int parse_stream_outer(struct in_str *inp, int flag)
2826 struct p_context ctx;
2827 o_string temp = NULL_O_STRING;
2831 initialize_context(&ctx);
2833 if (!(flag & FLAG_PARSE_SEMICOLON) || (flag & FLAG_REPARSING))
2835 inp->promptmode = 1;
2836 rcode = parse_stream(&temp, &ctx, inp, '\n');
2837 if (rcode != 1 && ctx.old_flag != 0) {
2840 if (rcode != 1 && ctx.old_flag == 0) {
2841 done_word(&temp, &ctx);
2842 done_pipe(&ctx, PIPE_SEQ);
2843 run_list(ctx.list_head);
2845 if (ctx.old_flag != 0) {
2852 free_pipe_list(ctx.list_head, 0);
2855 } while (rcode != -1 && !(flag & FLAG_EXIT_FROM_LOOP)); /* loop on syntax errors, return on EOF */
2859 static int parse_string_outer(const char *s, int flag)
2861 struct in_str input;
2862 setup_string_in_str(&input, s);
2863 return parse_stream_outer(&input, flag);
2866 static int parse_file_outer(FILE *f)
2869 struct in_str input;
2870 setup_file_in_str(&input, f);
2871 rcode = parse_stream_outer(&input, FLAG_PARSE_SEMICOLON);
2875 /* Make sure we have a controlling tty. If we get started under a job
2876 * aware app (like bash for example), make sure we are now in charge so
2877 * we don't fight over who gets the foreground */
2878 static void setup_job_control(void)
2882 saved_task_pgrp = getpgrp();
2883 debug_printf("saved_task_pgrp=%d\n", saved_task_pgrp);
2884 fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
2886 /* Loop until we are in the foreground. */
2888 shell_pgrp = getpgrp();
2889 if (tcgetpgrp(interactive_fd) == shell_pgrp)
2891 // and this does... what? need a comment here
2892 kill(- shell_pgrp, SIGTTIN);
2895 /* Ignore job-control and misc signals. */
2896 set_jobctrl_sighandler(SIG_IGN);
2897 set_misc_sighandler(SIG_IGN);
2898 //huh? signal(SIGCHLD, SIG_IGN);
2900 /* We _must_ do cleanup on fatal signals */
2901 set_fatal_sighandler(sigexit);
2903 /* Put ourselves in our own process group. */
2904 shell_pgrp = getpid();
2905 setpgrp(); /* is the same as setpgid(shell_pgrp, shell_pgrp); */
2907 /* Grab control of the terminal. */
2908 tcsetpgrp(interactive_fd, shell_pgrp);
2911 int hush_main(int argc, char **argv);
2912 int hush_main(int argc, char **argv)
2918 #if ENABLE_FEATURE_EDITING
2919 line_input_state = new_line_input_t(FOR_SHELL);
2922 /* XXX what should these be while sourcing /etc/profile? */
2926 /* (re?) initialize globals. Sometimes hush_main() ends up calling
2927 * hush_main(), therefore we cannot rely on the BSS to zero out this
2928 * stuff. Reset these to 0 every time. */
2930 /* map[] is taken care of with call to update_ifs_map() */
2933 close_me_head = NULL;
2938 /* Initialize some more globals to non-zero values */
2940 if (ENABLE_FEATURE_EDITING)
2941 cmdedit_set_initial_prompt();
2945 /* initialize our shell local variables with the values
2946 * currently living in the environment */
2950 set_local_var(*e++, 2); /* without call putenv() */
2952 last_return_code = EXIT_SUCCESS;
2954 if (argv[0] && argv[0][0] == '-') {
2955 debug_printf("\nsourcing /etc/profile\n");
2956 input = fopen("/etc/profile", "r");
2957 if (input != NULL) {
2958 mark_open(fileno(input));
2959 parse_file_outer(input);
2960 mark_closed(fileno(input));
2966 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
2969 global_argv = argv + optind;
2970 global_argc = argc - optind;
2971 opt = parse_string_outer(optarg, FLAG_PARSE_SEMICOLON);
2974 // Well, we cannot just declare interactiveness,
2975 // we have to have some stuff (ctty, etc)
2976 /*interactive_fd++;*/
2983 fprintf(stderr, "Usage: sh [FILE]...\n"
2984 " or: sh -c command [args]...\n\n");
2991 /* A shell is interactive if the '-i' flag was given, or if all of
2992 * the following conditions are met:
2994 * no arguments remaining or the -s flag given
2995 * standard input is a terminal
2996 * standard output is a terminal
2997 * Refer to Posix.2, the description of the 'sh' utility. */
2998 if (argv[optind] == NULL && input == stdin
2999 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3001 saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
3002 debug_printf("saved_tty_pgrp=%d\n", saved_tty_pgrp);
3003 if (saved_tty_pgrp >= 0) {
3004 /* try to dup to high fd#, >= 255 */
3005 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3006 if (interactive_fd < 0) {
3007 /* try to dup to any fd */
3008 interactive_fd = dup(STDIN_FILENO);
3009 if (interactive_fd < 0)
3013 // TODO: track & disallow any attempts of user
3014 // to (inadvertently) close/redirect it
3018 debug_printf("\ninteractive_fd=%d\n", interactive_fd);
3019 if (interactive_fd) {
3020 /* Looks like they want an interactive shell */
3021 setup_job_control();
3022 /* Make xfuncs do cleanup on exit */
3023 die_sleep = -1; /* flag */
3024 if (setjmp(die_jmp)) {
3025 /* xfunc has failed! die die die */
3026 hush_exit(xfunc_error_retval);
3028 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
3029 printf("\n\n%s hush - the humble shell v0.02\n", BB_BANNER);
3030 printf("Enter 'help' for a list of built-in commands.\n\n");
3034 if (argv[optind] == NULL) {
3035 opt = parse_file_outer(stdin);
3039 debug_printf("\nrunning script '%s'\n", argv[optind]);
3040 global_argv = argv + optind;
3041 global_argc = argc - optind;
3042 input = xfopen(argv[optind], "r");
3043 opt = parse_file_outer(input);
3045 #if ENABLE_FEATURE_CLEAN_UP
3047 if (cwd != bb_msg_unknown)
3050 struct variables *cur, *tmp;
3051 for (cur = top_vars; cur; cur = tmp) {
3053 if (!cur->flg_read_only) {
3054 free((char*)cur->name);
3055 free((char*)cur->value);
3063 hush_exit(opt ? opt : last_return_code);