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 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
87 #if !BB_MMU && ENABLE_HUSH_TICK
88 //#undef ENABLE_HUSH_TICK
89 //#define ENABLE_HUSH_TICK 0
90 #warning On NOMMU, hush command substitution is dangerous.
91 #warning Dont use it for commands which produce lots of output.
92 #warning For more info see shell/hush.c, generate_stream_from_list().
95 #if !BB_MMU && ENABLE_HUSH_JOB
96 #undef ENABLE_HUSH_JOB
97 #define ENABLE_HUSH_JOB 0
100 #if !ENABLE_HUSH_INTERACTIVE
101 #undef ENABLE_FEATURE_EDITING
102 #define ENABLE_FEATURE_EDITING 0
103 #undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
104 #define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
108 /* If you comment out one of these below, it will be #defined later
109 * to perform debug printfs to stderr: */
110 #define debug_printf(...) do {} while (0)
111 /* Finer-grained debug switches */
112 #define debug_printf_parse(...) do {} while (0)
113 #define debug_print_tree(a, b) do {} while (0)
114 #define debug_printf_exec(...) do {} while (0)
115 #define debug_printf_jobs(...) do {} while (0)
116 #define debug_printf_expand(...) do {} while (0)
117 #define debug_printf_clean(...) do {} while (0)
120 #define debug_printf(...) fprintf(stderr, __VA_ARGS__)
123 #ifndef debug_printf_parse
124 #define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
127 #ifndef debug_printf_exec
128 #define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
131 #ifndef debug_printf_jobs
132 #define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
133 #define DEBUG_SHELL_JOBS 1
136 #ifndef debug_printf_expand
137 #define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
138 #define DEBUG_EXPAND 1
141 /* Keep unconditionally on for now */
142 #define ENABLE_HUSH_DEBUG 1
144 #ifndef debug_printf_clean
145 /* broken, of course, but OK for testing */
146 static const char *indenter(int i)
148 static const char blanks[] ALIGN1 =
150 return &blanks[sizeof(blanks) - i - 1];
152 #define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
153 #define DEBUG_CLEAN 1
158 * Leak hunting. Use hush_leaktool.sh for post-processing.
160 #ifdef FOR_HUSH_LEAKTOOL
161 void *xxmalloc(int lineno, size_t size)
163 void *ptr = xmalloc((size + 0xff) & ~0xff);
164 fprintf(stderr, "line %d: malloc %p\n", lineno, ptr);
167 void *xxrealloc(int lineno, void *ptr, size_t size)
169 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
170 fprintf(stderr, "line %d: realloc %p\n", lineno, ptr);
173 char *xxstrdup(int lineno, const char *str)
175 char *ptr = xstrdup(str);
176 fprintf(stderr, "line %d: strdup %p\n", lineno, ptr);
179 void xxfree(void *ptr)
181 fprintf(stderr, "free %p\n", ptr);
184 #define xmalloc(s) xxmalloc(__LINE__, s)
185 #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
186 #define xstrdup(s) xxstrdup(__LINE__, s)
187 #define free(p) xxfree(p)
191 #define SPECIAL_VAR_SYMBOL 3
193 #define PARSEFLAG_EXIT_FROM_LOOP 1
194 #define PARSEFLAG_SEMICOLON (1 << 1) /* symbol ';' is special for parser */
195 #define PARSEFLAG_REPARSING (1 << 2) /* >= 2nd pass */
199 REDIRECT_OVERWRITE = 2,
205 /* The descrip member of this structure is only used to make debugging
207 static const struct {
209 signed char default_fd;
213 { O_RDONLY, 0, "<" },
214 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
215 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
216 { O_RDONLY, -1, "<<" },
227 /* might eventually control execution */
237 #if ENABLE_HUSH_LOOPS
249 FLAG_END = (1 << RES_NONE ),
251 FLAG_IF = (1 << RES_IF ),
252 FLAG_THEN = (1 << RES_THEN ),
253 FLAG_ELIF = (1 << RES_ELIF ),
254 FLAG_ELSE = (1 << RES_ELSE ),
255 FLAG_FI = (1 << RES_FI ),
257 #if ENABLE_HUSH_LOOPS
258 FLAG_FOR = (1 << RES_FOR ),
259 FLAG_WHILE = (1 << RES_WHILE),
260 FLAG_UNTIL = (1 << RES_UNTIL),
261 FLAG_DO = (1 << RES_DO ),
262 FLAG_DONE = (1 << RES_DONE ),
263 FLAG_IN = (1 << RES_IN ),
265 FLAG_START = (1 << RES_XXXX ),
268 /* This holds pointers to the various results of parsing */
270 struct child_prog *child;
271 struct pipe *list_head;
273 struct redir_struct *pending_redirect;
275 smallint parse_type; /* bitmask of PARSEFLAG_xxx, defines type of parser : ";$" common or special symbol */
276 int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */
277 struct p_context *stack;
278 /* How about quoting status? */
281 struct redir_struct {
282 struct redir_struct *next; /* pointer to the next redirect in the list */
283 redir_type type; /* type of redirection */
284 int fd; /* file descriptor being redirected */
285 int dup; /* -1, or file descriptor being duplicated */
286 char **glob_word; /* *word.gl_pathv is the filename */
290 pid_t pid; /* 0 if exited */
291 char **argv; /* program name and arguments */
292 struct pipe *group; /* if non-NULL, first in group or subshell */
293 smallint subshell; /* flag, non-zero if group must be forked */
294 smallint is_stopped; /* is the program currently running? */
295 struct redir_struct *redirects; /* I/O redirections */
296 struct pipe *family; /* pointer back to the child's parent pipe */
297 //sp counting seems to be broken... so commented out, grep for '//sp:'
298 //sp: int sp; /* number of SPECIAL_VAR_SYMBOL */
299 //seems to be unused, grep for '//pt:'
300 //pt: int parse_type;
302 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
303 * and on execution these are substituted with their values.
304 * Substitution can make _several_ words out of one argv[n]!
305 * Example: argv[0]=='.^C*^C.' here: echo .$*.
310 int num_progs; /* total number of programs in job */
311 int running_progs; /* number of programs running (not exited) */
312 int stopped_progs; /* number of programs alive, but stopped */
314 int jobid; /* job number */
315 pid_t pgrp; /* process group ID for the job */
316 char *cmdtext; /* name of job */
318 char *cmdbuf; /* buffer various argv's point into */
319 struct child_prog *progs; /* array of commands in pipe */
320 int job_context; /* bitmask defining current context */
321 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
322 smallint res_word; /* needed for if, for, while, until... */
325 /* On program start, environ points to initial environment.
326 * putenv adds new pointers into it, unsetenv removes them.
327 * Neither of these (de)allocates the strings.
328 * setenv allocates new strings in malloc space and does putenv,
329 * and thus setenv is unusable (leaky) for shell's purposes */
330 #define setenv(...) setenv_is_leaky_dont_use()
332 struct variable *next;
333 char *varstr; /* points to "name=" portion */
334 int max_len; /* if > 0, name is part of initial env; else name is malloced */
335 smallint flg_export; /* putenv should be done on this var */
336 smallint flg_read_only;
346 #define NULL_O_STRING {NULL,0,0,0,0}
347 /* used for initialization: o_string foo = NULL_O_STRING; */
349 /* I can almost use ordinary FILE *. Is open_memstream() universally
350 * available? Where is it documented? */
353 /* eof_flag=1: last char in ->p is really an EOF */
354 char eof_flag; /* meaningless if ->p == NULL */
356 #if ENABLE_HUSH_INTERACTIVE
358 smallint promptmode; /* 0: PS1, 1: PS2 */
361 int (*get) (struct in_str *);
362 int (*peek) (struct in_str *);
364 #define b_getch(input) ((input)->get(input))
365 #define b_peek(input) ((input)->peek(input))
369 CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
370 CHAR_IFS = 2, /* treated as ordinary if quoted */
371 CHAR_SPECIAL = 3, /* example: $ */
374 #define HUSH_VER_STR "0.02"
376 /* "Globals" within this file */
378 /* Sorted roughly by size (smaller offsets == smaller code) */
380 #if ENABLE_HUSH_INTERACTIVE
381 /* 'interactive_fd' is a fd# open to ctty, if we have one
382 * _AND_ if we decided to act interactively */
387 #if ENABLE_FEATURE_EDITING
388 line_input_t *line_input_state;
392 pid_t saved_task_pgrp;
393 pid_t saved_tty_pgrp;
395 struct pipe *job_list;
396 struct pipe *toplevel_list;
397 smallint ctrl_z_flag;
400 /* these three support $?, $#, and $1 */
403 int last_return_code;
406 unsigned last_bg_pid;
407 struct variable *top_var; /* = &shell_ver (set in main()) */
408 struct variable shell_ver;
409 #if ENABLE_FEATURE_SH_STANDALONE
410 struct nofork_save_area nofork_save;
413 sigjmp_buf toplevel_jb;
415 unsigned char charmap[256];
416 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
419 #define G (*ptr_to_globals)
421 #if !ENABLE_HUSH_INTERACTIVE
422 enum { interactive_fd = 0 };
425 enum { run_list_level = 0 };
428 #if ENABLE_HUSH_INTERACTIVE
429 #define interactive_fd (G.interactive_fd )
433 #if ENABLE_FEATURE_EDITING
434 #define line_input_state (G.line_input_state)
437 #define run_list_level (G.run_list_level )
438 #define saved_task_pgrp (G.saved_task_pgrp )
439 #define saved_tty_pgrp (G.saved_tty_pgrp )
440 #define last_jobid (G.last_jobid )
441 #define job_list (G.job_list )
442 #define toplevel_list (G.toplevel_list )
443 #define toplevel_jb (G.toplevel_jb )
444 #define ctrl_z_flag (G.ctrl_z_flag )
446 #define global_argv (G.global_argv )
447 #define global_argc (G.global_argc )
448 #define last_return_code (G.last_return_code)
450 #define fake_mode (G.fake_mode )
452 #define last_bg_pid (G.last_bg_pid )
453 #define top_var (G.top_var )
454 #define shell_ver (G.shell_ver )
455 #if ENABLE_FEATURE_SH_STANDALONE
456 #define nofork_save (G.nofork_save )
459 #define toplevel_jb (G.toplevel_jb )
461 #define charmap (G.charmap )
462 #define user_input_buf (G.user_input_buf )
467 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
471 static void syntax(const char *msg)
473 /* Was using fancy stuff:
474 * (interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
475 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
476 void (*fp)(const char *s, ...);
478 fp = (interactive_fd ? bb_error_msg : bb_error_msg_and_die);
479 fp(msg ? "%s: %s" : "syntax error", "syntax error", msg);
484 static void syntax_lineno(int line)
486 void (*fp)(const char *s, ...);
488 fp = (interactive_fd ? bb_error_msg : bb_error_msg_and_die);
489 fp("syntax error hush.c:%d", line);
491 #define syntax(str) syntax_lineno(__LINE__)
494 /* Index of subroutines: */
495 /* o_string manipulation: */
496 static int b_check_space(o_string *o, int len);
497 static int b_addchr(o_string *o, int ch);
498 static void b_reset(o_string *o);
499 static int b_addqchr(o_string *o, int ch, int quote);
500 /* in_str manipulations: */
501 static int static_get(struct in_str *i);
502 static int static_peek(struct in_str *i);
503 static int file_get(struct in_str *i);
504 static int file_peek(struct in_str *i);
505 static void setup_file_in_str(struct in_str *i, FILE *f);
506 static void setup_string_in_str(struct in_str *i, const char *s);
507 /* "run" the final data structures: */
508 #if !defined(DEBUG_CLEAN)
509 #define free_pipe_list(head, indent) free_pipe_list(head)
510 #define free_pipe(pi, indent) free_pipe(pi)
512 static int free_pipe_list(struct pipe *head, int indent);
513 static int free_pipe(struct pipe *pi, int indent);
514 /* really run the final data structures: */
515 static int setup_redirects(struct child_prog *prog, int squirrel[]);
516 static int run_list(struct pipe *pi);
517 static void pseudo_exec_argv(char **argv) ATTRIBUTE_NORETURN;
518 static void pseudo_exec(struct child_prog *child) ATTRIBUTE_NORETURN;
519 static int run_pipe(struct pipe *pi);
520 /* extended glob support: */
521 static char **globhack(const char *src, char **strings);
522 static int glob_needed(const char *s);
523 static int xglob(o_string *dest, char ***pglob);
524 /* variable assignment: */
525 static int is_assignment(const char *s);
526 /* data structure manipulation: */
527 static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
528 static void initialize_context(struct p_context *ctx);
529 static int done_word(o_string *dest, struct p_context *ctx);
530 static int done_command(struct p_context *ctx);
531 static int done_pipe(struct p_context *ctx, pipe_style type);
532 /* primary string parsing: */
533 static int redirect_dup_num(struct in_str *input);
534 static int redirect_opt_num(o_string *o);
536 static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, const char *subst_end);
538 static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
539 static const char *lookup_param(const char *src);
540 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
541 static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, const char *end_trigger);
543 static int parse_and_run_stream(struct in_str *inp, int parse_flag);
544 static int parse_and_run_string(const char *s, int parse_flag);
545 static int parse_and_run_file(FILE *f);
546 /* job management: */
547 static int checkjobs(struct pipe* fg_pipe);
549 static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
550 static void insert_bg_job(struct pipe *pi);
551 static void remove_bg_job(struct pipe *pi);
552 static void delete_finished_bg_job(struct pipe *pi);
554 int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
556 /* local variable support */
557 static char **expand_strvec_to_strvec(char **argv);
559 static char *expand_strvec_to_string(char **argv);
560 /* used for expansion of right hand of assignments */
561 static char *expand_string_to_string(const char *str);
562 static struct variable *get_local_var(const char *name);
563 static int set_local_var(char *str, int flg_export);
564 static void unset_local_var(const char *name);
567 static char **add_strings_to_strings(int need_xstrdup, char **strings, char **add)
588 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
589 v[count1 + count2] = NULL;
592 v[count1 + i] = need_xstrdup ? xstrdup(add[i]) : add[i];
596 /* 'add' should be a malloced pointer */
597 static char **add_string_to_strings(char **strings, char *add)
604 return add_strings_to_strings(0, strings, v);
607 static void free_strings(char **strings)
618 /* Function prototypes for builtins */
619 static int builtin_cd(char **argv);
620 static int builtin_echo(char **argv);
621 static int builtin_eval(char **argv);
622 static int builtin_exec(char **argv);
623 static int builtin_exit(char **argv);
624 static int builtin_export(char **argv);
626 static int builtin_fg_bg(char **argv);
627 static int builtin_jobs(char **argv);
630 static int builtin_help(char **argv);
632 static int builtin_pwd(char **argv);
633 static int builtin_read(char **argv);
634 static int builtin_test(char **argv);
635 static int builtin_set(char **argv);
636 static int builtin_shift(char **argv);
637 static int builtin_source(char **argv);
638 static int builtin_umask(char **argv);
639 static int builtin_unset(char **argv);
640 //static int builtin_not_written(char **argv);
642 /* Table of built-in functions. They can be forked or not, depending on
643 * context: within pipes, they fork. As simple commands, they do not.
644 * When used in non-forking context, they can change global variables
645 * in the parent shell process. If forked, of course they cannot.
646 * For example, 'unset foo | whatever' will parse and run, but foo will
647 * still be set at the end. */
648 struct built_in_command {
649 const char *cmd; /* name */
650 int (*function) (char **argv); /* function ptr */
652 const char *descr; /* description */
653 #define BLTIN(cmd, func, help) { cmd, func, help }
655 #define BLTIN(cmd, func, help) { cmd, func }
659 /* For now, echo and test are unconditionally enabled.
660 * Maybe make it configurable? */
661 static const struct built_in_command bltins[] = {
662 BLTIN("[" , builtin_test, "Test condition"),
663 BLTIN("[[" , builtin_test, "Test condition"),
665 BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"),
667 // BLTIN("break" , builtin_not_written, "Exit for, while or until loop"),
668 BLTIN("cd" , builtin_cd, "Change working directory"),
669 // BLTIN("continue", builtin_not_written, "Continue for, while or until loop"),
670 BLTIN("echo" , builtin_echo, "Write strings to stdout"),
671 BLTIN("eval" , builtin_eval, "Construct and run shell command"),
672 BLTIN("exec" , builtin_exec, "Exec command, replacing this shell with the exec'd process"),
673 BLTIN("exit" , builtin_exit, "Exit from shell"),
674 BLTIN("export", builtin_export, "Set environment variable"),
676 BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"),
677 BLTIN("jobs" , builtin_jobs, "Lists the active jobs"),
679 // TODO: remove pwd? we have it as an applet...
680 BLTIN("pwd" , builtin_pwd, "Print current directory"),
681 BLTIN("read" , builtin_read, "Input environment variable"),
682 // BLTIN("return", builtin_not_written, "Return from a function"),
683 BLTIN("set" , builtin_set, "Set/unset shell local variables"),
684 BLTIN("shift" , builtin_shift, "Shift positional parameters"),
685 // BLTIN("trap" , builtin_not_written, "Trap signals"),
686 BLTIN("test" , builtin_test, "Test condition"),
687 // BLTIN("ulimit", builtin_not_written, "Controls resource limits"),
688 BLTIN("umask" , builtin_umask, "Sets file creation mask"),
689 BLTIN("unset" , builtin_unset, "Unset environment variable"),
690 BLTIN("." , builtin_source, "Source-in and run commands in a file"),
692 BLTIN("help" , builtin_help, "List shell built-in commands"),
694 BLTIN(NULL, NULL, NULL)
700 static void signal_SA_RESTART(int sig, void (*handler)(int))
703 sa.sa_handler = handler;
704 sa.sa_flags = SA_RESTART;
705 sigemptyset(&sa.sa_mask);
706 sigaction(sig, &sa, NULL);
709 /* Signals are grouped, we handle them in batches */
710 static void set_fatal_sighandler(void (*handler)(int))
712 signal(SIGILL , handler);
713 signal(SIGTRAP, handler);
714 signal(SIGABRT, handler);
715 signal(SIGFPE , handler);
716 signal(SIGBUS , handler);
717 signal(SIGSEGV, handler);
718 /* bash 3.2 seems to handle these just like 'fatal' ones */
719 signal(SIGHUP , handler);
720 signal(SIGPIPE, handler);
721 signal(SIGALRM, handler);
723 static void set_jobctrl_sighandler(void (*handler)(int))
725 signal(SIGTSTP, handler);
726 signal(SIGTTIN, handler);
727 signal(SIGTTOU, handler);
729 static void set_misc_sighandler(void (*handler)(int))
731 signal(SIGINT , handler);
732 signal(SIGQUIT, handler);
733 signal(SIGTERM, handler);
735 /* SIGCHLD is special and handled separately */
737 static void set_every_sighandler(void (*handler)(int))
739 set_fatal_sighandler(handler);
740 set_jobctrl_sighandler(handler);
741 set_misc_sighandler(handler);
742 signal(SIGCHLD, handler);
745 static void handler_ctrl_c(int sig)
747 debug_printf_jobs("got sig %d\n", sig);
748 // as usual we can have all kinds of nasty problems with leaked malloc data here
749 siglongjmp(toplevel_jb, 1);
752 static void handler_ctrl_z(int sig)
756 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
758 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
761 if (!pid) { /* child */
763 die_sleep = 0; /* let nofork's xfuncs die */
765 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
766 set_every_sighandler(SIG_DFL);
767 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
768 debug_printf_jobs("returning in child\n");
769 /* return to nofork, it will eventually exit now,
770 * not return back to shell */
774 /* finish filling up pipe info */
775 toplevel_list->pgrp = pid; /* child is in its own pgrp */
776 toplevel_list->progs[0].pid = pid;
777 /* parent needs to longjmp out of running nofork.
778 * we will "return" exitcode 0, with child put in background */
779 // as usual we can have all kinds of nasty problems with leaked malloc data here
780 debug_printf_jobs("siglongjmp in parent\n");
781 siglongjmp(toplevel_jb, 1);
784 /* Restores tty foreground process group, and exits.
785 * May be called as signal handler for fatal signal
786 * (will faithfully resend signal to itself, producing correct exit state)
787 * or called directly with -EXITCODE.
788 * We also call it if xfunc is exiting. */
789 static void sigexit(int sig) ATTRIBUTE_NORETURN;
790 static void sigexit(int sig)
794 /* Disable all signals: job control, SIGPIPE, etc. */
795 sigfillset(&block_all);
796 sigprocmask(SIG_SETMASK, &block_all, NULL);
799 tcsetpgrp(interactive_fd, saved_tty_pgrp);
801 /* Not a signal, just exit */
805 /* Enable only this sig and kill ourself with it */
806 signal(sig, SIG_DFL);
807 sigdelset(&block_all, sig);
808 sigprocmask(SIG_SETMASK, &block_all, NULL);
810 _exit(1); /* Should not reach it */
813 /* Restores tty foreground process group, and exits. */
814 static void hush_exit(int exitcode) ATTRIBUTE_NORETURN;
815 static void hush_exit(int exitcode)
817 fflush(NULL); /* flush all streams */
818 sigexit(- (exitcode & 0xff));
823 #define set_fatal_sighandler(handler) ((void)0)
824 #define set_jobctrl_sighandler(handler) ((void)0)
825 #define set_misc_sighandler(handler) ((void)0)
826 #define hush_exit(e) exit(e)
831 static const char *set_cwd(void)
833 if (cwd == bb_msg_unknown)
834 cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
835 cwd = xrealloc_getcwd_or_warn((char *)cwd);
837 cwd = bb_msg_unknown;
842 /* built-in 'test' handler */
843 static int builtin_test(char **argv)
850 return test_main(argc, argv - argc);
853 /* built-in 'test' handler */
854 static int builtin_echo(char **argv)
861 return echo_main(argc, argv - argc);
864 /* built-in 'eval' handler */
865 static int builtin_eval(char **argv)
867 int rcode = EXIT_SUCCESS;
870 char *str = expand_strvec_to_string(argv + 1);
871 parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP |
872 PARSEFLAG_SEMICOLON);
874 rcode = last_return_code;
879 /* built-in 'cd <path>' handler */
880 static int builtin_cd(char **argv)
883 if (argv[1] == NULL) {
884 // bash does nothing (exitcode 0) if HOME is ""; if it's unset,
885 // bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
886 newdir = getenv("HOME") ? : "/";
890 printf("cd: %s: %s\n", newdir, strerror(errno));
897 /* built-in 'exec' handler */
898 static int builtin_exec(char **argv)
901 return EXIT_SUCCESS; /* Really? */
902 pseudo_exec_argv(argv + 1);
906 /* built-in 'exit' handler */
907 static int builtin_exit(char **argv)
909 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
910 //puts("exit"); /* bash does it */
911 // TODO: warn if we have background jobs: "There are stopped jobs"
912 // On second consecutive 'exit', exit anyway.
915 hush_exit(last_return_code);
916 /* mimic bash: exit 123abc == exit 255 + error msg */
917 xfunc_error_retval = 255;
918 /* bash: exit -2 == exit 254, no error msg */
919 hush_exit(xatoi(argv[1]) & 0xff);
922 /* built-in 'export VAR=value' handler */
923 static int builtin_export(char **argv)
926 char *name = argv[1];
930 // ash emits: export VAR='VAL'
931 // bash: declare -x VAR="VAL"
932 // (both also escape as needed (quotes, $, etc))
940 value = strchr(name, '=');
942 /* They are exporting something without a =VALUE */
943 struct variable *var;
945 var = get_local_var(name);
950 /* bash does not return an error when trying to export
951 * an undefined variable. Do likewise. */
955 set_local_var(xstrdup(name), 1);
960 /* built-in 'fg' and 'bg' handler */
961 static int builtin_fg_bg(char **argv)
968 /* If they gave us no args, assume they want the last backgrounded task */
970 for (pi = job_list; pi; pi = pi->next) {
971 if (pi->jobid == last_jobid) {
975 bb_error_msg("%s: no current job", argv[0]);
978 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
979 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
982 for (pi = job_list; pi; pi = pi->next) {
983 if (pi->jobid == jobnum) {
987 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
990 // TODO: bash prints a string representation
991 // of job being foregrounded (like "sleep 1 | cat")
992 if (*argv[0] == 'f') {
993 /* Put the job into the foreground. */
994 tcsetpgrp(interactive_fd, pi->pgrp);
997 /* Restart the processes in the job */
998 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_progs, pi->pgrp);
999 for (i = 0; i < pi->num_progs; i++) {
1000 debug_printf_jobs("reviving pid %d\n", pi->progs[i].pid);
1001 pi->progs[i].is_stopped = 0;
1003 pi->stopped_progs = 0;
1005 i = kill(- pi->pgrp, SIGCONT);
1007 if (errno == ESRCH) {
1008 delete_finished_bg_job(pi);
1009 return EXIT_SUCCESS;
1011 bb_perror_msg("kill (SIGCONT)");
1015 if (*argv[0] == 'f') {
1017 return checkjobs_and_fg_shell(pi);
1019 return EXIT_SUCCESS;
1023 /* built-in 'help' handler */
1024 #if ENABLE_HUSH_HELP
1025 static int builtin_help(char **argv ATTRIBUTE_UNUSED)
1027 const struct built_in_command *x;
1029 printf("\nBuilt-in commands:\n");
1030 printf("-------------------\n");
1031 for (x = bltins; x->cmd; x++) {
1032 printf("%s\t%s\n", x->cmd, x->descr);
1035 return EXIT_SUCCESS;
1040 /* built-in 'jobs' handler */
1041 static int builtin_jobs(char **argv ATTRIBUTE_UNUSED)
1044 const char *status_string;
1046 for (job = job_list; job; job = job->next) {
1047 if (job->running_progs == job->stopped_progs)
1048 status_string = "Stopped";
1050 status_string = "Running";
1052 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
1054 return EXIT_SUCCESS;
1058 /* built-in 'pwd' handler */
1059 static int builtin_pwd(char **argv ATTRIBUTE_UNUSED)
1062 return EXIT_SUCCESS;
1065 /* built-in 'read VAR' handler */
1066 static int builtin_read(char **argv)
1069 const char *name = argv[1] ? argv[1] : "REPLY";
1071 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name));
1072 return set_local_var(string, 0);
1075 /* built-in 'set [VAR=value]' handler */
1076 static int builtin_set(char **argv)
1078 char *temp = argv[1];
1082 for (e = top_var; e; e = e->next)
1085 set_local_var(xstrdup(temp), 0);
1087 return EXIT_SUCCESS;
1091 /* Built-in 'shift' handler */
1092 static int builtin_shift(char **argv)
1098 if (n >= 0 && n < global_argc) {
1099 global_argv[n] = global_argv[0];
1102 return EXIT_SUCCESS;
1104 return EXIT_FAILURE;
1107 /* Built-in '.' handler (read-in and execute commands from file) */
1108 static int builtin_source(char **argv)
1113 if (argv[1] == NULL)
1114 return EXIT_FAILURE;
1116 /* XXX search through $PATH is missing */
1117 input = fopen(argv[1], "r");
1119 bb_error_msg("cannot open '%s'", argv[1]);
1120 return EXIT_FAILURE;
1122 close_on_exec_on(fileno(input));
1124 /* Now run the file */
1125 /* XXX argv and argc are broken; need to save old global_argv
1126 * (pointer only is OK!) on this stack frame,
1127 * set global_argv=argv+1, recurse, and restore. */
1128 status = parse_and_run_file(input);
1133 static int builtin_umask(char **argv)
1136 const char *arg = argv[1];
1139 new_umask = strtoul(arg, &end, 8);
1140 if (*end != '\0' || end == arg) {
1141 return EXIT_FAILURE;
1144 new_umask = umask(0);
1145 printf("%.3o\n", (unsigned) new_umask);
1148 return EXIT_SUCCESS;
1151 /* built-in 'unset VAR' handler */
1152 static int builtin_unset(char **argv)
1154 /* bash always returns true */
1155 unset_local_var(argv[1]);
1156 return EXIT_SUCCESS;
1159 //static int builtin_not_written(char **argv)
1161 // printf("builtin_%s not written\n", argv[0]);
1162 // return EXIT_FAILURE;
1165 static int b_check_space(o_string *o, int len)
1167 /* It would be easy to drop a more restrictive policy
1168 * in here, such as setting a maximum string length */
1169 if (o->length + len > o->maxlen) {
1170 /* assert(data == NULL || o->maxlen != 0); */
1171 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1172 o->data = xrealloc(o->data, 1 + o->maxlen);
1174 return o->data == NULL;
1177 static int b_addchr(o_string *o, int ch)
1179 debug_printf("b_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1180 if (b_check_space(o, 1))
1182 o->data[o->length] = ch;
1184 o->data[o->length] = '\0';
1188 static void b_reset(o_string *o)
1196 static void b_free(o_string *o)
1199 memset(o, 0, sizeof(*o));
1202 /* My analysis of quoting semantics tells me that state information
1203 * is associated with a destination, not a source.
1205 static int b_addqchr(o_string *o, int ch, int quote)
1207 if (quote && strchr("*?[\\", ch)) {
1209 rc = b_addchr(o, '\\');
1213 return b_addchr(o, ch);
1216 static int static_get(struct in_str *i)
1219 if (ch == '\0') return EOF;
1223 static int static_peek(struct in_str *i)
1228 #if ENABLE_HUSH_INTERACTIVE
1229 #if ENABLE_FEATURE_EDITING
1230 static void cmdedit_set_initial_prompt(void)
1232 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1235 PS1 = getenv("PS1");
1240 #endif /* EDITING */
1242 static const char* setup_prompt_string(int promptmode)
1244 const char *prompt_str;
1245 debug_printf("setup_prompt_string %d ", promptmode);
1246 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1247 /* Set up the prompt */
1248 if (promptmode == 0) { /* PS1 */
1250 PS1 = xasprintf("%s %c ", cwd, (geteuid() != 0) ? '$' : '#');
1256 prompt_str = (promptmode == 0) ? PS1 : PS2;
1258 debug_printf("result '%s'\n", prompt_str);
1262 static void get_user_input(struct in_str *i)
1265 const char *prompt_str;
1267 prompt_str = setup_prompt_string(i->promptmode);
1268 #if ENABLE_FEATURE_EDITING
1269 /* Enable command line editing only while a command line
1270 * is actually being read; otherwise, we'll end up bequeathing
1271 * atexit() handlers and other unwanted stuff to our
1272 * child processes (rob@sysgo.de) */
1273 r = read_line_input(prompt_str, user_input_buf, BUFSIZ-1, line_input_state);
1274 i->eof_flag = (r < 0);
1275 if (i->eof_flag) { /* EOF/error detected */
1276 user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1277 user_input_buf[1] = '\0';
1280 fputs(prompt_str, stdout);
1282 user_input_buf[0] = r = fgetc(i->file);
1283 /*user_input_buf[1] = '\0'; - already is and never changed */
1284 i->eof_flag = (r == EOF);
1286 i->p = user_input_buf;
1288 #endif /* INTERACTIVE */
1290 /* This is the magic location that prints prompts
1291 * and gets data back from the user */
1292 static int file_get(struct in_str *i)
1296 /* If there is data waiting, eat it up */
1297 if (i->p && *i->p) {
1298 #if ENABLE_HUSH_INTERACTIVE
1302 if (i->eof_flag && !*i->p)
1305 /* need to double check i->file because we might be doing something
1306 * more complicated by now, like sourcing or substituting. */
1307 #if ENABLE_HUSH_INTERACTIVE
1308 if (interactive_fd && i->promptme && i->file == stdin) {
1311 } while (!*i->p); /* need non-empty line */
1312 i->promptmode = 1; /* PS2 */
1317 ch = fgetc(i->file);
1319 debug_printf("file_get: got a '%c' %d\n", ch, ch);
1320 #if ENABLE_HUSH_INTERACTIVE
1327 /* All the callers guarantee this routine will never be
1328 * used right after a newline, so prompting is not needed.
1330 static int file_peek(struct in_str *i)
1333 if (i->p && *i->p) {
1334 if (i->eof_flag && !i->p[1])
1338 ch = fgetc(i->file);
1339 i->eof_flag = (ch == EOF);
1340 i->peek_buf[0] = ch;
1341 i->peek_buf[1] = '\0';
1343 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
1347 static void setup_file_in_str(struct in_str *i, FILE *f)
1349 i->peek = file_peek;
1351 #if ENABLE_HUSH_INTERACTIVE
1353 i->promptmode = 0; /* PS1 */
1359 static void setup_string_in_str(struct in_str *i, const char *s)
1361 i->peek = static_peek;
1362 i->get = static_get;
1363 #if ENABLE_HUSH_INTERACTIVE
1365 i->promptmode = 0; /* PS1 */
1371 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
1372 * and stderr if they are redirected. */
1373 static int setup_redirects(struct child_prog *prog, int squirrel[])
1376 struct redir_struct *redir;
1378 for (redir = prog->redirects; redir; redir = redir->next) {
1379 if (redir->dup == -1 && redir->glob_word == NULL) {
1380 /* something went wrong in the parse. Pretend it didn't happen */
1383 if (redir->dup == -1) {
1385 mode = redir_table[redir->type].mode;
1386 p = expand_string_to_string(redir->glob_word[0]);
1387 openfd = open_or_warn(p, mode);
1390 /* this could get lost if stderr has been redirected, but
1391 bash and ash both lose it as well (though zsh doesn't!) */
1395 openfd = redir->dup;
1398 if (openfd != redir->fd) {
1399 if (squirrel && redir->fd < 3) {
1400 squirrel[redir->fd] = dup(redir->fd);
1403 //close(openfd); // close(-3) ??!
1405 dup2(openfd, redir->fd);
1406 if (redir->dup == -1)
1414 static void restore_redirects(int squirrel[])
1417 for (i = 0; i < 3; i++) {
1420 /* We simply die on error */
1426 /* Called after [v]fork() in run_pipe(), or from builtin_exec().
1428 * XXX no exit() here. If you don't exec, use _exit instead.
1429 * The at_exit handlers apparently confuse the calling process,
1430 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
1431 static void pseudo_exec_argv(char **argv)
1435 const struct built_in_command *x;
1437 for (i = 0; is_assignment(argv[i]); i++) {
1438 debug_printf_exec("pid %d environment modification: %s\n",
1440 // FIXME: vfork case??
1441 p = expand_string_to_string(argv[i]);
1445 /* If a variable is assigned in a forest, and nobody listens,
1446 * was it ever really set?
1449 _exit(EXIT_SUCCESS);
1451 argv = expand_strvec_to_strvec(argv);
1454 * Check if the command matches any of the builtins.
1455 * Depending on context, this might be redundant. But it's
1456 * easier to waste a few CPU cycles than it is to figure out
1457 * if this is one of those cases.
1459 for (x = bltins; x->cmd; x++) {
1460 if (strcmp(argv[0], x->cmd) == 0) {
1461 debug_printf_exec("running builtin '%s'\n", argv[0]);
1462 rcode = x->function(argv);
1468 /* Check if the command matches any busybox applets */
1469 #if ENABLE_FEATURE_SH_STANDALONE
1470 if (strchr(argv[0], '/') == NULL) {
1471 int a = find_applet_by_name(argv[0]);
1473 if (APPLET_IS_NOEXEC(a)) {
1474 debug_printf_exec("running applet '%s'\n", argv[0]);
1475 // is it ok that run_applet_no_and_exit() does exit(), not _exit()?
1476 run_applet_no_and_exit(a, argv);
1478 /* re-exec ourselves with the new arguments */
1479 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
1480 execvp(bb_busybox_exec_path, argv);
1481 /* If they called chroot or otherwise made the binary no longer
1482 * executable, fall through */
1487 debug_printf_exec("execing '%s'\n", argv[0]);
1488 execvp(argv[0], argv);
1489 bb_perror_msg("cannot exec '%s'", argv[0]);
1493 /* Called after [v]fork() in run_pipe()
1495 static void pseudo_exec(struct child_prog *child)
1497 // FIXME: buggy wrt NOMMU! Must not modify any global data
1498 // until it does exec/_exit, but currently it does
1499 // (puts malloc'ed stuff into environment)
1501 pseudo_exec_argv(child->argv);
1505 bb_error_msg_and_die("nested lists are not supported on NOMMU");
1509 #if ENABLE_HUSH_INTERACTIVE
1510 // run_list_level now takes care of it?
1511 // debug_printf_exec("pseudo_exec: setting interactive_fd=0\n");
1512 // interactive_fd = 0; /* crucial!!!! */
1514 debug_printf_exec("pseudo_exec: run_list\n");
1515 rcode = run_list(child->group);
1516 /* OK to leak memory by not calling free_pipe_list,
1517 * since this process is about to exit */
1522 /* Can happen. See what bash does with ">foo" by itself. */
1523 debug_printf("trying to pseudo_exec null command\n");
1524 _exit(EXIT_SUCCESS);
1528 static const char *get_cmdtext(struct pipe *pi)
1534 /* This is subtle. ->cmdtext is created only on first backgrounding.
1535 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
1536 * On subsequent bg argv is trashed, but we won't use it */
1539 argv = pi->progs[0].argv;
1540 if (!argv || !argv[0])
1541 return (pi->cmdtext = xzalloc(1));
1544 do len += strlen(*argv) + 1; while (*++argv);
1545 pi->cmdtext = p = xmalloc(len);
1546 argv = pi->progs[0].argv;
1548 len = strlen(*argv);
1549 memcpy(p, *argv, len);
1557 static void insert_bg_job(struct pipe *pi)
1559 struct pipe *thejob;
1562 /* Linear search for the ID of the job to use */
1564 for (thejob = job_list; thejob; thejob = thejob->next)
1565 if (thejob->jobid >= pi->jobid)
1566 pi->jobid = thejob->jobid + 1;
1568 /* Add thejob to the list of running jobs */
1570 thejob = job_list = xmalloc(sizeof(*thejob));
1572 for (thejob = job_list; thejob->next; thejob = thejob->next)
1574 thejob->next = xmalloc(sizeof(*thejob));
1575 thejob = thejob->next;
1578 /* Physically copy the struct job */
1579 memcpy(thejob, pi, sizeof(struct pipe));
1580 thejob->progs = xzalloc(sizeof(pi->progs[0]) * pi->num_progs);
1581 /* We cannot copy entire pi->progs[] vector! Double free()s will happen */
1582 for (i = 0; i < pi->num_progs; i++) {
1583 // TODO: do we really need to have so many fields which are just dead weight
1584 // at execution stage?
1585 thejob->progs[i].pid = pi->progs[i].pid;
1586 /* all other fields are not used and stay zero */
1588 thejob->next = NULL;
1589 thejob->cmdtext = xstrdup(get_cmdtext(pi));
1591 /* We don't wait for background thejobs to return -- append it
1592 to the list of backgrounded thejobs and leave it alone */
1593 printf("[%d] %d %s\n", thejob->jobid, thejob->progs[0].pid, thejob->cmdtext);
1594 last_bg_pid = thejob->progs[0].pid;
1595 last_jobid = thejob->jobid;
1598 static void remove_bg_job(struct pipe *pi)
1600 struct pipe *prev_pipe;
1602 if (pi == job_list) {
1603 job_list = pi->next;
1605 prev_pipe = job_list;
1606 while (prev_pipe->next != pi)
1607 prev_pipe = prev_pipe->next;
1608 prev_pipe->next = pi->next;
1611 last_jobid = job_list->jobid;
1616 /* remove a backgrounded job */
1617 static void delete_finished_bg_job(struct pipe *pi)
1620 pi->stopped_progs = 0;
1626 /* Checks to see if any processes have exited -- if they
1627 have, figure out why and see if a job has completed */
1628 static int checkjobs(struct pipe* fg_pipe)
1639 attributes = WUNTRACED;
1640 if (fg_pipe == NULL) {
1641 attributes |= WNOHANG;
1644 /* Do we do this right?
1645 * bash-3.00# sleep 20 | false
1647 * [3]+ Stopped sleep 20 | false
1648 * bash-3.00# echo $?
1649 * 1 <========== bg pipe is not fully done, but exitcode is already known!
1652 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
1653 //are stopped. Testcase: "cat | cat" in a script (not on command line)
1654 // + killall -STOP cat
1657 // TODO: safe_waitpid?
1658 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
1659 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
1661 #ifdef DEBUG_SHELL_JOBS
1662 if (WIFSTOPPED(status))
1663 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
1664 childpid, WSTOPSIG(status), WEXITSTATUS(status));
1665 if (WIFSIGNALED(status))
1666 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
1667 childpid, WTERMSIG(status), WEXITSTATUS(status));
1668 if (WIFEXITED(status))
1669 debug_printf_jobs("pid %d exited, exitcode %d\n",
1670 childpid, WEXITSTATUS(status));
1672 /* Were we asked to wait for fg pipe? */
1675 for (i = 0; i < fg_pipe->num_progs; i++) {
1676 debug_printf_jobs("check pid %d\n", fg_pipe->progs[i].pid);
1677 if (fg_pipe->progs[i].pid == childpid) {
1678 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
1680 fg_pipe->progs[i].pid = 0;
1681 fg_pipe->running_progs--;
1682 if (i == fg_pipe->num_progs - 1)
1683 /* last process gives overall exitstatus */
1684 rcode = WEXITSTATUS(status);
1686 fg_pipe->progs[i].is_stopped = 1;
1687 fg_pipe->stopped_progs++;
1689 debug_printf_jobs("fg_pipe: running_progs %d stopped_progs %d\n",
1690 fg_pipe->running_progs, fg_pipe->stopped_progs);
1691 if (fg_pipe->running_progs - fg_pipe->stopped_progs <= 0) {
1692 /* All processes in fg pipe have exited/stopped */
1694 if (fg_pipe->running_progs)
1695 insert_bg_job(fg_pipe);
1699 /* There are still running processes in the fg pipe */
1703 /* fall through to searching process in bg pipes */
1707 /* We asked to wait for bg or orphaned children */
1708 /* No need to remember exitcode in this case */
1709 for (pi = job_list; pi; pi = pi->next) {
1711 while (prognum < pi->num_progs) {
1712 if (pi->progs[prognum].pid == childpid)
1713 goto found_pi_and_prognum;
1719 /* Happens when shell is used as init process (init=/bin/sh) */
1720 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
1724 found_pi_and_prognum:
1727 pi->progs[prognum].pid = 0;
1728 pi->running_progs--;
1729 if (!pi->running_progs) {
1730 printf(JOB_STATUS_FORMAT, pi->jobid,
1731 "Done", pi->cmdtext);
1732 delete_finished_bg_job(pi);
1736 pi->stopped_progs++;
1737 pi->progs[prognum].is_stopped = 1;
1742 /* wait found no children or failed */
1744 if (childpid && errno != ECHILD)
1745 bb_perror_msg("waitpid");
1750 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1753 int rcode = checkjobs(fg_pipe);
1754 /* Job finished, move the shell to the foreground */
1755 p = getpgid(0); /* pgid of our process */
1756 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
1757 if (tcsetpgrp(interactive_fd, p) && errno != ENOTTY)
1758 bb_perror_msg("tcsetpgrp-4a");
1763 /* run_pipe() starts all the jobs, but doesn't wait for anything
1764 * to finish. See checkjobs().
1766 * return code is normally -1, when the caller has to wait for children
1767 * to finish to determine the exit status of the pipe. If the pipe
1768 * is a simple builtin command, however, the action is done by the
1769 * time run_pipe returns, and the exit code is provided as the
1772 * The input of the pipe is always stdin, the output is always
1773 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1774 * because it tries to avoid running the command substitution in
1775 * subshell, when that is in fact necessary. The subshell process
1776 * now has its stdout directed to the input of the appropriate pipe,
1777 * so this routine is noticeably simpler.
1779 * Returns -1 only if started some children. IOW: we have to
1780 * mask out retvals of builtins etc with 0xff!
1782 static int run_pipe(struct pipe *pi)
1786 int pipefds[2]; /* pipefds[0] is for reading */
1787 struct child_prog *child;
1788 const struct built_in_command *x;
1790 /* it is not always needed, but we aim to smaller code */
1791 int squirrel[] = { -1, -1, -1 };
1793 const int single_fg = (pi->num_progs == 1 && pi->followup != PIPE_BG);
1795 debug_printf_exec("run_pipe start: single_fg=%d\n", single_fg);
1800 pi->running_progs = 1;
1801 pi->stopped_progs = 0;
1803 /* Check if this is a simple builtin (not part of a pipe).
1804 * Builtins within pipes have to fork anyway, and are handled in
1805 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1807 child = &(pi->progs[0]);
1808 if (single_fg && child->group && child->subshell == 0) {
1809 debug_printf("non-subshell grouping\n");
1810 setup_redirects(child, squirrel);
1811 debug_printf_exec(": run_list\n");
1812 rcode = run_list(child->group) & 0xff;
1813 restore_redirects(squirrel);
1814 debug_printf_exec("run_pipe return %d\n", rcode);
1818 if (single_fg && child->argv != NULL) {
1819 char **argv_expanded;
1820 char **argv = child->argv;
1822 for (i = 0; is_assignment(argv[i]); i++)
1824 if (i != 0 && argv[i] == NULL) {
1825 /* assignments, but no command: set the local environment */
1826 for (i = 0; argv[i] != NULL; i++) {
1827 debug_printf("local environment set: %s\n", argv[i]);
1828 p = expand_string_to_string(argv[i]);
1829 set_local_var(p, 0);
1831 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1833 for (i = 0; is_assignment(argv[i]); i++) {
1834 p = expand_string_to_string(argv[i]);
1838 for (x = bltins; x->cmd; x++) {
1839 if (strcmp(argv[i], x->cmd) == 0) {
1840 if (x->function == builtin_exec && argv[i+1] == NULL) {
1841 debug_printf("magic exec\n");
1842 setup_redirects(child, NULL);
1843 return EXIT_SUCCESS;
1845 debug_printf("builtin inline %s\n", argv[0]);
1846 /* XXX setup_redirects acts on file descriptors, not FILEs.
1847 * This is perfect for work that comes after exec().
1848 * Is it really safe for inline use? Experimentally,
1849 * things seem to work with glibc. */
1850 setup_redirects(child, squirrel);
1851 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv[i+1]);
1852 //sp: if (child->sp) /* btw we can do it unconditionally... */
1853 argv_expanded = expand_strvec_to_strvec(argv + i);
1854 rcode = x->function(argv_expanded) & 0xff;
1855 free(argv_expanded);
1856 restore_redirects(squirrel);
1857 debug_printf_exec("run_pipe return %d\n", rcode);
1861 #if ENABLE_FEATURE_SH_STANDALONE
1863 int a = find_applet_by_name(argv[i]);
1864 if (a >= 0 && APPLET_IS_NOFORK(a)) {
1865 setup_redirects(child, squirrel);
1866 save_nofork_data(&nofork_save);
1867 argv_expanded = argv + i;
1868 //sp: if (child->sp)
1869 argv_expanded = expand_strvec_to_strvec(argv + i);
1870 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
1871 rcode = run_nofork_applet_prime(&nofork_save, a, argv_expanded) & 0xff;
1872 free(argv_expanded);
1873 restore_redirects(squirrel);
1874 debug_printf_exec("run_pipe return %d\n", rcode);
1881 /* Disable job control signals for shell (parent) and
1882 * for initial child code after fork */
1883 set_jobctrl_sighandler(SIG_IGN);
1885 /* Going to fork a child per each pipe member */
1886 pi->running_progs = 0;
1889 for (i = 0; i < pi->num_progs; i++) {
1890 child = &(pi->progs[i]);
1892 debug_printf_exec(": pipe member '%s' '%s'...\n", child->argv[0], child->argv[1]);
1894 debug_printf_exec(": pipe member with no argv\n");
1896 /* pipes are inserted between pairs of commands */
1899 if ((i + 1) < pi->num_progs)
1902 child->pid = BB_MMU ? fork() : vfork();
1903 if (!child->pid) { /* child */
1904 if (ENABLE_HUSH_JOB)
1905 die_sleep = 0; /* let nofork's xfuncs die */
1907 /* Every child adds itself to new process group
1908 * with pgid == pid_of_first_child_in_pipe */
1909 if (run_list_level == 1 && interactive_fd) {
1911 /* Don't do pgrp restore anymore on fatal signals */
1912 set_fatal_sighandler(SIG_DFL);
1914 if (pgrp < 0) /* true for 1st process only */
1916 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
1917 /* We do it in *every* child, not just first,
1919 tcsetpgrp(interactive_fd, pgrp);
1923 xmove_fd(nextin, 0);
1924 xmove_fd(pipefds[1], 1); /* write end */
1926 close(pipefds[0]); /* read end */
1927 /* Like bash, explicit redirects override pipes,
1928 * and the pipe fd is available for dup'ing. */
1929 setup_redirects(child, NULL);
1931 /* Restore default handlers just prior to exec */
1932 set_jobctrl_sighandler(SIG_DFL);
1933 set_misc_sighandler(SIG_DFL);
1934 signal(SIGCHLD, SIG_DFL);
1935 pseudo_exec(child); /* does not return */
1938 if (child->pid < 0) { /* [v]fork failed */
1939 /* Clearly indicate, was it fork or vfork */
1940 bb_perror_msg(BB_MMU ? "fork" : "vfork");
1942 pi->running_progs++;
1944 /* Second and next children need to know pid of first one */
1946 pi->pgrp = child->pid;
1952 if ((i + 1) < pi->num_progs)
1953 close(pipefds[1]); /* write end */
1954 /* Pass read (output) pipe end to next iteration */
1955 nextin = pipefds[0];
1958 if (!pi->running_progs) {
1959 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
1963 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->running_progs);
1967 #ifndef debug_print_tree
1968 static void debug_print_tree(struct pipe *pi, int lvl)
1970 static const char *PIPE[] = {
1976 static const char *RES[] = {
1977 [RES_NONE ] = "NONE" ,
1980 [RES_THEN ] = "THEN" ,
1981 [RES_ELIF ] = "ELIF" ,
1982 [RES_ELSE ] = "ELSE" ,
1985 #if ENABLE_HUSH_LOOPS
1986 [RES_FOR ] = "FOR" ,
1987 [RES_WHILE] = "WHILE",
1988 [RES_UNTIL] = "UNTIL",
1990 [RES_DONE ] = "DONE" ,
1993 [RES_XXXX ] = "XXXX" ,
1994 [RES_SNTX ] = "SNTX" ,
2001 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2002 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2004 while (prn < pi->num_progs) {
2005 struct child_prog *child = &pi->progs[prn];
2006 char **argv = child->argv;
2008 fprintf(stderr, "%*s prog %d", lvl*2, "", prn);
2010 fprintf(stderr, " group %s: (argv=%p)\n",
2011 (child->subshell ? "()" : "{}"),
2013 debug_print_tree(child->group, lvl+1);
2017 if (argv) while (*argv) {
2018 fprintf(stderr, " '%s'", *argv);
2021 fprintf(stderr, "\n");
2030 /* NB: called by pseudo_exec, and therefore must not modify any
2031 * global data until exec/_exit (we can be a child after vfork!) */
2032 static int run_list(struct pipe *pi)
2035 #if ENABLE_HUSH_LOOPS
2036 char *for_varname = NULL;
2037 char **for_lcur = NULL;
2038 char **for_list = NULL;
2042 int rcode = 0; /* probably for gcc only */
2043 int flag_restore = 0;
2045 int if_code = 0, next_if_code = 0; /* need double-buffer to handle elif */
2047 enum { if_code = 0, next_if_code = 0 };
2049 reserved_style rword;
2050 reserved_style skip_more_for_this_rword = RES_XXXX;
2052 debug_printf_exec("run_list start lvl %d\n", run_list_level + 1);
2054 #if ENABLE_HUSH_LOOPS
2055 /* check syntax for "for" */
2056 for (rpipe = pi; rpipe; rpipe = rpipe->next) {
2057 if ((rpipe->res_word == RES_IN || rpipe->res_word == RES_FOR)
2058 && (rpipe->next == NULL)
2060 syntax("malformed for"); /* no IN or no commands after IN */
2061 debug_printf_exec("run_list lvl %d return 1\n", run_list_level);
2064 if ((rpipe->res_word == RES_IN && rpipe->next->res_word == RES_IN && rpipe->next->progs[0].argv != NULL)
2065 || (rpipe->res_word == RES_FOR && rpipe->next->res_word != RES_IN)
2067 /* TODO: what is tested in the first condition? */
2068 syntax("malformed for"); /* 2nd condition: not followed by IN */
2069 debug_printf_exec("run_list lvl %d return 1\n", run_list_level);
2078 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
2079 * We are saving state before entering outermost list ("while...done")
2080 * so that ctrl-Z will correctly background _entire_ outermost list,
2081 * not just a part of it (like "sleep 1 | exit 2") */
2082 if (++run_list_level == 1 && interactive_fd) {
2083 if (sigsetjmp(toplevel_jb, 1)) {
2084 /* ctrl-Z forked and we are parent; or ctrl-C.
2085 * Sighandler has longjmped us here */
2086 signal(SIGINT, SIG_IGN);
2087 signal(SIGTSTP, SIG_IGN);
2088 /* Restore level (we can be coming from deep inside
2091 #if ENABLE_FEATURE_SH_STANDALONE
2092 if (nofork_save.saved) { /* if save area is valid */
2093 debug_printf_jobs("exiting nofork early\n");
2094 restore_nofork_data(&nofork_save);
2098 /* ctrl-Z has forked and stored pid of the child in pi->pid.
2099 * Remember this child as background job */
2102 /* ctrl-C. We just stop doing whatever we were doing */
2108 /* ctrl-Z handler will store pid etc in pi */
2111 #if ENABLE_FEATURE_SH_STANDALONE
2112 nofork_save.saved = 0; /* in case we will run a nofork later */
2114 signal_SA_RESTART(SIGTSTP, handler_ctrl_z);
2115 signal(SIGINT, handler_ctrl_c);
2119 for (; pi; pi = flag_restore ? rpipe : pi->next) {
2120 //why? int save_num_progs;
2121 rword = pi->res_word;
2122 #if ENABLE_HUSH_LOOPS
2123 if (rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR) {
2131 debug_printf_exec(": rword=%d if_code=%d next_if_code=%d skip_more=%d\n",
2132 rword, if_code, next_if_code, skip_more_for_this_rword);
2133 if (rword == skip_more_for_this_rword && flag_skip) {
2134 if (pi->followup == PIPE_SEQ)
2139 skip_more_for_this_rword = RES_XXXX;
2141 if (rword == RES_THEN || rword == RES_ELSE)
2142 if_code = next_if_code;
2143 if (rword == RES_THEN && if_code)
2145 if (rword == RES_ELSE && !if_code)
2147 if (rword == RES_ELIF && !if_code)
2150 #if ENABLE_HUSH_LOOPS
2151 if (rword == RES_FOR && pi->num_progs) {
2153 /* first loop through for */
2154 /* if no variable values after "in" we skip "for" */
2155 if (!pi->next->progs->argv)
2157 /* create list of variable values */
2158 for_list = expand_strvec_to_strvec(pi->next->progs->argv);
2159 for_lcur = for_list;
2160 for_varname = pi->progs->argv[0];
2161 pi->progs->argv[0] = NULL;
2164 free(pi->progs->argv[0]);
2166 /* for loop is over, clean up */
2170 pi->progs->argv[0] = for_varname;
2173 /* insert next value from for_lcur */
2174 /* vda: does it need escaping? */
2175 pi->progs->argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
2177 if (rword == RES_IN)
2179 if (rword == RES_DO) {
2183 if (rword == RES_DONE) {
2191 if (pi->num_progs == 0)
2193 //why? save_num_progs = pi->num_progs;
2194 debug_printf_exec(": run_pipe with %d members\n", pi->num_progs);
2195 rcode = run_pipe(pi);
2197 /* We only ran a builtin: rcode was set by the return value
2198 * of run_pipe(), and we don't need to wait for anything. */
2199 } else if (pi->followup == PIPE_BG) {
2200 /* What does bash do with attempts to background builtins? */
2201 /* Even bash 3.2 doesn't do that well with nested bg:
2202 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
2203 * I'm NOT treating inner &'s as jobs */
2205 if (run_list_level == 1)
2208 rcode = EXIT_SUCCESS;
2211 if (run_list_level == 1 && interactive_fd) {
2212 /* waits for completion, then fg's main shell */
2213 rcode = checkjobs_and_fg_shell(pi);
2217 /* this one just waits for completion */
2218 rcode = checkjobs(pi);
2220 debug_printf_exec(": checkjobs returned %d\n", rcode);
2222 debug_printf_exec(": setting last_return_code=%d\n", rcode);
2223 last_return_code = rcode;
2224 //why? pi->num_progs = save_num_progs;
2226 if (rword == RES_IF || rword == RES_ELIF)
2227 next_if_code = rcode; /* can be overwritten a number of times */
2229 #if ENABLE_HUSH_LOOPS
2230 if (rword == RES_WHILE)
2231 flag_rep = !last_return_code;
2232 if (rword == RES_UNTIL)
2233 flag_rep = last_return_code;
2235 if ((rcode == EXIT_SUCCESS && pi->followup == PIPE_OR)
2236 || (rcode != EXIT_SUCCESS && pi->followup == PIPE_AND)
2238 skip_more_for_this_rword = rword;
2245 /* ctrl-Z forked somewhere in the past, we are the child,
2246 * and now we completed running the list. Exit. */
2250 if (!--run_list_level && interactive_fd) {
2251 signal(SIGTSTP, SIG_IGN);
2252 signal(SIGINT, SIG_IGN);
2255 debug_printf_exec("run_list lvl %d return %d\n", run_list_level + 1, rcode);
2259 /* return code is the exit status of the pipe */
2260 static int free_pipe(struct pipe *pi, int indent)
2263 struct child_prog *child;
2264 struct redir_struct *r, *rnext;
2265 int a, i, ret_code = 0;
2267 if (pi->stopped_progs > 0)
2269 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2270 for (i = 0; i < pi->num_progs; i++) {
2271 child = &pi->progs[i];
2272 debug_printf_clean("%s command %d:\n", indenter(indent), i);
2274 for (a = 0, p = child->argv; *p; a++, p++) {
2275 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
2277 free_strings(child->argv);
2279 } else if (child->group) {
2280 debug_printf_clean("%s begin group (subshell:%d)\n", indenter(indent), child->subshell);
2281 ret_code = free_pipe_list(child->group, indent+3);
2282 debug_printf_clean("%s end group\n", indenter(indent));
2284 debug_printf_clean("%s (nil)\n", indenter(indent));
2286 for (r = child->redirects; r; r = rnext) {
2287 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->type].descrip);
2289 /* guard against the case >$FOO, where foo is unset or blank */
2291 debug_printf_clean(" %s\n", r->glob_word[0]);
2292 free_strings(r->glob_word);
2293 r->glob_word = NULL;
2296 debug_printf_clean("&%d\n", r->dup);
2301 child->redirects = NULL;
2303 free(pi->progs); /* children are an array, they get freed all at once */
2312 static int free_pipe_list(struct pipe *head, int indent)
2314 int rcode = 0; /* if list has no members */
2315 struct pipe *pi, *next;
2317 for (pi = head; pi; pi = next) {
2318 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
2319 rcode = free_pipe(pi, indent);
2320 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
2322 /*pi->next = NULL;*/
2328 /* Select which version we will use */
2329 static int run_and_free_list(struct pipe *pi)
2332 debug_printf_exec("run_and_free_list entered\n");
2334 debug_printf_exec(": run_list with %d members\n", pi->num_progs);
2335 rcode = run_list(pi);
2337 /* free_pipe_list has the side effect of clearing memory.
2338 * In the long run that function can be merged with run_list,
2339 * but doing that now would hobble the debugging effort. */
2340 free_pipe_list(pi, /* indent: */ 0);
2341 debug_printf_exec("run_nad_free_list return %d\n", rcode);
2345 /* Whoever decided to muck with glob internal data is AN IDIOT! */
2346 /* uclibc happily changed the way it works (and it has rights to do so!),
2347 all hell broke loose (SEGVs) */
2349 /* The API for glob is arguably broken. This routine pushes a non-matching
2350 * string into the output structure, removing non-backslashed backslashes.
2351 * If someone can prove me wrong, by performing this function within the
2352 * original glob(3) api, feel free to rewrite this routine into oblivion.
2353 * XXX broken if the last character is '\\', check that before calling.
2355 static char **globhack(const char *src, char **strings)
2361 for (cnt = 1, s = src; s && *s; s++) {
2362 if (*s == '\\') s++;
2365 v = dest = xmalloc(cnt);
2366 for (s = src; s && *s; s++, dest++) {
2367 if (*s == '\\') s++;
2372 return add_string_to_strings(strings, v);
2375 /* XXX broken if the last character is '\\', check that before calling */
2376 static int glob_needed(const char *s)
2381 if (strchr("*[?", *s))
2387 static int xglob(o_string *dest, char ***pglob)
2389 /* short-circuit for null word */
2390 /* we can code this better when the debug_printf's are gone */
2391 if (dest->length == 0) {
2392 if (dest->nonnull) {
2393 /* bash man page calls this an "explicit" null */
2394 *pglob = globhack(dest->data, *pglob);
2399 if (glob_needed(dest->data)) {
2403 memset(&globdata, 0, sizeof(globdata));
2404 gr = glob(dest->data, 0, NULL, &globdata);
2405 debug_printf("glob returned %d\n", gr);
2406 if (gr == GLOB_NOSPACE)
2407 bb_error_msg_and_die("out of memory during glob");
2408 if (gr == GLOB_NOMATCH) {
2409 debug_printf("globhack returned %d\n", gr);
2410 /* quote removal, or more accurately, backslash removal */
2411 *pglob = globhack(dest->data, *pglob);
2412 globfree(&globdata);
2415 if (gr != 0) { /* GLOB_ABORTED ? */
2416 bb_error_msg("glob(3) error %d", gr);
2418 if (globdata.gl_pathv && globdata.gl_pathv[0])
2419 *pglob = add_strings_to_strings(1, *pglob, globdata.gl_pathv);
2420 globfree(&globdata);
2424 *pglob = globhack(dest->data, *pglob);
2428 /* expand_strvec_to_strvec() takes a list of strings, expands
2429 * all variable references within and returns a pointer to
2430 * a list of expanded strings, possibly with larger number
2431 * of strings. (Think VAR="a b"; echo $VAR).
2432 * This new list is allocated as a single malloc block.
2433 * NULL-terminated list of char* pointers is at the beginning of it,
2434 * followed by strings themself.
2435 * Caller can deallocate entire list by single free(list). */
2438 * count_XXX estimates size of the block we need. It's okay
2439 * to over-estimate sizes a bit, if it makes code simpler */
2440 static int count_ifs(const char *str)
2443 debug_printf_expand("count_ifs('%s') ifs='%s'", str, ifs);
2445 str += strcspn(str, ifs);
2447 str++; /* str += strspn(str, ifs); */
2448 cnt++; /* cnt += strspn(str, ifs); - but this code is larger */
2450 debug_printf_expand(" return %d\n", cnt);
2454 static void count_var_expansion_space(int *countp, int *lenp, char *arg)
2459 int count = *countp;
2463 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2466 p = strchr(p, SPECIAL_VAR_SYMBOL);
2469 switch (first_ch & 0x7f) {
2470 /* high bit in 1st_ch indicates that var is double-quoted */
2472 case '!': /* bg pid */
2473 case '?': /* exitcode */
2474 case '#': /* argc */
2475 len += sizeof(int)*3 + 1; /* enough for int */
2479 for (i = 1; global_argv[i]; i++) {
2480 len += strlen(global_argv[i]) + 1;
2482 if (!(first_ch & 0x80))
2483 count += count_ifs(global_argv[i]);
2488 arg[0] = first_ch & 0x7f;
2489 if (isdigit(arg[0])) {
2492 if (i < global_argc)
2493 val = global_argv[i];
2495 val = lookup_param(arg);
2497 *p = SPECIAL_VAR_SYMBOL;
2500 len += strlen(val) + 1;
2501 if (!(first_ch & 0x80))
2502 count += count_ifs(val);
2508 len += strlen(arg) + 1;
2514 /* Store given string, finalizing the word and starting new one whenever
2515 * we encounter ifs char(s). This is used for expanding variable values.
2516 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2517 static int expand_on_ifs(char **list, int n, char **posp, const char *str)
2521 int word_len = strcspn(str, ifs);
2523 memcpy(pos, str, word_len); /* store non-ifs chars */
2527 if (!*str) /* EOL - do not finalize word */
2530 if (n) debug_printf_expand("expand_on_ifs finalized list[%d]=%p '%s' "
2531 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2532 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2534 str += strspn(str, ifs); /* skip ifs chars */
2540 /* Expand all variable references in given string, adding words to list[]
2541 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2542 * to be filled). This routine is extremely tricky: has to deal with
2543 * variables/parameters with whitespace, $* and $@, and constructs like
2544 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2545 /* NB: another bug is that we cannot detect empty strings yet:
2546 * "" or $empty"" expands to zero words, has to expand to empty word */
2547 static int expand_vars_to_list(char **list, int n, char **posp, char *arg, char or_mask)
2549 /* or_mask is either 0 (normal case) or 0x80
2550 * (expansion of right-hand side of assignment == 1-element expand) */
2552 char first_ch, ored_ch;
2560 if (n) debug_printf_expand("expand_vars_to_list finalized list[%d]=%p '%s' "
2561 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2562 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2565 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2566 memcpy(pos, arg, p - arg);
2569 p = strchr(p, SPECIAL_VAR_SYMBOL);
2571 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2572 ored_ch |= first_ch;
2574 switch (first_ch & 0x7f) {
2575 /* Highest bit in first_ch indicates that var is double-quoted */
2577 /* FIXME: (echo $$) should still print pid of main shell */
2578 val = utoa(getpid()); /* rootpid? */
2580 case '!': /* bg pid */
2581 val = last_bg_pid ? utoa(last_bg_pid) : (char*)"";
2583 case '?': /* exitcode */
2584 val = utoa(last_return_code);
2586 case '#': /* argc */
2587 val = utoa(global_argc ? global_argc-1 : 0);
2592 if (!global_argv[i])
2594 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2595 while (global_argv[i]) {
2596 n = expand_on_ifs(list, n, &pos, global_argv[i]);
2597 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, global_argc-1);
2598 if (global_argv[i++][0] && global_argv[i]) {
2599 /* this argv[] is not empty and not last:
2600 * put terminating NUL, start new word */
2602 if (n) debug_printf_expand("expand_vars_to_list 2 finalized list[%d]=%p '%s' "
2603 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2604 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2609 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2610 * and in this case should treat it like '$*' - see 'else...' below */
2611 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2613 strcpy(pos, global_argv[i]);
2614 pos += strlen(global_argv[i]);
2615 if (++i >= global_argc)
2618 if (n) debug_printf_expand("expand_vars_to_list 3 finalized list[%d]=%p '%s' "
2619 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2620 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2623 } else { /* quoted $*: add as one word */
2625 strcpy(pos, global_argv[i]);
2626 pos += strlen(global_argv[i]);
2627 if (!global_argv[++i])
2636 arg[0] = first_ch & 0x7f;
2637 if (isdigit(arg[0])) {
2640 if (i < global_argc)
2641 val = global_argv[i];
2643 val = lookup_param(arg);
2645 *p = SPECIAL_VAR_SYMBOL;
2646 if (!(first_ch & 0x80)) { /* unquoted $VAR */
2648 n = expand_on_ifs(list, n, &pos, val);
2651 } /* else: quoted $VAR, val will be appended at pos */
2659 debug_printf_expand("expand_vars_to_list adding tail '%s' at %p\n", arg, pos);
2661 pos += strlen(arg) + 1;
2662 if (pos == list[n-1] + 1) { /* expansion is empty */
2663 if (!(ored_ch & 0x80)) { /* all vars were not quoted... */
2664 debug_printf_expand("expand_vars_to_list list[%d] empty, going back\n", n);
2674 static char **expand_variables(char **argv, char or_mask)
2679 char *pos, **v, **list;
2682 if (!*v) debug_printf_expand("count_var_expansion_space: "
2683 "argv[0]=NULL count=%d len=%d alloc_space=%d\n",
2684 count, len, sizeof(char*) * count + len);
2686 count_var_expansion_space(&count, &len, *v);
2687 debug_printf_expand("count_var_expansion_space: "
2688 "'%s' count=%d len=%d alloc_space=%d\n",
2689 *v, count, len, sizeof(char*) * count + len);
2692 len += sizeof(char*) * count; /* total to alloc */
2693 list = xmalloc(len);
2694 pos = (char*)(list + count);
2695 debug_printf_expand("list=%p, list[0] should be %p\n", list, pos);
2699 n = expand_vars_to_list(list, n, &pos, *v++, or_mask);
2701 if (n) debug_printf_expand("finalized list[%d]=%p '%s' "
2702 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2703 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2710 debug_printf_expand("list[%d]=%p '%s'\n", m, list[m], list[m]);
2713 debug_printf_expand("used_space=%d\n", pos - (char*)list);
2716 if (ENABLE_HUSH_DEBUG)
2717 if (pos - (char*)list > len)
2718 bb_error_msg_and_die("BUG in varexp");
2722 static char **expand_strvec_to_strvec(char **argv)
2724 return expand_variables(argv, 0);
2727 static char *expand_string_to_string(const char *str)
2729 char *argv[2], **list;
2731 argv[0] = (char*)str;
2733 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2734 if (ENABLE_HUSH_DEBUG)
2735 if (!list[0] || list[1])
2736 bb_error_msg_and_die("BUG in varexp2");
2737 /* actually, just move string 2*sizeof(char*) bytes back */
2738 strcpy((char*)list, list[0]);
2739 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2743 static char* expand_strvec_to_string(char **argv)
2747 list = expand_variables(argv, 0x80);
2748 /* Convert all NULs to spaces */
2752 if (ENABLE_HUSH_DEBUG)
2753 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2754 bb_error_msg_and_die("BUG in varexp3");
2755 list[n][-1] = ' '; /* TODO: or to ifs[0]? */
2759 strcpy((char*)list, list[0]);
2760 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2764 /* This is used to get/check local shell variables */
2765 static struct variable *get_local_var(const char *name)
2767 struct variable *cur;
2773 for (cur = top_var; cur; cur = cur->next) {
2774 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
2780 /* str holds "NAME=VAL" and is expected to be malloced.
2781 * We take ownership of it. */
2782 static int set_local_var(char *str, int flg_export)
2784 struct variable *cur;
2788 value = strchr(str, '=');
2789 if (!value) { /* not expected to ever happen? */
2794 name_len = value - str + 1; /* including '=' */
2795 cur = top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
2797 if (strncmp(cur->varstr, str, name_len) != 0) {
2799 /* Bail out. Note that now cur points
2800 * to last var in linked list */
2806 /* We found an existing var with this name */
2808 if (cur->flg_read_only) {
2809 bb_error_msg("%s: readonly variable", str);
2813 unsetenv(str); /* just in case */
2815 if (strcmp(cur->varstr, str) == 0) {
2820 if (cur->max_len >= strlen(str)) {
2821 /* This one is from startup env, reuse space */
2822 strcpy(cur->varstr, str);
2825 /* max_len == 0 signifies "malloced" var, which we can
2826 * (and has to) free */
2830 goto set_str_and_exp;
2833 /* Not found - create next variable struct */
2834 cur->next = xzalloc(sizeof(*cur));
2841 cur->flg_export = 1;
2842 if (cur->flg_export)
2843 return putenv(cur->varstr);
2847 static void unset_local_var(const char *name)
2849 struct variable *cur;
2850 struct variable *prev = prev; /* for gcc */
2855 name_len = strlen(name);
2858 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2859 if (cur->flg_read_only) {
2860 bb_error_msg("%s: readonly variable", name);
2863 /* prev is ok to use here because 1st variable, HUSH_VERSION,
2864 * is ro, and we cannot reach this code on the 1st pass */
2865 prev->next = cur->next;
2866 unsetenv(cur->varstr);
2877 static int is_assignment(const char *s)
2879 if (!s || !isalpha(*s))
2882 while (isalnum(*s) || *s == '_')
2887 /* the src parameter allows us to peek forward to a possible &n syntax
2888 * for file descriptor duplication, e.g., "2>&1".
2889 * Return code is 0 normally, 1 if a syntax error is detected in src.
2890 * Resource errors (in xmalloc) cause the process to exit */
2891 static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2892 struct in_str *input)
2894 struct child_prog *child = ctx->child;
2895 struct redir_struct *redir = child->redirects;
2896 struct redir_struct *last_redir = NULL;
2898 /* Create a new redir_struct and drop it onto the end of the linked list */
2901 redir = redir->next;
2903 redir = xzalloc(sizeof(struct redir_struct));
2904 /* redir->next = NULL; */
2905 /* redir->glob_word = NULL; */
2907 last_redir->next = redir;
2909 child->redirects = redir;
2912 redir->type = style;
2913 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
2915 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2917 /* Check for a '2>&1' type redirect */
2918 redir->dup = redirect_dup_num(input);
2919 if (redir->dup == -2) return 1; /* syntax error */
2920 if (redir->dup != -1) {
2921 /* Erik had a check here that the file descriptor in question
2922 * is legit; I postpone that to "run time"
2923 * A "-" representation of "close me" shows up as a -3 here */
2924 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2926 /* We do _not_ try to open the file that src points to,
2927 * since we need to return and let src be expanded first.
2928 * Set ctx->pending_redirect, so we know what to do at the
2929 * end of the next parsed word. */
2930 ctx->pending_redirect = redir;
2935 static struct pipe *new_pipe(void)
2938 pi = xzalloc(sizeof(struct pipe));
2939 /*pi->num_progs = 0;*/
2940 /*pi->progs = NULL;*/
2941 /*pi->next = NULL;*/
2942 /*pi->followup = 0; invalid */
2944 pi->res_word = RES_NONE;
2948 static void initialize_context(struct p_context *ctx)
2951 ctx->pipe = ctx->list_head = new_pipe();
2952 ctx->pending_redirect = NULL;
2953 ctx->res_w = RES_NONE;
2954 //only ctx->parse_type is not touched... is this intentional?
2957 done_command(ctx); /* creates the memory for working child */
2960 /* normal return is 0
2961 * if a reserved word is found, and processed, return 1
2962 * should handle if, then, elif, else, fi, for, while, until, do, done.
2963 * case, function, and select are obnoxious, save those for later.
2965 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS
2966 static int reserved_word(o_string *dest, struct p_context *ctx)
2968 struct reserved_combo {
2973 /* Mostly a list of accepted follow-up reserved words.
2974 * FLAG_END means we are done with the sequence, and are ready
2975 * to turn the compound list into a command.
2976 * FLAG_START means the word must start a new compound list.
2978 static const struct reserved_combo reserved_list[] = {
2980 { "if", RES_IF, FLAG_THEN | FLAG_START },
2981 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2982 { "elif", RES_ELIF, FLAG_THEN },
2983 { "else", RES_ELSE, FLAG_FI },
2984 { "fi", RES_FI, FLAG_END },
2986 #if ENABLE_HUSH_LOOPS
2987 { "for", RES_FOR, FLAG_IN | FLAG_START },
2988 { "while", RES_WHILE, FLAG_DO | FLAG_START },
2989 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
2990 { "in", RES_IN, FLAG_DO },
2991 { "do", RES_DO, FLAG_DONE },
2992 { "done", RES_DONE, FLAG_END }
2996 const struct reserved_combo *r;
2998 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
2999 if (strcmp(dest->data, r->literal) != 0)
3001 debug_printf("found reserved word %s, code %d\n", r->literal, r->code);
3002 if (r->flag & FLAG_START) {
3003 struct p_context *new;
3004 debug_printf("push stack\n");
3005 #if ENABLE_HUSH_LOOPS
3006 if (ctx->res_w == RES_IN || ctx->res_w == RES_FOR) {
3007 syntax("malformed for"); /* example: 'for if' */
3008 ctx->res_w = RES_SNTX;
3013 new = xmalloc(sizeof(*new));
3014 *new = *ctx; /* physical copy */
3015 initialize_context(ctx);
3017 } else if (ctx->res_w == RES_NONE || !(ctx->old_flag & (1 << r->code))) {
3019 ctx->res_w = RES_SNTX;
3023 ctx->res_w = r->code;
3024 ctx->old_flag = r->flag;
3025 if (ctx->old_flag & FLAG_END) {
3026 struct p_context *old;
3027 debug_printf("pop stack\n");
3028 done_pipe(ctx, PIPE_SEQ);
3030 old->child->group = ctx->list_head;
3031 old->child->subshell = 0;
3032 *ctx = *old; /* physical copy */
3041 #define reserved_word(dest, ctx) ((int)0)
3044 /* Normal return is 0.
3045 * Syntax or xglob errors return 1. */
3046 static int done_word(o_string *dest, struct p_context *ctx)
3048 struct child_prog *child = ctx->child;
3049 char ***glob_target;
3052 debug_printf_parse("done_word entered: '%s' %p\n", dest->data, child);
3053 if (dest->length == 0 && !dest->nonnull) {
3054 debug_printf_parse("done_word return 0: true null, ignored\n");
3057 if (ctx->pending_redirect) {
3058 glob_target = &ctx->pending_redirect->glob_word;
3062 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
3065 if (!child->argv && (ctx->parse_type & PARSEFLAG_SEMICOLON)) {
3066 debug_printf_parse(": checking '%s' for reserved-ness\n", dest->data);
3067 if (reserved_word(dest, ctx)) {
3068 debug_printf_parse("done_word return %d\n", (ctx->res_w == RES_SNTX));
3069 return (ctx->res_w == RES_SNTX);
3072 glob_target = &child->argv;
3074 gr = xglob(dest, glob_target);
3076 debug_printf_parse("done_word return 1: xglob returned %d\n", gr);
3081 if (ctx->pending_redirect) {
3082 /* NB: don't free_strings(ctx->pending_redirect->glob_word) here */
3083 if (ctx->pending_redirect->glob_word
3084 && ctx->pending_redirect->glob_word[0]
3085 && ctx->pending_redirect->glob_word[1]
3087 /* more than one word resulted from globbing redir */
3088 ctx->pending_redirect = NULL;
3089 bb_error_msg("ambiguous redirect");
3090 debug_printf_parse("done_word return 1: ambiguous redirect\n");
3093 ctx->pending_redirect = NULL;
3095 #if ENABLE_HUSH_LOOPS
3096 if (ctx->res_w == RES_FOR) {
3097 done_word(dest, ctx);
3098 done_pipe(ctx, PIPE_SEQ);
3101 debug_printf_parse("done_word return 0\n");
3105 /* The only possible error here is out of memory, in which case
3107 static int done_command(struct p_context *ctx)
3109 /* The child is really already in the pipe structure, so
3110 * advance the pipe counter and make a new, null child. */
3111 struct pipe *pi = ctx->pipe;
3112 struct child_prog *child = ctx->child;
3115 if (child->group == NULL
3116 && child->argv == NULL
3117 && child->redirects == NULL
3119 debug_printf_parse("done_command: skipping null cmd, num_progs=%d\n", pi->num_progs);
3120 return pi->num_progs;
3123 debug_printf_parse("done_command: ++num_progs=%d\n", pi->num_progs);
3125 debug_printf_parse("done_command: initializing, num_progs=%d\n", pi->num_progs);
3128 /* Only real trickiness here is that the uncommitted
3129 * child structure is not counted in pi->num_progs. */
3130 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
3131 child = &pi->progs[pi->num_progs];
3133 memset(child, 0, sizeof(*child));
3134 /*child->redirects = NULL;*/
3135 /*child->argv = NULL;*/
3136 /*child->is_stopped = 0;*/
3137 /*child->group = NULL;*/
3139 //sp: /*child->sp = 0;*/
3140 //pt: child->parse_type = ctx->parse_type;
3143 /* but ctx->pipe and ctx->list_head remain unchanged */
3145 return pi->num_progs; /* used only for 0/nonzero check */
3148 static int done_pipe(struct p_context *ctx, pipe_style type)
3153 debug_printf_parse("done_pipe entered, followup %d\n", type);
3154 not_null = done_command(ctx); /* implicit closure of previous command */
3155 ctx->pipe->followup = type;
3156 ctx->pipe->res_word = ctx->res_w;
3157 /* Without this check, even just <enter> on command line generates
3158 * tree of three NOPs (!). Which is harmless but annoying.
3159 * IOW: it is safe to do it unconditionally. */
3162 ctx->pipe->next = new_p;
3165 done_command(ctx); /* set up new pipe to accept commands */
3167 debug_printf_parse("done_pipe return 0\n");
3171 /* peek ahead in the in_str to find out if we have a "&n" construct,
3172 * as in "2>&1", that represents duplicating a file descriptor.
3173 * returns either -2 (syntax error), -1 (no &), or the number found.
3175 static int redirect_dup_num(struct in_str *input)
3177 int ch, d = 0, ok = 0;
3179 if (ch != '&') return -1;
3181 b_getch(input); /* get the & */
3185 return -3; /* "-" represents "close me" */
3187 while (isdigit(ch)) {
3188 d = d*10 + (ch-'0');
3195 bb_error_msg("ambiguous redirect");
3199 /* If a redirect is immediately preceded by a number, that number is
3200 * supposed to tell which file descriptor to redirect. This routine
3201 * looks for such preceding numbers. In an ideal world this routine
3202 * needs to handle all the following classes of redirects...
3203 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3204 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3205 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3206 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3207 * A -1 output from this program means no valid number was found, so the
3208 * caller should use the appropriate default for this redirection.
3210 static int redirect_opt_num(o_string *o)
3216 for (num = 0; num < o->length; num++) {
3217 if (!isdigit(*(o->data + num))) {
3221 /* reuse num (and save an int) */
3222 num = atoi(o->data);
3227 #if ENABLE_HUSH_TICK
3228 /* NB: currently disabled on NOMMU */
3229 static FILE *generate_stream_from_list(struct pipe *head)
3232 int pid, channel[2];
3235 /* *** NOMMU WARNING *** */
3236 /* By using vfork here, we suspend parent till child exits or execs.
3237 * If child will not do it before it fills the pipe, it can block forever
3238 * in write(STDOUT_FILENO), and parent (shell) will be also stuck.
3240 pid = BB_MMU ? fork() : vfork();
3242 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
3243 if (pid == 0) { /* child */
3244 if (ENABLE_HUSH_JOB)
3245 die_sleep = 0; /* let nofork's xfuncs die */
3246 close(channel[0]); /* NB: close _first_, then move fd! */
3247 xmove_fd(channel[1], 1);
3248 /* Prevent it from trying to handle ctrl-z etc */
3252 /* Process substitution is not considered to be usual
3253 * 'command execution'.
3254 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not. */
3255 /* Not needed, we are relying on it being disabled
3256 * everywhere outside actual command execution. */
3257 /*set_jobctrl_sighandler(SIG_IGN);*/
3258 set_misc_sighandler(SIG_DFL);
3259 /* Freeing 'head' here would break NOMMU. */
3260 _exit(run_list(head));
3263 pf = fdopen(channel[0], "r");
3265 /* 'head' is freed by the caller */
3268 /* Return code is exit status of the process that is run. */
3269 static int process_command_subs(o_string *dest, struct p_context *ctx,
3270 struct in_str *input, const char *subst_end)
3272 int retcode, ch, eol_cnt;
3273 o_string result = NULL_O_STRING;
3274 struct p_context inner;
3276 struct in_str pipe_str;
3278 initialize_context(&inner);
3280 /* recursion to generate command */
3281 retcode = parse_stream(&result, &inner, input, subst_end);
3283 return retcode; /* syntax error or EOF */
3284 done_word(&result, &inner);
3285 done_pipe(&inner, PIPE_SEQ);
3288 p = generate_stream_from_list(inner.list_head);
3291 close_on_exec_on(fileno(p));
3292 setup_file_in_str(&pipe_str, p);
3294 /* now send results of command back into original context */
3296 while ((ch = b_getch(&pipe_str)) != EOF) {
3302 b_addqchr(dest, '\n', dest->o_quote);
3305 b_addqchr(dest, ch, dest->o_quote);
3308 debug_printf("done reading from pipe, pclose()ing\n");
3309 /* This is the step that wait()s for the child. Should be pretty
3310 * safe, since we just read an EOF from its stdout. We could try
3311 * to do better, by using wait(), and keeping track of background jobs
3312 * at the same time. That would be a lot of work, and contrary
3313 * to the KISS philosophy of this program. */
3314 retcode = fclose(p);
3315 free_pipe_list(inner.list_head, /* indent: */ 0);
3316 debug_printf("closed FILE from child, retcode=%d\n", retcode);
3321 static int parse_group(o_string *dest, struct p_context *ctx,
3322 struct in_str *input, int ch)
3325 const char *endch = NULL;
3326 struct p_context sub;
3327 struct child_prog *child = ctx->child;
3329 debug_printf_parse("parse_group entered\n");
3332 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3335 initialize_context(&sub);
3339 child->subshell = 1;
3341 rcode = parse_stream(dest, &sub, input, endch);
3343 done_word(dest, &sub); /* finish off the final word in the subcontext */
3344 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
3345 child->group = sub.list_head;
3347 debug_printf_parse("parse_group return %d\n", rcode);
3349 /* child remains "open", available for possible redirects */
3352 /* Basically useful version until someone wants to get fancier,
3353 * see the bash man page under "Parameter Expansion" */
3354 static const char *lookup_param(const char *src)
3356 struct variable *var = get_local_var(src);
3358 return strchr(var->varstr, '=') + 1;
3362 /* return code: 0 for OK, 1 for syntax error */
3363 static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
3365 int ch = b_peek(input); /* first character after the $ */
3366 unsigned char quote_mask = dest->o_quote ? 0x80 : 0;
3368 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
3370 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3371 //sp: ctx->child->sp++;
3373 debug_printf_parse(": '%c'\n", ch);
3375 b_addchr(dest, ch | quote_mask);
3378 if (!isalnum(ch) && ch != '_')
3381 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3382 } else if (isdigit(ch)) {
3384 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3385 //sp: ctx->child->sp++;
3386 debug_printf_parse(": '%c'\n", ch);
3388 b_addchr(dest, ch | quote_mask);
3389 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3390 } else switch (ch) {
3392 case '!': /* last bg pid */
3393 case '?': /* last exit code */
3394 case '#': /* number of args */
3395 case '*': /* args */
3396 case '@': /* args */
3397 goto make_one_char_var;
3399 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3400 //sp: ctx->child->sp++;
3402 /* XXX maybe someone will try to escape the '}' */
3404 ch = b_getch(input);
3407 if (!isalnum(ch) && ch != '_') {
3408 syntax("unterminated ${name}");
3409 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3412 debug_printf_parse(": '%c'\n", ch);
3413 b_addchr(dest, ch | quote_mask);
3416 b_addchr(dest, SPECIAL_VAR_SYMBOL);
3418 #if ENABLE_HUSH_TICK
3421 process_command_subs(dest, ctx, input, ")");
3426 /* still unhandled, but should be eventually */
3427 bb_error_msg("unhandled syntax: $%c", ch);
3431 b_addqchr(dest, '$', dest->o_quote);
3433 debug_printf_parse("handle_dollar return 0\n");
3437 /* return code is 0 for normal exit, 1 for syntax error */
3438 static int parse_stream(o_string *dest, struct p_context *ctx,
3439 struct in_str *input, const char *end_trigger)
3443 redir_type redir_style;
3446 /* Only double-quote state is handled in the state variable dest->o_quote.
3447 * A single-quote triggers a bypass of the main loop until its mate is
3448 * found. When recursing, quote state is passed in via dest->o_quote. */
3450 debug_printf_parse("parse_stream entered, end_trigger='%s'\n", end_trigger);
3455 ch = b_getch(input);
3459 next = b_peek(input);
3461 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
3462 ch, ch, m, dest->o_quote);
3463 if (m == CHAR_ORDINARY
3464 || (m != CHAR_SPECIAL && dest->o_quote)
3467 syntax("unterminated \"");
3468 debug_printf_parse("parse_stream return 1: unterminated \"\n");
3471 b_addqchr(dest, ch, dest->o_quote);
3474 if (m == CHAR_IFS) {
3475 if (done_word(dest, ctx)) {
3476 debug_printf_parse("parse_stream return 1: done_word!=0\n");
3481 /* If we aren't performing a substitution, treat
3482 * a newline as a command separator.
3483 * [why we don't handle it exactly like ';'? --vda] */
3484 if (end_trigger && ch == '\n') {
3485 done_pipe(ctx, PIPE_SEQ);
3488 if ((end_trigger && strchr(end_trigger, ch))
3489 && !dest->o_quote && ctx->res_w == RES_NONE
3491 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
3498 if (dest->length == 0 && !dest->o_quote) {
3501 if (ch == EOF || ch == '\n')
3506 b_addqchr(dest, ch, dest->o_quote);
3512 debug_printf_parse("parse_stream return 1: \\<eof>\n");
3515 b_addqchr(dest, '\\', dest->o_quote);
3516 b_addqchr(dest, b_getch(input), dest->o_quote);
3519 if (handle_dollar(dest, ctx, input) != 0) {
3520 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3527 ch = b_getch(input);
3528 if (ch == EOF || ch == '\'')
3533 syntax("unterminated '");
3534 debug_printf_parse("parse_stream return 1: unterminated '\n");
3540 dest->o_quote ^= 1; /* invert */
3542 #if ENABLE_HUSH_TICK
3544 process_command_subs(dest, ctx, input, "`");
3548 redir_fd = redirect_opt_num(dest);
3549 done_word(dest, ctx);
3550 redir_style = REDIRECT_OVERWRITE;
3552 redir_style = REDIRECT_APPEND;
3556 else if (next == '(') {
3557 syntax(">(process) not supported");
3558 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
3562 setup_redirect(ctx, redir_fd, redir_style, input);
3565 redir_fd = redirect_opt_num(dest);
3566 done_word(dest, ctx);
3567 redir_style = REDIRECT_INPUT;
3569 redir_style = REDIRECT_HEREIS;
3571 } else if (next == '>') {
3572 redir_style = REDIRECT_IO;
3576 else if (next == '(') {
3577 syntax("<(process) not supported");
3578 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
3582 setup_redirect(ctx, redir_fd, redir_style, input);
3585 done_word(dest, ctx);
3586 done_pipe(ctx, PIPE_SEQ);
3589 done_word(dest, ctx);
3592 done_pipe(ctx, PIPE_AND);
3594 done_pipe(ctx, PIPE_BG);
3598 done_word(dest, ctx);
3601 done_pipe(ctx, PIPE_OR);
3603 /* we could pick up a file descriptor choice here
3604 * with redirect_opt_num(), but bash doesn't do it.
3605 * "echo foo 2| cat" yields "foo 2". */
3611 if (parse_group(dest, ctx, input, ch) != 0) {
3612 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
3618 syntax("unexpected }"); /* Proper use of this character is caught by end_trigger */
3619 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
3622 if (ENABLE_HUSH_DEBUG)
3623 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
3626 /* Complain if quote? No, maybe we just finished a command substitution
3627 * that was quoted. Example:
3628 * $ echo "`cat foo` plus more"
3629 * and we just got the EOF generated by the subshell that ran "cat foo"
3630 * The only real complaint is if we got an EOF when end_trigger != NULL,
3631 * that is, we were really supposed to get end_trigger, and never got
3632 * one before the EOF. Can't use the standard "syntax error" return code,
3633 * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
3634 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
3640 static void set_in_charmap(const char *set, int code)
3643 charmap[(unsigned char)*set++] = code;
3646 static void update_charmap(void)
3648 /* char *ifs and char charmap[256] are both globals. */
3649 ifs = getenv("IFS");
3652 /* Precompute a list of 'flow through' behavior so it can be treated
3653 * quickly up front. Computation is necessary because of IFS.
3654 * Special case handling of IFS == " \t\n" is not implemented.
3655 * The charmap[] array only really needs two bits each,
3656 * and on most machines that would be faster (reduced L1 cache use).
3658 memset(charmap, CHAR_ORDINARY, sizeof(charmap));
3659 #if ENABLE_HUSH_TICK
3660 set_in_charmap("\\$\"`", CHAR_SPECIAL);
3662 set_in_charmap("\\$\"", CHAR_SPECIAL);
3664 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
3665 set_in_charmap(ifs, CHAR_IFS); /* are ordinary if quoted */
3668 /* most recursion does not come through here, the exception is
3669 * from builtin_source() and builtin_eval() */
3670 static int parse_and_run_stream(struct in_str *inp, int parse_flag)
3672 struct p_context ctx;
3673 o_string temp = NULL_O_STRING;
3676 ctx.parse_type = parse_flag;
3677 initialize_context(&ctx);
3679 if (!(parse_flag & PARSEFLAG_SEMICOLON) || (parse_flag & PARSEFLAG_REPARSING))
3680 set_in_charmap(";$&|", CHAR_ORDINARY);
3681 #if ENABLE_HUSH_INTERACTIVE
3682 inp->promptmode = 0; /* PS1 */
3684 /* We will stop & execute after each ';' or '\n'.
3685 * Example: "sleep 9999; echo TEST" + ctrl-C:
3686 * TEST should be printed */
3687 rcode = parse_stream(&temp, &ctx, inp, ";\n");
3688 if (rcode != 1 && ctx.old_flag != 0) {
3691 if (rcode != 1 && ctx.old_flag == 0) {
3692 done_word(&temp, &ctx);
3693 done_pipe(&ctx, PIPE_SEQ);
3694 debug_print_tree(ctx.list_head, 0);
3695 debug_printf_exec("parse_stream_outer: run_and_free_list\n");
3696 run_and_free_list(ctx.list_head);
3698 if (ctx.old_flag != 0) {
3705 free_pipe_list(ctx.list_head, /* indent: */ 0);
3708 } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP)); /* loop on syntax errors, return on EOF */
3712 static int parse_and_run_string(const char *s, int parse_flag)
3714 struct in_str input;
3715 setup_string_in_str(&input, s);
3716 return parse_and_run_stream(&input, parse_flag);
3719 static int parse_and_run_file(FILE *f)
3722 struct in_str input;
3723 setup_file_in_str(&input, f);
3724 rcode = parse_and_run_stream(&input, PARSEFLAG_SEMICOLON);
3729 /* Make sure we have a controlling tty. If we get started under a job
3730 * aware app (like bash for example), make sure we are now in charge so
3731 * we don't fight over who gets the foreground */
3732 static void setup_job_control(void)
3736 saved_task_pgrp = shell_pgrp = getpgrp();
3737 debug_printf_jobs("saved_task_pgrp=%d\n", saved_task_pgrp);
3738 close_on_exec_on(interactive_fd);
3740 /* If we were ran as 'hush &',
3741 * sleep until we are in the foreground. */
3742 while (tcgetpgrp(interactive_fd) != shell_pgrp) {
3743 /* Send TTIN to ourself (should stop us) */
3744 kill(- shell_pgrp, SIGTTIN);
3745 shell_pgrp = getpgrp();
3748 /* Ignore job-control and misc signals. */
3749 set_jobctrl_sighandler(SIG_IGN);
3750 set_misc_sighandler(SIG_IGN);
3751 //huh? signal(SIGCHLD, SIG_IGN);
3753 /* We _must_ restore tty pgrp on fatal signals */
3754 set_fatal_sighandler(sigexit);
3756 /* Put ourselves in our own process group. */
3757 setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
3758 /* Grab control of the terminal. */
3759 tcsetpgrp(interactive_fd, getpid());
3763 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
3764 int hush_main(int argc, char **argv)
3766 static const char version_str[] ALIGN1 = "HUSH_VERSION="HUSH_VER_STR;
3767 static const struct variable const_shell_ver = {
3769 .varstr = (char*)version_str,
3770 .max_len = 1, /* 0 can provoke free(name) */
3778 struct variable *cur_var;
3780 PTR_TO_GLOBALS = xzalloc(sizeof(G));
3782 /* Deal with HUSH_VERSION */
3783 shell_ver = const_shell_ver; /* copying struct here */
3784 top_var = &shell_ver;
3785 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
3786 /* Initialize our shell local variables with the values
3787 * currently living in the environment */
3791 char *value = strchr(*e, '=');
3792 if (value) { /* paranoia */
3793 cur_var->next = xzalloc(sizeof(*cur_var));
3794 cur_var = cur_var->next;
3795 cur_var->varstr = *e;
3796 cur_var->max_len = strlen(*e);
3797 cur_var->flg_export = 1;
3801 putenv((char *)version_str); /* reinstate HUSH_VERSION */
3803 #if ENABLE_FEATURE_EDITING
3804 line_input_state = new_line_input_t(FOR_SHELL);
3806 /* XXX what should these be while sourcing /etc/profile? */
3809 /* Initialize some more globals to non-zero values */
3811 #if ENABLE_HUSH_INTERACTIVE
3812 #if ENABLE_FEATURE_EDITING
3813 cmdedit_set_initial_prompt();
3818 if (EXIT_SUCCESS) /* otherwise is already done */
3819 last_return_code = EXIT_SUCCESS;
3821 if (argv[0] && argv[0][0] == '-') {
3822 debug_printf("sourcing /etc/profile\n");
3823 input = fopen("/etc/profile", "r");
3824 if (input != NULL) {
3825 close_on_exec_on(fileno(input));
3826 parse_and_run_file(input);
3832 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
3835 global_argv = argv + optind;
3836 global_argc = argc - optind;
3837 opt = parse_and_run_string(optarg, PARSEFLAG_SEMICOLON);
3840 /* Well, we cannot just declare interactiveness,
3841 * we have to have some stuff (ctty, etc) */
3842 /* interactive_fd++; */
3849 fprintf(stderr, "Usage: sh [FILE]...\n"
3850 " or: sh -c command [args]...\n\n");
3858 /* A shell is interactive if the '-i' flag was given, or if all of
3859 * the following conditions are met:
3861 * no arguments remaining or the -s flag given
3862 * standard input is a terminal
3863 * standard output is a terminal
3864 * Refer to Posix.2, the description of the 'sh' utility. */
3865 if (argv[optind] == NULL && input == stdin
3866 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3868 saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
3869 debug_printf("saved_tty_pgrp=%d\n", saved_tty_pgrp);
3870 if (saved_tty_pgrp >= 0) {
3871 /* try to dup to high fd#, >= 255 */
3872 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3873 if (interactive_fd < 0) {
3874 /* try to dup to any fd */
3875 interactive_fd = dup(STDIN_FILENO);
3876 if (interactive_fd < 0)
3880 // TODO: track & disallow any attempts of user
3881 // to (inadvertently) close/redirect it
3884 debug_printf("interactive_fd=%d\n", interactive_fd);
3885 if (interactive_fd) {
3886 fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
3887 /* Looks like they want an interactive shell */
3888 setup_job_control();
3889 /* -1 is special - makes xfuncs longjmp, not exit
3890 * (we reset die_sleep = 0 whereever we [v]fork) */
3892 if (setjmp(die_jmp)) {
3893 /* xfunc has failed! die die die */
3894 hush_exit(xfunc_error_retval);
3896 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
3897 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
3898 printf("Enter 'help' for a list of built-in commands.\n\n");
3901 #elif ENABLE_HUSH_INTERACTIVE
3902 /* no job control compiled, only prompt/line editing */
3903 if (argv[optind] == NULL && input == stdin
3904 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3906 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3907 if (interactive_fd < 0) {
3908 /* try to dup to any fd */
3909 interactive_fd = dup(STDIN_FILENO);
3910 if (interactive_fd < 0)
3915 fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
3919 if (argv[optind] == NULL) {
3920 opt = parse_and_run_file(stdin);
3922 debug_printf("\nrunning script '%s'\n", argv[optind]);
3923 global_argv = argv + optind;
3924 global_argc = argc - optind;
3925 input = xfopen(argv[optind], "r");
3926 fcntl(fileno(input), F_SETFD, FD_CLOEXEC);
3927 opt = parse_and_run_file(input);
3932 #if ENABLE_FEATURE_CLEAN_UP
3934 if (cwd != bb_msg_unknown)
3936 cur_var = top_var->next;
3938 struct variable *tmp = cur_var;
3939 if (!cur_var->max_len)
3940 free(cur_var->varstr);
3941 cur_var = cur_var->next;
3945 hush_exit(opt ? opt : last_return_code);
3950 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
3951 int lash_main(int argc, char **argv)
3953 //bb_error_msg("lash is deprecated, please use hush instead");
3954 return hush_main(argc, argv);