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?)
41 * ! negation operator for pipes
42 * &> and >& redirection of stdout+stderr
45 * fancy forms of Parameter Expansion
47 * Arithmetic Expansion
48 * <(list) and >(list) Process Substitution
49 * reserved words: case, esac, select, function
50 * Here Documents ( << word )
53 * job handling woefully incomplete and buggy (improved --vda)
54 * reserved word execution woefully incomplete and buggy
56 * port selected bugfixes from post-0.49 busybox lash - done?
57 * finish implementing reserved words: for, while, until, do, done
58 * change { and } from special chars to reserved words
59 * builtins: break, continue, eval, return, set, trap, ulimit
61 * handle children going into background
62 * clean up recognition of null pipes
63 * check setting of global_argc and global_argv
64 * control-C handling, probably with longjmp
65 * follow IFS rules more precisely, including update semantics
66 * figure out what to do with backslash-newline
67 * explain why we use signal instead of sigaction
68 * propagate syntax errors, die on resource errors?
69 * continuation lines, both explicit and implicit - done?
70 * memory leak finding and plugging - done?
71 * more testing, especially quoting rules and redirection
72 * document how quoting rules not precisely followed for variable assignments
73 * maybe change charmap[] to use 2-bit entries
74 * (eventually) remove all the printf's
76 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
80 #include <glob.h> /* glob, of course */
81 #include <getopt.h> /* should be pretty obvious */
82 /* #include <dmalloc.h> */
84 extern char **environ; /* This is in <unistd.h>, but protected with __USE_GNU */
86 #include "busybox.h" /* for struct bb_applet */
90 /* A bit drastic. Can allow some simpler commands
91 * by analysing command in generate_stream_from_list()
93 #undef ENABLE_HUSH_TICK
94 #define ENABLE_HUSH_TICK 0
98 /* If you comment out one of these below, it will be #defined later
99 * to perform debug printfs to stderr: */
100 #define debug_printf(...) do {} while (0)
101 /* Finer-grained debug switches */
102 #define debug_printf_parse(...) do {} while (0)
103 #define debug_print_tree(a, b) do {} while (0)
104 #define debug_printf_exec(...) do {} while (0)
105 #define debug_printf_jobs(...) do {} while (0)
106 #define debug_printf_expand(...) do {} while (0)
107 #define debug_printf_clean(...) do {} while (0)
110 #define debug_printf(...) fprintf(stderr, __VA_ARGS__)
113 #ifndef debug_printf_parse
114 #define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
117 #ifndef debug_printf_exec
118 #define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
121 #ifndef debug_printf_jobs
122 #define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
123 #define DEBUG_SHELL_JOBS 1
126 #ifndef debug_printf_expand
127 #define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
128 #define DEBUG_EXPAND 1
131 /* Keep unconditionally on for now */
132 #define ENABLE_HUSH_DEBUG 1
134 #ifndef debug_printf_clean
135 /* broken, of course, but OK for testing */
136 static const char *indenter(int i)
138 static const char blanks[] ALIGN1 =
140 return &blanks[sizeof(blanks) - i - 1];
142 #define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
143 #define DEBUG_CLEAN 1
148 * Leak hunting. Use hush_leaktool.sh for post-processing.
150 #ifdef FOR_HUSH_LEAKTOOL
151 void *xxmalloc(int lineno, size_t size)
153 void *ptr = xmalloc((size + 0xff) & ~0xff);
154 fprintf(stderr, "line %d: malloc %p\n", lineno, ptr);
157 void *xxrealloc(int lineno, void *ptr, size_t size)
159 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
160 fprintf(stderr, "line %d: realloc %p\n", lineno, ptr);
163 char *xxstrdup(int lineno, const char *str)
165 char *ptr = xstrdup(str);
166 fprintf(stderr, "line %d: strdup %p\n", lineno, ptr);
169 void xxfree(void *ptr)
171 fprintf(stderr, "free %p\n", ptr);
174 #define xmalloc(s) xxmalloc(__LINE__, s)
175 #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
176 #define xstrdup(s) xxstrdup(__LINE__, s)
177 #define free(p) xxfree(p)
181 #if !ENABLE_HUSH_INTERACTIVE
182 #undef ENABLE_FEATURE_EDITING
183 #define ENABLE_FEATURE_EDITING 0
184 #undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
185 #define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
188 #define SPECIAL_VAR_SYMBOL 3
190 #define PARSEFLAG_EXIT_FROM_LOOP 1
191 #define PARSEFLAG_SEMICOLON (1 << 1) /* symbol ';' is special for parser */
192 #define PARSEFLAG_REPARSING (1 << 2) /* >= 2nd pass */
196 REDIRECT_OVERWRITE = 2,
202 /* The descrip member of this structure is only used to make debugging
204 static const struct {
206 signed char default_fd;
210 { O_RDONLY, 0, "<" },
211 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
212 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
213 { O_RDONLY, -1, "<<" },
224 /* might eventually control execution */
234 #if ENABLE_HUSH_LOOPS
246 FLAG_END = (1 << RES_NONE ),
248 FLAG_IF = (1 << RES_IF ),
249 FLAG_THEN = (1 << RES_THEN ),
250 FLAG_ELIF = (1 << RES_ELIF ),
251 FLAG_ELSE = (1 << RES_ELSE ),
252 FLAG_FI = (1 << RES_FI ),
254 #if ENABLE_HUSH_LOOPS
255 FLAG_FOR = (1 << RES_FOR ),
256 FLAG_WHILE = (1 << RES_WHILE),
257 FLAG_UNTIL = (1 << RES_UNTIL),
258 FLAG_DO = (1 << RES_DO ),
259 FLAG_DONE = (1 << RES_DONE ),
260 FLAG_IN = (1 << RES_IN ),
262 FLAG_START = (1 << RES_XXXX ),
265 /* This holds pointers to the various results of parsing */
267 struct child_prog *child;
268 struct pipe *list_head;
270 struct redir_struct *pending_redirect;
272 smallint parse_type; /* bitmask of PARSEFLAG_xxx, defines type of parser : ";$" common or special symbol */
273 int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */
274 struct p_context *stack;
275 /* How about quoting status? */
278 struct redir_struct {
279 struct redir_struct *next; /* pointer to the next redirect in the list */
280 redir_type type; /* type of redirection */
281 int fd; /* file descriptor being redirected */
282 int dup; /* -1, or file descriptor being duplicated */
283 char **glob_word; /* *word.gl_pathv is the filename */
287 pid_t pid; /* 0 if exited */
288 char **argv; /* program name and arguments */
289 struct pipe *group; /* if non-NULL, first in group or subshell */
290 smallint subshell; /* flag, non-zero if group must be forked */
291 smallint is_stopped; /* is the program currently running? */
292 struct redir_struct *redirects; /* I/O redirections */
293 struct pipe *family; /* pointer back to the child's parent pipe */
294 //sp counting seems to be broken... so commented out, grep for '//sp:'
295 //sp: int sp; /* number of SPECIAL_VAR_SYMBOL */
296 //seems to be unused, grep for '//pt:'
297 //pt: int parse_type;
299 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
300 * and on execution these are substituted with their values.
301 * Substitution can make _several_ words out of one argv[n]!
302 * Example: argv[0]=='.^C*^C.' here: echo .$*.
307 int num_progs; /* total number of programs in job */
308 int running_progs; /* number of programs running (not exited) */
309 int stopped_progs; /* number of programs alive, but stopped */
311 int jobid; /* job number */
312 pid_t pgrp; /* process group ID for the job */
313 char *cmdtext; /* name of job */
315 char *cmdbuf; /* buffer various argv's point into */
316 struct child_prog *progs; /* array of commands in pipe */
317 int job_context; /* bitmask defining current context */
318 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
319 smallint res_word; /* needed for if, for, while, until... */
322 /* On program start, environ points to initial environment.
323 * putenv adds new pointers into it, unsetenv removes them.
324 * Neither of these (de)allocates the strings.
325 * setenv allocates new strings in malloc space and does putenv,
326 * and thus setenv is unusable (leaky) for shell's purposes */
327 #define setenv(...) setenv_is_leaky_dont_use()
329 struct variable *next;
330 char *varstr; /* points to "name=" portion */
331 int max_len; /* if > 0, name is part of initial env; else name is malloced */
332 smallint flg_export; /* putenv should be done on this var */
333 smallint flg_read_only;
343 #define NULL_O_STRING {NULL,0,0,0,0}
344 /* used for initialization: o_string foo = NULL_O_STRING; */
346 /* I can almost use ordinary FILE *. Is open_memstream() universally
347 * available? Where is it documented? */
350 /* eof_flag=1: last char in ->p is really an EOF */
351 char eof_flag; /* meaningless if ->p == NULL */
353 #if ENABLE_HUSH_INTERACTIVE
355 smallint promptmode; /* 0: PS1, 1: PS2 */
358 int (*get) (struct in_str *);
359 int (*peek) (struct in_str *);
361 #define b_getch(input) ((input)->get(input))
362 #define b_peek(input) ((input)->peek(input))
366 CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
367 CHAR_IFS = 2, /* treated as ordinary if quoted */
368 CHAR_SPECIAL = 3, /* example: $ */
371 #define HUSH_VER_STR "0.02"
373 /* "Globals" within this file */
375 /* Sorted roughly by size (smaller offsets == smaller code) */
377 #if ENABLE_HUSH_INTERACTIVE
378 /* 'interactive_fd' is a fd# open to ctty, if we have one
379 * _AND_ if we decided to act interactively */
384 #if ENABLE_FEATURE_EDITING
385 line_input_t *line_input_state;
389 pid_t saved_task_pgrp;
390 pid_t saved_tty_pgrp;
392 struct pipe *job_list;
393 struct pipe *toplevel_list;
394 smallint ctrl_z_flag;
397 /* these three support $?, $#, and $1 */
400 int last_return_code;
403 unsigned last_bg_pid;
404 struct variable *top_var; /* = &shell_ver (set in main()) */
405 struct variable shell_ver;
406 #if ENABLE_FEATURE_SH_STANDALONE
407 struct nofork_save_area nofork_save;
410 sigjmp_buf toplevel_jb;
412 unsigned char charmap[256];
413 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
416 #define G (*ptr_to_globals)
418 #if !ENABLE_HUSH_INTERACTIVE
419 enum { interactive_fd = 0 };
422 enum { run_list_level = 0 };
425 #if ENABLE_HUSH_INTERACTIVE
426 #define interactive_fd (G.interactive_fd )
430 #if ENABLE_FEATURE_EDITING
431 #define line_input_state (G.line_input_state)
434 #define run_list_level (G.run_list_level )
435 #define saved_task_pgrp (G.saved_task_pgrp )
436 #define saved_tty_pgrp (G.saved_tty_pgrp )
437 #define last_jobid (G.last_jobid )
438 #define job_list (G.job_list )
439 #define toplevel_list (G.toplevel_list )
440 #define toplevel_jb (G.toplevel_jb )
441 #define ctrl_z_flag (G.ctrl_z_flag )
443 #define global_argv (G.global_argv )
444 #define global_argc (G.global_argc )
445 #define last_return_code (G.last_return_code)
447 #define fake_mode (G.fake_mode )
449 #define last_bg_pid (G.last_bg_pid )
450 #define top_var (G.top_var )
451 #define shell_ver (G.shell_ver )
452 #if ENABLE_FEATURE_SH_STANDALONE
453 #define nofork_save (G.nofork_save )
456 #define toplevel_jb (G.toplevel_jb )
458 #define charmap (G.charmap )
459 #define user_input_buf (G.user_input_buf )
464 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
468 static void syntax(const char *msg)
470 /* Was using fancy stuff:
471 * (interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
472 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
473 void (*fp)(const char *s, ...);
475 fp = (interactive_fd ? bb_error_msg : bb_error_msg_and_die);
476 fp(msg ? "%s: %s" : "syntax error", "syntax error", msg);
481 static void syntax_lineno(int line)
483 void (*fp)(const char *s, ...);
485 fp = (interactive_fd ? bb_error_msg : bb_error_msg_and_die);
486 fp("syntax error hush.c:%d", line);
488 #define syntax(str) syntax_lineno(__LINE__)
491 /* Index of subroutines: */
492 /* function prototypes for builtins */
493 static int builtin_cd(char **argv);
494 static int builtin_eval(char **argv);
495 static int builtin_exec(char **argv);
496 static int builtin_exit(char **argv);
497 static int builtin_export(char **argv);
499 static int builtin_fg_bg(char **argv);
500 static int builtin_jobs(char **argv);
503 static int builtin_help(char **argv);
505 static int builtin_pwd(char **argv);
506 static int builtin_read(char **argv);
507 static int builtin_set(char **argv);
508 static int builtin_shift(char **argv);
509 static int builtin_source(char **argv);
510 static int builtin_umask(char **argv);
511 static int builtin_unset(char **argv);
512 //static int builtin_not_written(char **argv);
513 /* o_string manipulation: */
514 static int b_check_space(o_string *o, int len);
515 static int b_addchr(o_string *o, int ch);
516 static void b_reset(o_string *o);
517 static int b_addqchr(o_string *o, int ch, int quote);
518 /* in_str manipulations: */
519 static int static_get(struct in_str *i);
520 static int static_peek(struct in_str *i);
521 static int file_get(struct in_str *i);
522 static int file_peek(struct in_str *i);
523 static void setup_file_in_str(struct in_str *i, FILE *f);
524 static void setup_string_in_str(struct in_str *i, const char *s);
525 /* "run" the final data structures: */
526 #if !defined(DEBUG_CLEAN)
527 #define free_pipe_list(head, indent) free_pipe_list(head)
528 #define free_pipe(pi, indent) free_pipe(pi)
530 static int free_pipe_list(struct pipe *head, int indent);
531 static int free_pipe(struct pipe *pi, int indent);
532 /* really run the final data structures: */
533 static int setup_redirects(struct child_prog *prog, int squirrel[]);
534 static int run_list_real(struct pipe *pi);
535 static void pseudo_exec_argv(char **argv) ATTRIBUTE_NORETURN;
536 static void pseudo_exec(struct child_prog *child) ATTRIBUTE_NORETURN;
537 static int run_pipe_real(struct pipe *pi);
538 /* extended glob support: */
539 static char **globhack(const char *src, char **strings);
540 static int glob_needed(const char *s);
541 static int xglob(o_string *dest, char ***pglob);
542 /* variable assignment: */
543 static int is_assignment(const char *s);
544 /* data structure manipulation: */
545 static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
546 static void initialize_context(struct p_context *ctx);
547 static int done_word(o_string *dest, struct p_context *ctx);
548 static int done_command(struct p_context *ctx);
549 static int done_pipe(struct p_context *ctx, pipe_style type);
550 /* primary string parsing: */
551 static int redirect_dup_num(struct in_str *input);
552 static int redirect_opt_num(o_string *o);
554 static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, const char *subst_end);
556 static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
557 static const char *lookup_param(const char *src);
558 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
559 static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, const char *end_trigger);
561 static int parse_and_run_stream(struct in_str *inp, int parse_flag);
562 static int parse_and_run_string(const char *s, int parse_flag);
563 static int parse_and_run_file(FILE *f);
564 /* job management: */
565 static int checkjobs(struct pipe* fg_pipe);
567 static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
568 static void insert_bg_job(struct pipe *pi);
569 static void remove_bg_job(struct pipe *pi);
570 static void delete_finished_bg_job(struct pipe *pi);
572 int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
574 /* local variable support */
575 static char **expand_strvec_to_strvec(char **argv);
577 static char *expand_strvec_to_string(char **argv);
578 /* used for expansion of right hand of assignments */
579 static char *expand_string_to_string(const char *str);
580 static struct variable *get_local_var(const char *name);
581 static int set_local_var(char *str, int flg_export);
582 static void unset_local_var(const char *name);
585 static char **add_strings_to_strings(int need_xstrdup, char **strings, char **add)
606 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
607 v[count1 + count2] = NULL;
610 v[count1 + i] = need_xstrdup ? xstrdup(add[i]) : add[i];
614 /* 'add' should be a malloced pointer */
615 static char **add_string_to_strings(char **strings, char *add)
622 return add_strings_to_strings(0, strings, v);
625 static void free_strings(char **strings)
636 /* Table of built-in functions. They can be forked or not, depending on
637 * context: within pipes, they fork. As simple commands, they do not.
638 * When used in non-forking context, they can change global variables
639 * in the parent shell process. If forked, of course they cannot.
640 * For example, 'unset foo | whatever' will parse and run, but foo will
641 * still be set at the end. */
642 struct built_in_command {
643 const char *cmd; /* name */
644 int (*function) (char **argv); /* function ptr */
646 const char *descr; /* description */
647 #define BLTIN(cmd, func, help) { cmd, func, help }
649 #define BLTIN(cmd, func, help) { cmd, func }
653 static const struct built_in_command bltins[] = {
655 BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"),
657 // BLTIN("break" , builtin_not_written, "Exit for, while or until loop"),
658 BLTIN("cd" , builtin_cd, "Change working directory"),
659 // BLTIN("continue", builtin_not_written, "Continue for, while or until loop"),
660 BLTIN("eval" , builtin_eval, "Construct and run shell command"),
661 BLTIN("exec" , builtin_exec, "Exec command, replacing this shell with the exec'd process"),
662 BLTIN("exit" , builtin_exit, "Exit from shell"),
663 BLTIN("export", builtin_export, "Set environment variable"),
665 BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"),
666 BLTIN("jobs" , builtin_jobs, "Lists the active jobs"),
668 // TODO: remove pwd? we have it as an applet...
669 BLTIN("pwd" , builtin_pwd, "Print current directory"),
670 BLTIN("read" , builtin_read, "Input environment variable"),
671 // BLTIN("return", builtin_not_written, "Return from a function"),
672 BLTIN("set" , builtin_set, "Set/unset shell local variables"),
673 BLTIN("shift" , builtin_shift, "Shift positional parameters"),
674 // BLTIN("trap" , builtin_not_written, "Trap signals"),
675 // BLTIN("ulimit", builtin_not_written, "Controls resource limits"),
676 BLTIN("umask" , builtin_umask, "Sets file creation mask"),
677 BLTIN("unset" , builtin_unset, "Unset environment variable"),
678 BLTIN("." , builtin_source, "Source-in and run commands in a file"),
680 BLTIN("help" , builtin_help, "List shell built-in commands"),
682 BLTIN(NULL, NULL, NULL)
688 static void signal_SA_RESTART(int sig, void (*handler)(int))
691 sa.sa_handler = handler;
692 sa.sa_flags = SA_RESTART;
693 sigemptyset(&sa.sa_mask);
694 sigaction(sig, &sa, NULL);
697 /* Signals are grouped, we handle them in batches */
698 static void set_fatal_sighandler(void (*handler)(int))
700 signal(SIGILL , handler);
701 signal(SIGTRAP, handler);
702 signal(SIGABRT, handler);
703 signal(SIGFPE , handler);
704 signal(SIGBUS , handler);
705 signal(SIGSEGV, handler);
706 /* bash 3.2 seems to handle these just like 'fatal' ones */
707 signal(SIGHUP , handler);
708 signal(SIGPIPE, handler);
709 signal(SIGALRM, handler);
711 static void set_jobctrl_sighandler(void (*handler)(int))
713 signal(SIGTSTP, handler);
714 signal(SIGTTIN, handler);
715 signal(SIGTTOU, handler);
717 static void set_misc_sighandler(void (*handler)(int))
719 signal(SIGINT , handler);
720 signal(SIGQUIT, handler);
721 signal(SIGTERM, handler);
723 /* SIGCHLD is special and handled separately */
725 static void set_every_sighandler(void (*handler)(int))
727 set_fatal_sighandler(handler);
728 set_jobctrl_sighandler(handler);
729 set_misc_sighandler(handler);
730 signal(SIGCHLD, handler);
733 static void handler_ctrl_c(int sig)
735 debug_printf_jobs("got sig %d\n", sig);
736 // as usual we can have all kinds of nasty problems with leaked malloc data here
737 siglongjmp(toplevel_jb, 1);
740 static void handler_ctrl_z(int sig)
744 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
746 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
749 if (!pid) { /* child */
751 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
752 set_every_sighandler(SIG_DFL);
753 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
754 debug_printf_jobs("returning in child\n");
755 /* return to nofork, it will eventually exit now,
756 * not return back to shell */
760 /* finish filling up pipe info */
761 toplevel_list->pgrp = pid; /* child is in its own pgrp */
762 toplevel_list->progs[0].pid = pid;
763 /* parent needs to longjmp out of running nofork.
764 * we will "return" exitcode 0, with child put in background */
765 // as usual we can have all kinds of nasty problems with leaked malloc data here
766 debug_printf_jobs("siglongjmp in parent\n");
767 siglongjmp(toplevel_jb, 1);
770 /* Restores tty foreground process group, and exits.
771 * May be called as signal handler for fatal signal
772 * (will faithfully resend signal to itself, producing correct exit state)
773 * or called directly with -EXITCODE.
774 * We also call it if xfunc is exiting. */
775 static void sigexit(int sig) ATTRIBUTE_NORETURN;
776 static void sigexit(int sig)
780 /* Disable all signals: job control, SIGPIPE, etc. */
781 sigfillset(&block_all);
782 sigprocmask(SIG_SETMASK, &block_all, NULL);
785 tcsetpgrp(interactive_fd, saved_tty_pgrp);
787 /* Not a signal, just exit */
791 /* Enable only this sig and kill ourself with it */
792 signal(sig, SIG_DFL);
793 sigdelset(&block_all, sig);
794 sigprocmask(SIG_SETMASK, &block_all, NULL);
796 _exit(1); /* Should not reach it */
799 /* Restores tty foreground process group, and exits. */
800 static void hush_exit(int exitcode) ATTRIBUTE_NORETURN;
801 static void hush_exit(int exitcode)
803 fflush(NULL); /* flush all streams */
804 sigexit(- (exitcode & 0xff));
809 #define set_fatal_sighandler(handler) ((void)0)
810 #define set_jobctrl_sighandler(handler) ((void)0)
811 #define set_misc_sighandler(handler) ((void)0)
812 #define hush_exit(e) exit(e)
817 static const char *set_cwd(void)
819 if (cwd == bb_msg_unknown)
820 cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
821 cwd = xrealloc_getcwd_or_warn((char *)cwd);
823 cwd = bb_msg_unknown;
827 /* built-in 'eval' handler */
828 static int builtin_eval(char **argv)
830 int rcode = EXIT_SUCCESS;
833 char *str = expand_strvec_to_string(argv + 1);
834 parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP |
835 PARSEFLAG_SEMICOLON);
837 rcode = last_return_code;
842 /* built-in 'cd <path>' handler */
843 static int builtin_cd(char **argv)
846 if (argv[1] == NULL) {
847 // bash does nothing (exitcode 0) if HOME is ""; if it's unset,
848 // bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
849 newdir = getenv("HOME") ? : "/";
853 printf("cd: %s: %s\n", newdir, strerror(errno));
860 /* built-in 'exec' handler */
861 static int builtin_exec(char **argv)
864 return EXIT_SUCCESS; /* Really? */
865 pseudo_exec_argv(argv + 1);
869 /* built-in 'exit' handler */
870 static int builtin_exit(char **argv)
872 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
873 //puts("exit"); /* bash does it */
874 // TODO: warn if we have background jobs: "There are stopped jobs"
875 // On second consecutive 'exit', exit anyway.
878 hush_exit(last_return_code);
879 /* mimic bash: exit 123abc == exit 255 + error msg */
880 xfunc_error_retval = 255;
881 /* bash: exit -2 == exit 254, no error msg */
882 hush_exit(xatoi(argv[1]) & 0xff);
885 /* built-in 'export VAR=value' handler */
886 static int builtin_export(char **argv)
889 char *name = argv[1];
893 // ash emits: export VAR='VAL'
894 // bash: declare -x VAR="VAL"
895 // (both also escape as needed (quotes, $, etc))
903 value = strchr(name, '=');
905 /* They are exporting something without a =VALUE */
906 struct variable *var;
908 var = get_local_var(name);
913 /* bash does not return an error when trying to export
914 * an undefined variable. Do likewise. */
918 set_local_var(xstrdup(name), 1);
923 /* built-in 'fg' and 'bg' handler */
924 static int builtin_fg_bg(char **argv)
931 /* If they gave us no args, assume they want the last backgrounded task */
933 for (pi = job_list; pi; pi = pi->next) {
934 if (pi->jobid == last_jobid) {
938 bb_error_msg("%s: no current job", argv[0]);
941 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
942 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
945 for (pi = job_list; pi; pi = pi->next) {
946 if (pi->jobid == jobnum) {
950 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
953 // TODO: bash prints a string representation
954 // of job being foregrounded (like "sleep 1 | cat")
955 if (*argv[0] == 'f') {
956 /* Put the job into the foreground. */
957 tcsetpgrp(interactive_fd, pi->pgrp);
960 /* Restart the processes in the job */
961 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_progs, pi->pgrp);
962 for (i = 0; i < pi->num_progs; i++) {
963 debug_printf_jobs("reviving pid %d\n", pi->progs[i].pid);
964 pi->progs[i].is_stopped = 0;
966 pi->stopped_progs = 0;
968 i = kill(- pi->pgrp, SIGCONT);
970 if (errno == ESRCH) {
971 delete_finished_bg_job(pi);
974 bb_perror_msg("kill (SIGCONT)");
978 if (*argv[0] == 'f') {
980 return checkjobs_and_fg_shell(pi);
986 /* built-in 'help' handler */
988 static int builtin_help(char **argv ATTRIBUTE_UNUSED)
990 const struct built_in_command *x;
992 printf("\nBuilt-in commands:\n");
993 printf("-------------------\n");
994 for (x = bltins; x->cmd; x++) {
995 printf("%s\t%s\n", x->cmd, x->descr);
1003 /* built-in 'jobs' handler */
1004 static int builtin_jobs(char **argv ATTRIBUTE_UNUSED)
1007 const char *status_string;
1009 for (job = job_list; job; job = job->next) {
1010 if (job->running_progs == job->stopped_progs)
1011 status_string = "Stopped";
1013 status_string = "Running";
1015 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
1017 return EXIT_SUCCESS;
1021 /* built-in 'pwd' handler */
1022 static int builtin_pwd(char **argv ATTRIBUTE_UNUSED)
1025 return EXIT_SUCCESS;
1028 /* built-in 'read VAR' handler */
1029 static int builtin_read(char **argv)
1032 const char *name = argv[1] ? argv[1] : "REPLY";
1034 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name));
1035 return set_local_var(string, 0);
1038 /* built-in 'set [VAR=value]' handler */
1039 static int builtin_set(char **argv)
1041 char *temp = argv[1];
1045 for (e = top_var; e; e = e->next)
1048 set_local_var(xstrdup(temp), 0);
1050 return EXIT_SUCCESS;
1054 /* Built-in 'shift' handler */
1055 static int builtin_shift(char **argv)
1061 if (n >= 0 && n < global_argc) {
1062 global_argv[n] = global_argv[0];
1065 return EXIT_SUCCESS;
1067 return EXIT_FAILURE;
1070 /* Built-in '.' handler (read-in and execute commands from file) */
1071 static int builtin_source(char **argv)
1076 if (argv[1] == NULL)
1077 return EXIT_FAILURE;
1079 /* XXX search through $PATH is missing */
1080 input = fopen(argv[1], "r");
1082 bb_error_msg("cannot open '%s'", argv[1]);
1083 return EXIT_FAILURE;
1085 close_on_exec_on(fileno(input));
1087 /* Now run the file */
1088 /* XXX argv and argc are broken; need to save old global_argv
1089 * (pointer only is OK!) on this stack frame,
1090 * set global_argv=argv+1, recurse, and restore. */
1091 status = parse_and_run_file(input);
1096 static int builtin_umask(char **argv)
1099 const char *arg = argv[1];
1102 new_umask = strtoul(arg, &end, 8);
1103 if (*end != '\0' || end == arg) {
1104 return EXIT_FAILURE;
1107 new_umask = umask(0);
1108 printf("%.3o\n", (unsigned) new_umask);
1111 return EXIT_SUCCESS;
1114 /* built-in 'unset VAR' handler */
1115 static int builtin_unset(char **argv)
1117 /* bash always returns true */
1118 unset_local_var(argv[1]);
1119 return EXIT_SUCCESS;
1122 //static int builtin_not_written(char **argv)
1124 // printf("builtin_%s not written\n", argv[0]);
1125 // return EXIT_FAILURE;
1128 static int b_check_space(o_string *o, int len)
1130 /* It would be easy to drop a more restrictive policy
1131 * in here, such as setting a maximum string length */
1132 if (o->length + len > o->maxlen) {
1133 /* assert(data == NULL || o->maxlen != 0); */
1134 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1135 o->data = xrealloc(o->data, 1 + o->maxlen);
1137 return o->data == NULL;
1140 static int b_addchr(o_string *o, int ch)
1142 debug_printf("b_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1143 if (b_check_space(o, 1))
1145 o->data[o->length] = ch;
1147 o->data[o->length] = '\0';
1151 static void b_reset(o_string *o)
1159 static void b_free(o_string *o)
1162 memset(o, 0, sizeof(*o));
1165 /* My analysis of quoting semantics tells me that state information
1166 * is associated with a destination, not a source.
1168 static int b_addqchr(o_string *o, int ch, int quote)
1170 if (quote && strchr("*?[\\", ch)) {
1172 rc = b_addchr(o, '\\');
1176 return b_addchr(o, ch);
1179 static int static_get(struct in_str *i)
1182 if (ch == '\0') return EOF;
1186 static int static_peek(struct in_str *i)
1191 #if ENABLE_HUSH_INTERACTIVE
1192 #if ENABLE_FEATURE_EDITING
1193 static void cmdedit_set_initial_prompt(void)
1195 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1198 PS1 = getenv("PS1");
1203 #endif /* EDITING */
1205 static const char* setup_prompt_string(int promptmode)
1207 const char *prompt_str;
1208 debug_printf("setup_prompt_string %d ", promptmode);
1209 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1210 /* Set up the prompt */
1211 if (promptmode == 0) { /* PS1 */
1213 PS1 = xasprintf("%s %c ", cwd, (geteuid() != 0) ? '$' : '#');
1219 prompt_str = (promptmode == 0) ? PS1 : PS2;
1221 debug_printf("result '%s'\n", prompt_str);
1225 static void get_user_input(struct in_str *i)
1228 const char *prompt_str;
1230 prompt_str = setup_prompt_string(i->promptmode);
1231 #if ENABLE_FEATURE_EDITING
1232 /* Enable command line editing only while a command line
1233 * is actually being read; otherwise, we'll end up bequeathing
1234 * atexit() handlers and other unwanted stuff to our
1235 * child processes (rob@sysgo.de) */
1236 r = read_line_input(prompt_str, user_input_buf, BUFSIZ-1, line_input_state);
1237 i->eof_flag = (r < 0);
1238 if (i->eof_flag) { /* EOF/error detected */
1239 user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1240 user_input_buf[1] = '\0';
1243 fputs(prompt_str, stdout);
1245 user_input_buf[0] = r = fgetc(i->file);
1246 /*user_input_buf[1] = '\0'; - already is and never changed */
1247 i->eof_flag = (r == EOF);
1249 i->p = user_input_buf;
1251 #endif /* INTERACTIVE */
1253 /* This is the magic location that prints prompts
1254 * and gets data back from the user */
1255 static int file_get(struct in_str *i)
1259 /* If there is data waiting, eat it up */
1260 if (i->p && *i->p) {
1261 #if ENABLE_HUSH_INTERACTIVE
1265 if (i->eof_flag && !*i->p)
1268 /* need to double check i->file because we might be doing something
1269 * more complicated by now, like sourcing or substituting. */
1270 #if ENABLE_HUSH_INTERACTIVE
1271 if (interactive_fd && i->promptme && i->file == stdin) {
1274 } while (!*i->p); /* need non-empty line */
1275 i->promptmode = 1; /* PS2 */
1280 ch = fgetc(i->file);
1282 debug_printf("file_get: got a '%c' %d\n", ch, ch);
1283 #if ENABLE_HUSH_INTERACTIVE
1290 /* All the callers guarantee this routine will never be
1291 * used right after a newline, so prompting is not needed.
1293 static int file_peek(struct in_str *i)
1296 if (i->p && *i->p) {
1297 if (i->eof_flag && !i->p[1])
1301 ch = fgetc(i->file);
1302 i->eof_flag = (ch == EOF);
1303 i->peek_buf[0] = ch;
1304 i->peek_buf[1] = '\0';
1306 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
1310 static void setup_file_in_str(struct in_str *i, FILE *f)
1312 i->peek = file_peek;
1314 #if ENABLE_HUSH_INTERACTIVE
1316 i->promptmode = 0; /* PS1 */
1322 static void setup_string_in_str(struct in_str *i, const char *s)
1324 i->peek = static_peek;
1325 i->get = static_get;
1326 #if ENABLE_HUSH_INTERACTIVE
1328 i->promptmode = 0; /* PS1 */
1334 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
1335 * and stderr if they are redirected. */
1336 static int setup_redirects(struct child_prog *prog, int squirrel[])
1339 struct redir_struct *redir;
1341 for (redir = prog->redirects; redir; redir = redir->next) {
1342 if (redir->dup == -1 && redir->glob_word == NULL) {
1343 /* something went wrong in the parse. Pretend it didn't happen */
1346 if (redir->dup == -1) {
1347 mode = redir_table[redir->type].mode;
1348 openfd = open_or_warn(redir->glob_word[0], mode);
1350 /* this could get lost if stderr has been redirected, but
1351 bash and ash both lose it as well (though zsh doesn't!) */
1355 openfd = redir->dup;
1358 if (openfd != redir->fd) {
1359 if (squirrel && redir->fd < 3) {
1360 squirrel[redir->fd] = dup(redir->fd);
1363 //close(openfd); // close(-3) ??!
1365 dup2(openfd, redir->fd);
1366 if (redir->dup == -1)
1374 static void restore_redirects(int squirrel[])
1377 for (i = 0; i < 3; i++) {
1380 /* We simply die on error */
1386 /* Called after [v]fork() in run_pipe_real(), or from builtin_exec().
1388 * XXX no exit() here. If you don't exec, use _exit instead.
1389 * The at_exit handlers apparently confuse the calling process,
1390 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
1391 static void pseudo_exec_argv(char **argv)
1395 const struct built_in_command *x;
1397 for (i = 0; is_assignment(argv[i]); i++) {
1398 debug_printf_exec("pid %d environment modification: %s\n",
1400 // FIXME: vfork case??
1401 p = expand_string_to_string(argv[i]);
1405 /* If a variable is assigned in a forest, and nobody listens,
1406 * was it ever really set?
1408 if (argv[0] == NULL) {
1409 _exit(EXIT_SUCCESS);
1412 argv = expand_strvec_to_strvec(argv);
1415 * Check if the command matches any of the builtins.
1416 * Depending on context, this might be redundant. But it's
1417 * easier to waste a few CPU cycles than it is to figure out
1418 * if this is one of those cases.
1420 for (x = bltins; x->cmd; x++) {
1421 if (strcmp(argv[0], x->cmd) == 0) {
1422 debug_printf_exec("running builtin '%s'\n", argv[0]);
1423 rcode = x->function(argv);
1429 /* Check if the command matches any busybox applets */
1430 #if ENABLE_FEATURE_SH_STANDALONE
1431 if (strchr(argv[0], '/') == NULL) {
1432 const struct bb_applet *a = find_applet_by_name(argv[0]);
1435 debug_printf_exec("running applet '%s'\n", argv[0]);
1436 // is it ok that run_appletstruct_and_exit() does exit(), not _exit()?
1437 run_appletstruct_and_exit(a, argv);
1439 /* re-exec ourselves with the new arguments */
1440 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
1441 execvp(bb_busybox_exec_path, argv);
1442 /* If they called chroot or otherwise made the binary no longer
1443 * executable, fall through */
1448 debug_printf_exec("execing '%s'\n", argv[0]);
1449 execvp(argv[0], argv);
1450 bb_perror_msg("cannot exec '%s'", argv[0]);
1454 /* Called after [v]fork() in run_pipe_real()
1456 static void pseudo_exec(struct child_prog *child)
1458 // FIXME: buggy wrt NOMMU! Must not modify any global data
1459 // until it does exec/_exit, but currently it does.
1463 pseudo_exec_argv(child->argv);
1468 bb_error_msg_and_exit("nested lists are not supported on NOMMU");
1470 #if ENABLE_HUSH_INTERACTIVE
1471 debug_printf_exec("pseudo_exec: setting interactive_fd=0\n");
1472 interactive_fd = 0; /* crucial!!!! */
1474 debug_printf_exec("pseudo_exec: run_list_real\n");
1475 rcode = run_list_real(child->group);
1476 /* OK to leak memory by not calling free_pipe_list,
1477 * since this process is about to exit */
1482 /* Can happen. See what bash does with ">foo" by itself. */
1483 debug_printf("trying to pseudo_exec null command\n");
1484 _exit(EXIT_SUCCESS);
1488 static const char *get_cmdtext(struct pipe *pi)
1494 /* This is subtle. ->cmdtext is created only on first backgrounding.
1495 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
1496 * On subsequent bg argv is trashed, but we won't use it */
1499 argv = pi->progs[0].argv;
1500 if (!argv || !argv[0])
1501 return (pi->cmdtext = xzalloc(1));
1504 do len += strlen(*argv) + 1; while (*++argv);
1505 pi->cmdtext = p = xmalloc(len);
1506 argv = pi->progs[0].argv;
1508 len = strlen(*argv);
1509 memcpy(p, *argv, len);
1517 static void insert_bg_job(struct pipe *pi)
1519 struct pipe *thejob;
1522 /* Linear search for the ID of the job to use */
1524 for (thejob = job_list; thejob; thejob = thejob->next)
1525 if (thejob->jobid >= pi->jobid)
1526 pi->jobid = thejob->jobid + 1;
1528 /* Add thejob to the list of running jobs */
1530 thejob = job_list = xmalloc(sizeof(*thejob));
1532 for (thejob = job_list; thejob->next; thejob = thejob->next)
1534 thejob->next = xmalloc(sizeof(*thejob));
1535 thejob = thejob->next;
1538 /* Physically copy the struct job */
1539 memcpy(thejob, pi, sizeof(struct pipe));
1540 thejob->progs = xzalloc(sizeof(pi->progs[0]) * pi->num_progs);
1541 /* We cannot copy entire pi->progs[] vector! Double free()s will happen */
1542 for (i = 0; i < pi->num_progs; i++) {
1543 // TODO: do we really need to have so many fields which are just dead weight
1544 // at execution stage?
1545 thejob->progs[i].pid = pi->progs[i].pid;
1546 /* all other fields are not used and stay zero */
1548 thejob->next = NULL;
1549 thejob->cmdtext = xstrdup(get_cmdtext(pi));
1551 /* We don't wait for background thejobs to return -- append it
1552 to the list of backgrounded thejobs and leave it alone */
1553 printf("[%d] %d %s\n", thejob->jobid, thejob->progs[0].pid, thejob->cmdtext);
1554 last_bg_pid = thejob->progs[0].pid;
1555 last_jobid = thejob->jobid;
1558 static void remove_bg_job(struct pipe *pi)
1560 struct pipe *prev_pipe;
1562 if (pi == job_list) {
1563 job_list = pi->next;
1565 prev_pipe = job_list;
1566 while (prev_pipe->next != pi)
1567 prev_pipe = prev_pipe->next;
1568 prev_pipe->next = pi->next;
1571 last_jobid = job_list->jobid;
1576 /* remove a backgrounded job */
1577 static void delete_finished_bg_job(struct pipe *pi)
1580 pi->stopped_progs = 0;
1586 /* Checks to see if any processes have exited -- if they
1587 have, figure out why and see if a job has completed */
1588 static int checkjobs(struct pipe* fg_pipe)
1599 attributes = WUNTRACED;
1600 if (fg_pipe == NULL) {
1601 attributes |= WNOHANG;
1604 /* Do we do this right?
1605 * bash-3.00# sleep 20 | false
1607 * [3]+ Stopped sleep 20 | false
1608 * bash-3.00# echo $?
1609 * 1 <========== bg pipe is not fully done, but exitcode is already known!
1612 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
1613 //are stopped. Testcase: "cat | cat" in a script (not on command line)
1614 // + killall -STOP cat
1617 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
1618 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
1620 #ifdef DEBUG_SHELL_JOBS
1621 if (WIFSTOPPED(status))
1622 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
1623 childpid, WSTOPSIG(status), WEXITSTATUS(status));
1624 if (WIFSIGNALED(status))
1625 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
1626 childpid, WTERMSIG(status), WEXITSTATUS(status));
1627 if (WIFEXITED(status))
1628 debug_printf_jobs("pid %d exited, exitcode %d\n",
1629 childpid, WEXITSTATUS(status));
1631 /* Were we asked to wait for fg pipe? */
1634 for (i = 0; i < fg_pipe->num_progs; i++) {
1635 debug_printf_jobs("check pid %d\n", fg_pipe->progs[i].pid);
1636 if (fg_pipe->progs[i].pid == childpid) {
1637 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
1639 fg_pipe->progs[i].pid = 0;
1640 fg_pipe->running_progs--;
1641 if (i == fg_pipe->num_progs-1)
1642 /* last process gives overall exitstatus */
1643 rcode = WEXITSTATUS(status);
1645 fg_pipe->progs[i].is_stopped = 1;
1646 fg_pipe->stopped_progs++;
1648 debug_printf_jobs("fg_pipe: running_progs %d stopped_progs %d\n",
1649 fg_pipe->running_progs, fg_pipe->stopped_progs);
1650 if (fg_pipe->running_progs - fg_pipe->stopped_progs <= 0) {
1651 /* All processes in fg pipe have exited/stopped */
1653 if (fg_pipe->running_progs)
1654 insert_bg_job(fg_pipe);
1658 /* There are still running processes in the fg pipe */
1662 /* fall through to searching process in bg pipes */
1666 /* We asked to wait for bg or orphaned children */
1667 /* No need to remember exitcode in this case */
1668 for (pi = job_list; pi; pi = pi->next) {
1670 while (prognum < pi->num_progs) {
1671 if (pi->progs[prognum].pid == childpid)
1672 goto found_pi_and_prognum;
1678 /* Happens when shell is used as init process (init=/bin/sh) */
1679 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
1683 found_pi_and_prognum:
1686 pi->progs[prognum].pid = 0;
1687 pi->running_progs--;
1688 if (!pi->running_progs) {
1689 printf(JOB_STATUS_FORMAT, pi->jobid,
1690 "Done", pi->cmdtext);
1691 delete_finished_bg_job(pi);
1695 pi->stopped_progs++;
1696 pi->progs[prognum].is_stopped = 1;
1701 /* wait found no children or failed */
1703 if (childpid && errno != ECHILD)
1704 bb_perror_msg("waitpid");
1709 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1712 int rcode = checkjobs(fg_pipe);
1713 /* Job finished, move the shell to the foreground */
1714 p = getpgid(0); /* pgid of our process */
1715 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
1716 if (tcsetpgrp(interactive_fd, p) && errno != ENOTTY)
1717 bb_perror_msg("tcsetpgrp-4a");
1722 /* run_pipe_real() starts all the jobs, but doesn't wait for anything
1723 * to finish. See checkjobs().
1725 * return code is normally -1, when the caller has to wait for children
1726 * to finish to determine the exit status of the pipe. If the pipe
1727 * is a simple builtin command, however, the action is done by the
1728 * time run_pipe_real returns, and the exit code is provided as the
1731 * The input of the pipe is always stdin, the output is always
1732 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1733 * because it tries to avoid running the command substitution in
1734 * subshell, when that is in fact necessary. The subshell process
1735 * now has its stdout directed to the input of the appropriate pipe,
1736 * so this routine is noticeably simpler.
1738 * Returns -1 only if started some children. IOW: we have to
1739 * mask out retvals of builtins etc with 0xff!
1741 static int run_pipe_real(struct pipe *pi)
1744 int nextin, nextout;
1745 int pipefds[2]; /* pipefds[0] is for reading */
1746 struct child_prog *child;
1747 const struct built_in_command *x;
1749 /* it is not always needed, but we aim to smaller code */
1750 int squirrel[] = { -1, -1, -1 };
1752 const int single_fg = (pi->num_progs == 1 && pi->followup != PIPE_BG);
1754 debug_printf_exec("run_pipe_real start: single_fg=%d\n", single_fg);
1760 pi->running_progs = 1;
1761 pi->stopped_progs = 0;
1763 /* Check if this is a simple builtin (not part of a pipe).
1764 * Builtins within pipes have to fork anyway, and are handled in
1765 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1767 child = &(pi->progs[0]);
1768 if (single_fg && child->group && child->subshell == 0) {
1769 debug_printf("non-subshell grouping\n");
1770 setup_redirects(child, squirrel);
1771 debug_printf_exec(": run_list_real\n");
1772 rcode = run_list_real(child->group);
1773 restore_redirects(squirrel);
1774 debug_printf_exec("run_pipe_real return %d\n", rcode);
1775 return rcode; // do we need to add '... & 0xff' ?
1778 if (single_fg && child->argv != NULL) {
1779 char **argv_expanded;
1780 char **argv = child->argv;
1782 for (i = 0; is_assignment(argv[i]); i++)
1784 if (i != 0 && argv[i] == NULL) {
1785 /* assignments, but no command: set the local environment */
1786 for (i = 0; argv[i] != NULL; i++) {
1787 debug_printf("local environment set: %s\n", argv[i]);
1788 p = expand_string_to_string(argv[i]);
1789 set_local_var(p, 0);
1791 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1793 for (i = 0; is_assignment(argv[i]); i++) {
1794 p = expand_string_to_string(argv[i]);
1798 for (x = bltins; x->cmd; x++) {
1799 if (strcmp(argv[i], x->cmd) == 0) {
1800 if (x->function == builtin_exec && argv[i+1] == NULL) {
1801 debug_printf("magic exec\n");
1802 setup_redirects(child, NULL);
1803 return EXIT_SUCCESS;
1805 debug_printf("builtin inline %s\n", argv[0]);
1806 /* XXX setup_redirects acts on file descriptors, not FILEs.
1807 * This is perfect for work that comes after exec().
1808 * Is it really safe for inline use? Experimentally,
1809 * things seem to work with glibc. */
1810 setup_redirects(child, squirrel);
1811 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv[i+1]);
1812 //sp: if (child->sp) /* btw we can do it unconditionally... */
1813 argv_expanded = expand_strvec_to_strvec(argv + i);
1814 rcode = x->function(argv_expanded) & 0xff;
1815 free(argv_expanded);
1816 restore_redirects(squirrel);
1817 debug_printf_exec("run_pipe_real return %d\n", rcode);
1821 #if ENABLE_FEATURE_SH_STANDALONE
1823 const struct bb_applet *a = find_applet_by_name(argv[i]);
1824 if (a && a->nofork) {
1825 setup_redirects(child, squirrel);
1826 save_nofork_data(&nofork_save);
1827 argv_expanded = argv + i;
1828 //sp: if (child->sp)
1829 argv_expanded = expand_strvec_to_strvec(argv + i);
1830 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
1831 rcode = run_nofork_applet_prime(&nofork_save, a, argv_expanded) & 0xff;
1832 free(argv_expanded);
1833 restore_redirects(squirrel);
1834 debug_printf_exec("run_pipe_real return %d\n", rcode);
1841 /* Going to fork a child per each pipe member */
1842 pi->running_progs = 0;
1844 /* Disable job control signals for shell (parent) and
1845 * for initial child code after fork */
1846 set_jobctrl_sighandler(SIG_IGN);
1848 for (i = 0; i < pi->num_progs; i++) {
1849 child = &(pi->progs[i]);
1851 debug_printf_exec(": pipe member '%s' '%s'...\n", child->argv[0], child->argv[1]);
1853 debug_printf_exec(": pipe member with no argv\n");
1855 /* pipes are inserted between pairs of commands */
1856 if ((i + 1) < pi->num_progs) {
1858 nextout = pipefds[1];
1864 /* XXX test for failed fork()? */
1866 child->pid = fork();
1868 child->pid = vfork();
1870 if (!child->pid) { /* child */
1871 /* Every child adds itself to new process group
1872 * with pgid == pid of first child in pipe */
1874 if (run_list_level == 1 && interactive_fd) {
1875 /* Don't do pgrp restore anymore on fatal signals */
1876 set_fatal_sighandler(SIG_DFL);
1877 if (pi->pgrp < 0) /* true for 1st process only */
1878 pi->pgrp = getpid();
1879 if (setpgid(0, pi->pgrp) == 0 && pi->followup != PIPE_BG) {
1880 /* We do it in *every* child, not just first,
1882 tcsetpgrp(interactive_fd, pi->pgrp);
1886 /* in non-interactive case fatal sigs are already SIG_DFL */
1887 xmove_fd(nextin, 0);
1888 xmove_fd(nextout, 1);
1889 if (pipefds[0] != -1) {
1890 close(pipefds[0]); /* opposite end of our output pipe */
1892 /* Like bash, explicit redirects override pipes,
1893 * and the pipe fd is available for dup'ing. */
1894 setup_redirects(child, NULL);
1896 /* Restore default handlers just prior to exec */
1897 set_jobctrl_sighandler(SIG_DFL);
1898 set_misc_sighandler(SIG_DFL);
1899 signal(SIGCHLD, SIG_DFL);
1903 pi->running_progs++;
1906 /* Second and next children need to know pid of first one */
1908 pi->pgrp = child->pid;
1915 /* If there isn't another process, nextin is garbage
1916 but it doesn't matter */
1917 nextin = pipefds[0];
1919 debug_printf_exec("run_pipe_real return -1\n");
1923 #ifndef debug_print_tree
1924 static void debug_print_tree(struct pipe *pi, int lvl)
1926 static const char *PIPE[] = {
1932 static const char *RES[] = {
1933 [RES_NONE ] = "NONE" ,
1936 [RES_THEN ] = "THEN" ,
1937 [RES_ELIF ] = "ELIF" ,
1938 [RES_ELSE ] = "ELSE" ,
1941 #if ENABLE_HUSH_LOOPS
1942 [RES_FOR ] = "FOR" ,
1943 [RES_WHILE] = "WHILE",
1944 [RES_UNTIL] = "UNTIL",
1946 [RES_DONE ] = "DONE" ,
1949 [RES_XXXX ] = "XXXX" ,
1950 [RES_SNTX ] = "SNTX" ,
1957 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
1958 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
1960 while (prn < pi->num_progs) {
1961 struct child_prog *child = &pi->progs[prn];
1962 char **argv = child->argv;
1964 fprintf(stderr, "%*s prog %d", lvl*2, "", prn);
1966 fprintf(stderr, " group %s: (argv=%p)\n",
1967 (child->subshell ? "()" : "{}"),
1969 debug_print_tree(child->group, lvl+1);
1973 if (argv) while (*argv) {
1974 fprintf(stderr, " '%s'", *argv);
1977 fprintf(stderr, "\n");
1986 /* NB: called by pseudo_exec, and therefore must not modify any
1987 * global data until exec/_exit (we can be a child after vfork!) */
1988 static int run_list_real(struct pipe *pi)
1991 #if ENABLE_HUSH_LOOPS
1992 char *for_varname = NULL;
1993 char **for_lcur = NULL;
1994 char **for_list = NULL;
1999 int rcode = 0; /* probably for gcc only */
2000 int flag_restore = 0;
2002 int if_code = 0, next_if_code = 0; /* need double-buffer to handle elif */
2004 enum { if_code = 0, next_if_code = 0 };
2006 reserved_style rword;
2007 reserved_style skip_more_for_this_rword = RES_XXXX;
2009 debug_printf_exec("run_list_real start lvl %d\n", run_list_level + 1);
2011 #if ENABLE_HUSH_LOOPS
2012 /* check syntax for "for" */
2013 for (rpipe = pi; rpipe; rpipe = rpipe->next) {
2014 if ((rpipe->res_word == RES_IN || rpipe->res_word == RES_FOR)
2015 && (rpipe->next == NULL)
2017 syntax("malformed for"); /* no IN or no commands after IN */
2018 debug_printf_exec("run_list_real lvl %d return 1\n", run_list_level);
2021 if ((rpipe->res_word == RES_IN && rpipe->next->res_word == RES_IN && rpipe->next->progs[0].argv != NULL)
2022 || (rpipe->res_word == RES_FOR && rpipe->next->res_word != RES_IN)
2024 /* TODO: what is tested in the first condition? */
2025 syntax("malformed for"); /* 2nd condition: not followed by IN */
2026 debug_printf_exec("run_list_real lvl %d return 1\n", run_list_level);
2035 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
2036 * We are saving state before entering outermost list ("while...done")
2037 * so that ctrl-Z will correctly background _entire_ outermost list,
2038 * not just a part of it (like "sleep 1 | exit 2") */
2039 if (++run_list_level == 1 && interactive_fd) {
2040 if (sigsetjmp(toplevel_jb, 1)) {
2041 /* ctrl-Z forked and we are parent; or ctrl-C.
2042 * Sighandler has longjmped us here */
2043 signal(SIGINT, SIG_IGN);
2044 signal(SIGTSTP, SIG_IGN);
2045 /* Restore level (we can be coming from deep inside
2048 #if ENABLE_FEATURE_SH_STANDALONE
2049 if (nofork_save.saved) { /* if save area is valid */
2050 debug_printf_jobs("exiting nofork early\n");
2051 restore_nofork_data(&nofork_save);
2055 /* ctrl-Z has forked and stored pid of the child in pi->pid.
2056 * Remember this child as background job */
2059 /* ctrl-C. We just stop doing whatever we were doing */
2065 /* ctrl-Z handler will store pid etc in pi */
2068 #if ENABLE_FEATURE_SH_STANDALONE
2069 nofork_save.saved = 0; /* in case we will run a nofork later */
2071 signal_SA_RESTART(SIGTSTP, handler_ctrl_z);
2072 signal(SIGINT, handler_ctrl_c);
2076 for (; pi; pi = flag_restore ? rpipe : pi->next) {
2077 rword = pi->res_word;
2078 #if ENABLE_HUSH_LOOPS
2079 if (rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR) {
2087 debug_printf_exec(": rword=%d if_code=%d next_if_code=%d skip_more=%d\n",
2088 rword, if_code, next_if_code, skip_more_for_this_rword);
2089 if (rword == skip_more_for_this_rword && flag_skip) {
2090 if (pi->followup == PIPE_SEQ)
2095 skip_more_for_this_rword = RES_XXXX;
2097 if (rword == RES_THEN || rword == RES_ELSE)
2098 if_code = next_if_code;
2099 if (rword == RES_THEN && if_code)
2101 if (rword == RES_ELSE && !if_code)
2103 if (rword == RES_ELIF && !if_code)
2106 #if ENABLE_HUSH_LOOPS
2107 if (rword == RES_FOR && pi->num_progs) {
2109 /* first loop through for */
2110 /* if no variable values after "in" we skip "for" */
2111 if (!pi->next->progs->argv)
2113 /* create list of variable values */
2114 for_list = expand_strvec_to_strvec(pi->next->progs->argv);
2115 for_lcur = for_list;
2116 for_varname = pi->progs->argv[0];
2117 pi->progs->argv[0] = NULL;
2120 free(pi->progs->argv[0]);
2122 /* for loop is over, clean up */
2126 pi->progs->argv[0] = for_varname;
2129 /* insert next value from for_lcur */
2130 /* vda: does it need escaping? */
2131 pi->progs->argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
2133 if (rword == RES_IN)
2135 if (rword == RES_DO) {
2139 if (rword == RES_DONE) {
2147 if (pi->num_progs == 0)
2149 save_num_progs = pi->num_progs; /* save number of programs */
2150 debug_printf_exec(": run_pipe_real with %d members\n", pi->num_progs);
2151 rcode = run_pipe_real(pi);
2153 /* We only ran a builtin: rcode was set by the return value
2154 * of run_pipe_real(), and we don't need to wait for anything. */
2155 } else if (pi->followup == PIPE_BG) {
2156 /* What does bash do with attempts to background builtins? */
2157 /* Even bash 3.2 doesn't do that well with nested bg:
2158 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
2159 * I'm NOT treating inner &'s as jobs */
2161 if (run_list_level == 1)
2164 rcode = EXIT_SUCCESS;
2167 /* Paranoia, just "interactive_fd" should be enough? */
2168 if (run_list_level == 1 && interactive_fd) {
2169 /* waits for completion, then fg's main shell */
2170 rcode = checkjobs_and_fg_shell(pi);
2174 /* this one just waits for completion */
2175 rcode = checkjobs(pi);
2177 debug_printf_exec(": checkjobs returned %d\n", rcode);
2179 debug_printf_exec(": setting last_return_code=%d\n", rcode);
2180 last_return_code = rcode;
2181 pi->num_progs = save_num_progs; /* restore number of programs */
2183 if (rword == RES_IF || rword == RES_ELIF)
2184 next_if_code = rcode; /* can be overwritten a number of times */
2186 #if ENABLE_HUSH_LOOPS
2187 if (rword == RES_WHILE)
2188 flag_rep = !last_return_code;
2189 if (rword == RES_UNTIL)
2190 flag_rep = last_return_code;
2192 if ((rcode == EXIT_SUCCESS && pi->followup == PIPE_OR)
2193 || (rcode != EXIT_SUCCESS && pi->followup == PIPE_AND)
2195 skip_more_for_this_rword = rword;
2202 /* ctrl-Z forked somewhere in the past, we are the child,
2203 * and now we completed running the list. Exit. */
2207 if (!--run_list_level && interactive_fd) {
2208 signal(SIGTSTP, SIG_IGN);
2209 signal(SIGINT, SIG_IGN);
2212 debug_printf_exec("run_list_real lvl %d return %d\n", run_list_level + 1, rcode);
2216 /* return code is the exit status of the pipe */
2217 static int free_pipe(struct pipe *pi, int indent)
2220 struct child_prog *child;
2221 struct redir_struct *r, *rnext;
2222 int a, i, ret_code = 0;
2224 if (pi->stopped_progs > 0)
2226 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2227 for (i = 0; i < pi->num_progs; i++) {
2228 child = &pi->progs[i];
2229 debug_printf_clean("%s command %d:\n", indenter(indent), i);
2231 for (a = 0, p = child->argv; *p; a++, p++) {
2232 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
2234 free_strings(child->argv);
2236 } else if (child->group) {
2237 debug_printf_clean("%s begin group (subshell:%d)\n", indenter(indent), child->subshell);
2238 ret_code = free_pipe_list(child->group, indent+3);
2239 debug_printf_clean("%s end group\n", indenter(indent));
2241 debug_printf_clean("%s (nil)\n", indenter(indent));
2243 for (r = child->redirects; r; r = rnext) {
2244 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->type].descrip);
2246 /* guard against the case >$FOO, where foo is unset or blank */
2248 debug_printf_clean(" %s\n", r->glob_word[0]);
2249 free_strings(r->glob_word);
2250 r->glob_word = NULL;
2253 debug_printf_clean("&%d\n", r->dup);
2258 child->redirects = NULL;
2260 free(pi->progs); /* children are an array, they get freed all at once */
2269 static int free_pipe_list(struct pipe *head, int indent)
2271 int rcode = 0; /* if list has no members */
2272 struct pipe *pi, *next;
2274 for (pi = head; pi; pi = next) {
2275 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
2276 rcode = free_pipe(pi, indent);
2277 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
2279 /*pi->next = NULL;*/
2285 /* Select which version we will use */
2286 static int run_list(struct pipe *pi)
2289 debug_printf_exec("run_list entered\n");
2290 if (fake_mode == 0) {
2291 debug_printf_exec(": run_list_real with %d members\n", pi->num_progs);
2292 rcode = run_list_real(pi);
2294 /* free_pipe_list has the side effect of clearing memory.
2295 * In the long run that function can be merged with run_list_real,
2296 * but doing that now would hobble the debugging effort. */
2297 free_pipe_list(pi, 0);
2298 debug_printf_exec("run_list return %d\n", rcode);
2302 /* Whoever decided to muck with glob internal data is AN IDIOT! */
2303 /* uclibc happily changed the way it works (and it has rights to do so!),
2304 all hell broke loose (SEGVs) */
2306 /* The API for glob is arguably broken. This routine pushes a non-matching
2307 * string into the output structure, removing non-backslashed backslashes.
2308 * If someone can prove me wrong, by performing this function within the
2309 * original glob(3) api, feel free to rewrite this routine into oblivion.
2310 * XXX broken if the last character is '\\', check that before calling.
2312 static char **globhack(const char *src, char **strings)
2318 for (cnt = 1, s = src; s && *s; s++) {
2319 if (*s == '\\') s++;
2322 v = dest = xmalloc(cnt);
2323 for (s = src; s && *s; s++, dest++) {
2324 if (*s == '\\') s++;
2329 return add_string_to_strings(strings, v);
2332 /* XXX broken if the last character is '\\', check that before calling */
2333 static int glob_needed(const char *s)
2338 if (strchr("*[?", *s))
2344 static int xglob(o_string *dest, char ***pglob)
2346 /* short-circuit for null word */
2347 /* we can code this better when the debug_printf's are gone */
2348 if (dest->length == 0) {
2349 if (dest->nonnull) {
2350 /* bash man page calls this an "explicit" null */
2351 *pglob = globhack(dest->data, *pglob);
2356 if (glob_needed(dest->data)) {
2360 memset(&globdata, 0, sizeof(globdata));
2361 gr = glob(dest->data, 0, NULL, &globdata);
2362 debug_printf("glob returned %d\n", gr);
2363 if (gr == GLOB_NOSPACE)
2364 bb_error_msg_and_die("out of memory during glob");
2365 if (gr == GLOB_NOMATCH) {
2366 debug_printf("globhack returned %d\n", gr);
2367 /* quote removal, or more accurately, backslash removal */
2368 *pglob = globhack(dest->data, *pglob);
2369 globfree(&globdata);
2372 if (gr != 0) { /* GLOB_ABORTED ? */
2373 bb_error_msg("glob(3) error %d", gr);
2375 if (globdata.gl_pathv && globdata.gl_pathv[0])
2376 *pglob = add_strings_to_strings(1, *pglob, globdata.gl_pathv);
2377 globfree(&globdata);
2381 *pglob = globhack(dest->data, *pglob);
2385 /* expand_strvec_to_strvec() takes a list of strings, expands
2386 * all variable references within and returns a pointer to
2387 * a list of expanded strings, possibly with larger number
2388 * of strings. (Think VAR="a b"; echo $VAR).
2389 * This new list is allocated as a single malloc block.
2390 * NULL-terminated list of char* pointers is at the beginning of it,
2391 * followed by strings themself.
2392 * Caller can deallocate entire list by single free(list). */
2395 * count_XXX estimates size of the block we need. It's okay
2396 * to over-estimate sizes a bit, if it makes code simpler */
2397 static int count_ifs(const char *str)
2400 debug_printf_expand("count_ifs('%s') ifs='%s'", str, ifs);
2402 str += strcspn(str, ifs);
2404 str++; /* str += strspn(str, ifs); */
2405 cnt++; /* cnt += strspn(str, ifs); - but this code is larger */
2407 debug_printf_expand(" return %d\n", cnt);
2411 static void count_var_expansion_space(int *countp, int *lenp, char *arg)
2416 int count = *countp;
2420 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2423 p = strchr(p, SPECIAL_VAR_SYMBOL);
2426 switch (first_ch & 0x7f) {
2427 /* high bit in 1st_ch indicates that var is double-quoted */
2429 case '!': /* bg pid */
2430 case '?': /* exitcode */
2431 case '#': /* argc */
2432 len += sizeof(int)*3 + 1; /* enough for int */
2436 for (i = 1; i < global_argc; i++) {
2437 len += strlen(global_argv[i]) + 1;
2439 if (!(first_ch & 0x80))
2440 count += count_ifs(global_argv[i]);
2445 arg[0] = first_ch & 0x7f;
2446 if (isdigit(arg[0])) {
2449 if (i < global_argc)
2450 val = global_argv[i];
2452 val = lookup_param(arg);
2454 *p = SPECIAL_VAR_SYMBOL;
2457 len += strlen(val) + 1;
2458 if (!(first_ch & 0x80))
2459 count += count_ifs(val);
2465 len += strlen(arg) + 1;
2471 /* Store given string, finalizing the word and starting new one whenever
2472 * we encounter ifs char(s). This is used for expanding variable values.
2473 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2474 static int expand_on_ifs(char **list, int n, char **posp, const char *str)
2478 int word_len = strcspn(str, ifs);
2480 memcpy(pos, str, word_len); /* store non-ifs chars */
2484 if (!*str) /* EOL - do not finalize word */
2487 if (n) debug_printf_expand("expand_on_ifs finalized list[%d]=%p '%s' "
2488 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2489 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2491 str += strspn(str, ifs); /* skip ifs chars */
2497 /* Expand all variable references in given string, adding words to list[]
2498 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2499 * to be filled). This routine is extremely tricky: has to deal with
2500 * variables/parameters with whitespace, $* and $@, and constructs like
2501 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2502 /* NB: another bug is that we cannot detect empty strings yet:
2503 * "" or $empty"" expands to zero words, has to expand to empty word */
2504 static int expand_vars_to_list(char **list, int n, char **posp, char *arg, char or_mask)
2506 /* or_mask is either 0 (normal case) or 0x80
2507 * (expansion of right-hand side of assignment == 1-element expand) */
2509 char first_ch, ored_ch;
2517 if (n) debug_printf_expand("expand_vars_to_list finalized list[%d]=%p '%s' "
2518 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2519 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2522 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2523 memcpy(pos, arg, p - arg);
2526 p = strchr(p, SPECIAL_VAR_SYMBOL);
2528 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2529 ored_ch |= first_ch;
2531 switch (first_ch & 0x7f) {
2532 /* Highest bit in first_ch indicates that var is double-quoted */
2534 /* FIXME: (echo $$) should still print pid of main shell */
2535 val = utoa(getpid());
2537 case '!': /* bg pid */
2538 val = last_bg_pid ? utoa(last_bg_pid) : (char*)"";
2540 case '?': /* exitcode */
2541 val = utoa(last_return_code);
2543 case '#': /* argc */
2544 val = utoa(global_argc ? global_argc-1 : 0);
2549 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2550 while (i < global_argc) {
2551 n = expand_on_ifs(list, n, &pos, global_argv[i]);
2552 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, global_argc-1);
2553 if (global_argv[i++][0] && i < global_argc) {
2554 /* this argv[] is not empty and not last:
2555 * put terminating NUL, start new word */
2557 if (n) debug_printf_expand("expand_vars_to_list 2 finalized list[%d]=%p '%s' "
2558 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2559 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2564 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2565 * and in this case should theat it like '$*' */
2566 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2568 strcpy(pos, global_argv[i]);
2569 pos += strlen(global_argv[i]);
2570 if (++i >= global_argc)
2573 if (n) debug_printf_expand("expand_vars_to_list 3 finalized list[%d]=%p '%s' "
2574 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2575 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2578 } else { /* quoted $*: add as one word */
2580 strcpy(pos, global_argv[i]);
2581 pos += strlen(global_argv[i]);
2582 if (++i >= global_argc)
2591 arg[0] = first_ch & 0x7f;
2592 if (isdigit(arg[0])) {
2595 if (i < global_argc)
2596 val = global_argv[i];
2598 val = lookup_param(arg);
2600 *p = SPECIAL_VAR_SYMBOL;
2601 if (!(first_ch & 0x80)) { /* unquoted $VAR */
2603 n = expand_on_ifs(list, n, &pos, val);
2606 } /* else: quoted $VAR, val will be appended at pos */
2614 debug_printf_expand("expand_vars_to_list adding tail '%s' at %p\n", arg, pos);
2616 pos += strlen(arg) + 1;
2617 if (pos == list[n-1] + 1) { /* expansion is empty */
2618 if (!(ored_ch & 0x80)) { /* all vars were not quoted... */
2619 debug_printf_expand("expand_vars_to_list list[%d] empty, going back\n", n);
2629 static char **expand_variables(char **argv, char or_mask)
2634 char *pos, **v, **list;
2637 if (!*v) debug_printf_expand("count_var_expansion_space: "
2638 "argv[0]=NULL count=%d len=%d alloc_space=%d\n",
2639 count, len, sizeof(char*) * count + len);
2641 count_var_expansion_space(&count, &len, *v);
2642 debug_printf_expand("count_var_expansion_space: "
2643 "'%s' count=%d len=%d alloc_space=%d\n",
2644 *v, count, len, sizeof(char*) * count + len);
2647 len += sizeof(char*) * count; /* total to alloc */
2648 list = xmalloc(len);
2649 pos = (char*)(list + count);
2650 debug_printf_expand("list=%p, list[0] should be %p\n", list, pos);
2654 n = expand_vars_to_list(list, n, &pos, *v++, or_mask);
2656 if (n) debug_printf_expand("finalized list[%d]=%p '%s' "
2657 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2658 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2665 debug_printf_expand("list[%d]=%p '%s'\n", m, list[m], list[m]);
2668 debug_printf_expand("used_space=%d\n", pos - (char*)list);
2671 if (ENABLE_HUSH_DEBUG)
2672 if (pos - (char*)list > len)
2673 bb_error_msg_and_die("BUG in varexp");
2677 static char **expand_strvec_to_strvec(char **argv)
2679 return expand_variables(argv, 0);
2682 static char *expand_string_to_string(const char *str)
2684 char *argv[2], **list;
2686 argv[0] = (char*)str;
2688 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2689 if (ENABLE_HUSH_DEBUG)
2690 if (!list[0] || list[1])
2691 bb_error_msg_and_die("BUG in varexp2");
2692 /* actually, just move string 2*sizeof(char*) bytes back */
2693 strcpy((char*)list, list[0]);
2694 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2698 static char* expand_strvec_to_string(char **argv)
2702 list = expand_variables(argv, 0x80);
2703 /* Convert all NULs to spaces */
2707 if (ENABLE_HUSH_DEBUG)
2708 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2709 bb_error_msg_and_die("BUG in varexp3");
2710 list[n][-1] = ' '; /* TODO: or to ifs[0]? */
2714 strcpy((char*)list, list[0]);
2715 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2719 /* This is used to get/check local shell variables */
2720 static struct variable *get_local_var(const char *name)
2722 struct variable *cur;
2728 for (cur = top_var; cur; cur = cur->next) {
2729 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
2735 /* str holds "NAME=VAL" and is expected to be malloced.
2736 * We take ownership of it. */
2737 static int set_local_var(char *str, int flg_export)
2739 struct variable *cur;
2743 value = strchr(str, '=');
2744 if (!value) { /* not expected to ever happen? */
2749 name_len = value - str + 1; /* including '=' */
2750 cur = top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
2752 if (strncmp(cur->varstr, str, name_len) != 0) {
2754 /* Bail out. Note that now cur points
2755 * to last var in linked list */
2761 /* We found an existing var with this name */
2763 if (cur->flg_read_only) {
2764 bb_error_msg("%s: readonly variable", str);
2768 unsetenv(str); /* just in case */
2770 if (strcmp(cur->varstr, str) == 0) {
2775 if (cur->max_len >= strlen(str)) {
2776 /* This one is from startup env, reuse space */
2777 strcpy(cur->varstr, str);
2780 /* max_len == 0 signifies "malloced" var, which we can
2781 * (and has to) free */
2785 goto set_str_and_exp;
2788 /* Not found - create next variable struct */
2789 cur->next = xzalloc(sizeof(*cur));
2796 cur->flg_export = 1;
2797 if (cur->flg_export)
2798 return putenv(cur->varstr);
2802 static void unset_local_var(const char *name)
2804 struct variable *cur;
2805 struct variable *prev = prev; /* for gcc */
2810 name_len = strlen(name);
2813 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2814 if (cur->flg_read_only) {
2815 bb_error_msg("%s: readonly variable", name);
2818 /* prev is ok to use here because 1st variable, HUSH_VERSION,
2819 * is ro, and we cannot reach this code on the 1st pass */
2820 prev->next = cur->next;
2821 unsetenv(cur->varstr);
2832 static int is_assignment(const char *s)
2834 if (!s || !isalpha(*s))
2837 while (isalnum(*s) || *s == '_')
2842 /* the src parameter allows us to peek forward to a possible &n syntax
2843 * for file descriptor duplication, e.g., "2>&1".
2844 * Return code is 0 normally, 1 if a syntax error is detected in src.
2845 * Resource errors (in xmalloc) cause the process to exit */
2846 static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2847 struct in_str *input)
2849 struct child_prog *child = ctx->child;
2850 struct redir_struct *redir = child->redirects;
2851 struct redir_struct *last_redir = NULL;
2853 /* Create a new redir_struct and drop it onto the end of the linked list */
2856 redir = redir->next;
2858 redir = xzalloc(sizeof(struct redir_struct));
2859 /* redir->next = NULL; */
2860 /* redir->glob_word = NULL; */
2862 last_redir->next = redir;
2864 child->redirects = redir;
2867 redir->type = style;
2868 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
2870 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2872 /* Check for a '2>&1' type redirect */
2873 redir->dup = redirect_dup_num(input);
2874 if (redir->dup == -2) return 1; /* syntax error */
2875 if (redir->dup != -1) {
2876 /* Erik had a check here that the file descriptor in question
2877 * is legit; I postpone that to "run time"
2878 * A "-" representation of "close me" shows up as a -3 here */
2879 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2881 /* We do _not_ try to open the file that src points to,
2882 * since we need to return and let src be expanded first.
2883 * Set ctx->pending_redirect, so we know what to do at the
2884 * end of the next parsed word. */
2885 ctx->pending_redirect = redir;
2890 static struct pipe *new_pipe(void)
2893 pi = xzalloc(sizeof(struct pipe));
2894 /*pi->num_progs = 0;*/
2895 /*pi->progs = NULL;*/
2896 /*pi->next = NULL;*/
2897 /*pi->followup = 0; invalid */
2899 pi->res_word = RES_NONE;
2903 static void initialize_context(struct p_context *ctx)
2906 ctx->pipe = ctx->list_head = new_pipe();
2907 ctx->pending_redirect = NULL;
2908 ctx->res_w = RES_NONE;
2909 //only ctx->parse_type is not touched... is this intentional?
2912 done_command(ctx); /* creates the memory for working child */
2915 /* normal return is 0
2916 * if a reserved word is found, and processed, return 1
2917 * should handle if, then, elif, else, fi, for, while, until, do, done.
2918 * case, function, and select are obnoxious, save those for later.
2920 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS
2921 static int reserved_word(o_string *dest, struct p_context *ctx)
2923 struct reserved_combo {
2928 /* Mostly a list of accepted follow-up reserved words.
2929 * FLAG_END means we are done with the sequence, and are ready
2930 * to turn the compound list into a command.
2931 * FLAG_START means the word must start a new compound list.
2933 static const struct reserved_combo reserved_list[] = {
2935 { "if", RES_IF, FLAG_THEN | FLAG_START },
2936 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2937 { "elif", RES_ELIF, FLAG_THEN },
2938 { "else", RES_ELSE, FLAG_FI },
2939 { "fi", RES_FI, FLAG_END },
2941 #if ENABLE_HUSH_LOOPS
2942 { "for", RES_FOR, FLAG_IN | FLAG_START },
2943 { "while", RES_WHILE, FLAG_DO | FLAG_START },
2944 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
2945 { "in", RES_IN, FLAG_DO },
2946 { "do", RES_DO, FLAG_DONE },
2947 { "done", RES_DONE, FLAG_END }
2951 const struct reserved_combo *r;
2953 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
2954 if (strcmp(dest->data, r->literal) != 0)
2956 debug_printf("found reserved word %s, code %d\n", r->literal, r->code);
2957 if (r->flag & FLAG_START) {
2958 struct p_context *new;
2959 debug_printf("push stack\n");
2960 #if ENABLE_HUSH_LOOPS
2961 if (ctx->res_w == RES_IN || ctx->res_w == RES_FOR) {
2962 syntax("malformed for"); /* example: 'for if' */
2963 ctx->res_w = RES_SNTX;
2968 new = xmalloc(sizeof(*new));
2969 *new = *ctx; /* physical copy */
2970 initialize_context(ctx);
2972 } else if (ctx->res_w == RES_NONE || !(ctx->old_flag & (1 << r->code))) {
2974 ctx->res_w = RES_SNTX;
2978 ctx->res_w = r->code;
2979 ctx->old_flag = r->flag;
2980 if (ctx->old_flag & FLAG_END) {
2981 struct p_context *old;
2982 debug_printf("pop stack\n");
2983 done_pipe(ctx, PIPE_SEQ);
2985 old->child->group = ctx->list_head;
2986 old->child->subshell = 0;
2987 *ctx = *old; /* physical copy */
2996 #define reserved_word(dest, ctx) ((int)0)
2999 /* Normal return is 0.
3000 * Syntax or xglob errors return 1. */
3001 static int done_word(o_string *dest, struct p_context *ctx)
3003 struct child_prog *child = ctx->child;
3004 char ***glob_target;
3007 debug_printf_parse("done_word entered: '%s' %p\n", dest->data, child);
3008 if (dest->length == 0 && !dest->nonnull) {
3009 debug_printf_parse("done_word return 0: true null, ignored\n");
3012 if (ctx->pending_redirect) {
3013 glob_target = &ctx->pending_redirect->glob_word;
3017 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
3020 if (!child->argv && (ctx->parse_type & PARSEFLAG_SEMICOLON)) {
3021 debug_printf_parse(": checking '%s' for reserved-ness\n", dest->data);
3022 if (reserved_word(dest, ctx)) {
3023 debug_printf_parse("done_word return %d\n", (ctx->res_w == RES_SNTX));
3024 return (ctx->res_w == RES_SNTX);
3027 glob_target = &child->argv;
3029 gr = xglob(dest, glob_target);
3031 debug_printf_parse("done_word return 1: xglob returned %d\n", gr);
3036 if (ctx->pending_redirect) {
3037 /* NB: don't free_strings(ctx->pending_redirect->glob_word) here */
3038 if (ctx->pending_redirect->glob_word
3039 && ctx->pending_redirect->glob_word[0]
3040 && ctx->pending_redirect->glob_word[1]
3042 /* more than one word resulted from globbing redir */
3043 ctx->pending_redirect = NULL;
3044 bb_error_msg("ambiguous redirect");
3045 debug_printf_parse("done_word return 1: ambiguous redirect\n");
3048 ctx->pending_redirect = NULL;
3050 #if ENABLE_HUSH_LOOPS
3051 if (ctx->res_w == RES_FOR) {
3052 done_word(dest, ctx);
3053 done_pipe(ctx, PIPE_SEQ);
3056 debug_printf_parse("done_word return 0\n");
3060 /* The only possible error here is out of memory, in which case
3062 static int done_command(struct p_context *ctx)
3064 /* The child is really already in the pipe structure, so
3065 * advance the pipe counter and make a new, null child. */
3066 struct pipe *pi = ctx->pipe;
3067 struct child_prog *child = ctx->child;
3070 if (child->group == NULL
3071 && child->argv == NULL
3072 && child->redirects == NULL
3074 debug_printf_parse("done_command: skipping null cmd, num_progs=%d\n", pi->num_progs);
3075 return pi->num_progs;
3078 debug_printf_parse("done_command: ++num_progs=%d\n", pi->num_progs);
3080 debug_printf_parse("done_command: initializing, num_progs=%d\n", pi->num_progs);
3083 /* Only real trickiness here is that the uncommitted
3084 * child structure is not counted in pi->num_progs. */
3085 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
3086 child = &pi->progs[pi->num_progs];
3088 memset(child, 0, sizeof(*child));
3089 /*child->redirects = NULL;*/
3090 /*child->argv = NULL;*/
3091 /*child->is_stopped = 0;*/
3092 /*child->group = NULL;*/
3094 //sp: /*child->sp = 0;*/
3095 //pt: child->parse_type = ctx->parse_type;
3098 /* but ctx->pipe and ctx->list_head remain unchanged */
3100 return pi->num_progs; /* used only for 0/nonzero check */
3103 static int done_pipe(struct p_context *ctx, pipe_style type)
3108 debug_printf_parse("done_pipe entered, followup %d\n", type);
3109 not_null = done_command(ctx); /* implicit closure of previous command */
3110 ctx->pipe->followup = type;
3111 ctx->pipe->res_word = ctx->res_w;
3112 /* Without this check, even just <enter> on command line generates
3113 * tree of three NOPs (!). Which is harmless but annoying.
3114 * IOW: it is safe to do it unconditionally. */
3117 ctx->pipe->next = new_p;
3120 done_command(ctx); /* set up new pipe to accept commands */
3122 debug_printf_parse("done_pipe return 0\n");
3126 /* peek ahead in the in_str to find out if we have a "&n" construct,
3127 * as in "2>&1", that represents duplicating a file descriptor.
3128 * returns either -2 (syntax error), -1 (no &), or the number found.
3130 static int redirect_dup_num(struct in_str *input)
3132 int ch, d = 0, ok = 0;
3134 if (ch != '&') return -1;
3136 b_getch(input); /* get the & */
3140 return -3; /* "-" represents "close me" */
3142 while (isdigit(ch)) {
3143 d = d*10 + (ch-'0');
3150 bb_error_msg("ambiguous redirect");
3154 /* If a redirect is immediately preceded by a number, that number is
3155 * supposed to tell which file descriptor to redirect. This routine
3156 * looks for such preceding numbers. In an ideal world this routine
3157 * needs to handle all the following classes of redirects...
3158 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3159 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3160 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3161 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3162 * A -1 output from this program means no valid number was found, so the
3163 * caller should use the appropriate default for this redirection.
3165 static int redirect_opt_num(o_string *o)
3171 for (num = 0; num < o->length; num++) {
3172 if (!isdigit(*(o->data + num))) {
3176 /* reuse num (and save an int) */
3177 num = atoi(o->data);
3182 #if ENABLE_HUSH_TICK
3183 /* NB: currently disabled on NOMMU */
3184 static FILE *generate_stream_from_list(struct pipe *head)
3187 int pid, channel[2];
3192 bb_perror_msg_and_die("fork");
3193 } else if (pid == 0) {
3195 if (channel[1] != 1) {
3196 dup2(channel[1], 1);
3199 /* Prevent it from trying to handle ctrl-z etc */
3203 /* Process substitution is not considered to be usual
3204 * 'command execution'.
3205 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not. */
3206 /* Not needed, we are relying on it being disabled
3207 * everywhere outside actual command execution. */
3208 /*set_jobctrl_sighandler(SIG_IGN);*/
3209 set_misc_sighandler(SIG_DFL);
3210 _exit(run_list_real(head)); /* leaks memory */
3213 pf = fdopen(channel[0], "r");
3217 /* Return code is exit status of the process that is run. */
3218 static int process_command_subs(o_string *dest, struct p_context *ctx,
3219 struct in_str *input, const char *subst_end)
3221 int retcode, ch, eol_cnt;
3222 o_string result = NULL_O_STRING;
3223 struct p_context inner;
3225 struct in_str pipe_str;
3227 initialize_context(&inner);
3229 /* recursion to generate command */
3230 retcode = parse_stream(&result, &inner, input, subst_end);
3232 return retcode; /* syntax error or EOF */
3233 done_word(&result, &inner);
3234 done_pipe(&inner, PIPE_SEQ);
3237 p = generate_stream_from_list(inner.list_head);
3238 if (p == NULL) return 1;
3239 close_on_exec_on(fileno(p));
3240 setup_file_in_str(&pipe_str, p);
3242 /* now send results of command back into original context */
3244 while ((ch = b_getch(&pipe_str)) != EOF) {
3250 b_addqchr(dest, '\n', dest->o_quote);
3253 b_addqchr(dest, ch, dest->o_quote);
3256 debug_printf("done reading from pipe, pclose()ing\n");
3257 /* This is the step that wait()s for the child. Should be pretty
3258 * safe, since we just read an EOF from its stdout. We could try
3259 * to do better, by using wait(), and keeping track of background jobs
3260 * at the same time. That would be a lot of work, and contrary
3261 * to the KISS philosophy of this program. */
3262 retcode = fclose(p);
3263 free_pipe_list(inner.list_head, 0);
3264 debug_printf("closed FILE from child, retcode=%d\n", retcode);
3269 static int parse_group(o_string *dest, struct p_context *ctx,
3270 struct in_str *input, int ch)
3273 const char *endch = NULL;
3274 struct p_context sub;
3275 struct child_prog *child = ctx->child;
3277 debug_printf_parse("parse_group entered\n");
3280 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3283 initialize_context(&sub);
3287 child->subshell = 1;
3289 rcode = parse_stream(dest, &sub, input, endch);
3291 done_word(dest, &sub); /* finish off the final word in the subcontext */
3292 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
3293 child->group = sub.list_head;
3295 debug_printf_parse("parse_group return %d\n", rcode);
3297 /* child remains "open", available for possible redirects */
3300 /* Basically useful version until someone wants to get fancier,
3301 * see the bash man page under "Parameter Expansion" */
3302 static const char *lookup_param(const char *src)
3304 struct variable *var = get_local_var(src);
3306 return strchr(var->varstr, '=') + 1;
3310 /* return code: 0 for OK, 1 for syntax error */
3311 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
3313 int ch = b_peek(input); /* first character after the $ */
3314 unsigned char quote_mask = dest->o_quote ? 0x80 : 0;
3316 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
3318 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3319 //sp: ctx->child->sp++;
3321 debug_printf_parse(": '%c'\n", ch);
3323 b_addchr(dest, ch | quote_mask);
3326 if (!isalnum(ch) && ch != '_')
3329 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3330 } else if (isdigit(ch)) {
3332 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3333 //sp: ctx->child->sp++;
3334 debug_printf_parse(": '%c'\n", ch);
3336 b_addchr(dest, ch | quote_mask);
3337 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3338 } else switch (ch) {
3340 case '!': /* last bg pid */
3341 case '?': /* last exit code */
3342 case '#': /* number of args */
3343 case '*': /* args */
3344 case '@': /* args */
3345 goto make_one_char_var;
3347 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3348 //sp: ctx->child->sp++;
3350 /* XXX maybe someone will try to escape the '}' */
3352 ch = b_getch(input);
3355 if (!isalnum(ch) && ch != '_') {
3356 syntax("unterminated ${name}");
3357 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3360 debug_printf_parse(": '%c'\n", ch);
3361 b_addchr(dest, ch | quote_mask);
3364 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3366 #if ENABLE_HUSH_TICK
3369 process_command_subs(dest, ctx, input, ")");
3374 /* still unhandled, but should be eventually */
3375 bb_error_msg("unhandled syntax: $%c", ch);
3379 b_addqchr(dest, '$', dest->o_quote);
3381 debug_printf_parse("handle_dollar return 0\n");
3385 /* return code is 0 for normal exit, 1 for syntax error */
3386 static int parse_stream(o_string *dest, struct p_context *ctx,
3387 struct in_str *input, const char *end_trigger)
3391 redir_type redir_style;
3394 /* Only double-quote state is handled in the state variable dest->o_quote.
3395 * A single-quote triggers a bypass of the main loop until its mate is
3396 * found. When recursing, quote state is passed in via dest->o_quote. */
3398 debug_printf_parse("parse_stream entered, end_trigger='%s'\n", end_trigger);
3403 ch = b_getch(input);
3407 next = b_peek(input);
3409 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
3410 ch, ch, m, dest->o_quote);
3411 if (m == CHAR_ORDINARY
3412 || (m != CHAR_SPECIAL && dest->o_quote)
3415 syntax("unterminated \"");
3416 debug_printf_parse("parse_stream return 1: unterminated \"\n");
3419 b_addqchr(dest, ch, dest->o_quote);
3422 if (m == CHAR_IFS) {
3423 if (done_word(dest, ctx)) {
3424 debug_printf_parse("parse_stream return 1: done_word!=0\n");
3429 /* If we aren't performing a substitution, treat
3430 * a newline as a command separator.
3431 * [why we don't handle it exactly like ';'? --vda] */
3432 if (end_trigger && ch == '\n') {
3433 done_pipe(ctx, PIPE_SEQ);
3436 if ((end_trigger && strchr(end_trigger, ch))
3437 && !dest->o_quote && ctx->res_w == RES_NONE
3439 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
3446 if (dest->length == 0 && !dest->o_quote) {
3449 if (ch == EOF || ch == '\n')
3454 b_addqchr(dest, ch, dest->o_quote);
3460 debug_printf_parse("parse_stream return 1: \\<eof>\n");
3463 b_addqchr(dest, '\\', dest->o_quote);
3464 b_addqchr(dest, b_getch(input), dest->o_quote);
3467 if (handle_dollar(dest, ctx, input) != 0) {
3468 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3475 ch = b_getch(input);
3476 if (ch == EOF || ch == '\'')
3481 syntax("unterminated '");
3482 debug_printf_parse("parse_stream return 1: unterminated '\n");
3488 dest->o_quote ^= 1; /* invert */
3490 #if ENABLE_HUSH_TICK
3492 process_command_subs(dest, ctx, input, "`");
3496 redir_fd = redirect_opt_num(dest);
3497 done_word(dest, ctx);
3498 redir_style = REDIRECT_OVERWRITE;
3500 redir_style = REDIRECT_APPEND;
3504 else if (next == '(') {
3505 syntax(">(process) not supported");
3506 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
3510 setup_redirect(ctx, redir_fd, redir_style, input);
3513 redir_fd = redirect_opt_num(dest);
3514 done_word(dest, ctx);
3515 redir_style = REDIRECT_INPUT;
3517 redir_style = REDIRECT_HEREIS;
3519 } else if (next == '>') {
3520 redir_style = REDIRECT_IO;
3524 else if (next == '(') {
3525 syntax("<(process) not supported");
3526 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
3530 setup_redirect(ctx, redir_fd, redir_style, input);
3533 done_word(dest, ctx);
3534 done_pipe(ctx, PIPE_SEQ);
3537 done_word(dest, ctx);
3540 done_pipe(ctx, PIPE_AND);
3542 done_pipe(ctx, PIPE_BG);
3546 done_word(dest, ctx);
3549 done_pipe(ctx, PIPE_OR);
3551 /* we could pick up a file descriptor choice here
3552 * with redirect_opt_num(), but bash doesn't do it.
3553 * "echo foo 2| cat" yields "foo 2". */
3559 if (parse_group(dest, ctx, input, ch) != 0) {
3560 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
3566 syntax("unexpected }"); /* Proper use of this character is caught by end_trigger */
3567 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
3570 if (ENABLE_HUSH_DEBUG)
3571 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
3574 /* Complain if quote? No, maybe we just finished a command substitution
3575 * that was quoted. Example:
3576 * $ echo "`cat foo` plus more"
3577 * and we just got the EOF generated by the subshell that ran "cat foo"
3578 * The only real complaint is if we got an EOF when end_trigger != NULL,
3579 * that is, we were really supposed to get end_trigger, and never got
3580 * one before the EOF. Can't use the standard "syntax error" return code,
3581 * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
3582 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
3588 static void set_in_charmap(const char *set, int code)
3591 charmap[(unsigned char)*set++] = code;
3594 static void update_charmap(void)
3596 /* char *ifs and char charmap[256] are both globals. */
3597 ifs = getenv("IFS");
3600 /* Precompute a list of 'flow through' behavior so it can be treated
3601 * quickly up front. Computation is necessary because of IFS.
3602 * Special case handling of IFS == " \t\n" is not implemented.
3603 * The charmap[] array only really needs two bits each,
3604 * and on most machines that would be faster (reduced L1 cache use).
3606 memset(charmap, CHAR_ORDINARY, sizeof(charmap));
3607 #if ENABLE_HUSH_TICK
3608 set_in_charmap("\\$\"`", CHAR_SPECIAL);
3610 set_in_charmap("\\$\"", CHAR_SPECIAL);
3612 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
3613 set_in_charmap(ifs, CHAR_IFS); /* are ordinary if quoted */
3616 /* most recursion does not come through here, the exception is
3617 * from builtin_source() and builtin_eval() */
3618 static int parse_and_run_stream(struct in_str *inp, int parse_flag)
3620 struct p_context ctx;
3621 o_string temp = NULL_O_STRING;
3624 ctx.parse_type = parse_flag;
3625 initialize_context(&ctx);
3627 if (!(parse_flag & PARSEFLAG_SEMICOLON) || (parse_flag & PARSEFLAG_REPARSING))
3628 set_in_charmap(";$&|", CHAR_ORDINARY);
3629 #if ENABLE_HUSH_INTERACTIVE
3630 inp->promptmode = 0; /* PS1 */
3632 /* We will stop & execute after each ';' or '\n'.
3633 * Example: "sleep 9999; echo TEST" + ctrl-C:
3634 * TEST should be printed */
3635 rcode = parse_stream(&temp, &ctx, inp, ";\n");
3636 if (rcode != 1 && ctx.old_flag != 0) {
3639 if (rcode != 1 && ctx.old_flag == 0) {
3640 done_word(&temp, &ctx);
3641 done_pipe(&ctx, PIPE_SEQ);
3642 debug_print_tree(ctx.list_head, 0);
3643 debug_printf_exec("parse_stream_outer: run_list\n");
3644 run_list(ctx.list_head);
3646 if (ctx.old_flag != 0) {
3653 free_pipe_list(ctx.list_head, 0);
3656 } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP)); /* loop on syntax errors, return on EOF */
3660 static int parse_and_run_string(const char *s, int parse_flag)
3662 struct in_str input;
3663 setup_string_in_str(&input, s);
3664 return parse_and_run_stream(&input, parse_flag);
3667 static int parse_and_run_file(FILE *f)
3670 struct in_str input;
3671 setup_file_in_str(&input, f);
3672 rcode = parse_and_run_stream(&input, PARSEFLAG_SEMICOLON);
3677 /* Make sure we have a controlling tty. If we get started under a job
3678 * aware app (like bash for example), make sure we are now in charge so
3679 * we don't fight over who gets the foreground */
3680 static void setup_job_control(void)
3684 saved_task_pgrp = shell_pgrp = getpgrp();
3685 debug_printf_jobs("saved_task_pgrp=%d\n", saved_task_pgrp);
3686 close_on_exec_on(interactive_fd);
3688 /* If we were ran as 'hush &',
3689 * sleep until we are in the foreground. */
3690 while (tcgetpgrp(interactive_fd) != shell_pgrp) {
3691 /* Send TTIN to ourself (should stop us) */
3692 kill(- shell_pgrp, SIGTTIN);
3693 shell_pgrp = getpgrp();
3696 /* Ignore job-control and misc signals. */
3697 set_jobctrl_sighandler(SIG_IGN);
3698 set_misc_sighandler(SIG_IGN);
3699 //huh? signal(SIGCHLD, SIG_IGN);
3701 /* We _must_ restore tty pgrp on fatal signals */
3702 set_fatal_sighandler(sigexit);
3704 /* Put ourselves in our own process group. */
3705 setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
3706 /* Grab control of the terminal. */
3707 tcsetpgrp(interactive_fd, getpid());
3711 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
3712 int hush_main(int argc, char **argv)
3714 static const char version_str[] ALIGN1 = "HUSH_VERSION="HUSH_VER_STR;
3715 static const struct variable const_shell_ver = {
3717 .varstr = (char*)version_str,
3718 .max_len = 1, /* 0 can provoke free(name) */
3726 struct variable *cur_var;
3728 PTR_TO_GLOBALS = xzalloc(sizeof(G));
3730 /* Deal with HUSH_VERSION */
3731 shell_ver = const_shell_ver; /* copying struct here */
3732 top_var = &shell_ver;
3733 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
3734 /* Initialize our shell local variables with the values
3735 * currently living in the environment */
3739 char *value = strchr(*e, '=');
3740 if (value) { /* paranoia */
3741 cur_var->next = xzalloc(sizeof(*cur_var));
3742 cur_var = cur_var->next;
3743 cur_var->varstr = *e;
3744 cur_var->max_len = strlen(*e);
3745 cur_var->flg_export = 1;
3749 putenv((char *)version_str); /* reinstate HUSH_VERSION */
3751 #if ENABLE_FEATURE_EDITING
3752 line_input_state = new_line_input_t(FOR_SHELL);
3754 /* XXX what should these be while sourcing /etc/profile? */
3757 /* Initialize some more globals to non-zero values */
3759 #if ENABLE_HUSH_INTERACTIVE
3760 #if ENABLE_FEATURE_EDITING
3761 cmdedit_set_initial_prompt();
3766 if (EXIT_SUCCESS) /* otherwise is already done */
3767 last_return_code = EXIT_SUCCESS;
3769 if (argv[0] && argv[0][0] == '-') {
3770 debug_printf("sourcing /etc/profile\n");
3771 input = fopen("/etc/profile", "r");
3772 if (input != NULL) {
3773 close_on_exec_on(fileno(input));
3774 parse_and_run_file(input);
3780 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
3783 global_argv = argv + optind;
3784 global_argc = argc - optind;
3785 opt = parse_and_run_string(optarg, PARSEFLAG_SEMICOLON);
3788 /* Well, we cannot just declare interactiveness,
3789 * we have to have some stuff (ctty, etc) */
3790 /* interactive_fd++; */
3797 fprintf(stderr, "Usage: sh [FILE]...\n"
3798 " or: sh -c command [args]...\n\n");
3806 /* A shell is interactive if the '-i' flag was given, or if all of
3807 * the following conditions are met:
3809 * no arguments remaining or the -s flag given
3810 * standard input is a terminal
3811 * standard output is a terminal
3812 * Refer to Posix.2, the description of the 'sh' utility. */
3813 if (argv[optind] == NULL && input == stdin
3814 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3816 saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
3817 debug_printf("saved_tty_pgrp=%d\n", saved_tty_pgrp);
3818 if (saved_tty_pgrp >= 0) {
3819 /* try to dup to high fd#, >= 255 */
3820 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3821 if (interactive_fd < 0) {
3822 /* try to dup to any fd */
3823 interactive_fd = dup(STDIN_FILENO);
3824 if (interactive_fd < 0)
3828 // TODO: track & disallow any attempts of user
3829 // to (inadvertently) close/redirect it
3832 debug_printf("interactive_fd=%d\n", interactive_fd);
3833 if (interactive_fd) {
3834 /* Looks like they want an interactive shell */
3835 setup_job_control();
3836 /* Make xfuncs do cleanup on exit */
3837 die_sleep = -1; /* flag */
3838 // FIXME: should we reset die_sleep = 0 whereever we fork?
3839 if (setjmp(die_jmp)) {
3840 /* xfunc has failed! die die die */
3841 hush_exit(xfunc_error_retval);
3843 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
3844 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
3845 printf("Enter 'help' for a list of built-in commands.\n\n");
3848 #elif ENABLE_HUSH_INTERACTIVE
3849 /* no job control compiled, only prompt/line editing */
3850 if (argv[optind] == NULL && input == stdin
3851 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3853 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3854 if (interactive_fd < 0) {
3855 /* try to dup to any fd */
3856 interactive_fd = dup(STDIN_FILENO);
3857 if (interactive_fd < 0)
3865 if (argv[optind] == NULL) {
3866 opt = parse_and_run_file(stdin);
3870 debug_printf("\nrunning script '%s'\n", argv[optind]);
3871 global_argv = argv + optind;
3872 global_argc = argc - optind;
3873 input = xfopen(argv[optind], "r");
3874 opt = parse_and_run_file(input);
3878 #if ENABLE_FEATURE_CLEAN_UP
3880 if (cwd != bb_msg_unknown)
3882 cur_var = top_var->next;
3884 struct variable *tmp = cur_var;
3885 if (!cur_var->max_len)
3886 free(cur_var->varstr);
3887 cur_var = cur_var->next;
3891 hush_exit(opt ? opt : last_return_code);