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 void insert_bg_job(struct pipe *pi);
388 static void remove_bg_job(struct pipe *pi);
389 /* local variable support */
390 static char **make_list_in(char **inp, char *name);
391 static char *insert_var_value(char *inp);
392 static const char *get_local_var(const char *var);
393 static int set_local_var(const char *s, int flg_export);
394 static void unset_local_var(const char *name);
396 /* Table of built-in functions. They can be forked or not, depending on
397 * context: within pipes, they fork. As simple commands, they do not.
398 * When used in non-forking context, they can change global variables
399 * in the parent shell process. If forked, of course they cannot.
400 * For example, 'unset foo | whatever' will parse and run, but foo will
401 * still be set at the end. */
402 static const struct built_in_command bltins[] = {
403 { "bg", "Resume a job in the background", builtin_fg_bg },
404 { "break", "Exit for, while or until loop", builtin_not_written },
405 { "cd", "Change working directory", builtin_cd },
406 { "continue", "Continue for, while or until loop", builtin_not_written },
407 { "env", "Print all environment variables", builtin_env },
408 { "eval", "Construct and run shell command", builtin_eval },
409 { "exec", "Exec command, replacing this shell with the exec'd process",
411 { "exit", "Exit from shell()", builtin_exit },
412 { "export", "Set environment variable", builtin_export },
413 { "fg", "Bring job into the foreground", builtin_fg_bg },
414 { "jobs", "Lists the active jobs", builtin_jobs },
415 { "pwd", "Print current directory", builtin_pwd },
416 { "read", "Input environment variable", builtin_read },
417 { "return", "Return from a function", builtin_not_written },
418 { "set", "Set/unset shell local variables", builtin_set },
419 { "shift", "Shift positional parameters", builtin_shift },
420 { "trap", "Trap signals", builtin_not_written },
421 { "ulimit","Controls resource limits", builtin_not_written },
422 { "umask","Sets file creation mask", builtin_umask },
423 { "unset", "Unset environment variable", builtin_unset },
424 { ".", "Source-in and run commands in a file", builtin_source },
425 { "help", "List shell built-in commands", builtin_help },
429 /* Restores tty foreground process group, and exits.
430 * May be called as signal handler for fatal signal
431 * (will faithfully resend signal to itself, producing correct exit state)
432 * or called directly with -EXITCODE.
433 * We also call it if xfunc is exiting. */
434 static void sigexit(int sig) ATTRIBUTE_NORETURN;
435 static void sigexit(int sig)
439 /* Disable all signals: job control, SIGPIPE, etc. */
440 sigfillset(&block_all);
441 sigprocmask(SIG_SETMASK, &block_all, NULL);
444 tcsetpgrp(interactive_fd, saved_tty_pgrp);
446 /* Not a signal, just exit */
450 /* Enable only this sig and kill ourself with it */
451 signal(sig, SIG_DFL);
452 sigdelset(&block_all, sig);
453 sigprocmask(SIG_SETMASK, &block_all, NULL);
455 _exit(1); /* Should not reach it */
458 /* Restores tty foreground process group, and exits. */
459 static void hush_exit(int exitcode) ATTRIBUTE_NORETURN;
460 static void hush_exit(int exitcode)
462 fflush(NULL); /* flush all streams */
463 sigexit(- (exitcode & 0xff));
466 /* Signals are grouped, we handle them in batches */
467 static void set_fatal_sighandler(void (*handler)(int))
469 signal(SIGILL , handler);
470 signal(SIGTRAP, handler);
471 signal(SIGABRT, handler);
472 signal(SIGFPE , handler);
473 signal(SIGBUS , handler);
474 signal(SIGSEGV, handler);
475 /* bash 3.2 seems to handle these just like 'fatal' ones,
476 * but _without_ printing signal name. TODO: mimic this too? */
477 signal(SIGHUP , handler);
478 signal(SIGPIPE, handler);
479 signal(SIGALRM, handler);
481 static void set_jobctrl_sighandler(void (*handler)(int))
483 signal(SIGTSTP, handler);
484 signal(SIGTTIN, handler);
485 signal(SIGTTOU, handler);
487 static void set_misc_sighandler(void (*handler)(int))
489 signal(SIGINT , handler);
490 signal(SIGQUIT, handler);
491 signal(SIGTERM, handler);
493 /* SIGCHLD is special and handled separately */
495 static const char *set_cwd(void)
497 if (cwd == bb_msg_unknown)
498 cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
499 cwd = xrealloc_getcwd_or_warn((char *)cwd);
501 cwd = bb_msg_unknown;
505 /* built-in 'eval' handler */
506 static int builtin_eval(struct child_prog *child)
509 int rcode = EXIT_SUCCESS;
511 if (child->argv[1]) {
512 str = make_string(child->argv + 1);
513 parse_string_outer(str, FLAG_EXIT_FROM_LOOP |
514 FLAG_PARSE_SEMICOLON);
516 rcode = last_return_code;
521 /* built-in 'cd <path>' handler */
522 static int builtin_cd(struct child_prog *child)
525 if (child->argv[1] == NULL)
526 newdir = getenv("HOME");
528 newdir = child->argv[1];
530 printf("cd: %s: %s\n", newdir, strerror(errno));
537 /* built-in 'env' handler */
538 static int builtin_env(struct child_prog *dummy ATTRIBUTE_UNUSED)
540 /* TODO: call env applet's code instead */
550 /* built-in 'exec' handler */
551 static int builtin_exec(struct child_prog *child)
553 if (child->argv[1] == NULL)
554 return EXIT_SUCCESS; /* Really? */
560 /* built-in 'exit' handler */
561 static int builtin_exit(struct child_prog *child)
563 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
564 //puts("exit"); /* bash does it */
566 if (child->argv[1] == NULL)
567 hush_exit(last_return_code);
568 /* mimic bash: exit 123abc == exit 255 + error msg */
569 xfunc_error_retval = 255;
570 /* bash: exit -2 == exit 254, no error msg */
571 hush_exit(xatoi(child->argv[1]));
574 /* built-in 'export VAR=value' handler */
575 static int builtin_export(struct child_prog *child)
578 char *name = child->argv[1];
581 return builtin_env(child);
587 const char *value = strchr(name, '=');
591 /* They are exporting something without an =VALUE */
593 value = get_local_var(name);
595 size_t ln = strlen(name);
597 tmp = realloc(name, ln+strlen(value)+2);
601 sprintf(tmp+ln, "=%s", value);
605 /* bash does not return an error when trying to export
606 * an undefined variable. Do likewise. */
612 bb_perror_msg("export");
614 res = set_local_var(name, 1);
621 /* built-in 'fg' and 'bg' handler */
622 static int builtin_fg_bg(struct child_prog *child)
629 /* If they gave us no args, assume they want the last backgrounded task */
630 if (!child->argv[1]) {
631 for (pi = job_list; pi; pi = pi->next) {
632 if (pi->jobid == last_jobid) {
636 bb_error_msg("%s: no current job", child->argv[0]);
639 if (sscanf(child->argv[1], "%%%d", &jobnum) != 1) {
640 bb_error_msg("%s: bad argument '%s'", child->argv[0], child->argv[1]);
643 for (pi = job_list; pi; pi = pi->next) {
644 if (pi->jobid == jobnum) {
648 bb_error_msg("%s: %d: no such job", child->argv[0], jobnum);
651 if (*child->argv[0] == 'f') {
652 /* Put the job into the foreground. */
653 tcsetpgrp(interactive_fd, pi->pgrp);
656 /* Restart the processes in the job */
657 for (i = 0; i < pi->num_progs; i++)
658 pi->progs[i].is_stopped = 0;
660 i = kill(- pi->pgrp, SIGCONT);
662 if (errno == ESRCH) {
665 bb_perror_msg("kill (SIGCONT)");
669 pi->stopped_progs = 0;
673 /* built-in 'help' handler */
674 static int builtin_help(struct child_prog *dummy ATTRIBUTE_UNUSED)
676 const struct built_in_command *x;
678 printf("\nBuilt-in commands:\n");
679 printf("-------------------\n");
680 for (x = bltins; x->cmd; x++) {
681 if (x->descr == NULL)
683 printf("%s\t%s\n", x->cmd, x->descr);
689 /* built-in 'jobs' handler */
690 static int builtin_jobs(struct child_prog *child ATTRIBUTE_UNUSED)
693 const char *status_string;
695 for (job = job_list; job; job = job->next) {
696 if (job->running_progs == job->stopped_progs)
697 status_string = "Stopped";
699 status_string = "Running";
701 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->text);
706 /* built-in 'pwd' handler */
707 static int builtin_pwd(struct child_prog *dummy ATTRIBUTE_UNUSED)
713 /* built-in 'read VAR' handler */
714 static int builtin_read(struct child_prog *child)
718 if (child->argv[1]) {
722 string[0] = '\0'; /* In case stdin has only EOF */
724 fgets(string, sizeof(string), stdin);
726 var = malloc(strlen(child->argv[1]) + strlen(string) + 2);
728 sprintf(var, "%s=%s", child->argv[1], string);
729 res = set_local_var(var, 0);
733 bb_perror_msg("read");
734 free(var); /* So not move up to avoid breaking errno */
737 do res = getchar(); while (res != '\n' && res != EOF);
741 /* built-in 'set VAR=value' handler */
742 static int builtin_set(struct child_prog *child)
744 char *temp = child->argv[1];
748 for (e = top_vars; e; e = e->next)
749 printf("%s=%s\n", e->name, e->value);
751 set_local_var(temp, 0);
757 /* Built-in 'shift' handler */
758 static int builtin_shift(struct child_prog *child)
761 if (child->argv[1]) {
762 n = atoi(child->argv[1]);
764 if (n >= 0 && n < global_argc) {
765 /* XXX This probably breaks $0 */
773 /* Built-in '.' handler (read-in and execute commands from file) */
774 static int builtin_source(struct child_prog *child)
779 if (child->argv[1] == NULL)
782 /* XXX search through $PATH is missing */
783 input = fopen(child->argv[1], "r");
785 bb_error_msg("cannot open '%s'", child->argv[1]);
789 /* Now run the file */
790 /* XXX argv and argc are broken; need to save old global_argv
791 * (pointer only is OK!) on this stack frame,
792 * set global_argv=child->argv+1, recurse, and restore. */
793 mark_open(fileno(input));
794 status = parse_file_outer(input);
795 mark_closed(fileno(input));
800 static int builtin_umask(struct child_prog *child)
803 const char *arg = child->argv[1];
806 new_umask = strtoul(arg, &end, 8);
807 if (*end != '\0' || end == arg) {
811 new_umask = umask(0);
812 printf("%.3o\n", (unsigned) new_umask);
818 /* built-in 'unset VAR' handler */
819 static int builtin_unset(struct child_prog *child)
821 /* bash returned already true */
822 unset_local_var(child->argv[1]);
826 static int builtin_not_written(struct child_prog *child)
828 printf("builtin_%s not written\n", child->argv[0]);
832 static int b_check_space(o_string *o, int len)
834 /* It would be easy to drop a more restrictive policy
835 * in here, such as setting a maximum string length */
836 if (o->length + len > o->maxlen) {
837 char *old_data = o->data;
838 /* assert(data == NULL || o->maxlen != 0); */
839 o->maxlen += max(2*len, B_CHUNK);
840 o->data = realloc(o->data, 1 + o->maxlen);
841 if (o->data == NULL) {
845 return o->data == NULL;
848 static int b_addchr(o_string *o, int ch)
850 debug_printf("b_addchr: %c %d %p\n", ch, o->length, o);
851 if (b_check_space(o, 1))
853 o->data[o->length] = ch;
855 o->data[o->length] = '\0';
859 static void b_reset(o_string *o)
867 static void b_free(o_string *o)
875 /* My analysis of quoting semantics tells me that state information
876 * is associated with a destination, not a source.
878 static int b_addqchr(o_string *o, int ch, int quote)
880 if (quote && strchr("*?[\\", ch)) {
882 rc = b_addchr(o, '\\');
886 return b_addchr(o, ch);
889 static int b_adduint(o_string *o, unsigned i)
892 char buf[sizeof(unsigned)*3 + 1];
894 *(utoa_to_buf(i, buf, sizeof(buf))) = '\0';
895 /* no escape checking necessary */
896 do r = b_addchr(o, *p++); while (r == 0 && *p);
900 static int static_get(struct in_str *i)
903 if (ch == '\0') return EOF;
907 static int static_peek(struct in_str *i)
912 static void cmdedit_set_initial_prompt(void)
914 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
923 static const char* setup_prompt_string(int promptmode)
925 const char *prompt_str;
926 debug_printf("setup_prompt_string %d ", promptmode);
927 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
928 /* Set up the prompt */
929 if (promptmode == 1) {
932 ns = xmalloc(strlen(cwd)+4);
933 sprintf(ns, "%s %s", cwd, (geteuid() != 0) ? "$ " : "# ");
940 prompt_str = (promptmode == 1) ? PS1 : PS2;
942 debug_printf("result %s\n", prompt_str);
946 #if ENABLE_FEATURE_EDITING
947 static line_input_t *line_input_state;
950 static void get_user_input(struct in_str *i)
952 const char *prompt_str;
953 static char the_command[BUFSIZ];
955 prompt_str = setup_prompt_string(i->promptmode);
956 #if ENABLE_FEATURE_EDITING
958 ** enable command line editing only while a command line
959 ** is actually being read; otherwise, we'll end up bequeathing
960 ** atexit() handlers and other unwanted stuff to our
961 ** child processes (rob@sysgo.de)
963 read_line_input(prompt_str, the_command, BUFSIZ, line_input_state);
965 fputs(prompt_str, stdout);
967 the_command[0] = fgetc(i->file);
968 the_command[1] = '\0';
974 /* This is the magic location that prints prompts
975 * and gets data back from the user */
976 static int file_get(struct in_str *i)
981 /* If there is data waiting, eat it up */
985 /* need to double check i->file because we might be doing something
986 * more complicated by now, like sourcing or substituting. */
987 if (i->__promptme && interactive_fd && i->file == stdin) {
988 while (!i->p || !(interactive_fd && strlen(i->p))) {
1000 debug_printf("b_getch: got a %d\n", ch);
1007 /* All the callers guarantee this routine will never be
1008 * used right after a newline, so prompting is not needed.
1010 static int file_peek(struct in_str *i)
1012 if (i->p && *i->p) {
1015 i->peek_buf[0] = fgetc(i->file);
1016 i->peek_buf[1] = '\0';
1018 debug_printf("b_peek: got a %d\n", *i->p);
1022 static void setup_file_in_str(struct in_str *i, FILE *f)
1024 i->peek = file_peek;
1032 static void setup_string_in_str(struct in_str *i, const char *s)
1034 i->peek = static_peek;
1035 i->get = static_get;
1041 static void mark_open(int fd)
1043 struct close_me *new = xmalloc(sizeof(struct close_me));
1045 new->next = close_me_head;
1046 close_me_head = new;
1049 static void mark_closed(int fd)
1051 struct close_me *tmp;
1052 if (close_me_head == NULL || close_me_head->fd != fd)
1053 bb_error_msg_and_die("corrupt close_me");
1054 tmp = close_me_head;
1055 close_me_head = close_me_head->next;
1059 static void close_all(void)
1062 for (c = close_me_head; c; c = c->next) {
1065 close_me_head = NULL;
1068 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
1069 * and stderr if they are redirected. */
1070 static int setup_redirects(struct child_prog *prog, int squirrel[])
1073 struct redir_struct *redir;
1075 for (redir = prog->redirects; redir; redir = redir->next) {
1076 if (redir->dup == -1 && redir->word.gl_pathv == NULL) {
1077 /* something went wrong in the parse. Pretend it didn't happen */
1080 if (redir->dup == -1) {
1081 mode = redir_table[redir->type].mode;
1082 openfd = open_or_warn(redir->word.gl_pathv[0], mode);
1084 /* this could get lost if stderr has been redirected, but
1085 bash and ash both lose it as well (though zsh doesn't!) */
1089 openfd = redir->dup;
1092 if (openfd != redir->fd) {
1093 if (squirrel && redir->fd < 3) {
1094 squirrel[redir->fd] = dup(redir->fd);
1099 dup2(openfd, redir->fd);
1100 if (redir->dup == -1)
1108 static void restore_redirects(int squirrel[])
1111 for (i = 0; i < 3; i++) {
1114 /* No error checking. I sure wouldn't know what
1115 * to do with an error if I found one! */
1123 /* XXX no exit() here. If you don't exec, use _exit instead.
1124 * The at_exit handlers apparently confuse the calling process,
1125 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
1126 static void pseudo_exec(struct child_prog *child)
1130 const struct built_in_command *x;
1133 for (i = 0; is_assignment(child->argv[i]); i++) {
1134 debug_printf("pid %d environment modification: %s\n",
1135 getpid(), child->argv[i]);
1136 // FIXME: vfork case??
1137 p = insert_var_value(child->argv[i]);
1139 if (p != child->argv[i])
1142 child->argv += i; /* XXX this hack isn't so horrible, since we are about
1143 to exit, and therefore don't need to keep data
1144 structures consistent for free() use. */
1145 // FIXME: ...unless we have _vforked_! Think NOMMU!
1147 /* If a variable is assigned in a forest, and nobody listens,
1148 * was it ever really set?
1150 if (child->argv[0] == NULL) {
1151 _exit(EXIT_SUCCESS);
1155 * Check if the command matches any of the builtins.
1156 * Depending on context, this might be redundant. But it's
1157 * easier to waste a few CPU cycles than it is to figure out
1158 * if this is one of those cases.
1160 for (x = bltins; x->cmd; x++) {
1161 if (strcmp(child->argv[0], x->cmd) == 0) {
1162 debug_printf("builtin exec %s\n", child->argv[0]);
1163 rcode = x->function(child);
1169 /* Check if the command matches any busybox internal commands
1171 * FIXME: This feature is not 100% safe, since
1172 * BusyBox is not fully reentrant, so we have no guarantee the things
1173 * from the .bss are still zeroed, or that things from .data are still
1174 * at their defaults. We could exec ourself from /proc/self/exe, but I
1175 * really dislike relying on /proc for things. We could exec ourself
1176 * from global_argv[0], but if we are in a chroot, we may not be able
1177 * to find ourself... */
1178 #if ENABLE_FEATURE_SH_STANDALONE
1179 debug_printf("running applet %s\n", child->argv[0]);
1180 run_applet_and_exit(child->argv[0], child->argv);
1181 // is it ok that run_applet_and_exit() does exit(), not _exit()?
1182 // NB: IIRC on NOMMU we are after _vfork_, not fork!
1184 debug_printf("exec of %s\n", child->argv[0]);
1185 execvp(child->argv[0], child->argv);
1186 bb_perror_msg("cannot exec '%s'", child->argv[0]);
1191 debug_printf("runtime nesting to group\n");
1192 // FIXME: do not modify globals! Think vfork!
1193 interactive_fd = 0; /* crucial!!!! */
1194 rcode = run_list_real(child->group);
1195 /* OK to leak memory by not calling free_pipe_list,
1196 * since this process is about to exit */
1200 /* Can happen. See what bash does with ">foo" by itself. */
1201 debug_printf("trying to pseudo_exec null command\n");
1202 _exit(EXIT_SUCCESS);
1205 static void insert_bg_job(struct pipe *pi)
1207 struct pipe *thejob;
1209 /* Linear search for the ID of the job to use */
1211 for (thejob = job_list; thejob; thejob = thejob->next)
1212 if (thejob->jobid >= pi->jobid)
1213 pi->jobid = thejob->jobid + 1;
1215 /* add thejob to the list of running jobs */
1217 thejob = job_list = xmalloc(sizeof(*thejob));
1219 for (thejob = job_list; thejob->next; thejob = thejob->next)
1221 thejob->next = xmalloc(sizeof(*thejob));
1222 thejob = thejob->next;
1225 /* physically copy the struct job */
1226 memcpy(thejob, pi, sizeof(struct pipe));
1227 thejob->next = NULL;
1228 thejob->running_progs = thejob->num_progs;
1229 thejob->stopped_progs = 0;
1230 thejob->text = xmalloc(BUFSIZ); /* cmdedit buffer size */
1232 //if (pi->progs[0] && pi->progs[0].argv && pi->progs[0].argv[0])
1234 char *bar = thejob->text;
1235 char **foo = pi->progs[0].argv;
1238 bar += sprintf(bar, "%s ", *foo++);
1241 /* we don't wait for background thejobs to return -- append it
1242 to the list of backgrounded thejobs and leave it alone */
1243 printf("[%d] %d\n", thejob->jobid, thejob->progs[0].pid);
1244 last_bg_pid = thejob->progs[0].pid;
1245 last_jobid = thejob->jobid;
1248 /* remove a backgrounded job */
1249 static void remove_bg_job(struct pipe *pi)
1251 struct pipe *prev_pipe;
1253 if (pi == job_list) {
1254 job_list = pi->next;
1256 prev_pipe = job_list;
1257 while (prev_pipe->next != pi)
1258 prev_pipe = prev_pipe->next;
1259 prev_pipe->next = pi->next;
1262 last_jobid = job_list->jobid;
1266 pi->stopped_progs = 0;
1271 /* Checks to see if any processes have exited -- if they
1272 have, figure out why and see if a job has completed */
1273 static int checkjobs(struct pipe* fg_pipe)
1282 attributes = WUNTRACED;
1283 //WUNTRACED?? huh, what will happed on Ctrl-Z? fg waiting code
1284 //doesn't seem to be ready for stopped children! (only exiting ones)...
1285 if (fg_pipe == NULL) {
1286 attributes |= WNOHANG;
1290 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
1291 /* Were we asked to wait for fg pipe? */
1294 for (i = 0; i < fg_pipe->num_progs; i++) {
1295 if (fg_pipe->progs[i].pid == childpid) {
1296 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
1297 fg_pipe->progs[i].pid = 0;
1298 if (i == fg_pipe->num_progs-1)
1299 /* last process gives overall exitstatus */
1300 rcode = WEXITSTATUS(status);
1301 if (--fg_pipe->running_progs <= 0)
1302 /* All processes in fg pipe have exited */
1304 /* There are still running processes in the fg pipe */
1310 /* We asked to wait for bg or orphaned children */
1311 /* No need to remember exitcode in this case */
1313 for (pi = job_list; pi; pi = pi->next) {
1315 while (prognum < pi->num_progs) {
1316 if (pi->progs[prognum].pid == childpid)
1317 goto found_pi_and_prognum;
1322 /* Happens when shell is used as init process (init=/bin/sh) */
1323 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
1326 found_pi_and_prognum:
1327 if (WIFEXITED(status) || WIFSIGNALED(status)) {
1329 pi->running_progs--;
1330 pi->progs[prognum].pid = 0;
1332 if (!pi->running_progs) {
1333 printf(JOB_STATUS_FORMAT, pi->jobid,
1339 pi->stopped_progs++;
1340 pi->progs[prognum].is_stopped = 1;
1344 if (childpid == -1 && errno != ECHILD)
1345 bb_perror_msg("waitpid");
1347 /* move the shell to the foreground */
1348 //if (interactive_fd && tcsetpgrp(interactive_fd, getpgid(0)))
1349 // bb_perror_msg("tcsetpgrp-2");
1353 /* run_pipe_real() starts all the jobs, but doesn't wait for anything
1354 * to finish. See checkjobs().
1356 * return code is normally -1, when the caller has to wait for children
1357 * to finish to determine the exit status of the pipe. If the pipe
1358 * is a simple builtin command, however, the action is done by the
1359 * time run_pipe_real returns, and the exit code is provided as the
1362 * The input of the pipe is always stdin, the output is always
1363 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1364 * because it tries to avoid running the command substitution in
1365 * subshell, when that is in fact necessary. The subshell process
1366 * now has its stdout directed to the input of the appropriate pipe,
1367 * so this routine is noticeably simpler.
1369 static int run_pipe_real(struct pipe *pi)
1372 int nextin, nextout;
1373 int pipefds[2]; /* pipefds[0] is for reading */
1374 struct child_prog *child;
1375 const struct built_in_command *x;
1377 /* it is not always needed, but we aim to smaller code */
1378 int squirrel[] = { -1, -1, -1 };
1384 /* Check if this is a simple builtin (not part of a pipe).
1385 * Builtins within pipes have to fork anyway, and are handled in
1386 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1388 child = &(pi->progs[0]);
1389 if (pi->num_progs == 1 && child->group && child->subshell == 0) {
1390 debug_printf("non-subshell grouping\n");
1391 setup_redirects(child, squirrel);
1392 /* XXX could we merge code with following builtin case,
1393 * by creating a pseudo builtin that calls run_list_real? */
1394 rcode = run_list_real(child->group);
1395 restore_redirects(squirrel);
1399 if (pi->num_progs == 1 && pi->progs[0].argv != NULL) {
1400 for (i = 0; is_assignment(child->argv[i]); i++)
1402 if (i != 0 && child->argv[i] == NULL) {
1403 /* assignments, but no command: set the local environment */
1404 for (i = 0; child->argv[i] != NULL; i++) {
1405 /* Ok, this case is tricky. We have to decide if this is a
1406 * local variable, or an already exported variable. If it is
1407 * already exported, we have to export the new value. If it is
1408 * not exported, we need only set this as a local variable.
1409 * This junk is all to decide whether or not to export this
1413 name = xstrdup(child->argv[i]);
1414 debug_printf("Local environment set: %s\n", name);
1415 value = strchr(name, '=');
1418 if (get_local_var(name)) {
1422 p = insert_var_value(child->argv[i]);
1423 set_local_var(p, export_me);
1424 if (p != child->argv[i])
1427 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1429 for (i = 0; is_assignment(child->argv[i]); i++) {
1430 p = insert_var_value(child->argv[i]);
1432 if (p != child->argv[i]) {
1440 str = make_string(child->argv + i);
1441 parse_string_outer(str, FLAG_EXIT_FROM_LOOP | FLAG_REPARSING);
1443 return last_return_code;
1445 for (x = bltins; x->cmd; x++) {
1446 if (strcmp(child->argv[i], x->cmd) == 0) {
1447 if (x->function == builtin_exec && child->argv[i+1] == NULL) {
1448 debug_printf("magic exec\n");
1449 setup_redirects(child, NULL);
1450 return EXIT_SUCCESS;
1452 debug_printf("builtin inline %s\n", child->argv[0]);
1453 /* XXX setup_redirects acts on file descriptors, not FILEs.
1454 * This is perfect for work that comes after exec().
1455 * Is it really safe for inline use? Experimentally,
1456 * things seem to work with glibc. */
1457 setup_redirects(child, squirrel);
1458 child->argv += i; /* XXX horrible hack */
1459 rcode = x->function(child);
1460 child->argv -= i; /* XXX restore hack so free() can work right */
1461 restore_redirects(squirrel);
1465 #if ENABLE_FEATURE_SH_STANDALONE
1467 // FIXME: applet runs like part of shell - for example, it ignores
1468 // SIGINT! Try to Ctrl-C out of "rm -i"... doesn't work
1469 const struct bb_applet *a = find_applet_by_name(child->argv[i]);
1470 if (a && a->nofork) {
1471 setup_redirects(child, squirrel);
1472 rcode = run_nofork_applet(a, child->argv + i);
1473 restore_redirects(squirrel);
1480 /* Disable job control signals for shell (parent) and
1481 * for initial child code after fork */
1482 set_jobctrl_sighandler(SIG_IGN);
1484 pi->running_progs = 0;
1485 for (i = 0; i < pi->num_progs; i++) {
1486 child = &(pi->progs[i]);
1488 /* pipes are inserted between pairs of commands */
1489 if ((i + 1) < pi->num_progs) {
1490 if (pipe(pipefds) < 0)
1491 bb_perror_msg_and_die("pipe");
1492 nextout = pipefds[1];
1498 /* XXX test for failed fork()? */
1500 child->pid = fork();
1502 child->pid = vfork();
1504 if (!child->pid) { /* child */
1505 /* Every child adds itself to new process group
1506 * with pgid == pid of first child in pipe */
1507 if (interactive_fd) {
1508 if (pi->pgrp < 0) /* true for 1st process only */
1509 pi->pgrp = getpid();
1510 if (setpgid(0, pi->pgrp) == 0 && pi->followup != PIPE_BG) {
1511 /* We do it in *every* child, not just first,
1513 tcsetpgrp(interactive_fd, pi->pgrp);
1515 /* Don't do pgrp restore anymore on fatal signals */
1516 set_fatal_sighandler(SIG_DFL);
1528 if (pipefds[0] != -1) {
1529 close(pipefds[0]); /* opposite end of our output pipe */
1531 /* Like bash, explicit redirects override pipes,
1532 * and the pipe fd is available for dup'ing. */
1533 setup_redirects(child, NULL);
1535 /* Restore default handlers just prior to exec */
1536 set_jobctrl_sighandler(SIG_DFL);
1537 set_misc_sighandler(SIG_DFL);
1538 signal(SIGCHLD, SIG_DFL);
1542 pi->running_progs++;
1544 /* Second and next children need to know pid of first one */
1546 pi->pgrp = child->pid;
1548 /* Don't check for errors. The child may be dead already,
1549 * in which case setpgid returns error code EACCES. */
1550 //why we do it at all?? child does it itself
1551 //if (interactive_fd)
1552 // setpgid(child->pid, pi->pgrp);
1559 /* If there isn't another process, nextin is garbage
1560 but it doesn't matter */
1561 nextin = pipefds[0];
1566 static int run_list_real(struct pipe *pi)
1568 char *save_name = NULL;
1570 char **save_list = NULL;
1574 int rcode = 0, flag_skip = 1;
1575 int flag_restore = 0;
1576 int if_code = 0, next_if_code = 0; /* need double-buffer to handle elif */
1577 reserved_style rmode, skip_more_in_this_rmode = RES_XXXX;
1578 /* check syntax for "for" */
1579 for (rpipe = pi; rpipe; rpipe = rpipe->next) {
1580 if ((rpipe->r_mode == RES_IN || rpipe->r_mode == RES_FOR)
1581 && (rpipe->next == NULL)
1586 if ((rpipe->r_mode == RES_IN && rpipe->next->r_mode == RES_IN && rpipe->next->progs->argv != NULL)
1587 || (rpipe->r_mode == RES_FOR && rpipe->next->r_mode != RES_IN)
1593 for (; pi; pi = (flag_restore != 0) ? rpipe : pi->next) {
1594 if (pi->r_mode == RES_WHILE || pi->r_mode == RES_UNTIL
1595 || pi->r_mode == RES_FOR
1604 debug_printf("rmode=%d if_code=%d next_if_code=%d skip_more=%d\n",
1605 rmode, if_code, next_if_code, skip_more_in_this_rmode);
1606 if (rmode == skip_more_in_this_rmode && flag_skip) {
1607 if (pi->followup == PIPE_SEQ)
1612 skip_more_in_this_rmode = RES_XXXX;
1613 if (rmode == RES_THEN || rmode == RES_ELSE)
1614 if_code = next_if_code;
1615 if (rmode == RES_THEN && if_code)
1617 if (rmode == RES_ELSE && !if_code)
1619 if (rmode == RES_ELIF && !if_code)
1621 if (rmode == RES_FOR && pi->num_progs) {
1623 /* if no variable values after "in" we skip "for" */
1624 if (!pi->next->progs->argv)
1626 /* create list of variable values */
1627 list = make_list_in(pi->next->progs->argv,
1628 pi->progs->argv[0]);
1630 save_name = pi->progs->argv[0];
1631 pi->progs->argv[0] = NULL;
1635 free(pi->progs->argv[0]);
1639 pi->progs->argv[0] = save_name;
1640 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
1643 /* insert new value from list for variable */
1644 if (pi->progs->argv[0])
1645 free(pi->progs->argv[0]);
1646 pi->progs->argv[0] = *list++;
1647 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
1649 if (rmode == RES_IN)
1651 if (rmode == RES_DO) {
1655 if (rmode == RES_DONE) {
1662 if (pi->num_progs == 0)
1664 save_num_progs = pi->num_progs; /* save number of programs */
1665 rcode = run_pipe_real(pi);
1666 debug_printf("run_pipe_real returned %d\n", rcode);
1668 /* We only ran a builtin: rcode was set by the return value
1669 * of run_pipe_real(), and we don't need to wait for anything. */
1670 } else if (pi->followup == PIPE_BG) {
1671 /* XXX check bash's behavior with nontrivial pipes */
1672 /* XXX compute jobid */
1673 /* XXX what does bash do with attempts to background builtins? */
1675 rcode = EXIT_SUCCESS;
1677 if (interactive_fd) {
1679 rcode = checkjobs(pi);
1680 /* move the shell to the foreground */
1682 if (tcsetpgrp(interactive_fd, p) && errno != ENOTTY)
1683 bb_perror_msg("tcsetpgrp-4");
1684 debug_printf("getpgid(0)=%d\n", (int)p);
1686 rcode = checkjobs(pi);
1688 debug_printf("checkjobs returned %d\n", rcode);
1690 last_return_code = rcode;
1691 pi->num_progs = save_num_progs; /* restore number of programs */
1692 if (rmode == RES_IF || rmode == RES_ELIF)
1693 next_if_code = rcode; /* can be overwritten a number of times */
1694 if (rmode == RES_WHILE)
1695 flag_rep = !last_return_code;
1696 if (rmode == RES_UNTIL)
1697 flag_rep = last_return_code;
1698 if ((rcode == EXIT_SUCCESS && pi->followup == PIPE_OR)
1699 || (rcode != EXIT_SUCCESS && pi->followup == PIPE_AND)
1701 skip_more_in_this_rmode = rmode;
1708 /* return code is the exit status of the pipe */
1709 static int free_pipe(struct pipe *pi, int indent)
1712 struct child_prog *child;
1713 struct redir_struct *r, *rnext;
1714 int a, i, ret_code = 0;
1716 if (pi->stopped_progs > 0)
1718 final_printf("%s run pipe: (pid %d)\n", indenter(indent), getpid());
1719 for (i = 0; i < pi->num_progs; i++) {
1720 child = &pi->progs[i];
1721 final_printf("%s command %d:\n", indenter(indent), i);
1723 for (a = 0, p = child->argv; *p; a++, p++) {
1724 final_printf("%s argv[%d] = %s\n", indenter(indent), a, *p);
1726 globfree(&child->glob_result);
1728 } else if (child->group) {
1729 final_printf("%s begin group (subshell:%d)\n", indenter(indent), child->subshell);
1730 ret_code = free_pipe_list(child->group, indent+3);
1731 final_printf("%s end group\n", indenter(indent));
1733 final_printf("%s (nil)\n", indenter(indent));
1735 for (r = child->redirects; r; r = rnext) {
1736 final_printf("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->type].descrip);
1738 /* guard against the case >$FOO, where foo is unset or blank */
1739 if (r->word.gl_pathv) {
1740 final_printf(" %s\n", *r->word.gl_pathv);
1744 final_printf("&%d\n", r->dup);
1749 child->redirects = NULL;
1751 free(pi->progs); /* children are an array, they get freed all at once */
1756 static int free_pipe_list(struct pipe *head, int indent)
1758 int rcode = 0; /* if list has no members */
1759 struct pipe *pi, *next;
1760 for (pi = head; pi; pi = next) {
1761 final_printf("%s pipe reserved mode %d\n", indenter(indent), pi->r_mode);
1762 rcode = free_pipe(pi, indent);
1763 final_printf("%s pipe followup code %d\n", indenter(indent), pi->followup);
1765 /*pi->next = NULL;*/
1771 /* Select which version we will use */
1772 static int run_list(struct pipe *pi)
1775 if (fake_mode == 0) {
1776 rcode = run_list_real(pi);
1778 /* free_pipe_list has the side effect of clearing memory
1779 * In the long run that function can be merged with run_list_real,
1780 * but doing that now would hobble the debugging effort. */
1781 free_pipe_list(pi,0);
1785 /* The API for glob is arguably broken. This routine pushes a non-matching
1786 * string into the output structure, removing non-backslashed backslashes.
1787 * If someone can prove me wrong, by performing this function within the
1788 * original glob(3) api, feel free to rewrite this routine into oblivion.
1789 * Return code (0 vs. GLOB_NOSPACE) matches glob(3).
1790 * XXX broken if the last character is '\\', check that before calling.
1792 static int globhack(const char *src, int flags, glob_t *pglob)
1797 for (cnt = 1, s = src; s && *s; s++) {
1798 if (*s == '\\') s++;
1803 return GLOB_NOSPACE;
1804 if (!(flags & GLOB_APPEND)) {
1805 pglob->gl_pathv = NULL;
1806 pglob->gl_pathc = 0;
1810 pathc = ++pglob->gl_pathc;
1811 pglob->gl_pathv = realloc(pglob->gl_pathv, (pathc+1)*sizeof(*pglob->gl_pathv));
1812 if (pglob->gl_pathv == NULL)
1813 return GLOB_NOSPACE;
1814 pglob->gl_pathv[pathc-1] = dest;
1815 pglob->gl_pathv[pathc] = NULL;
1816 for (s = src; s && *s; s++, dest++) {
1817 if (*s == '\\') s++;
1824 /* XXX broken if the last character is '\\', check that before calling */
1825 static int glob_needed(const char *s)
1828 if (*s == '\\') s++;
1829 if (strchr("*[?", *s)) return 1;
1834 static int xglob(o_string *dest, int flags, glob_t *pglob)
1838 /* short-circuit for null word */
1839 /* we can code this better when the debug_printf's are gone */
1840 if (dest->length == 0) {
1841 if (dest->nonnull) {
1842 /* bash man page calls this an "explicit" null */
1843 gr = globhack(dest->data, flags, pglob);
1844 debug_printf("globhack returned %d\n", gr);
1848 } else if (glob_needed(dest->data)) {
1849 gr = glob(dest->data, flags, NULL, pglob);
1850 debug_printf("glob returned %d\n", gr);
1851 if (gr == GLOB_NOMATCH) {
1852 /* quote removal, or more accurately, backslash removal */
1853 gr = globhack(dest->data, flags, pglob);
1854 debug_printf("globhack returned %d\n", gr);
1857 gr = globhack(dest->data, flags, pglob);
1858 debug_printf("globhack returned %d\n", gr);
1860 if (gr == GLOB_NOSPACE)
1861 bb_error_msg_and_die("out of memory during glob");
1862 if (gr != 0) { /* GLOB_ABORTED ? */
1863 bb_error_msg("glob(3) error %d", gr);
1865 /* globprint(glob_target); */
1869 static char **make_list_in(char **inp, char *name)
1872 int name_len = strlen(name);
1877 /* create list of variable values */
1878 list = xmalloc(sizeof(*list));
1879 for (i = 0; inp[i]; i++) {
1880 p3 = insert_var_value(inp[i]);
1887 p2 = strchr(p1, ' ');
1894 /* we use n + 2 in realloc for list, because we add
1895 * new element and then we will add NULL element */
1896 list = xrealloc(list, sizeof(*list) * (n + 2));
1897 list[n] = xmalloc(2 + name_len + len);
1898 strcpy(list[n], name);
1899 strcat(list[n], "=");
1900 strncat(list[n], p1, len);
1901 list[n++][name_len + len + 1] = '\0';
1904 if (p3 != inp[i]) free(p3);
1910 static char *insert_var_value(char *inp)
1912 int res_str_len = 0;
1915 char *p, *res_str = NULL;
1918 while ((p = strchr(inp, SPECIAL_VAR_SYMBOL))) {
1921 res_str = xrealloc(res_str, (res_str_len + len));
1922 strncpy((res_str + res_str_len), inp, len);
1926 p = strchr(inp, SPECIAL_VAR_SYMBOL);
1928 p1 = lookup_param(inp);
1930 len = res_str_len + strlen(p1);
1931 res_str = xrealloc(res_str, (1 + len));
1932 strcpy((res_str + res_str_len), p1);
1935 *p = SPECIAL_VAR_SYMBOL;
1940 res_str = xrealloc(res_str, (1 + res_str_len + strlen(inp)));
1941 strcpy((res_str + res_str_len), inp);
1942 while ((p = strchr(res_str, '\n'))) {
1946 return (res_str == NULL) ? inp : res_str;
1949 /* This is used to get/check local shell variables */
1950 static const char *get_local_var(const char *s)
1952 struct variables *cur;
1956 for (cur = top_vars; cur; cur = cur->next)
1957 if (strcmp(cur->name, s) == 0)
1962 /* This is used to set local shell variables
1963 flg_export == 0 if only local (not exporting) variable
1964 flg_export == 1 if "new" exporting environ
1965 flg_export > 1 if current startup environ (not call putenv()) */
1966 static int set_local_var(const char *s, int flg_export)
1970 struct variables *cur;
1974 /* Assume when we enter this function that we are already in
1975 * NAME=VALUE format. So the first order of business is to
1976 * split 's' on the '=' into 'name' and 'value' */
1977 value = strchr(name, '=');
1978 /*if (value == 0 && ++value == 0) ??? -vda */
1979 if (value == NULL || value[1] == '\0') {
1985 for (cur = top_vars; cur; cur = cur->next) {
1986 if (strcmp(cur->name, name) == 0)
1991 if (strcmp(cur->value, value) == 0) {
1992 if (flg_export > 0 && cur->flg_export == 0)
1993 cur->flg_export = flg_export;
1996 } else if (cur->flg_read_only) {
1997 bb_error_msg("%s: readonly variable", name);
2000 if (flg_export > 0 || cur->flg_export > 1)
2001 cur->flg_export = 1;
2002 free((char*)cur->value);
2004 cur->value = strdup(value);
2007 cur = malloc(sizeof(struct variables));
2011 cur->name = strdup(name);
2016 struct variables *bottom = top_vars;
2017 cur->value = strdup(value);
2019 cur->flg_export = flg_export;
2020 cur->flg_read_only = 0;
2021 while (bottom->next)
2022 bottom = bottom->next;
2028 if (result == 0 && cur->flg_export == 1) {
2030 result = putenv(name);
2033 if (result > 0) /* equivalent to previous set */
2039 static void unset_local_var(const char *name)
2041 struct variables *cur, *next;
2045 for (cur = top_vars; cur; cur = cur->next) {
2046 if (strcmp(cur->name, name) == 0) {
2047 if (cur->flg_read_only) {
2048 bb_error_msg("%s: readonly variable", name);
2051 if (cur->flg_export)
2052 unsetenv(cur->name);
2053 free((char*)cur->name);
2054 free((char*)cur->value);
2056 while (next->next != cur)
2058 next->next = cur->next;
2065 static int is_assignment(const char *s)
2067 if (!s || !isalpha(*s))
2070 while (isalnum(*s) || *s == '_')
2075 /* the src parameter allows us to peek forward to a possible &n syntax
2076 * for file descriptor duplication, e.g., "2>&1".
2077 * Return code is 0 normally, 1 if a syntax error is detected in src.
2078 * Resource errors (in xmalloc) cause the process to exit */
2079 static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2080 struct in_str *input)
2082 struct child_prog *child = ctx->child;
2083 struct redir_struct *redir = child->redirects;
2084 struct redir_struct *last_redir = NULL;
2086 /* Create a new redir_struct and drop it onto the end of the linked list */
2089 redir = redir->next;
2091 redir = xmalloc(sizeof(struct redir_struct));
2093 redir->word.gl_pathv = NULL;
2095 last_redir->next = redir;
2097 child->redirects = redir;
2100 redir->type = style;
2101 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
2103 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2105 /* Check for a '2>&1' type redirect */
2106 redir->dup = redirect_dup_num(input);
2107 if (redir->dup == -2) return 1; /* syntax error */
2108 if (redir->dup != -1) {
2109 /* Erik had a check here that the file descriptor in question
2110 * is legit; I postpone that to "run time"
2111 * A "-" representation of "close me" shows up as a -3 here */
2112 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2114 /* We do _not_ try to open the file that src points to,
2115 * since we need to return and let src be expanded first.
2116 * Set ctx->pending_redirect, so we know what to do at the
2117 * end of the next parsed word.
2119 ctx->pending_redirect = redir;
2124 static struct pipe *new_pipe(void)
2127 pi = xmalloc(sizeof(struct pipe));
2131 pi->followup = 0; /* invalid */
2132 pi->r_mode = RES_NONE;
2136 static void initialize_context(struct p_context *ctx)
2139 ctx->pending_redirect = NULL;
2141 ctx->list_head = new_pipe();
2142 ctx->pipe = ctx->list_head;
2146 done_command(ctx); /* creates the memory for working child */
2149 /* normal return is 0
2150 * if a reserved word is found, and processed, return 1
2151 * should handle if, then, elif, else, fi, for, while, until, do, done.
2152 * case, function, and select are obnoxious, save those for later.
2154 static int reserved_word(o_string *dest, struct p_context *ctx)
2156 struct reserved_combo {
2161 /* Mostly a list of accepted follow-up reserved words.
2162 * FLAG_END means we are done with the sequence, and are ready
2163 * to turn the compound list into a command.
2164 * FLAG_START means the word must start a new compound list.
2166 static const struct reserved_combo reserved_list[] = {
2167 { "if", RES_IF, FLAG_THEN | FLAG_START },
2168 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2169 { "elif", RES_ELIF, FLAG_THEN },
2170 { "else", RES_ELSE, FLAG_FI },
2171 { "fi", RES_FI, FLAG_END },
2172 { "for", RES_FOR, FLAG_IN | FLAG_START },
2173 { "while", RES_WHILE, FLAG_DO | FLAG_START },
2174 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
2175 { "in", RES_IN, FLAG_DO },
2176 { "do", RES_DO, FLAG_DONE },
2177 { "done", RES_DONE, FLAG_END }
2179 enum { NRES = sizeof(reserved_list)/sizeof(reserved_list[0]) };
2180 const struct reserved_combo *r;
2182 for (r = reserved_list; r < reserved_list+NRES; r++) {
2183 if (strcmp(dest->data, r->literal) == 0) {
2184 debug_printf("found reserved word %s, code %d\n", r->literal, r->code);
2185 if (r->flag & FLAG_START) {
2186 struct p_context *new = xmalloc(sizeof(struct p_context));
2187 debug_printf("push stack\n");
2188 if (ctx->w == RES_IN || ctx->w == RES_FOR) {
2195 *new = *ctx; /* physical copy */
2196 initialize_context(ctx);
2198 } else if (ctx->w == RES_NONE || !(ctx->old_flag & (1 << r->code))) {
2205 ctx->old_flag = r->flag;
2206 if (ctx->old_flag & FLAG_END) {
2207 struct p_context *old;
2208 debug_printf("pop stack\n");
2209 done_pipe(ctx, PIPE_SEQ);
2211 old->child->group = ctx->list_head;
2212 old->child->subshell = 0;
2213 *ctx = *old; /* physical copy */
2223 /* normal return is 0.
2224 * Syntax or xglob errors return 1. */
2225 static int done_word(o_string *dest, struct p_context *ctx)
2227 struct child_prog *child = ctx->child;
2228 glob_t *glob_target;
2231 debug_printf("done_word: %s %p\n", dest->data, child);
2232 if (dest->length == 0 && !dest->nonnull) {
2233 debug_printf(" true null, ignored\n");
2236 if (ctx->pending_redirect) {
2237 glob_target = &ctx->pending_redirect->word;
2241 return 1; /* syntax error, groups and arglists don't mix */
2243 if (!child->argv && (ctx->type & FLAG_PARSE_SEMICOLON)) {
2244 debug_printf("checking %s for reserved-ness\n", dest->data);
2245 if (reserved_word(dest, ctx))
2246 return (ctx->w == RES_SNTX);
2248 glob_target = &child->glob_result;
2249 if (child->argv) flags |= GLOB_APPEND;
2251 gr = xglob(dest, flags, glob_target);
2252 if (gr != 0) return 1;
2255 if (ctx->pending_redirect) {
2256 ctx->pending_redirect = NULL;
2257 if (glob_target->gl_pathc != 1) {
2258 bb_error_msg("ambiguous redirect");
2262 child->argv = glob_target->gl_pathv;
2264 if (ctx->w == RES_FOR) {
2265 done_word(dest, ctx);
2266 done_pipe(ctx, PIPE_SEQ);
2271 /* The only possible error here is out of memory, in which case
2273 static int done_command(struct p_context *ctx)
2275 /* The child is really already in the pipe structure, so
2276 * advance the pipe counter and make a new, null child.
2277 * Only real trickiness here is that the uncommitted
2278 * child structure, to which ctx->child points, is not
2279 * counted in pi->num_progs. */
2280 struct pipe *pi = ctx->pipe;
2281 struct child_prog *prog = ctx->child;
2283 if (prog && prog->group == NULL
2284 && prog->argv == NULL
2285 && prog->redirects == NULL
2287 debug_printf("done_command: skipping null command\n");
2292 debug_printf("done_command: num_progs incremented to %d\n", pi->num_progs);
2294 debug_printf("done_command: initializing\n");
2296 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
2298 prog = pi->progs + pi->num_progs;
2299 prog->redirects = NULL;
2301 prog->is_stopped = 0;
2303 prog->glob_result.gl_pathv = NULL;
2307 prog->type = ctx->type;
2309 /* but ctx->pipe and ctx->list_head remain unchanged */
2313 static int done_pipe(struct p_context *ctx, pipe_style type)
2316 done_command(ctx); /* implicit closure of previous command */
2317 debug_printf("done_pipe, type %d\n", type);
2318 ctx->pipe->followup = type;
2319 ctx->pipe->r_mode = ctx->w;
2321 ctx->pipe->next = new_p;
2324 done_command(ctx); /* set up new pipe to accept commands */
2328 /* peek ahead in the in_str to find out if we have a "&n" construct,
2329 * as in "2>&1", that represents duplicating a file descriptor.
2330 * returns either -2 (syntax error), -1 (no &), or the number found.
2332 static int redirect_dup_num(struct in_str *input)
2334 int ch, d = 0, ok = 0;
2336 if (ch != '&') return -1;
2338 b_getch(input); /* get the & */
2342 return -3; /* "-" represents "close me" */
2344 while (isdigit(ch)) {
2345 d = d*10 + (ch-'0');
2352 bb_error_msg("ambiguous redirect");
2356 /* If a redirect is immediately preceded by a number, that number is
2357 * supposed to tell which file descriptor to redirect. This routine
2358 * looks for such preceding numbers. In an ideal world this routine
2359 * needs to handle all the following classes of redirects...
2360 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
2361 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
2362 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
2363 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
2364 * A -1 output from this program means no valid number was found, so the
2365 * caller should use the appropriate default for this redirection.
2367 static int redirect_opt_num(o_string *o)
2373 for (num = 0; num < o->length; num++) {
2374 if (!isdigit(*(o->data + num))) {
2378 /* reuse num (and save an int) */
2379 num = atoi(o->data);
2384 static FILE *generate_stream_from_list(struct pipe *head)
2387 int pid, channel[2];
2388 if (pipe(channel) < 0) bb_perror_msg_and_die("pipe");
2395 bb_perror_msg_and_die("fork");
2396 } else if (pid == 0) {
2398 if (channel[1] != 1) {
2399 dup2(channel[1], 1);
2402 _exit(run_list_real(head)); /* leaks memory */
2404 debug_printf("forked child %d\n", pid);
2406 pf = fdopen(channel[0], "r");
2407 debug_printf("pipe on FILE *%p\n", pf);
2411 /* this version hacked for testing purposes */
2412 /* return code is exit status of the process that is run. */
2413 static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end)
2416 o_string result = NULL_O_STRING;
2417 struct p_context inner;
2419 struct in_str pipe_str;
2420 initialize_context(&inner);
2422 /* recursion to generate command */
2423 retcode = parse_stream(&result, &inner, input, subst_end);
2424 if (retcode != 0) return retcode; /* syntax error or EOF */
2425 done_word(&result, &inner);
2426 done_pipe(&inner, PIPE_SEQ);
2429 p = generate_stream_from_list(inner.list_head);
2430 if (p == NULL) return 1;
2431 mark_open(fileno(p));
2432 setup_file_in_str(&pipe_str, p);
2434 /* now send results of command back into original context */
2435 retcode = parse_stream(dest, ctx, &pipe_str, '\0');
2436 /* XXX In case of a syntax error, should we try to kill the child?
2437 * That would be tough to do right, so just read until EOF. */
2439 while (b_getch(&pipe_str) != EOF)
2443 debug_printf("done reading from pipe, pclose()ing\n");
2444 /* This is the step that wait()s for the child. Should be pretty
2445 * safe, since we just read an EOF from its stdout. We could try
2446 * to better, by using wait(), and keeping track of background jobs
2447 * at the same time. That would be a lot of work, and contrary
2448 * to the KISS philosophy of this program. */
2449 mark_closed(fileno(p));
2450 retcode = pclose(p);
2451 free_pipe_list(inner.list_head, 0);
2452 debug_printf("pclosed, retcode=%d\n", retcode);
2453 /* XXX this process fails to trim a single trailing newline */
2457 static int parse_group(o_string *dest, struct p_context *ctx,
2458 struct in_str *input, int ch)
2460 int rcode, endch = 0;
2461 struct p_context sub;
2462 struct child_prog *child = ctx->child;
2465 return 1; /* syntax error, groups and arglists don't mix */
2467 initialize_context(&sub);
2471 child->subshell = 1;
2477 syntax(); /* really logic error */
2479 rcode = parse_stream(dest, &sub, input, endch);
2480 done_word(dest, &sub); /* finish off the final word in the subcontext */
2481 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
2482 child->group = sub.list_head;
2484 /* child remains "open", available for possible redirects */
2487 /* basically useful version until someone wants to get fancier,
2488 * see the bash man page under "Parameter Expansion" */
2489 static const char *lookup_param(const char *src)
2491 const char *p = NULL;
2495 p = get_local_var(src);
2500 /* Make new string for parser */
2501 static char* make_string(char ** inp)
2508 for (n = 0; inp[n]; n++) {
2509 p = insert_var_value(inp[n]);
2510 str = xrealloc(str, (len + strlen(p)));
2517 len = strlen(str) + 3;
2518 if (p != inp[n]) free(p);
2526 /* return code: 0 for OK, 1 for syntax error */
2527 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
2531 int ch = input->peek(input); /* first character after the $ */
2532 debug_printf("handle_dollar: ch=%c\n", ch);
2534 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2536 while (ch = b_peek(input), isalnum(ch) || ch == '_') {
2540 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2541 } else if (isdigit(ch)) {
2542 i = ch - '0'; /* XXX is $0 special? */
2543 if (i < global_argc) {
2544 parse_string(dest, ctx, global_argv[i]); /* recursion */
2547 } else switch (ch) {
2549 b_adduint(dest, getpid());
2553 if (last_bg_pid > 0) b_adduint(dest, last_bg_pid);
2557 b_adduint(dest, last_return_code);
2561 b_adduint(dest, global_argc ? global_argc-1 : 0);
2565 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2568 /* XXX maybe someone will try to escape the '}' */
2570 ch = b_getch(input);
2571 if (ch == EOF || ch == '}')
2579 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2583 process_command_subs(dest, ctx, input, ')');
2587 for (i = 1; i < global_argc; i++) {
2588 parse_string(dest, ctx, global_argv[i]);
2589 if (i+1 < global_argc)
2590 parse_string(dest, ctx, sep);
2596 /* still unhandled, but should be eventually */
2597 bb_error_msg("unhandled syntax: $%c", ch);
2601 b_addqchr(dest,'$', dest->quote);
2603 /* Eat the character if the flag was set. If the compiler
2604 * is smart enough, we could substitute "b_getch(input);"
2605 * for all the "advance = 1;" above, and also end up with
2606 * a nice size-optimized program. Hah! That'll be the day.
2608 if (advance) b_getch(input);
2612 static int parse_string(o_string *dest, struct p_context *ctx, const char *src)
2615 setup_string_in_str(&foo, src);
2616 return parse_stream(dest, ctx, &foo, '\0');
2619 /* return code is 0 for normal exit, 1 for syntax error */
2620 static int parse_stream(o_string *dest, struct p_context *ctx,
2621 struct in_str *input, int end_trigger)
2625 redir_type redir_style;
2628 /* Only double-quote state is handled in the state variable dest->quote.
2629 * A single-quote triggers a bypass of the main loop until its mate is
2630 * found. When recursing, quote state is passed in via dest->quote. */
2632 debug_printf("parse_stream, end_trigger=%d\n", end_trigger);
2633 while ((ch = b_getch(input)) != EOF) {
2635 next = (ch == '\n') ? 0 : b_peek(input);
2636 debug_printf("parse_stream: ch=%c (%d) m=%d quote=%d\n",
2637 ch, ch, m, dest->quote);
2638 if (m == 0 || ((m == 1 || m == 2) && dest->quote)) {
2639 b_addqchr(dest, ch, dest->quote);
2642 if (m == 2) { /* unquoted IFS */
2643 if (done_word(dest, ctx)) {
2646 /* If we aren't performing a substitution, treat a newline as a
2647 * command separator. */
2648 if (end_trigger != '\0' && ch == '\n')
2649 done_pipe(ctx, PIPE_SEQ);
2651 if (ch == end_trigger && !dest->quote && ctx->w == RES_NONE) {
2652 debug_printf("leaving parse_stream (triggered)\n");
2659 if (dest->length == 0 && !dest->quote) {
2662 if (ch == EOF || ch == '\n')
2667 b_addqchr(dest, ch, dest->quote);
2675 b_addqchr(dest, '\\', dest->quote);
2676 b_addqchr(dest, b_getch(input), dest->quote);
2679 if (handle_dollar(dest, ctx, input) != 0) return 1;
2684 ch = b_getch(input);
2685 if (ch == EOF || ch == '\'')
2696 dest->quote = !dest->quote;
2699 process_command_subs(dest, ctx, input, '`');
2702 redir_fd = redirect_opt_num(dest);
2703 done_word(dest, ctx);
2704 redir_style = REDIRECT_OVERWRITE;
2706 redir_style = REDIRECT_APPEND;
2708 } else if (next == '(') {
2709 syntax(); /* until we support >(list) Process Substitution */
2712 setup_redirect(ctx, redir_fd, redir_style, input);
2715 redir_fd = redirect_opt_num(dest);
2716 done_word(dest, ctx);
2717 redir_style = REDIRECT_INPUT;
2719 redir_style = REDIRECT_HEREIS;
2721 } else if (next == '>') {
2722 redir_style = REDIRECT_IO;
2724 } else if (next == '(') {
2725 syntax(); /* until we support <(list) Process Substitution */
2728 setup_redirect(ctx, redir_fd, redir_style, input);
2731 done_word(dest, ctx);
2732 done_pipe(ctx, PIPE_SEQ);
2735 done_word(dest, ctx);
2738 done_pipe(ctx, PIPE_AND);
2740 done_pipe(ctx, PIPE_BG);
2744 done_word(dest, ctx);
2747 done_pipe(ctx, PIPE_OR);
2749 /* we could pick up a file descriptor choice here
2750 * with redirect_opt_num(), but bash doesn't do it.
2751 * "echo foo 2| cat" yields "foo 2". */
2757 if (parse_group(dest, ctx, input, ch) != 0)
2762 syntax(); /* Proper use of this character caught by end_trigger */
2765 syntax(); /* this is really an internal logic error */
2769 /* complain if quote? No, maybe we just finished a command substitution
2770 * that was quoted. Example:
2771 * $ echo "`cat foo` plus more"
2772 * and we just got the EOF generated by the subshell that ran "cat foo"
2773 * The only real complaint is if we got an EOF when end_trigger != '\0',
2774 * that is, we were really supposed to get end_trigger, and never got
2775 * one before the EOF. Can't use the standard "syntax error" return code,
2776 * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
2777 debug_printf("leaving parse_stream (EOF)\n");
2778 if (end_trigger != '\0')
2783 static void mapset(const char *set, int code)
2786 map[(unsigned char)*set++] = code;
2789 static void update_ifs_map(void)
2791 /* char *ifs and char map[256] are both globals. */
2792 ifs = getenv("IFS");
2793 if (ifs == NULL) ifs = " \t\n";
2794 /* Precompute a list of 'flow through' behavior so it can be treated
2795 * quickly up front. Computation is necessary because of IFS.
2796 * Special case handling of IFS == " \t\n" is not implemented.
2797 * The map[] array only really needs two bits each, and on most machines
2798 * that would be faster because of the reduced L1 cache footprint.
2800 memset(map, 0, sizeof(map)); /* most characters flow through always */
2801 mapset("\\$'\"`", 3); /* never flow through */
2802 mapset("<>;&|(){}#", 1); /* flow through if quoted */
2803 mapset(ifs, 2); /* also flow through if quoted */
2806 /* most recursion does not come through here, the exception is
2807 * from builtin_source() */
2808 static int parse_stream_outer(struct in_str *inp, int flag)
2810 struct p_context ctx;
2811 o_string temp = NULL_O_STRING;
2815 initialize_context(&ctx);
2817 if (!(flag & FLAG_PARSE_SEMICOLON) || (flag & FLAG_REPARSING))
2819 inp->promptmode = 1;
2820 rcode = parse_stream(&temp, &ctx, inp, '\n');
2821 if (rcode != 1 && ctx.old_flag != 0) {
2824 if (rcode != 1 && ctx.old_flag == 0) {
2825 done_word(&temp, &ctx);
2826 done_pipe(&ctx, PIPE_SEQ);
2827 run_list(ctx.list_head);
2829 if (ctx.old_flag != 0) {
2836 free_pipe_list(ctx.list_head, 0);
2839 } while (rcode != -1 && !(flag & FLAG_EXIT_FROM_LOOP)); /* loop on syntax errors, return on EOF */
2843 static int parse_string_outer(const char *s, int flag)
2845 struct in_str input;
2846 setup_string_in_str(&input, s);
2847 return parse_stream_outer(&input, flag);
2850 static int parse_file_outer(FILE *f)
2853 struct in_str input;
2854 setup_file_in_str(&input, f);
2855 rcode = parse_stream_outer(&input, FLAG_PARSE_SEMICOLON);
2859 /* Make sure we have a controlling tty. If we get started under a job
2860 * aware app (like bash for example), make sure we are now in charge so
2861 * we don't fight over who gets the foreground */
2862 static void setup_job_control(void)
2866 saved_task_pgrp = getpgrp();
2867 debug_printf("saved_task_pgrp=%d\n", saved_task_pgrp);
2868 fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
2870 /* Loop until we are in the foreground. */
2872 shell_pgrp = getpgrp();
2873 if (tcgetpgrp(interactive_fd) == shell_pgrp)
2875 // and this does... what? need a comment here
2876 kill(- shell_pgrp, SIGTTIN);
2879 /* Ignore job-control and misc signals. */
2880 set_jobctrl_sighandler(SIG_IGN);
2881 set_misc_sighandler(SIG_IGN);
2882 //huh? signal(SIGCHLD, SIG_IGN);
2884 /* We _must_ do cleanup on fatal signals */
2885 set_fatal_sighandler(sigexit);
2887 /* Put ourselves in our own process group. */
2888 shell_pgrp = getpid();
2889 setpgrp(); /* is the same as setpgid(shell_pgrp, shell_pgrp); */
2891 /* Grab control of the terminal. */
2892 tcsetpgrp(interactive_fd, shell_pgrp);
2895 int hush_main(int argc, char **argv);
2896 int hush_main(int argc, char **argv)
2902 #if ENABLE_FEATURE_EDITING
2903 line_input_state = new_line_input_t(FOR_SHELL);
2906 /* XXX what should these be while sourcing /etc/profile? */
2910 /* (re?) initialize globals. Sometimes hush_main() ends up calling
2911 * hush_main(), therefore we cannot rely on the BSS to zero out this
2912 * stuff. Reset these to 0 every time. */
2914 /* map[] is taken care of with call to update_ifs_map() */
2917 close_me_head = NULL;
2922 /* Initialize some more globals to non-zero values */
2924 if (ENABLE_FEATURE_EDITING)
2925 cmdedit_set_initial_prompt();
2929 /* initialize our shell local variables with the values
2930 * currently living in the environment */
2934 set_local_var(*e++, 2); /* without call putenv() */
2936 last_return_code = EXIT_SUCCESS;
2938 if (argv[0] && argv[0][0] == '-') {
2939 debug_printf("\nsourcing /etc/profile\n");
2940 input = fopen("/etc/profile", "r");
2941 if (input != NULL) {
2942 mark_open(fileno(input));
2943 parse_file_outer(input);
2944 mark_closed(fileno(input));
2950 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
2953 global_argv = argv + optind;
2954 global_argc = argc - optind;
2955 opt = parse_string_outer(optarg, FLAG_PARSE_SEMICOLON);
2958 // Well, we cannot just declare interactiveness,
2959 // we have to have some stuff (ctty, etc)
2960 /*interactive_fd++;*/
2967 fprintf(stderr, "Usage: sh [FILE]...\n"
2968 " or: sh -c command [args]...\n\n");
2975 /* A shell is interactive if the '-i' flag was given, or if all of
2976 * the following conditions are met:
2978 * no arguments remaining or the -s flag given
2979 * standard input is a terminal
2980 * standard output is a terminal
2981 * Refer to Posix.2, the description of the 'sh' utility. */
2982 if (argv[optind] == NULL && input == stdin
2983 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
2985 saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
2986 debug_printf("saved_tty_pgrp=%d\n", saved_tty_pgrp);
2987 if (saved_tty_pgrp >= 0) {
2988 /* try to dup to high fd#, >= 255 */
2989 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
2990 if (interactive_fd < 0) {
2991 /* try to dup to any fd */
2992 interactive_fd = dup(STDIN_FILENO);
2993 if (interactive_fd < 0)
2997 // TODO: track & disallow any attempts of user
2998 // to (inadvertently) close/redirect it
3002 debug_printf("\ninteractive_fd=%d\n", interactive_fd);
3003 if (interactive_fd) {
3004 /* Looks like they want an interactive shell */
3005 setup_job_control();
3006 /* Make xfuncs do cleanup on exit */
3007 die_sleep = -1; /* flag */
3008 if (setjmp(die_jmp)) {
3009 /* xfunc has failed! die die die */
3010 hush_exit(xfunc_error_retval);
3012 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
3013 printf("\n\n%s hush - the humble shell v0.02\n", BB_BANNER);
3014 printf("Enter 'help' for a list of built-in commands.\n\n");
3018 if (argv[optind] == NULL) {
3019 opt = parse_file_outer(stdin);
3023 debug_printf("\nrunning script '%s'\n", argv[optind]);
3024 global_argv = argv + optind;
3025 global_argc = argc - optind;
3026 input = xfopen(argv[optind], "r");
3027 opt = parse_file_outer(input);
3029 #if ENABLE_FEATURE_CLEAN_UP
3031 if (cwd != bb_msg_unknown)
3034 struct variables *cur, *tmp;
3035 for (cur = top_vars; cur; cur = tmp) {
3037 if (!cur->flg_read_only) {
3038 free((char*)cur->name);
3039 free((char*)cur->value);
3047 hush_exit(opt ? opt : last_return_code);