1 /* vi: set sw=4 ts=4: */
3 * sh.c -- a prototype Bourne shell grammar parser
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
11 * The parser routines proper are all original material, first
12 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
13 * execution engine, the builtins, and much of the underlying
14 * support has been adapted from busybox-0.49pre's lash, which is
15 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
16 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
17 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
18 * Troan, which they placed in the public domain. I don't know
19 * how much of the Johnson/Troan code has survived the repeated
23 * b_addchr() derived from similar w_addchar function in glibc-2.2
24 * setup_redirect(), redirect_opt_num(), and big chunks of main()
25 * and many builtins derived from contributions by Erik Andersen
26 * miscellaneous bugfixes from Matt Kraai
28 * There are two big (and related) architecture differences between
29 * this parser and the lash parser. One is that this version is
30 * actually designed from the ground up to understand nearly all
31 * of the Bourne grammar. The second, consequential change is that
32 * the parser and input reader have been turned inside out. Now,
33 * the parser is in control, and asks for input as needed. The old
34 * way had the input reader in control, and it asked for parsing to
35 * take place as needed. The new way makes it much easier to properly
36 * handle the recursion implicit in the various substitutions, especially
37 * across continuation lines.
39 * Bash grammar not implemented: (how many of these were in original sh?)
40 * $@ (those sure look like weird quoting rules)
42 * ! negation operator for pipes
43 * &> and >& redirection of stdout+stderr
46 * fancy forms of Parameter Expansion
48 * Arithmetic Expansion
49 * <(list) and >(list) Process Substitution
50 * reserved words: case, esac, select, function
51 * Here Documents ( << word )
54 * job handling woefully incomplete and buggy
55 * reserved word execution woefully incomplete and buggy
57 * port selected bugfixes from post-0.49 busybox lash - done?
58 * finish implementing reserved words: for, while, until, do, done
59 * change { and } from special chars to reserved words
60 * builtins: break, continue, eval, return, set, trap, ulimit
62 * handle children going into background
63 * clean up recognition of null pipes
64 * check setting of global_argc and global_argv
65 * control-C handling, probably with longjmp
66 * follow IFS rules more precisely, including update semantics
67 * figure out what to do with backslash-newline
68 * explain why we use signal instead of sigaction
69 * propagate syntax errors, die on resource errors?
70 * continuation lines, both explicit and implicit - done?
71 * memory leak finding and plugging - done?
72 * more testing, especially quoting rules and redirection
73 * document how quoting rules not precisely followed for variable assignments
74 * maybe change map[] to use 2-bit entries
75 * (eventually) remove all the printf's
77 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
81 #include <glob.h> /* glob, of course */
82 #include <getopt.h> /* should be pretty obvious */
84 /* #include <dmalloc.h> */
86 /* Finer-grained debug switch */
87 //#define DEBUG_SHELL_JOBS
90 #define SPECIAL_VAR_SYMBOL 03
91 #define FLAG_EXIT_FROM_LOOP 1
92 #define FLAG_PARSE_SEMICOLON (1 << 1) /* symbol ';' is special for parser */
93 #define FLAG_REPARSING (1 << 2) /* >=2nd pass */
97 REDIRECT_OVERWRITE = 2,
103 /* The descrip member of this structure is only used to make debugging
105 static const struct {
111 { O_RDONLY, 0, "<" },
112 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
113 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
114 { O_RDONLY, -1, "<<" },
125 /* might eventually control execution */
143 FLAG_END = (1 << RES_NONE ),
144 FLAG_IF = (1 << RES_IF ),
145 FLAG_THEN = (1 << RES_THEN ),
146 FLAG_ELIF = (1 << RES_ELIF ),
147 FLAG_ELSE = (1 << RES_ELSE ),
148 FLAG_FI = (1 << RES_FI ),
149 FLAG_FOR = (1 << RES_FOR ),
150 FLAG_WHILE = (1 << RES_WHILE),
151 FLAG_UNTIL = (1 << RES_UNTIL),
152 FLAG_DO = (1 << RES_DO ),
153 FLAG_DONE = (1 << RES_DONE ),
154 FLAG_IN = (1 << RES_IN ),
155 FLAG_START = (1 << RES_XXXX ),
158 /* This holds pointers to the various results of parsing */
160 struct child_prog *child;
161 struct pipe *list_head;
163 struct redir_struct *pending_redirect;
165 int old_flag; /* for figuring out valid reserved words */
166 struct p_context *stack;
167 int type; /* define type of parser : ";$" common or special symbol */
168 /* How about quoting status? */
171 struct redir_struct {
172 redir_type type; /* type of redirection */
173 int fd; /* file descriptor being redirected */
174 int dup; /* -1, or file descriptor being duplicated */
175 struct redir_struct *next; /* pointer to the next redirect in the list */
176 glob_t word; /* *word.gl_pathv is the filename */
180 pid_t pid; /* 0 if exited */
181 char **argv; /* program name and arguments */
182 struct pipe *group; /* if non-NULL, first in group or subshell */
183 int subshell; /* flag, non-zero if group must be forked */
184 struct redir_struct *redirects; /* I/O redirections */
185 glob_t glob_result; /* result of parameter globbing */
186 int is_stopped; /* is the program currently running? */
187 struct pipe *family; /* pointer back to the child's parent pipe */
188 int sp; /* number of SPECIAL_VAR_SYMBOL */
193 int jobid; /* job number */
194 int num_progs; /* total number of programs in job */
195 int running_progs; /* number of programs running (not exited) */
196 char *text; /* name of job */
197 char *cmdbuf; /* buffer various argv's point into */
198 pid_t pgrp; /* process group ID for the job */
199 struct child_prog *progs; /* array of commands in pipe */
200 struct pipe *next; /* to track background commands */
201 int stopped_progs; /* number of programs alive, but stopped */
202 int job_context; /* bitmask defining current context */
203 pipe_style followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
204 reserved_style r_mode; /* supports if, for, while, until */
209 struct close_me *next;
217 struct variables *next;
220 /* globals, connect us to the outside world
221 * the first three support $?, $#, and $1 */
222 static char **global_argv;
223 static int global_argc;
224 static int last_return_code;
225 extern char **environ; /* This is in <unistd.h>, but protected with __USE_GNU */
227 /* "globals" within this file */
228 static const char *ifs;
229 static unsigned char map[256];
230 static int fake_mode;
231 static struct close_me *close_me_head;
232 static const char *cwd;
233 static struct pipe *job_list;
234 static unsigned last_bg_pid;
235 static int last_jobid;
236 /* 'interactive_fd' is a fd# open to ctty, if we have one
237 * _AND_ if we decided to mess with job control */
238 static int interactive_fd;
239 static pid_t saved_task_pgrp;
240 static pid_t saved_tty_pgrp;
242 static const char *PS1;
243 static const char *PS2;
244 static struct variables shell_ver = { "HUSH_VERSION", "0.01", 1, 1, 0 };
245 static struct variables *top_vars = &shell_ver;
248 #define B_CHUNK (100)
258 #define NULL_O_STRING {NULL,0,0,0,0}
259 /* used for initialization:
260 o_string foo = NULL_O_STRING; */
262 /* I can almost use ordinary FILE *. Is open_memstream() universally
263 * available? Where is it documented? */
270 int (*get) (struct in_str *);
271 int (*peek) (struct in_str *);
273 #define b_getch(input) ((input)->get(input))
274 #define b_peek(input) ((input)->peek(input))
276 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
278 struct built_in_command {
279 const char *cmd; /* name */
280 const char *descr; /* description */
281 int (*function) (char **argv); /* function ptr */
284 /* belongs in busybox.h */
285 static int max(int a, int b)
287 return (a > b) ? a : b;
291 #define debug_printf(...) fprintf(stderr, __VA_ARGS__)
292 /* broken, of course, but OK for testing */
293 static char *indenter(int i)
295 static char blanks[] = " ";
296 return &blanks[sizeof(blanks) - i - 1];
299 #define debug_printf(...) do {} while (0)
302 #ifdef DEBUG_SHELL_JOBS
303 #define debug_jobs_printf(...) fprintf(stderr, __VA_ARGS__)
305 #define debug_jobs_printf(...) do {} while (0)
308 #define final_printf debug_printf
310 static void __syntax(const char *file, int line)
312 bb_error_msg("syntax error %s:%d", file, line);
314 /* NB: was __FILE__, but that produces full path sometimes, so... */
315 #define syntax() __syntax("hush.c", __LINE__)
317 /* Index of subroutines: */
318 /* function prototypes for builtins */
319 static int builtin_cd(char **argv);
320 static int builtin_env(char **argv);
321 static int builtin_eval(char **argv);
322 static int builtin_exec(char **argv);
323 static int builtin_exit(char **argv);
324 static int builtin_export(char **argv);
325 static int builtin_fg_bg(char **argv);
326 static int builtin_help(char **argv);
327 static int builtin_jobs(char **argv);
328 static int builtin_pwd(char **argv);
329 static int builtin_read(char **argv);
330 static int builtin_set(char **argv);
331 static int builtin_shift(char **argv);
332 static int builtin_source(char **argv);
333 static int builtin_umask(char **argv);
334 static int builtin_unset(char **argv);
335 static int builtin_not_written(char **argv);
336 /* o_string manipulation: */
337 static int b_check_space(o_string *o, int len);
338 static int b_addchr(o_string *o, int ch);
339 static void b_reset(o_string *o);
340 static int b_addqchr(o_string *o, int ch, int quote);
341 static int b_adduint(o_string *o, unsigned i);
342 /* in_str manipulations: */
343 static int static_get(struct in_str *i);
344 static int static_peek(struct in_str *i);
345 static int file_get(struct in_str *i);
346 static int file_peek(struct in_str *i);
347 static void setup_file_in_str(struct in_str *i, FILE *f);
348 static void setup_string_in_str(struct in_str *i, const char *s);
349 /* close_me manipulations: */
350 static void mark_open(int fd);
351 static void mark_closed(int fd);
352 static void close_all(void);
353 /* "run" the final data structures: */
354 static int free_pipe_list(struct pipe *head, int indent);
355 static int free_pipe(struct pipe *pi, int indent);
356 /* really run the final data structures: */
357 static int setup_redirects(struct child_prog *prog, int squirrel[]);
358 static int run_list_real(struct pipe *pi);
359 static void pseudo_exec_argv(char **argv) ATTRIBUTE_NORETURN;
360 static void pseudo_exec(struct child_prog *child) ATTRIBUTE_NORETURN;
361 static int run_pipe_real(struct pipe *pi);
362 /* extended glob support: */
363 static int globhack(const char *src, int flags, glob_t *pglob);
364 static int glob_needed(const char *s);
365 static int xglob(o_string *dest, int flags, glob_t *pglob);
366 /* variable assignment: */
367 static int is_assignment(const char *s);
368 /* data structure manipulation: */
369 static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
370 static void initialize_context(struct p_context *ctx);
371 static int done_word(o_string *dest, struct p_context *ctx);
372 static int done_command(struct p_context *ctx);
373 static int done_pipe(struct p_context *ctx, pipe_style type);
374 /* primary string parsing: */
375 static int redirect_dup_num(struct in_str *input);
376 static int redirect_opt_num(o_string *o);
377 static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end);
378 static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
379 static const char *lookup_param(const char *src);
380 static char *make_string(char **inp);
381 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
382 static int parse_string(o_string *dest, struct p_context *ctx, const char *src);
383 static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, int end_trigger);
385 static int parse_stream_outer(struct in_str *inp, int flag);
386 static int parse_string_outer(const char *s, int flag);
387 static int parse_file_outer(FILE *f);
388 /* job management: */
389 static int checkjobs(struct pipe* fg_pipe);
390 static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
391 static void insert_bg_job(struct pipe *pi);
392 static void remove_bg_job(struct pipe *pi);
393 static void delete_finished_bg_job(struct pipe *pi);
394 /* local variable support */
395 static char **make_list_in(char **inp, char *name);
396 static char *insert_var_value(char *inp);
397 static const char *get_local_var(const char *var);
398 static int set_local_var(const char *s, int flg_export);
399 static void unset_local_var(const char *name);
401 /* Table of built-in functions. They can be forked or not, depending on
402 * context: within pipes, they fork. As simple commands, they do not.
403 * When used in non-forking context, they can change global variables
404 * in the parent shell process. If forked, of course they cannot.
405 * For example, 'unset foo | whatever' will parse and run, but foo will
406 * still be set at the end. */
407 static const struct built_in_command bltins[] = {
408 { "bg", "Resume a job in the background", builtin_fg_bg },
409 { "break", "Exit for, while or until loop", builtin_not_written },
410 { "cd", "Change working directory", builtin_cd },
411 { "continue", "Continue for, while or until loop", builtin_not_written },
412 { "env", "Print all environment variables", builtin_env },
413 { "eval", "Construct and run shell command", builtin_eval },
414 { "exec", "Exec command, replacing this shell with the exec'd process",
416 { "exit", "Exit from shell()", builtin_exit },
417 { "export", "Set environment variable", builtin_export },
418 { "fg", "Bring job into the foreground", builtin_fg_bg },
419 { "jobs", "Lists the active jobs", builtin_jobs },
420 { "pwd", "Print current directory", builtin_pwd },
421 { "read", "Input environment variable", builtin_read },
422 { "return", "Return from a function", builtin_not_written },
423 { "set", "Set/unset shell local variables", builtin_set },
424 { "shift", "Shift positional parameters", builtin_shift },
425 { "trap", "Trap signals", builtin_not_written },
426 { "ulimit","Controls resource limits", builtin_not_written },
427 { "umask","Sets file creation mask", builtin_umask },
428 { "unset", "Unset environment variable", builtin_unset },
429 { ".", "Source-in and run commands in a file", builtin_source },
430 { "help", "List shell built-in commands", builtin_help },
435 static void signal_SA_RESTART(int sig, void (*handler)(int))
438 sa.sa_handler = handler;
439 sa.sa_flags = SA_RESTART;
440 sigemptyset(&sa.sa_mask);
441 sigaction(sig, &sa, NULL);
444 static sigjmp_buf nofork_jb;
445 static smallint nofork_flag;
446 static struct pipe *nofork_pipe;
448 static void handler_ctrl_z(int sig)
452 fprintf(stderr, "got tty sig %d\n", sig);
456 if (pid < 0) /* can't fork. Pretend there were no Ctrl-Z */
458 fprintf(stderr, "bg'ing nofork\n");
460 nofork_pipe->running_progs = 1;
461 nofork_pipe->stopped_progs = 0;
462 if (!pid) { /* child */
463 fprintf(stderr, "setting pgrp for child\n");
465 signal(sig, SIG_DFL); /* make child do default action (stop) */
466 raise(sig); /* resend TSTP so that child will be stopped */
467 fprintf(stderr, "returning to child\n");
468 /* return to nofork, it will eventually exit now,
469 * not return back to shell */
473 /* finish filling up pipe info */
474 nofork_pipe->pgrp = pid; /* child is in its own pgrp */
475 nofork_pipe->progs[0].pid = pid;
476 nofork_pipe->running_progs = 1;
477 nofork_pipe->stopped_progs = 0;
478 /* parent needs to longjmp out of running nofork.
479 * we will "return" exitcode 0, with child put in background */
480 // as usual we can have all kinds of nasty problems with leaked malloc data here
481 siglongjmp(nofork_jb, 1);
484 /* Restores tty foreground process group, and exits.
485 * May be called as signal handler for fatal signal
486 * (will faithfully resend signal to itself, producing correct exit state)
487 * or called directly with -EXITCODE.
488 * We also call it if xfunc is exiting. */
489 static void sigexit(int sig) ATTRIBUTE_NORETURN;
490 static void sigexit(int sig)
494 /* Disable all signals: job control, SIGPIPE, etc. */
495 sigfillset(&block_all);
496 sigprocmask(SIG_SETMASK, &block_all, NULL);
499 tcsetpgrp(interactive_fd, saved_tty_pgrp);
501 /* Not a signal, just exit */
505 /* Enable only this sig and kill ourself with it */
506 signal(sig, SIG_DFL);
507 sigdelset(&block_all, sig);
508 sigprocmask(SIG_SETMASK, &block_all, NULL);
510 _exit(1); /* Should not reach it */
513 /* Restores tty foreground process group, and exits. */
514 static void hush_exit(int exitcode) ATTRIBUTE_NORETURN;
515 static void hush_exit(int exitcode)
517 fflush(NULL); /* flush all streams */
518 sigexit(- (exitcode & 0xff));
521 /* Signals are grouped, we handle them in batches */
522 static void set_fatal_sighandler(void (*handler)(int))
524 signal(SIGILL , handler);
525 signal(SIGTRAP, handler);
526 signal(SIGABRT, handler);
527 signal(SIGFPE , handler);
528 signal(SIGBUS , handler);
529 signal(SIGSEGV, handler);
530 /* bash 3.2 seems to handle these just like 'fatal' ones,
531 * but _without_ printing signal name. TODO: mimic this too? */
532 signal(SIGHUP , handler);
533 signal(SIGPIPE, handler);
534 signal(SIGALRM, handler);
536 static void set_jobctrl_sighandler(void (*handler)(int))
538 signal(SIGTSTP, handler);
539 signal(SIGTTIN, handler);
540 signal(SIGTTOU, handler);
542 static void set_misc_sighandler(void (*handler)(int))
544 signal(SIGINT , handler);
545 signal(SIGQUIT, handler);
546 signal(SIGTERM, handler);
548 /* SIGCHLD is special and handled separately */
550 static const char *set_cwd(void)
552 if (cwd == bb_msg_unknown)
553 cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
554 cwd = xrealloc_getcwd_or_warn((char *)cwd);
556 cwd = bb_msg_unknown;
560 /* built-in 'eval' handler */
561 static int builtin_eval(char **argv)
564 int rcode = EXIT_SUCCESS;
567 str = make_string(argv + 1);
568 parse_string_outer(str, FLAG_EXIT_FROM_LOOP |
569 FLAG_PARSE_SEMICOLON);
571 rcode = last_return_code;
576 /* built-in 'cd <path>' handler */
577 static int builtin_cd(char **argv)
581 newdir = getenv("HOME");
585 printf("cd: %s: %s\n", newdir, strerror(errno));
592 /* built-in 'env' handler */
593 static int builtin_env(char **argv ATTRIBUTE_UNUSED)
595 /* TODO: call env applet's code instead */
605 /* built-in 'exec' handler */
606 static int builtin_exec(char **argv)
609 return EXIT_SUCCESS; /* Really? */
610 pseudo_exec_argv(argv + 1);
614 /* built-in 'exit' handler */
615 static int builtin_exit(char **argv)
617 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
618 //puts("exit"); /* bash does it */
621 hush_exit(last_return_code);
622 /* mimic bash: exit 123abc == exit 255 + error msg */
623 xfunc_error_retval = 255;
624 /* bash: exit -2 == exit 254, no error msg */
625 hush_exit(xatoi(argv[1]));
628 /* built-in 'export VAR=value' handler */
629 static int builtin_export(char **argv)
632 char *name = argv[1];
635 return builtin_env(argv);
641 const char *value = strchr(name, '=');
645 /* They are exporting something without an =VALUE */
647 value = get_local_var(name);
649 size_t ln = strlen(name);
651 tmp = realloc(name, ln+strlen(value)+2);
655 sprintf(tmp+ln, "=%s", value);
659 /* bash does not return an error when trying to export
660 * an undefined variable. Do likewise. */
666 bb_perror_msg("export");
668 res = set_local_var(name, 1);
675 /* built-in 'fg' and 'bg' handler */
676 static int builtin_fg_bg(char **argv)
683 /* If they gave us no args, assume they want the last backgrounded task */
685 for (pi = job_list; pi; pi = pi->next) {
686 if (pi->jobid == last_jobid) {
690 bb_error_msg("%s: no current job", argv[0]);
693 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
694 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
697 for (pi = job_list; pi; pi = pi->next) {
698 if (pi->jobid == jobnum) {
702 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
705 // TODO: bash prints a string representation
706 // of job being foregrounded (like "sleep 1 | cat")
707 if (*argv[0] == 'f') {
708 /* Put the job into the foreground. */
709 tcsetpgrp(interactive_fd, pi->pgrp);
712 /* Restart the processes in the job */
713 debug_jobs_printf("reviving %d procs, pgrp %d\n", pi->num_progs, pi->pgrp);
714 for (i = 0; i < pi->num_progs; i++) {
715 debug_jobs_printf("reviving pid %d\n", pi->progs[i].pid);
716 pi->progs[i].is_stopped = 0;
718 pi->stopped_progs = 0;
720 i = kill(- pi->pgrp, SIGCONT);
722 if (errno == ESRCH) {
723 delete_finished_bg_job(pi);
725 bb_perror_msg("kill (SIGCONT)");
729 if (*argv[0] == 'f') {
731 return checkjobs_and_fg_shell(pi);
736 /* built-in 'help' handler */
737 static int builtin_help(char **argv ATTRIBUTE_UNUSED)
739 const struct built_in_command *x;
741 printf("\nBuilt-in commands:\n");
742 printf("-------------------\n");
743 for (x = bltins; x->cmd; x++) {
744 if (x->descr == NULL)
746 printf("%s\t%s\n", x->cmd, x->descr);
752 /* built-in 'jobs' handler */
753 static int builtin_jobs(char **argv ATTRIBUTE_UNUSED)
756 const char *status_string;
758 for (job = job_list; job; job = job->next) {
759 if (job->running_progs == job->stopped_progs)
760 status_string = "Stopped";
762 status_string = "Running";
764 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->text);
769 /* built-in 'pwd' handler */
770 static int builtin_pwd(char **argv ATTRIBUTE_UNUSED)
776 /* built-in 'read VAR' handler */
777 static int builtin_read(char **argv)
785 string[0] = '\0'; /* In case stdin has only EOF */
787 fgets(string, sizeof(string), stdin);
789 var = malloc(strlen(argv[1]) + strlen(string) + 2);
791 sprintf(var, "%s=%s", argv[1], string);
792 res = set_local_var(var, 0);
796 bb_perror_msg("read");
797 free(var); /* So not move up to avoid breaking errno */
800 do res = getchar(); while (res != '\n' && res != EOF);
804 /* built-in 'set VAR=value' handler */
805 static int builtin_set(char **argv)
807 char *temp = argv[1];
811 for (e = top_vars; e; e = e->next)
812 printf("%s=%s\n", e->name, e->value);
814 set_local_var(temp, 0);
820 /* Built-in 'shift' handler */
821 static int builtin_shift(char **argv)
827 if (n >= 0 && n < global_argc) {
828 /* XXX This probably breaks $0 */
836 /* Built-in '.' handler (read-in and execute commands from file) */
837 static int builtin_source(char **argv)
845 /* XXX search through $PATH is missing */
846 input = fopen(argv[1], "r");
848 bb_error_msg("cannot open '%s'", argv[1]);
852 /* Now run the file */
853 /* XXX argv and argc are broken; need to save old global_argv
854 * (pointer only is OK!) on this stack frame,
855 * set global_argv=argv+1, recurse, and restore. */
856 mark_open(fileno(input));
857 status = parse_file_outer(input);
858 mark_closed(fileno(input));
863 static int builtin_umask(char **argv)
866 const char *arg = argv[1];
869 new_umask = strtoul(arg, &end, 8);
870 if (*end != '\0' || end == arg) {
874 new_umask = umask(0);
875 printf("%.3o\n", (unsigned) new_umask);
881 /* built-in 'unset VAR' handler */
882 static int builtin_unset(char **argv)
884 /* bash returned already true */
885 unset_local_var(argv[1]);
889 static int builtin_not_written(char **argv)
891 printf("builtin_%s not written\n", argv[0]);
895 static int b_check_space(o_string *o, int len)
897 /* It would be easy to drop a more restrictive policy
898 * in here, such as setting a maximum string length */
899 if (o->length + len > o->maxlen) {
900 char *old_data = o->data;
901 /* assert(data == NULL || o->maxlen != 0); */
902 o->maxlen += max(2*len, B_CHUNK);
903 o->data = realloc(o->data, 1 + o->maxlen);
904 if (o->data == NULL) {
908 return o->data == NULL;
911 static int b_addchr(o_string *o, int ch)
913 debug_printf("b_addchr: %c %d %p\n", ch, o->length, o);
914 if (b_check_space(o, 1))
916 o->data[o->length] = ch;
918 o->data[o->length] = '\0';
922 static void b_reset(o_string *o)
930 static void b_free(o_string *o)
938 /* My analysis of quoting semantics tells me that state information
939 * is associated with a destination, not a source.
941 static int b_addqchr(o_string *o, int ch, int quote)
943 if (quote && strchr("*?[\\", ch)) {
945 rc = b_addchr(o, '\\');
949 return b_addchr(o, ch);
952 static int b_adduint(o_string *o, unsigned i)
955 char buf[sizeof(unsigned)*3 + 1];
957 *(utoa_to_buf(i, buf, sizeof(buf))) = '\0';
958 /* no escape checking necessary */
959 do r = b_addchr(o, *p++); while (r == 0 && *p);
963 static int static_get(struct in_str *i)
966 if (ch == '\0') return EOF;
970 static int static_peek(struct in_str *i)
975 static void cmdedit_set_initial_prompt(void)
977 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
986 static const char* setup_prompt_string(int promptmode)
988 const char *prompt_str;
989 debug_printf("setup_prompt_string %d ", promptmode);
990 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
991 /* Set up the prompt */
992 if (promptmode == 1) {
995 ns = xmalloc(strlen(cwd)+4);
996 sprintf(ns, "%s %s", cwd, (geteuid() != 0) ? "$ " : "# ");
1003 prompt_str = (promptmode == 1) ? PS1 : PS2;
1005 debug_printf("result %s\n", prompt_str);
1009 #if ENABLE_FEATURE_EDITING
1010 static line_input_t *line_input_state;
1013 static void get_user_input(struct in_str *i)
1015 const char *prompt_str;
1016 static char the_command[BUFSIZ];
1018 prompt_str = setup_prompt_string(i->promptmode);
1019 #if ENABLE_FEATURE_EDITING
1021 ** enable command line editing only while a command line
1022 ** is actually being read; otherwise, we'll end up bequeathing
1023 ** atexit() handlers and other unwanted stuff to our
1024 ** child processes (rob@sysgo.de)
1026 read_line_input(prompt_str, the_command, BUFSIZ, line_input_state);
1028 fputs(prompt_str, stdout);
1030 the_command[0] = fgetc(i->file);
1031 the_command[1] = '\0';
1037 /* This is the magic location that prints prompts
1038 * and gets data back from the user */
1039 static int file_get(struct in_str *i)
1044 /* If there is data waiting, eat it up */
1045 if (i->p && *i->p) {
1048 /* need to double check i->file because we might be doing something
1049 * more complicated by now, like sourcing or substituting. */
1050 if (i->__promptme && interactive_fd && i->file == stdin) {
1051 while (!i->p || !(interactive_fd && strlen(i->p))) {
1056 if (i->p && *i->p) {
1060 ch = fgetc(i->file);
1063 debug_printf("b_getch: got a %d\n", ch);
1070 /* All the callers guarantee this routine will never be
1071 * used right after a newline, so prompting is not needed.
1073 static int file_peek(struct in_str *i)
1075 if (i->p && *i->p) {
1078 i->peek_buf[0] = fgetc(i->file);
1079 i->peek_buf[1] = '\0';
1081 debug_printf("b_peek: got a %d\n", *i->p);
1085 static void setup_file_in_str(struct in_str *i, FILE *f)
1087 i->peek = file_peek;
1095 static void setup_string_in_str(struct in_str *i, const char *s)
1097 i->peek = static_peek;
1098 i->get = static_get;
1104 static void mark_open(int fd)
1106 struct close_me *new = xmalloc(sizeof(struct close_me));
1108 new->next = close_me_head;
1109 close_me_head = new;
1112 static void mark_closed(int fd)
1114 struct close_me *tmp;
1115 if (close_me_head == NULL || close_me_head->fd != fd)
1116 bb_error_msg_and_die("corrupt close_me");
1117 tmp = close_me_head;
1118 close_me_head = close_me_head->next;
1122 static void close_all(void)
1125 for (c = close_me_head; c; c = c->next) {
1128 close_me_head = NULL;
1131 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
1132 * and stderr if they are redirected. */
1133 static int setup_redirects(struct child_prog *prog, int squirrel[])
1136 struct redir_struct *redir;
1138 for (redir = prog->redirects; redir; redir = redir->next) {
1139 if (redir->dup == -1 && redir->word.gl_pathv == NULL) {
1140 /* something went wrong in the parse. Pretend it didn't happen */
1143 if (redir->dup == -1) {
1144 mode = redir_table[redir->type].mode;
1145 openfd = open_or_warn(redir->word.gl_pathv[0], mode);
1147 /* this could get lost if stderr has been redirected, but
1148 bash and ash both lose it as well (though zsh doesn't!) */
1152 openfd = redir->dup;
1155 if (openfd != redir->fd) {
1156 if (squirrel && redir->fd < 3) {
1157 squirrel[redir->fd] = dup(redir->fd);
1162 dup2(openfd, redir->fd);
1163 if (redir->dup == -1)
1171 static void restore_redirects(int squirrel[])
1174 for (i = 0; i < 3; i++) {
1177 /* No error checking. I sure wouldn't know what
1178 * to do with an error if I found one! */
1186 /* XXX no exit() here. If you don't exec, use _exit instead.
1187 * The at_exit handlers apparently confuse the calling process,
1188 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
1189 static void pseudo_exec_argv(char **argv)
1193 const struct built_in_command *x;
1195 for (i = 0; is_assignment(argv[i]); i++) {
1196 debug_printf("pid %d environment modification: %s\n",
1198 // FIXME: vfork case??
1199 p = insert_var_value(argv[i]);
1205 /* If a variable is assigned in a forest, and nobody listens,
1206 * was it ever really set?
1208 if (argv[0] == NULL) {
1209 _exit(EXIT_SUCCESS);
1213 * Check if the command matches any of the builtins.
1214 * Depending on context, this might be redundant. But it's
1215 * easier to waste a few CPU cycles than it is to figure out
1216 * if this is one of those cases.
1218 for (x = bltins; x->cmd; x++) {
1219 if (strcmp(argv[0], x->cmd) == 0) {
1220 debug_printf("builtin exec %s\n", argv[0]);
1221 rcode = x->function(argv);
1227 /* Check if the command matches any busybox internal commands
1229 * FIXME: This feature is not 100% safe, since
1230 * BusyBox is not fully reentrant, so we have no guarantee the things
1231 * from the .bss are still zeroed, or that things from .data are still
1232 * at their defaults. We could exec ourself from /proc/self/exe, but I
1233 * really dislike relying on /proc for things. We could exec ourself
1234 * from global_argv[0], but if we are in a chroot, we may not be able
1235 * to find ourself... */
1236 #if ENABLE_FEATURE_SH_STANDALONE
1237 debug_printf("running applet %s\n", argv[0]);
1238 run_applet_and_exit(argv[0], argv);
1239 // is it ok that run_applet_and_exit() does exit(), not _exit()?
1240 // NB: IIRC on NOMMU we are after _vfork_, not fork!
1242 debug_printf("exec of %s\n", argv[0]);
1243 execvp(argv[0], argv);
1244 bb_perror_msg("cannot exec '%s'", argv[0]);
1248 static void pseudo_exec(struct child_prog *child)
1253 pseudo_exec_argv(child->argv);
1257 debug_printf("runtime nesting to group\n");
1258 // FIXME: do not modify globals! Think vfork!
1259 interactive_fd = 0; /* crucial!!!! */
1260 rcode = run_list_real(child->group);
1261 /* OK to leak memory by not calling free_pipe_list,
1262 * since this process is about to exit */
1266 /* Can happen. See what bash does with ">foo" by itself. */
1267 debug_printf("trying to pseudo_exec null command\n");
1268 _exit(EXIT_SUCCESS);
1271 static void insert_bg_job(struct pipe *pi)
1273 struct pipe *thejob;
1275 /* Linear search for the ID of the job to use */
1277 for (thejob = job_list; thejob; thejob = thejob->next)
1278 if (thejob->jobid >= pi->jobid)
1279 pi->jobid = thejob->jobid + 1;
1281 /* add thejob to the list of running jobs */
1283 thejob = job_list = xmalloc(sizeof(*thejob));
1285 for (thejob = job_list; thejob->next; thejob = thejob->next)
1287 thejob->next = xmalloc(sizeof(*thejob));
1288 thejob = thejob->next;
1291 /* physically copy the struct job */
1292 memcpy(thejob, pi, sizeof(struct pipe));
1293 // (pi->num_progs+1) is one-too-many I think?
1294 thejob->progs = xmalloc(sizeof(pi->progs[0]) * (pi->num_progs+1));
1295 memcpy(thejob->progs, pi->progs, sizeof(pi->progs[0]) * (pi->num_progs+1));
1296 thejob->next = NULL;
1297 /*seems to be wrong:*/
1298 /*thejob->running_progs = thejob->num_progs;*/
1299 /*thejob->stopped_progs = 0;*/
1300 thejob->text = xmalloc(BUFSIZ); /* cmdedit buffer size */
1301 //if (pi->progs[0] && pi->progs[0].argv && pi->progs[0].argv[0])
1303 // FIXME: overflow check? and also trim the size, BUFSIZ can be 4K!
1304 char *bar = thejob->text;
1305 char **foo = pi->progs[0].argv;
1308 bar += sprintf(bar, "%s ", *foo++);
1311 /* we don't wait for background thejobs to return -- append it
1312 to the list of backgrounded thejobs and leave it alone */
1313 printf("[%d] %d\n", thejob->jobid, thejob->progs[0].pid);
1314 last_bg_pid = thejob->progs[0].pid;
1315 last_jobid = thejob->jobid;
1318 static void remove_bg_job(struct pipe *pi)
1320 struct pipe *prev_pipe;
1322 if (pi == job_list) {
1323 job_list = pi->next;
1325 prev_pipe = job_list;
1326 while (prev_pipe->next != pi)
1327 prev_pipe = prev_pipe->next;
1328 prev_pipe->next = pi->next;
1331 last_jobid = job_list->jobid;
1336 /* remove a backgrounded job */
1337 static void delete_finished_bg_job(struct pipe *pi)
1340 pi->stopped_progs = 0;
1345 /* Checks to see if any processes have exited -- if they
1346 have, figure out why and see if a job has completed */
1347 static int checkjobs(struct pipe* fg_pipe)
1356 attributes = WUNTRACED;
1357 if (fg_pipe == NULL) {
1358 attributes |= WNOHANG;
1361 /* Do we do this right?
1362 * bash-3.00# sleep 20 | false
1364 * [3]+ Stopped sleep 20 | false
1365 * bash-3.00# echo $?
1366 * 1 <========== bg pipe is not fully done, but exitcode is already known!
1370 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
1371 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
1373 #ifdef DEBUG_SHELL_JOBS
1374 if (WIFSTOPPED(status))
1375 debug_jobs_printf("pid %d stopped by sig %d (exitcode %d)\n",
1376 childpid, WSTOPSIG(status), WEXITSTATUS(status));
1377 if (WIFSIGNALED(status))
1378 debug_jobs_printf("pid %d killed by sig %d (exitcode %d)\n",
1379 childpid, WTERMSIG(status), WEXITSTATUS(status));
1380 if (WIFEXITED(status))
1381 debug_jobs_printf("pid %d exited, exitcode %d\n",
1382 childpid, WEXITSTATUS(status));
1384 /* Were we asked to wait for fg pipe? */
1387 for (i = 0; i < fg_pipe->num_progs; i++) {
1388 debug_jobs_printf("check pid %d\n", fg_pipe->progs[i].pid);
1389 if (fg_pipe->progs[i].pid == childpid) {
1390 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
1392 fg_pipe->progs[i].pid = 0;
1393 fg_pipe->running_progs--;
1394 if (i == fg_pipe->num_progs-1)
1395 /* last process gives overall exitstatus */
1396 rcode = WEXITSTATUS(status);
1398 fg_pipe->progs[i].is_stopped = 1;
1399 fg_pipe->stopped_progs++;
1401 debug_jobs_printf("fg_pipe: running_progs %d stopped_progs %d\n",
1402 fg_pipe->running_progs, fg_pipe->stopped_progs);
1403 if (fg_pipe->running_progs - fg_pipe->stopped_progs <= 0) {
1404 /* All processes in fg pipe have exited/stopped */
1405 if (fg_pipe->running_progs)
1406 insert_bg_job(fg_pipe);
1409 /* There are still running processes in the fg pipe */
1413 /* fall through to searching process in bg pipes */
1416 /* We asked to wait for bg or orphaned children */
1417 /* No need to remember exitcode in this case */
1418 for (pi = job_list; pi; pi = pi->next) {
1420 while (prognum < pi->num_progs) {
1421 if (pi->progs[prognum].pid == childpid)
1422 goto found_pi_and_prognum;
1427 /* Happens when shell is used as init process (init=/bin/sh) */
1428 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
1431 found_pi_and_prognum:
1434 pi->progs[prognum].pid = 0;
1435 pi->running_progs--;
1436 if (!pi->running_progs) {
1437 printf(JOB_STATUS_FORMAT, pi->jobid,
1439 delete_finished_bg_job(pi);
1443 pi->stopped_progs++;
1444 pi->progs[prognum].is_stopped = 1;
1448 /* wait found no children or failed */
1450 if (childpid && errno != ECHILD)
1451 bb_perror_msg("waitpid");
1453 /* move the shell to the foreground */
1454 //if (interactive_fd && tcsetpgrp(interactive_fd, getpgid(0)))
1455 // bb_perror_msg("tcsetpgrp-2");
1459 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1462 int rcode = checkjobs(fg_pipe);
1463 /* Job finished, move the shell to the foreground */
1465 debug_printf("fg'ing ourself: getpgid(0)=%d\n", (int)p);
1466 if (tcsetpgrp(interactive_fd, p) && errno != ENOTTY)
1467 bb_perror_msg("tcsetpgrp-4a");
1471 /* run_pipe_real() starts all the jobs, but doesn't wait for anything
1472 * to finish. See checkjobs().
1474 * return code is normally -1, when the caller has to wait for children
1475 * to finish to determine the exit status of the pipe. If the pipe
1476 * is a simple builtin command, however, the action is done by the
1477 * time run_pipe_real returns, and the exit code is provided as the
1480 * The input of the pipe is always stdin, the output is always
1481 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1482 * because it tries to avoid running the command substitution in
1483 * subshell, when that is in fact necessary. The subshell process
1484 * now has its stdout directed to the input of the appropriate pipe,
1485 * so this routine is noticeably simpler.
1487 static int run_pipe_real(struct pipe *pi)
1490 int nextin, nextout;
1491 int pipefds[2]; /* pipefds[0] is for reading */
1492 struct child_prog *child;
1493 const struct built_in_command *x;
1495 /* it is not always needed, but we aim to smaller code */
1496 int squirrel[] = { -1, -1, -1 };
1498 const int single_fg = (pi->num_progs == 1 && pi->followup != PIPE_BG);
1502 pi->running_progs = 0;
1503 pi->stopped_progs = 0;
1505 /* Check if this is a simple builtin (not part of a pipe).
1506 * Builtins within pipes have to fork anyway, and are handled in
1507 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1509 child = &(pi->progs[0]);
1510 if (single_fg && child->group && child->subshell == 0) {
1511 debug_printf("non-subshell grouping\n");
1512 setup_redirects(child, squirrel);
1513 /* XXX could we merge code with following builtin case,
1514 * by creating a pseudo builtin that calls run_list_real? */
1515 rcode = run_list_real(child->group);
1516 restore_redirects(squirrel);
1520 if (single_fg && child->argv != NULL) {
1521 char **argv = child->argv;
1523 for (i = 0; is_assignment(argv[i]); i++)
1525 if (i != 0 && argv[i] == NULL) {
1526 /* assignments, but no command: set the local environment */
1527 for (i = 0; argv[i] != NULL; i++) {
1528 /* Ok, this case is tricky. We have to decide if this is a
1529 * local variable, or an already exported variable. If it is
1530 * already exported, we have to export the new value. If it is
1531 * not exported, we need only set this as a local variable.
1532 * This junk is all to decide whether or not to export this
1536 name = xstrdup(argv[i]);
1537 debug_printf("Local environment set: %s\n", name);
1538 value = strchr(name, '=');
1541 if (get_local_var(name)) {
1545 p = insert_var_value(argv[i]);
1546 set_local_var(p, export_me);
1550 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1552 for (i = 0; is_assignment(argv[i]); i++) {
1553 p = insert_var_value(argv[i]);
1563 str = make_string(argv + i);
1564 parse_string_outer(str, FLAG_EXIT_FROM_LOOP | FLAG_REPARSING);
1566 return last_return_code;
1568 for (x = bltins; x->cmd; x++) {
1569 if (strcmp(argv[i], x->cmd) == 0) {
1570 if (x->function == builtin_exec && argv[i+1] == NULL) {
1571 debug_printf("magic exec\n");
1572 setup_redirects(child, NULL);
1573 return EXIT_SUCCESS;
1575 debug_printf("builtin inline %s\n", argv[0]);
1576 /* XXX setup_redirects acts on file descriptors, not FILEs.
1577 * This is perfect for work that comes after exec().
1578 * Is it really safe for inline use? Experimentally,
1579 * things seem to work with glibc. */
1580 setup_redirects(child, squirrel);
1581 rcode = x->function(argv + i);
1582 restore_redirects(squirrel);
1586 #if ENABLE_FEATURE_SH_STANDALONE
1588 const struct bb_applet *a = find_applet_by_name(argv[i]);
1589 if (a && a->nofork) {
1590 setup_redirects(child, squirrel);
1591 if (sigsetjmp(nofork_jb, 1) == 0) {
1592 // enable ctrl_z here, not globally?
1594 /* TSTP handler will store pid there etc */
1596 rcode = run_nofork_applet(a, argv + i);
1597 if (--nofork_flag != 0)
1598 /* Ctrl-Z! forked, we are child */
1600 restore_redirects(squirrel);
1603 fprintf(stderr, "Exiting nofork early\n");
1604 /* Ctrl-Z, forked, we are parent.
1605 * Sighandler has longjmped us here */
1606 //problem: run_nofork_applet did not do the
1607 // "restore" trick and globals are trashed:
1608 // for one, applet_name is not "hush" :)
1609 // need to split run_nofork_applet into setup/run/restore...
1610 restore_redirects(squirrel);
1619 /* Disable job control signals for shell (parent) and
1620 * for initial child code after fork */
1621 set_jobctrl_sighandler(SIG_IGN);
1623 for (i = 0; i < pi->num_progs; i++) {
1624 child = &(pi->progs[i]);
1626 /* pipes are inserted between pairs of commands */
1627 if ((i + 1) < pi->num_progs) {
1628 if (pipe(pipefds) < 0)
1629 bb_perror_msg_and_die("pipe");
1630 nextout = pipefds[1];
1636 /* XXX test for failed fork()? */
1638 child->pid = fork();
1640 child->pid = vfork();
1642 if (!child->pid) { /* child */
1643 /* Every child adds itself to new process group
1644 * with pgid == pid of first child in pipe */
1645 if (interactive_fd) {
1646 if (pi->pgrp < 0) /* true for 1st process only */
1647 pi->pgrp = getpid();
1648 if (setpgid(0, pi->pgrp) == 0 && pi->followup != PIPE_BG) {
1649 /* We do it in *every* child, not just first,
1651 tcsetpgrp(interactive_fd, pi->pgrp);
1653 /* Don't do pgrp restore anymore on fatal signals */
1654 set_fatal_sighandler(SIG_DFL);
1656 // in non-interactive case fatal sigs are already SIG_DFL
1666 if (pipefds[0] != -1) {
1667 close(pipefds[0]); /* opposite end of our output pipe */
1669 /* Like bash, explicit redirects override pipes,
1670 * and the pipe fd is available for dup'ing. */
1671 setup_redirects(child, NULL);
1673 /* Restore default handlers just prior to exec */
1674 set_jobctrl_sighandler(SIG_DFL);
1675 set_misc_sighandler(SIG_DFL);
1676 signal(SIGCHLD, SIG_DFL);
1680 pi->running_progs++;
1682 /* Second and next children need to know pid of first one */
1684 pi->pgrp = child->pid;
1686 /* Don't check for errors. The child may be dead already,
1687 * in which case setpgid returns error code EACCES. */
1688 //why we do it at all?? child does it itself
1689 //if (interactive_fd)
1690 // setpgid(child->pid, pi->pgrp);
1697 /* If there isn't another process, nextin is garbage
1698 but it doesn't matter */
1699 nextin = pipefds[0];
1704 static int run_list_real(struct pipe *pi)
1706 char *save_name = NULL;
1708 char **save_list = NULL;
1712 int rcode = 0, flag_skip = 1;
1713 int flag_restore = 0;
1714 int if_code = 0, next_if_code = 0; /* need double-buffer to handle elif */
1715 reserved_style rmode, skip_more_in_this_rmode = RES_XXXX;
1716 /* check syntax for "for" */
1717 for (rpipe = pi; rpipe; rpipe = rpipe->next) {
1718 if ((rpipe->r_mode == RES_IN || rpipe->r_mode == RES_FOR)
1719 && (rpipe->next == NULL)
1724 if ((rpipe->r_mode == RES_IN && rpipe->next->r_mode == RES_IN && rpipe->next->progs->argv != NULL)
1725 || (rpipe->r_mode == RES_FOR && rpipe->next->r_mode != RES_IN)
1731 for (; pi; pi = (flag_restore != 0) ? rpipe : pi->next) {
1732 if (pi->r_mode == RES_WHILE || pi->r_mode == RES_UNTIL
1733 || pi->r_mode == RES_FOR
1742 debug_printf("rmode=%d if_code=%d next_if_code=%d skip_more=%d\n",
1743 rmode, if_code, next_if_code, skip_more_in_this_rmode);
1744 if (rmode == skip_more_in_this_rmode && flag_skip) {
1745 if (pi->followup == PIPE_SEQ)
1750 skip_more_in_this_rmode = RES_XXXX;
1751 if (rmode == RES_THEN || rmode == RES_ELSE)
1752 if_code = next_if_code;
1753 if (rmode == RES_THEN && if_code)
1755 if (rmode == RES_ELSE && !if_code)
1757 if (rmode == RES_ELIF && !if_code)
1759 if (rmode == RES_FOR && pi->num_progs) {
1761 /* if no variable values after "in" we skip "for" */
1762 if (!pi->next->progs->argv)
1764 /* create list of variable values */
1765 list = make_list_in(pi->next->progs->argv,
1766 pi->progs->argv[0]);
1768 save_name = pi->progs->argv[0];
1769 pi->progs->argv[0] = NULL;
1773 free(pi->progs->argv[0]);
1777 pi->progs->argv[0] = save_name;
1778 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
1781 /* insert new value from list for variable */
1782 if (pi->progs->argv[0])
1783 free(pi->progs->argv[0]);
1784 pi->progs->argv[0] = *list++;
1785 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
1787 if (rmode == RES_IN)
1789 if (rmode == RES_DO) {
1793 if (rmode == RES_DONE) {
1800 if (pi->num_progs == 0)
1802 save_num_progs = pi->num_progs; /* save number of programs */
1803 rcode = run_pipe_real(pi);
1804 debug_printf("run_pipe_real returned %d\n", rcode);
1806 /* We only ran a builtin: rcode was set by the return value
1807 * of run_pipe_real(), and we don't need to wait for anything. */
1808 } else if (pi->followup == PIPE_BG) {
1809 /* XXX check bash's behavior with nontrivial pipes */
1810 /* XXX compute jobid */
1811 /* XXX what does bash do with attempts to background builtins? */
1813 rcode = EXIT_SUCCESS;
1815 if (interactive_fd) {
1816 rcode = checkjobs_and_fg_shell(pi);
1818 rcode = checkjobs(pi);
1820 debug_printf("checkjobs returned %d\n", rcode);
1822 last_return_code = rcode;
1823 pi->num_progs = save_num_progs; /* restore number of programs */
1824 if (rmode == RES_IF || rmode == RES_ELIF)
1825 next_if_code = rcode; /* can be overwritten a number of times */
1826 if (rmode == RES_WHILE)
1827 flag_rep = !last_return_code;
1828 if (rmode == RES_UNTIL)
1829 flag_rep = last_return_code;
1830 if ((rcode == EXIT_SUCCESS && pi->followup == PIPE_OR)
1831 || (rcode != EXIT_SUCCESS && pi->followup == PIPE_AND)
1833 skip_more_in_this_rmode = rmode;
1840 /* return code is the exit status of the pipe */
1841 static int free_pipe(struct pipe *pi, int indent)
1844 struct child_prog *child;
1845 struct redir_struct *r, *rnext;
1846 int a, i, ret_code = 0;
1848 if (pi->stopped_progs > 0)
1850 final_printf("%s run pipe: (pid %d)\n", indenter(indent), getpid());
1851 for (i = 0; i < pi->num_progs; i++) {
1852 child = &pi->progs[i];
1853 final_printf("%s command %d:\n", indenter(indent), i);
1855 for (a = 0, p = child->argv; *p; a++, p++) {
1856 final_printf("%s argv[%d] = %s\n", indenter(indent), a, *p);
1858 globfree(&child->glob_result);
1860 } else if (child->group) {
1861 final_printf("%s begin group (subshell:%d)\n", indenter(indent), child->subshell);
1862 ret_code = free_pipe_list(child->group, indent+3);
1863 final_printf("%s end group\n", indenter(indent));
1865 final_printf("%s (nil)\n", indenter(indent));
1867 for (r = child->redirects; r; r = rnext) {
1868 final_printf("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->type].descrip);
1870 /* guard against the case >$FOO, where foo is unset or blank */
1871 if (r->word.gl_pathv) {
1872 final_printf(" %s\n", *r->word.gl_pathv);
1876 final_printf("&%d\n", r->dup);
1881 child->redirects = NULL;
1883 free(pi->progs); /* children are an array, they get freed all at once */
1888 static int free_pipe_list(struct pipe *head, int indent)
1890 int rcode = 0; /* if list has no members */
1891 struct pipe *pi, *next;
1892 for (pi = head; pi; pi = next) {
1893 final_printf("%s pipe reserved mode %d\n", indenter(indent), pi->r_mode);
1894 rcode = free_pipe(pi, indent);
1895 final_printf("%s pipe followup code %d\n", indenter(indent), pi->followup);
1897 /*pi->next = NULL;*/
1903 /* Select which version we will use */
1904 static int run_list(struct pipe *pi)
1907 if (fake_mode == 0) {
1908 rcode = run_list_real(pi);
1910 /* free_pipe_list has the side effect of clearing memory
1911 * In the long run that function can be merged with run_list_real,
1912 * but doing that now would hobble the debugging effort. */
1913 free_pipe_list(pi,0);
1917 /* The API for glob is arguably broken. This routine pushes a non-matching
1918 * string into the output structure, removing non-backslashed backslashes.
1919 * If someone can prove me wrong, by performing this function within the
1920 * original glob(3) api, feel free to rewrite this routine into oblivion.
1921 * Return code (0 vs. GLOB_NOSPACE) matches glob(3).
1922 * XXX broken if the last character is '\\', check that before calling.
1924 static int globhack(const char *src, int flags, glob_t *pglob)
1929 for (cnt = 1, s = src; s && *s; s++) {
1930 if (*s == '\\') s++;
1935 return GLOB_NOSPACE;
1936 if (!(flags & GLOB_APPEND)) {
1937 pglob->gl_pathv = NULL;
1938 pglob->gl_pathc = 0;
1942 pathc = ++pglob->gl_pathc;
1943 pglob->gl_pathv = realloc(pglob->gl_pathv, (pathc+1)*sizeof(*pglob->gl_pathv));
1944 if (pglob->gl_pathv == NULL)
1945 return GLOB_NOSPACE;
1946 pglob->gl_pathv[pathc-1] = dest;
1947 pglob->gl_pathv[pathc] = NULL;
1948 for (s = src; s && *s; s++, dest++) {
1949 if (*s == '\\') s++;
1956 /* XXX broken if the last character is '\\', check that before calling */
1957 static int glob_needed(const char *s)
1960 if (*s == '\\') s++;
1961 if (strchr("*[?", *s)) return 1;
1966 static int xglob(o_string *dest, int flags, glob_t *pglob)
1970 /* short-circuit for null word */
1971 /* we can code this better when the debug_printf's are gone */
1972 if (dest->length == 0) {
1973 if (dest->nonnull) {
1974 /* bash man page calls this an "explicit" null */
1975 gr = globhack(dest->data, flags, pglob);
1976 debug_printf("globhack returned %d\n", gr);
1980 } else if (glob_needed(dest->data)) {
1981 gr = glob(dest->data, flags, NULL, pglob);
1982 debug_printf("glob returned %d\n", gr);
1983 if (gr == GLOB_NOMATCH) {
1984 /* quote removal, or more accurately, backslash removal */
1985 gr = globhack(dest->data, flags, pglob);
1986 debug_printf("globhack returned %d\n", gr);
1989 gr = globhack(dest->data, flags, pglob);
1990 debug_printf("globhack returned %d\n", gr);
1992 if (gr == GLOB_NOSPACE)
1993 bb_error_msg_and_die("out of memory during glob");
1994 if (gr != 0) { /* GLOB_ABORTED ? */
1995 bb_error_msg("glob(3) error %d", gr);
1997 /* globprint(glob_target); */
2001 static char **make_list_in(char **inp, char *name)
2004 int name_len = strlen(name);
2009 /* create list of variable values */
2010 list = xmalloc(sizeof(*list));
2011 for (i = 0; inp[i]; i++) {
2012 p3 = insert_var_value(inp[i]);
2019 p2 = strchr(p1, ' ');
2026 /* we use n + 2 in realloc for list, because we add
2027 * new element and then we will add NULL element */
2028 list = xrealloc(list, sizeof(*list) * (n + 2));
2029 list[n] = xmalloc(2 + name_len + len);
2030 strcpy(list[n], name);
2031 strcat(list[n], "=");
2032 strncat(list[n], p1, len);
2033 list[n++][name_len + len + 1] = '\0';
2036 if (p3 != inp[i]) free(p3);
2042 static char *insert_var_value(char *inp)
2044 int res_str_len = 0;
2047 char *p, *res_str = NULL;
2050 while ((p = strchr(inp, SPECIAL_VAR_SYMBOL))) {
2053 res_str = xrealloc(res_str, (res_str_len + len));
2054 strncpy((res_str + res_str_len), inp, len);
2058 p = strchr(inp, SPECIAL_VAR_SYMBOL);
2060 p1 = lookup_param(inp);
2062 len = res_str_len + strlen(p1);
2063 res_str = xrealloc(res_str, (1 + len));
2064 strcpy((res_str + res_str_len), p1);
2067 *p = SPECIAL_VAR_SYMBOL;
2072 res_str = xrealloc(res_str, (1 + res_str_len + strlen(inp)));
2073 strcpy((res_str + res_str_len), inp);
2074 while ((p = strchr(res_str, '\n'))) {
2078 return (res_str == NULL) ? inp : res_str;
2081 /* This is used to get/check local shell variables */
2082 static const char *get_local_var(const char *s)
2084 struct variables *cur;
2088 for (cur = top_vars; cur; cur = cur->next)
2089 if (strcmp(cur->name, s) == 0)
2094 /* This is used to set local shell variables
2095 flg_export == 0 if only local (not exporting) variable
2096 flg_export == 1 if "new" exporting environ
2097 flg_export > 1 if current startup environ (not call putenv()) */
2098 static int set_local_var(const char *s, int flg_export)
2102 struct variables *cur;
2106 /* Assume when we enter this function that we are already in
2107 * NAME=VALUE format. So the first order of business is to
2108 * split 's' on the '=' into 'name' and 'value' */
2109 value = strchr(name, '=');
2110 /*if (value == 0 && ++value == 0) ??? -vda */
2111 if (value == NULL || value[1] == '\0') {
2117 for (cur = top_vars; cur; cur = cur->next) {
2118 if (strcmp(cur->name, name) == 0)
2123 if (strcmp(cur->value, value) == 0) {
2124 if (flg_export > 0 && cur->flg_export == 0)
2125 cur->flg_export = flg_export;
2128 } else if (cur->flg_read_only) {
2129 bb_error_msg("%s: readonly variable", name);
2132 if (flg_export > 0 || cur->flg_export > 1)
2133 cur->flg_export = 1;
2134 free((char*)cur->value);
2136 cur->value = strdup(value);
2139 cur = malloc(sizeof(struct variables));
2143 cur->name = strdup(name);
2148 struct variables *bottom = top_vars;
2149 cur->value = strdup(value);
2151 cur->flg_export = flg_export;
2152 cur->flg_read_only = 0;
2153 while (bottom->next)
2154 bottom = bottom->next;
2160 if (result == 0 && cur->flg_export == 1) {
2162 result = putenv(name);
2165 if (result > 0) /* equivalent to previous set */
2171 static void unset_local_var(const char *name)
2173 struct variables *cur, *next;
2177 for (cur = top_vars; cur; cur = cur->next) {
2178 if (strcmp(cur->name, name) == 0) {
2179 if (cur->flg_read_only) {
2180 bb_error_msg("%s: readonly variable", name);
2183 if (cur->flg_export)
2184 unsetenv(cur->name);
2185 free((char*)cur->name);
2186 free((char*)cur->value);
2188 while (next->next != cur)
2190 next->next = cur->next;
2197 static int is_assignment(const char *s)
2199 if (!s || !isalpha(*s))
2202 while (isalnum(*s) || *s == '_')
2207 /* the src parameter allows us to peek forward to a possible &n syntax
2208 * for file descriptor duplication, e.g., "2>&1".
2209 * Return code is 0 normally, 1 if a syntax error is detected in src.
2210 * Resource errors (in xmalloc) cause the process to exit */
2211 static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2212 struct in_str *input)
2214 struct child_prog *child = ctx->child;
2215 struct redir_struct *redir = child->redirects;
2216 struct redir_struct *last_redir = NULL;
2218 /* Create a new redir_struct and drop it onto the end of the linked list */
2221 redir = redir->next;
2223 redir = xmalloc(sizeof(struct redir_struct));
2225 redir->word.gl_pathv = NULL;
2227 last_redir->next = redir;
2229 child->redirects = redir;
2232 redir->type = style;
2233 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
2235 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2237 /* Check for a '2>&1' type redirect */
2238 redir->dup = redirect_dup_num(input);
2239 if (redir->dup == -2) return 1; /* syntax error */
2240 if (redir->dup != -1) {
2241 /* Erik had a check here that the file descriptor in question
2242 * is legit; I postpone that to "run time"
2243 * A "-" representation of "close me" shows up as a -3 here */
2244 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2246 /* We do _not_ try to open the file that src points to,
2247 * since we need to return and let src be expanded first.
2248 * Set ctx->pending_redirect, so we know what to do at the
2249 * end of the next parsed word.
2251 ctx->pending_redirect = redir;
2256 static struct pipe *new_pipe(void)
2259 pi = xmalloc(sizeof(struct pipe));
2263 pi->followup = 0; /* invalid */
2264 pi->r_mode = RES_NONE;
2268 static void initialize_context(struct p_context *ctx)
2271 ctx->pending_redirect = NULL;
2273 ctx->list_head = new_pipe();
2274 ctx->pipe = ctx->list_head;
2278 done_command(ctx); /* creates the memory for working child */
2281 /* normal return is 0
2282 * if a reserved word is found, and processed, return 1
2283 * should handle if, then, elif, else, fi, for, while, until, do, done.
2284 * case, function, and select are obnoxious, save those for later.
2286 static int reserved_word(o_string *dest, struct p_context *ctx)
2288 struct reserved_combo {
2293 /* Mostly a list of accepted follow-up reserved words.
2294 * FLAG_END means we are done with the sequence, and are ready
2295 * to turn the compound list into a command.
2296 * FLAG_START means the word must start a new compound list.
2298 static const struct reserved_combo reserved_list[] = {
2299 { "if", RES_IF, FLAG_THEN | FLAG_START },
2300 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2301 { "elif", RES_ELIF, FLAG_THEN },
2302 { "else", RES_ELSE, FLAG_FI },
2303 { "fi", RES_FI, FLAG_END },
2304 { "for", RES_FOR, FLAG_IN | FLAG_START },
2305 { "while", RES_WHILE, FLAG_DO | FLAG_START },
2306 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
2307 { "in", RES_IN, FLAG_DO },
2308 { "do", RES_DO, FLAG_DONE },
2309 { "done", RES_DONE, FLAG_END }
2311 enum { NRES = sizeof(reserved_list)/sizeof(reserved_list[0]) };
2312 const struct reserved_combo *r;
2314 for (r = reserved_list; r < reserved_list+NRES; r++) {
2315 if (strcmp(dest->data, r->literal) == 0) {
2316 debug_printf("found reserved word %s, code %d\n", r->literal, r->code);
2317 if (r->flag & FLAG_START) {
2318 struct p_context *new = xmalloc(sizeof(struct p_context));
2319 debug_printf("push stack\n");
2320 if (ctx->w == RES_IN || ctx->w == RES_FOR) {
2327 *new = *ctx; /* physical copy */
2328 initialize_context(ctx);
2330 } else if (ctx->w == RES_NONE || !(ctx->old_flag & (1 << r->code))) {
2337 ctx->old_flag = r->flag;
2338 if (ctx->old_flag & FLAG_END) {
2339 struct p_context *old;
2340 debug_printf("pop stack\n");
2341 done_pipe(ctx, PIPE_SEQ);
2343 old->child->group = ctx->list_head;
2344 old->child->subshell = 0;
2345 *ctx = *old; /* physical copy */
2355 /* normal return is 0.
2356 * Syntax or xglob errors return 1. */
2357 static int done_word(o_string *dest, struct p_context *ctx)
2359 struct child_prog *child = ctx->child;
2360 glob_t *glob_target;
2363 debug_printf("done_word: %s %p\n", dest->data, child);
2364 if (dest->length == 0 && !dest->nonnull) {
2365 debug_printf(" true null, ignored\n");
2368 if (ctx->pending_redirect) {
2369 glob_target = &ctx->pending_redirect->word;
2373 return 1; /* syntax error, groups and arglists don't mix */
2375 if (!child->argv && (ctx->type & FLAG_PARSE_SEMICOLON)) {
2376 debug_printf("checking %s for reserved-ness\n", dest->data);
2377 if (reserved_word(dest, ctx))
2378 return (ctx->w == RES_SNTX);
2380 glob_target = &child->glob_result;
2381 if (child->argv) flags |= GLOB_APPEND;
2383 gr = xglob(dest, flags, glob_target);
2384 if (gr != 0) return 1;
2387 if (ctx->pending_redirect) {
2388 ctx->pending_redirect = NULL;
2389 if (glob_target->gl_pathc != 1) {
2390 bb_error_msg("ambiguous redirect");
2394 child->argv = glob_target->gl_pathv;
2396 if (ctx->w == RES_FOR) {
2397 done_word(dest, ctx);
2398 done_pipe(ctx, PIPE_SEQ);
2403 /* The only possible error here is out of memory, in which case
2405 static int done_command(struct p_context *ctx)
2407 /* The child is really already in the pipe structure, so
2408 * advance the pipe counter and make a new, null child.
2409 * Only real trickiness here is that the uncommitted
2410 * child structure, to which ctx->child points, is not
2411 * counted in pi->num_progs. */
2412 struct pipe *pi = ctx->pipe;
2413 struct child_prog *prog = ctx->child;
2415 if (prog && prog->group == NULL
2416 && prog->argv == NULL
2417 && prog->redirects == NULL
2419 debug_printf("done_command: skipping null command\n");
2424 debug_printf("done_command: num_progs incremented to %d\n", pi->num_progs);
2426 debug_printf("done_command: initializing\n");
2428 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
2430 prog = pi->progs + pi->num_progs;
2431 prog->redirects = NULL;
2433 prog->is_stopped = 0;
2435 prog->glob_result.gl_pathv = NULL;
2439 prog->type = ctx->type;
2441 /* but ctx->pipe and ctx->list_head remain unchanged */
2445 static int done_pipe(struct p_context *ctx, pipe_style type)
2448 done_command(ctx); /* implicit closure of previous command */
2449 debug_printf("done_pipe, type %d\n", type);
2450 ctx->pipe->followup = type;
2451 ctx->pipe->r_mode = ctx->w;
2453 ctx->pipe->next = new_p;
2456 done_command(ctx); /* set up new pipe to accept commands */
2460 /* peek ahead in the in_str to find out if we have a "&n" construct,
2461 * as in "2>&1", that represents duplicating a file descriptor.
2462 * returns either -2 (syntax error), -1 (no &), or the number found.
2464 static int redirect_dup_num(struct in_str *input)
2466 int ch, d = 0, ok = 0;
2468 if (ch != '&') return -1;
2470 b_getch(input); /* get the & */
2474 return -3; /* "-" represents "close me" */
2476 while (isdigit(ch)) {
2477 d = d*10 + (ch-'0');
2484 bb_error_msg("ambiguous redirect");
2488 /* If a redirect is immediately preceded by a number, that number is
2489 * supposed to tell which file descriptor to redirect. This routine
2490 * looks for such preceding numbers. In an ideal world this routine
2491 * needs to handle all the following classes of redirects...
2492 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
2493 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
2494 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
2495 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
2496 * A -1 output from this program means no valid number was found, so the
2497 * caller should use the appropriate default for this redirection.
2499 static int redirect_opt_num(o_string *o)
2505 for (num = 0; num < o->length; num++) {
2506 if (!isdigit(*(o->data + num))) {
2510 /* reuse num (and save an int) */
2511 num = atoi(o->data);
2516 static FILE *generate_stream_from_list(struct pipe *head)
2519 int pid, channel[2];
2520 if (pipe(channel) < 0) bb_perror_msg_and_die("pipe");
2527 bb_perror_msg_and_die("fork");
2528 } else if (pid == 0) {
2530 if (channel[1] != 1) {
2531 dup2(channel[1], 1);
2534 _exit(run_list_real(head)); /* leaks memory */
2536 debug_printf("forked child %d\n", pid);
2538 pf = fdopen(channel[0], "r");
2539 debug_printf("pipe on FILE *%p\n", pf);
2543 /* this version hacked for testing purposes */
2544 /* return code is exit status of the process that is run. */
2545 static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end)
2548 o_string result = NULL_O_STRING;
2549 struct p_context inner;
2551 struct in_str pipe_str;
2552 initialize_context(&inner);
2554 /* recursion to generate command */
2555 retcode = parse_stream(&result, &inner, input, subst_end);
2556 if (retcode != 0) return retcode; /* syntax error or EOF */
2557 done_word(&result, &inner);
2558 done_pipe(&inner, PIPE_SEQ);
2561 p = generate_stream_from_list(inner.list_head);
2562 if (p == NULL) return 1;
2563 mark_open(fileno(p));
2564 setup_file_in_str(&pipe_str, p);
2566 /* now send results of command back into original context */
2567 retcode = parse_stream(dest, ctx, &pipe_str, '\0');
2568 /* XXX In case of a syntax error, should we try to kill the child?
2569 * That would be tough to do right, so just read until EOF. */
2571 while (b_getch(&pipe_str) != EOF)
2575 debug_printf("done reading from pipe, pclose()ing\n");
2576 /* This is the step that wait()s for the child. Should be pretty
2577 * safe, since we just read an EOF from its stdout. We could try
2578 * to better, by using wait(), and keeping track of background jobs
2579 * at the same time. That would be a lot of work, and contrary
2580 * to the KISS philosophy of this program. */
2581 mark_closed(fileno(p));
2582 retcode = pclose(p);
2583 free_pipe_list(inner.list_head, 0);
2584 debug_printf("pclosed, retcode=%d\n", retcode);
2585 /* XXX this process fails to trim a single trailing newline */
2589 static int parse_group(o_string *dest, struct p_context *ctx,
2590 struct in_str *input, int ch)
2592 int rcode, endch = 0;
2593 struct p_context sub;
2594 struct child_prog *child = ctx->child;
2597 return 1; /* syntax error, groups and arglists don't mix */
2599 initialize_context(&sub);
2603 child->subshell = 1;
2609 syntax(); /* really logic error */
2611 rcode = parse_stream(dest, &sub, input, endch);
2612 done_word(dest, &sub); /* finish off the final word in the subcontext */
2613 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
2614 child->group = sub.list_head;
2616 /* child remains "open", available for possible redirects */
2619 /* basically useful version until someone wants to get fancier,
2620 * see the bash man page under "Parameter Expansion" */
2621 static const char *lookup_param(const char *src)
2623 const char *p = NULL;
2627 p = get_local_var(src);
2632 /* Make new string for parser */
2633 static char* make_string(char ** inp)
2640 for (n = 0; inp[n]; n++) {
2641 p = insert_var_value(inp[n]);
2642 str = xrealloc(str, (len + strlen(p)));
2649 len = strlen(str) + 3;
2650 if (p != inp[n]) free(p);
2658 /* return code: 0 for OK, 1 for syntax error */
2659 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
2663 int ch = input->peek(input); /* first character after the $ */
2664 debug_printf("handle_dollar: ch=%c\n", ch);
2666 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2668 while (ch = b_peek(input), isalnum(ch) || ch == '_') {
2672 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2673 } else if (isdigit(ch)) {
2674 i = ch - '0'; /* XXX is $0 special? */
2675 if (i < global_argc) {
2676 parse_string(dest, ctx, global_argv[i]); /* recursion */
2679 } else switch (ch) {
2681 b_adduint(dest, getpid());
2685 if (last_bg_pid > 0) b_adduint(dest, last_bg_pid);
2689 b_adduint(dest, last_return_code);
2693 b_adduint(dest, global_argc ? global_argc-1 : 0);
2697 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2700 /* XXX maybe someone will try to escape the '}' */
2702 ch = b_getch(input);
2703 if (ch == EOF || ch == '}')
2711 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2715 process_command_subs(dest, ctx, input, ')');
2719 for (i = 1; i < global_argc; i++) {
2720 parse_string(dest, ctx, global_argv[i]);
2721 if (i+1 < global_argc)
2722 parse_string(dest, ctx, sep);
2728 /* still unhandled, but should be eventually */
2729 bb_error_msg("unhandled syntax: $%c", ch);
2733 b_addqchr(dest,'$', dest->quote);
2735 /* Eat the character if the flag was set. If the compiler
2736 * is smart enough, we could substitute "b_getch(input);"
2737 * for all the "advance = 1;" above, and also end up with
2738 * a nice size-optimized program. Hah! That'll be the day.
2740 if (advance) b_getch(input);
2744 static int parse_string(o_string *dest, struct p_context *ctx, const char *src)
2747 setup_string_in_str(&foo, src);
2748 return parse_stream(dest, ctx, &foo, '\0');
2751 /* return code is 0 for normal exit, 1 for syntax error */
2752 static int parse_stream(o_string *dest, struct p_context *ctx,
2753 struct in_str *input, int end_trigger)
2757 redir_type redir_style;
2760 /* Only double-quote state is handled in the state variable dest->quote.
2761 * A single-quote triggers a bypass of the main loop until its mate is
2762 * found. When recursing, quote state is passed in via dest->quote. */
2764 debug_printf("parse_stream, end_trigger=%d\n", end_trigger);
2765 while ((ch = b_getch(input)) != EOF) {
2767 next = (ch == '\n') ? 0 : b_peek(input);
2768 debug_printf("parse_stream: ch=%c (%d) m=%d quote=%d\n",
2769 ch, ch, m, dest->quote);
2770 if (m == 0 || ((m == 1 || m == 2) && dest->quote)) {
2771 b_addqchr(dest, ch, dest->quote);
2774 if (m == 2) { /* unquoted IFS */
2775 if (done_word(dest, ctx)) {
2778 /* If we aren't performing a substitution, treat a newline as a
2779 * command separator. */
2780 if (end_trigger != '\0' && ch == '\n')
2781 done_pipe(ctx, PIPE_SEQ);
2783 if (ch == end_trigger && !dest->quote && ctx->w == RES_NONE) {
2784 debug_printf("leaving parse_stream (triggered)\n");
2791 if (dest->length == 0 && !dest->quote) {
2794 if (ch == EOF || ch == '\n')
2799 b_addqchr(dest, ch, dest->quote);
2807 b_addqchr(dest, '\\', dest->quote);
2808 b_addqchr(dest, b_getch(input), dest->quote);
2811 if (handle_dollar(dest, ctx, input) != 0) return 1;
2816 ch = b_getch(input);
2817 if (ch == EOF || ch == '\'')
2828 dest->quote = !dest->quote;
2831 process_command_subs(dest, ctx, input, '`');
2834 redir_fd = redirect_opt_num(dest);
2835 done_word(dest, ctx);
2836 redir_style = REDIRECT_OVERWRITE;
2838 redir_style = REDIRECT_APPEND;
2840 } else if (next == '(') {
2841 syntax(); /* until we support >(list) Process Substitution */
2844 setup_redirect(ctx, redir_fd, redir_style, input);
2847 redir_fd = redirect_opt_num(dest);
2848 done_word(dest, ctx);
2849 redir_style = REDIRECT_INPUT;
2851 redir_style = REDIRECT_HEREIS;
2853 } else if (next == '>') {
2854 redir_style = REDIRECT_IO;
2856 } else if (next == '(') {
2857 syntax(); /* until we support <(list) Process Substitution */
2860 setup_redirect(ctx, redir_fd, redir_style, input);
2863 done_word(dest, ctx);
2864 done_pipe(ctx, PIPE_SEQ);
2867 done_word(dest, ctx);
2870 done_pipe(ctx, PIPE_AND);
2872 done_pipe(ctx, PIPE_BG);
2876 done_word(dest, ctx);
2879 done_pipe(ctx, PIPE_OR);
2881 /* we could pick up a file descriptor choice here
2882 * with redirect_opt_num(), but bash doesn't do it.
2883 * "echo foo 2| cat" yields "foo 2". */
2889 if (parse_group(dest, ctx, input, ch) != 0)
2894 syntax(); /* Proper use of this character caught by end_trigger */
2897 syntax(); /* this is really an internal logic error */
2901 /* complain if quote? No, maybe we just finished a command substitution
2902 * that was quoted. Example:
2903 * $ echo "`cat foo` plus more"
2904 * and we just got the EOF generated by the subshell that ran "cat foo"
2905 * The only real complaint is if we got an EOF when end_trigger != '\0',
2906 * that is, we were really supposed to get end_trigger, and never got
2907 * one before the EOF. Can't use the standard "syntax error" return code,
2908 * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
2909 debug_printf("leaving parse_stream (EOF)\n");
2910 if (end_trigger != '\0')
2915 static void mapset(const char *set, int code)
2918 map[(unsigned char)*set++] = code;
2921 static void update_ifs_map(void)
2923 /* char *ifs and char map[256] are both globals. */
2924 ifs = getenv("IFS");
2925 if (ifs == NULL) ifs = " \t\n";
2926 /* Precompute a list of 'flow through' behavior so it can be treated
2927 * quickly up front. Computation is necessary because of IFS.
2928 * Special case handling of IFS == " \t\n" is not implemented.
2929 * The map[] array only really needs two bits each, and on most machines
2930 * that would be faster because of the reduced L1 cache footprint.
2932 memset(map, 0, sizeof(map)); /* most characters flow through always */
2933 mapset("\\$'\"`", 3); /* never flow through */
2934 mapset("<>;&|(){}#", 1); /* flow through if quoted */
2935 mapset(ifs, 2); /* also flow through if quoted */
2938 /* most recursion does not come through here, the exception is
2939 * from builtin_source() */
2940 static int parse_stream_outer(struct in_str *inp, int flag)
2942 struct p_context ctx;
2943 o_string temp = NULL_O_STRING;
2947 initialize_context(&ctx);
2949 if (!(flag & FLAG_PARSE_SEMICOLON) || (flag & FLAG_REPARSING))
2951 inp->promptmode = 1;
2952 rcode = parse_stream(&temp, &ctx, inp, '\n');
2953 if (rcode != 1 && ctx.old_flag != 0) {
2956 if (rcode != 1 && ctx.old_flag == 0) {
2957 done_word(&temp, &ctx);
2958 done_pipe(&ctx, PIPE_SEQ);
2959 run_list(ctx.list_head);
2961 if (ctx.old_flag != 0) {
2968 free_pipe_list(ctx.list_head, 0);
2971 } while (rcode != -1 && !(flag & FLAG_EXIT_FROM_LOOP)); /* loop on syntax errors, return on EOF */
2975 static int parse_string_outer(const char *s, int flag)
2977 struct in_str input;
2978 setup_string_in_str(&input, s);
2979 return parse_stream_outer(&input, flag);
2982 static int parse_file_outer(FILE *f)
2985 struct in_str input;
2986 setup_file_in_str(&input, f);
2987 rcode = parse_stream_outer(&input, FLAG_PARSE_SEMICOLON);
2991 /* Make sure we have a controlling tty. If we get started under a job
2992 * aware app (like bash for example), make sure we are now in charge so
2993 * we don't fight over who gets the foreground */
2994 static void setup_job_control(void)
2998 saved_task_pgrp = shell_pgrp = getpgrp();
2999 debug_printf("saved_task_pgrp=%d\n", saved_task_pgrp);
3000 fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
3002 /* If we were ran as 'hush &',
3003 * sleep until we are in the foreground. */
3004 while (tcgetpgrp(interactive_fd) != shell_pgrp) {
3005 /* Send TTIN to ourself (will stop us) */
3006 kill(- shell_pgrp, SIGTTIN);
3007 shell_pgrp = getpgrp();
3010 /* Ignore job-control and misc signals. */
3011 set_jobctrl_sighandler(SIG_IGN);
3012 set_misc_sighandler(SIG_IGN);
3013 //huh? signal(SIGCHLD, SIG_IGN);
3015 /* We _must_ do cleanup on fatal signals */
3016 set_fatal_sighandler(sigexit);
3018 /* Put ourselves in our own process group. */
3019 shell_pgrp = getpid();
3020 setpgrp(); /* is the same as setpgid(shell_pgrp, shell_pgrp); */
3022 /* Grab control of the terminal. */
3023 tcsetpgrp(interactive_fd, shell_pgrp);
3025 signal_SA_RESTART(SIGTSTP, handler_ctrl_z);
3028 int hush_main(int argc, char **argv);
3029 int hush_main(int argc, char **argv)
3035 #if ENABLE_FEATURE_EDITING
3036 line_input_state = new_line_input_t(FOR_SHELL);
3039 /* XXX what should these be while sourcing /etc/profile? */
3043 /* (re?) initialize globals. Sometimes hush_main() ends up calling
3044 * hush_main(), therefore we cannot rely on the BSS to zero out this
3045 * stuff. Reset these to 0 every time. */
3047 /* map[] is taken care of with call to update_ifs_map() */
3050 close_me_head = NULL;
3055 /* Initialize some more globals to non-zero values */
3057 if (ENABLE_FEATURE_EDITING)
3058 cmdedit_set_initial_prompt();
3062 /* initialize our shell local variables with the values
3063 * currently living in the environment */
3067 set_local_var(*e++, 2); /* without call putenv() */
3069 last_return_code = EXIT_SUCCESS;
3071 if (argv[0] && argv[0][0] == '-') {
3072 debug_printf("\nsourcing /etc/profile\n");
3073 input = fopen("/etc/profile", "r");
3074 if (input != NULL) {
3075 mark_open(fileno(input));
3076 parse_file_outer(input);
3077 mark_closed(fileno(input));
3083 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
3086 global_argv = argv + optind;
3087 global_argc = argc - optind;
3088 opt = parse_string_outer(optarg, FLAG_PARSE_SEMICOLON);
3091 // Well, we cannot just declare interactiveness,
3092 // we have to have some stuff (ctty, etc)
3093 /*interactive_fd++;*/
3100 fprintf(stderr, "Usage: sh [FILE]...\n"
3101 " or: sh -c command [args]...\n\n");
3108 /* A shell is interactive if the '-i' flag was given, or if all of
3109 * the following conditions are met:
3111 * no arguments remaining or the -s flag given
3112 * standard input is a terminal
3113 * standard output is a terminal
3114 * Refer to Posix.2, the description of the 'sh' utility. */
3115 if (argv[optind] == NULL && input == stdin
3116 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3118 saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
3119 debug_printf("saved_tty_pgrp=%d\n", saved_tty_pgrp);
3120 if (saved_tty_pgrp >= 0) {
3121 /* try to dup to high fd#, >= 255 */
3122 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3123 if (interactive_fd < 0) {
3124 /* try to dup to any fd */
3125 interactive_fd = dup(STDIN_FILENO);
3126 if (interactive_fd < 0)
3130 // TODO: track & disallow any attempts of user
3131 // to (inadvertently) close/redirect it
3135 debug_printf("\ninteractive_fd=%d\n", interactive_fd);
3136 if (interactive_fd) {
3137 /* Looks like they want an interactive shell */
3138 setup_job_control();
3139 /* Make xfuncs do cleanup on exit */
3140 die_sleep = -1; /* flag */
3141 if (setjmp(die_jmp)) {
3142 /* xfunc has failed! die die die */
3143 hush_exit(xfunc_error_retval);
3145 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
3146 printf("\n\n%s hush - the humble shell v0.02\n", BB_BANNER);
3147 printf("Enter 'help' for a list of built-in commands.\n\n");
3151 if (argv[optind] == NULL) {
3152 opt = parse_file_outer(stdin);
3156 debug_printf("\nrunning script '%s'\n", argv[optind]);
3157 global_argv = argv + optind;
3158 global_argc = argc - optind;
3159 input = xfopen(argv[optind], "r");
3160 opt = parse_file_outer(input);
3162 #if ENABLE_FEATURE_CLEAN_UP
3164 if (cwd != bb_msg_unknown)
3167 struct variables *cur, *tmp;
3168 for (cur = top_vars; cur; cur = tmp) {
3170 if (!cur->flg_read_only) {
3171 free((char*)cur->name);
3172 free((char*)cur->value);
3180 hush_exit(opt ? opt : last_return_code);