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 * o_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 * &> and >& redirection of stdout+stderr
44 * fancy forms of Parameter Expansion
46 * Arithmetic Expansion
47 * <(list) and >(list) Process Substitution
48 * reserved words: select, function
49 * Here Documents ( << word )
52 * job handling woefully incomplete and buggy (improved --vda)
54 * port selected bugfixes from post-0.49 busybox lash - done?
55 * change { and } from special chars to reserved words
56 * builtins: return, trap, ulimit
57 * test magic exec with redirection only
58 * check setting of global_argc and global_argv
59 * follow IFS rules more precisely, including update semantics
60 * figure out what to do with backslash-newline
61 * propagate syntax errors, die on resource errors?
62 * continuation lines, both explicit and implicit - done?
63 * memory leak finding and plugging - done?
64 * maybe change charmap[] to use 2-bit entries
66 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
69 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
70 //TODO: pull in some .h and find out do we have SINGLE_APPLET_MAIN?
71 //#include "applet_tables.h" doesn't work
73 /* #include <dmalloc.h> */
78 #define HUSH_VER_STR "0.91"
80 #if defined SINGLE_APPLET_MAIN
81 /* STANDALONE does not make sense, and won't compile */
82 #undef CONFIG_FEATURE_SH_STANDALONE
83 #undef ENABLE_FEATURE_SH_STANDALONE
84 #undef USE_FEATURE_SH_STANDALONE
85 #define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
86 #define ENABLE_FEATURE_SH_STANDALONE 0
87 #define USE_FEATURE_SH_STANDALONE(...)
88 #define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
91 #if !BB_MMU && ENABLE_HUSH_TICK
92 //#undef ENABLE_HUSH_TICK
93 //#define ENABLE_HUSH_TICK 0
94 #warning On NOMMU, hush command substitution is dangerous.
95 #warning Dont use it for commands which produce lots of output.
96 #warning For more info see shell/hush.c, generate_stream_from_list().
99 #if !BB_MMU && ENABLE_HUSH_JOB
100 #undef ENABLE_HUSH_JOB
101 #define ENABLE_HUSH_JOB 0
104 #if !ENABLE_HUSH_INTERACTIVE
105 #undef ENABLE_FEATURE_EDITING
106 #define ENABLE_FEATURE_EDITING 0
107 #undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
108 #define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
112 /* Keep unconditionally on for now */
115 #define ENABLE_HUSH_FUNCTIONS 0
118 /* If you comment out one of these below, it will be #defined later
119 * to perform debug printfs to stderr: */
120 #define debug_printf(...) do {} while (0)
121 /* Finer-grained debug switches */
122 #define debug_printf_parse(...) do {} while (0)
123 #define debug_print_tree(a, b) do {} while (0)
124 #define debug_printf_exec(...) do {} while (0)
125 #define debug_printf_env(...) do {} while (0)
126 #define debug_printf_jobs(...) do {} while (0)
127 #define debug_printf_expand(...) do {} while (0)
128 #define debug_printf_glob(...) do {} while (0)
129 #define debug_printf_list(...) do {} while (0)
130 #define debug_printf_subst(...) do {} while (0)
131 #define debug_printf_clean(...) do {} while (0)
134 #define debug_printf(...) fprintf(stderr, __VA_ARGS__)
137 #ifndef debug_printf_parse
138 #define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
141 #ifndef debug_printf_exec
142 #define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
145 #ifndef debug_printf_env
146 #define debug_printf_env(...) fprintf(stderr, __VA_ARGS__)
149 #ifndef debug_printf_jobs
150 #define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
156 #ifndef debug_printf_expand
157 #define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
158 #define DEBUG_EXPAND 1
160 #define DEBUG_EXPAND 0
163 #ifndef debug_printf_glob
164 #define debug_printf_glob(...) fprintf(stderr, __VA_ARGS__)
170 #ifndef debug_printf_list
171 #define debug_printf_list(...) fprintf(stderr, __VA_ARGS__)
174 #ifndef debug_printf_subst
175 #define debug_printf_subst(...) fprintf(stderr, __VA_ARGS__)
178 #ifndef debug_printf_clean
179 /* broken, of course, but OK for testing */
180 static const char *indenter(int i)
182 static const char blanks[] ALIGN1 =
184 return &blanks[sizeof(blanks) - i - 1];
186 #define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
187 #define DEBUG_CLEAN 1
191 static void debug_print_strings(const char *prefix, char **vv)
193 fprintf(stderr, "%s:\n", prefix);
195 fprintf(stderr, " '%s'\n", *vv++);
198 #define debug_print_strings(prefix, vv) ((void)0)
202 * Leak hunting. Use hush_leaktool.sh for post-processing.
204 #ifdef FOR_HUSH_LEAKTOOL
205 /* suppress "warning: no previous prototype..." */
206 void *xxmalloc(int lineno, size_t size);
207 void *xxrealloc(int lineno, void *ptr, size_t size);
208 char *xxstrdup(int lineno, const char *str);
209 void xxfree(void *ptr);
210 void *xxmalloc(int lineno, size_t size)
212 void *ptr = xmalloc((size + 0xff) & ~0xff);
213 fprintf(stderr, "line %d: malloc %p\n", lineno, ptr);
216 void *xxrealloc(int lineno, void *ptr, size_t size)
218 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
219 fprintf(stderr, "line %d: realloc %p\n", lineno, ptr);
222 char *xxstrdup(int lineno, const char *str)
224 char *ptr = xstrdup(str);
225 fprintf(stderr, "line %d: strdup %p\n", lineno, ptr);
228 void xxfree(void *ptr)
230 fprintf(stderr, "free %p\n", ptr);
233 #define xmalloc(s) xxmalloc(__LINE__, s)
234 #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
235 #define xstrdup(s) xxstrdup(__LINE__, s)
236 #define free(p) xxfree(p)
240 /* Do we support ANY keywords? */
241 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
242 #define HAS_KEYWORDS 1
243 #define IF_HAS_KEYWORDS(...) __VA_ARGS__
244 #define IF_HAS_NO_KEYWORDS(...)
246 #define HAS_KEYWORDS 0
247 #define IF_HAS_KEYWORDS(...)
248 #define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
252 #define SPECIAL_VAR_SYMBOL 3
253 #define PARSEFLAG_EXIT_FROM_LOOP 1
255 typedef enum redir_type {
257 REDIRECT_OVERWRITE = 2,
263 /* The descrip member of this structure is only used to make
264 * debugging output pretty */
265 static const struct {
267 signed char default_fd;
271 { O_RDONLY, 0, "<" },
272 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
273 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
274 { O_RDONLY, -1, "<<" },
278 typedef enum pipe_style {
285 typedef enum reserved_style {
294 #if ENABLE_HUSH_LOOPS
301 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
306 /* two pseudo-keywords support contrived "case" syntax: */
307 RES_MATCH , /* "word)" */
308 RES_CASEI , /* "this command is inside CASE" */
315 struct redir_struct {
316 struct redir_struct *next;
317 char *rd_filename; /* filename */
318 int fd; /* file descriptor being redirected */
319 int dup; /* -1, or file descriptor being duplicated */
320 smallint /*enum redir_type*/ rd_type;
324 pid_t pid; /* 0 if exited */
325 int assignment_cnt; /* how many argv[i] are assignments? */
326 smallint is_stopped; /* is the command currently running? */
328 struct pipe *group; /* if non-NULL, this "prog" is {} group,
329 * subshell, or a compound statement */
330 char **argv; /* command name and arguments */
331 struct redir_struct *redirects; /* I/O redirections */
333 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
334 * and on execution these are substituted with their values.
335 * Substitution can make _several_ words out of one argv[n]!
336 * Example: argv[0]=='.^C*^C.' here: echo .$*.
337 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
340 #define GRP_SUBSHELL 1
341 #if ENABLE_HUSH_FUNCTIONS
342 #define GRP_FUNCTION 2
347 int num_cmds; /* total number of commands in job */
348 int alive_cmds; /* number of commands running (not exited) */
349 int stopped_cmds; /* number of commands alive, but stopped */
351 int jobid; /* job number */
352 pid_t pgrp; /* process group ID for the job */
353 char *cmdtext; /* name of job */
355 struct command *cmds; /* array of commands in pipe */
356 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
357 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
358 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
361 /* This holds pointers to the various results of parsing */
362 struct parse_context {
363 struct command *command;
364 struct pipe *list_head;
366 struct redir_struct *pending_redirect;
369 smallint ctx_inverted; /* "! cmd | cmd" */
371 smallint ctx_dsemicolon; /* ";;" seen */
373 int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */
374 struct parse_context *stack;
378 /* On program start, environ points to initial environment.
379 * putenv adds new pointers into it, unsetenv removes them.
380 * Neither of these (de)allocates the strings.
381 * setenv allocates new strings in malloc space and does putenv,
382 * and thus setenv is unusable (leaky) for shell's purposes */
383 #define setenv(...) setenv_is_leaky_dont_use()
385 struct variable *next;
386 char *varstr; /* points to "name=" portion */
387 int max_len; /* if > 0, name is part of initial env; else name is malloced */
388 smallint flg_export; /* putenv should be done on this var */
389 smallint flg_read_only;
392 typedef struct o_string {
394 int length; /* position where data is appended */
396 /* Misnomer! it's not "quoting", it's "protection against globbing"!
397 * (by prepending \ to *, ?, [ and to \ too) */
401 smallint has_empty_slot;
402 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
405 MAYBE_ASSIGNMENT = 0,
406 DEFINITELY_ASSIGNMENT = 1,
408 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
410 /* Used for initialization: o_string foo = NULL_O_STRING; */
411 #define NULL_O_STRING { NULL }
413 /* I can almost use ordinary FILE*. Is open_memstream() universally
414 * available? Where is it documented? */
415 typedef struct in_str {
417 /* eof_flag=1: last char in ->p is really an EOF */
418 char eof_flag; /* meaningless if ->p == NULL */
420 #if ENABLE_HUSH_INTERACTIVE
422 smallint promptmode; /* 0: PS1, 1: PS2 */
425 int (*get) (struct in_str *);
426 int (*peek) (struct in_str *);
428 #define i_getch(input) ((input)->get(input))
429 #define i_peek(input) ((input)->peek(input))
433 CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
434 CHAR_IFS = 2, /* treated as ordinary if quoted */
435 CHAR_SPECIAL = 3, /* example: $ */
444 /* "Globals" within this file */
446 /* Sorted roughly by size (smaller offsets == smaller code) */
448 #if ENABLE_HUSH_INTERACTIVE
449 /* 'interactive_fd' is a fd# open to ctty, if we have one
450 * _AND_ if we decided to act interactively */
455 #if ENABLE_FEATURE_EDITING
456 line_input_t *line_input_state;
462 pid_t saved_tty_pgrp;
464 struct pipe *job_list;
465 struct pipe *toplevel_list;
466 smallint ctrl_z_flag;
468 #if ENABLE_HUSH_LOOPS
469 smallint flag_break_continue;
472 /* these three support $?, $#, and $1 */
473 smalluint last_return_code;
476 #if ENABLE_HUSH_LOOPS
477 unsigned depth_break_continue;
478 unsigned depth_of_loop;
482 struct variable *top_var; /* = &G.shell_ver (set in main()) */
483 struct variable shell_ver;
484 #if ENABLE_FEATURE_SH_STANDALONE
485 struct nofork_save_area nofork_save;
488 sigjmp_buf toplevel_jb;
490 unsigned char charmap[256];
491 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
494 #define G (*ptr_to_globals)
495 /* Not #defining name to G.name - this quickly gets unwieldy
496 * (too many defines). Also, I actually prefer to see when a variable
497 * is global, thus "G." prefix is a useful hint */
498 #define INIT_G() do { \
499 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
503 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
507 static void syntax(const char *msg)
509 #if ENABLE_HUSH_INTERACTIVE
510 /* Was using fancy stuff:
511 * (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
512 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
513 void FAST_FUNC (*fp)(const char *s, ...);
514 fp = (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die);
515 fp(msg ? "%s: %s" : "syntax error", "syntax error", msg);
517 bb_error_msg_and_die(msg ? "%s: %s" : "syntax error", "syntax error", msg);
523 static void syntax_lineno(int line)
525 #if ENABLE_HUSH_INTERACTIVE
526 void FAST_FUNC (*fp)(const char *s, ...);
527 fp = (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die);
528 fp("syntax error hush.c:%d", line);
530 bb_error_msg_and_die("syntax error hush.c:%d", line);
533 #define syntax(str) syntax_lineno(__LINE__)
536 /* Index of subroutines: */
537 /* in_str manipulations: */
538 static int static_get(struct in_str *i);
539 static int static_peek(struct in_str *i);
540 static int file_get(struct in_str *i);
541 static int file_peek(struct in_str *i);
542 static void setup_file_in_str(struct in_str *i, FILE *f);
543 static void setup_string_in_str(struct in_str *i, const char *s);
544 /* "run" the final data structures: */
545 #if !defined(DEBUG_CLEAN)
546 #define free_pipe_list(head, indent) free_pipe_list(head)
547 #define free_pipe(pi, indent) free_pipe(pi)
549 static int free_pipe_list(struct pipe *head, int indent);
550 static int free_pipe(struct pipe *pi, int indent);
551 /* really run the final data structures: */
552 typedef struct nommu_save_t {
558 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
559 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
560 #define pseudo_exec(nommu_save, command, argv_expanded) \
561 pseudo_exec(command, argv_expanded)
563 static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded) NORETURN;
564 static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded) NORETURN;
565 static int setup_redirects(struct command *prog, int squirrel[]);
566 static int run_list(struct pipe *pi);
567 static int run_pipe(struct pipe *pi);
568 /* data structure manipulation: */
569 static int setup_redirect(struct parse_context *ctx, int fd, redir_type style, struct in_str *input);
570 static void initialize_context(struct parse_context *ctx);
571 static int done_word(o_string *dest, struct parse_context *ctx);
572 static int done_command(struct parse_context *ctx);
573 static void done_pipe(struct parse_context *ctx, pipe_style type);
574 /* primary string parsing: */
575 static int redirect_dup_num(struct in_str *input);
576 static int redirect_opt_num(o_string *o);
578 static int process_command_subs(o_string *dest,
579 struct in_str *input, const char *subst_end);
581 static int parse_group(o_string *dest, struct parse_context *ctx, struct in_str *input, int ch);
582 static const char *lookup_param(const char *src);
583 static int handle_dollar(o_string *dest,
584 struct in_str *input);
585 static int parse_stream(o_string *dest, struct parse_context *ctx, struct in_str *input0, const char *end_trigger);
587 static int parse_and_run_stream(struct in_str *inp, int parse_flag);
588 static int parse_and_run_string(const char *s, int parse_flag);
589 static int parse_and_run_file(FILE *f);
590 /* job management: */
591 static int checkjobs(struct pipe* fg_pipe);
593 static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
594 static void insert_bg_job(struct pipe *pi);
595 static void remove_bg_job(struct pipe *pi);
596 static void delete_finished_bg_job(struct pipe *pi);
598 int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
600 /* local variable support */
601 static char **expand_strvec_to_strvec(char **argv);
603 static char *expand_strvec_to_string(char **argv);
604 /* used for expansion of right hand of assignments */
605 static char *expand_string_to_string(const char *str);
606 static struct variable *get_local_var(const char *name);
607 static int set_local_var(char *str, int flg_export);
608 static void unset_local_var(const char *name);
611 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="HUSH_VER_STR;
614 static int glob_needed(const char *s)
619 if (*s == '*' || *s == '[' || *s == '?')
626 static int is_assignment(const char *s)
628 if (!s || !(isalpha(*s) || *s == '_'))
631 while (isalnum(*s) || *s == '_')
636 /* Replace each \x with x in place, return ptr past NUL. */
637 static char *unbackslash(char *src)
643 if ((*dst++ = *src++) == '\0')
649 static char **add_strings_to_strings(char **strings, char **add)
670 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
671 v[count1 + count2] = NULL;
674 v[count1 + i] = add[i];
678 static char **add_string_to_strings(char **strings, char *add)
683 return add_strings_to_strings(strings, v);
686 static void putenv_all(char **strings)
691 debug_printf_env("putenv '%s'\n", *strings);
696 static char **putenv_all_and_save_old(char **strings)
706 eq = strchr(*strings, '=');
709 v = getenv(*strings);
712 /* v points to VAL in VAR=VAL, go back to VAR */
713 v -= (eq - *strings) + 1;
714 old = add_string_to_strings(old, v);
723 static void free_strings_and_unsetenv(char **strings, int unset)
733 debug_printf_env("unsetenv '%s'\n", *v);
741 static void free_strings(char **strings)
743 free_strings_and_unsetenv(strings, 0);
747 /* Function prototypes for builtins */
748 static int builtin_cd(char **argv);
749 static int builtin_echo(char **argv);
750 static int builtin_eval(char **argv);
751 static int builtin_exec(char **argv);
752 static int builtin_exit(char **argv);
753 static int builtin_export(char **argv);
755 static int builtin_fg_bg(char **argv);
756 static int builtin_jobs(char **argv);
759 static int builtin_help(char **argv);
761 static int builtin_pwd(char **argv);
762 static int builtin_read(char **argv);
763 static int builtin_test(char **argv);
764 static int builtin_true(char **argv);
765 static int builtin_set(char **argv);
766 static int builtin_shift(char **argv);
767 static int builtin_source(char **argv);
768 static int builtin_umask(char **argv);
769 static int builtin_unset(char **argv);
770 #if ENABLE_HUSH_LOOPS
771 static int builtin_break(char **argv);
772 static int builtin_continue(char **argv);
774 //static int builtin_not_written(char **argv);
776 /* Table of built-in functions. They can be forked or not, depending on
777 * context: within pipes, they fork. As simple commands, they do not.
778 * When used in non-forking context, they can change global variables
779 * in the parent shell process. If forked, of course they cannot.
780 * For example, 'unset foo | whatever' will parse and run, but foo will
781 * still be set at the end. */
782 struct built_in_command {
784 int (*function)(char **argv);
787 #define BLTIN(cmd, func, help) { cmd, func, help }
789 #define BLTIN(cmd, func, help) { cmd, func }
793 /* For now, echo and test are unconditionally enabled.
794 * Maybe make it configurable? */
795 static const struct built_in_command bltins[] = {
796 BLTIN("." , builtin_source, "Run commands in a file"),
797 BLTIN(":" , builtin_true, "No-op"),
798 BLTIN("[" , builtin_test, "Test condition"),
799 BLTIN("[[" , builtin_test, "Test condition"),
801 BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"),
803 #if ENABLE_HUSH_LOOPS
804 BLTIN("break" , builtin_break, "Exit from a loop"),
806 BLTIN("cd" , builtin_cd, "Change directory"),
807 #if ENABLE_HUSH_LOOPS
808 BLTIN("continue", builtin_continue, "Start new loop iteration"),
810 BLTIN("echo" , builtin_echo, "Write to stdout"),
811 BLTIN("eval" , builtin_eval, "Construct and run shell command"),
812 BLTIN("exec" , builtin_exec, "Execute command, don't return to shell"),
813 BLTIN("exit" , builtin_exit, "Exit"),
814 BLTIN("export", builtin_export, "Set environment variable"),
816 BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"),
817 BLTIN("jobs" , builtin_jobs, "List active jobs"),
819 BLTIN("pwd" , builtin_pwd, "Print current directory"),
820 BLTIN("read" , builtin_read, "Input environment variable"),
821 // BLTIN("return", builtin_not_written, "Return from a function"),
822 BLTIN("set" , builtin_set, "Set/unset shell local variables"),
823 BLTIN("shift" , builtin_shift, "Shift positional parameters"),
824 // BLTIN("trap" , builtin_not_written, "Trap signals"),
825 BLTIN("test" , builtin_test, "Test condition"),
826 // BLTIN("ulimit", builtin_not_written, "Control resource limits"),
827 BLTIN("umask" , builtin_umask, "Set file creation mask"),
828 BLTIN("unset" , builtin_unset, "Unset environment variable"),
830 BLTIN("help" , builtin_help, "List shell built-in commands"),
835 /* Signals are grouped, we handle them in batches */
836 static void set_misc_sighandler(void (*handler)(int))
847 static void set_fatal_sighandler(void (*handler)(int))
856 /* bash 3.2 seems to handle these just like 'fatal' ones */
862 static void set_jobctrl_sighandler(void (*handler)(int))
870 /* SIGCHLD is special and handled separately */
872 static void set_every_sighandler(void (*handler)(int))
874 set_fatal_sighandler(handler);
875 set_jobctrl_sighandler(handler);
876 set_misc_sighandler(handler);
877 signal(SIGCHLD, handler);
880 static void handler_ctrl_c(int sig UNUSED_PARAM)
882 debug_printf_jobs("got sig %d\n", sig);
883 // as usual we can have all kinds of nasty problems with leaked malloc data here
884 siglongjmp(G.toplevel_jb, 1);
887 static void handler_ctrl_z(int sig UNUSED_PARAM)
891 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
893 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
896 if (!pid) { /* child */
898 die_sleep = 0; /* let nofork's xfuncs die */
900 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
901 set_every_sighandler(SIG_DFL);
902 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
903 debug_printf_jobs("returning in child\n");
904 /* return to nofork, it will eventually exit now,
905 * not return back to shell */
909 /* finish filling up pipe info */
910 G.toplevel_list->pgrp = pid; /* child is in its own pgrp */
911 G.toplevel_list->cmds[0].pid = pid;
912 /* parent needs to longjmp out of running nofork.
913 * we will "return" exitcode 0, with child put in background */
914 // as usual we can have all kinds of nasty problems with leaked malloc data here
915 debug_printf_jobs("siglongjmp in parent\n");
916 siglongjmp(G.toplevel_jb, 1);
919 /* Restores tty foreground process group, and exits.
920 * May be called as signal handler for fatal signal
921 * (will faithfully resend signal to itself, producing correct exit state)
922 * or called directly with -EXITCODE.
923 * We also call it if xfunc is exiting. */
924 static void sigexit(int sig) NORETURN;
925 static void sigexit(int sig)
927 /* Disable all signals: job control, SIGPIPE, etc. */
928 sigprocmask_allsigs(SIG_BLOCK);
930 #if ENABLE_HUSH_INTERACTIVE
931 if (G.interactive_fd)
932 tcsetpgrp(G.interactive_fd, G.saved_tty_pgrp);
935 /* Not a signal, just exit */
939 kill_myself_with_sig(sig); /* does not return */
942 /* Restores tty foreground process group, and exits. */
943 static void hush_exit(int exitcode) NORETURN;
944 static void hush_exit(int exitcode)
946 fflush(NULL); /* flush all streams */
947 sigexit(- (exitcode & 0xff));
952 #define set_fatal_sighandler(handler) ((void)0)
953 #define set_jobctrl_sighandler(handler) ((void)0)
954 #define hush_exit(e) exit(e)
959 static const char *set_cwd(void)
961 if (G.cwd == bb_msg_unknown)
962 G.cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
963 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
965 G.cwd = bb_msg_unknown;
973 #define B_CHUNK (32 * sizeof(char*))
975 static void o_reset(o_string *o)
983 static void o_free(o_string *o)
986 memset(o, 0, sizeof(*o));
989 static void o_grow_by(o_string *o, int len)
991 if (o->length + len > o->maxlen) {
992 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
993 o->data = xrealloc(o->data, 1 + o->maxlen);
997 static void o_addchr(o_string *o, int ch)
999 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1001 o->data[o->length] = ch;
1003 o->data[o->length] = '\0';
1006 static void o_addstr(o_string *o, const char *str, int len)
1009 memcpy(&o->data[o->length], str, len);
1011 o->data[o->length] = '\0';
1014 static void o_addstr_duplicate_backslash(o_string *o, const char *str, int len)
1019 && (*str != '*' && *str != '?' && *str != '[')
1027 /* My analysis of quoting semantics tells me that state information
1028 * is associated with a destination, not a source.
1030 static void o_addqchr(o_string *o, int ch)
1033 char *found = strchr("*?[\\", ch);
1038 o->data[o->length] = '\\';
1041 o->data[o->length] = ch;
1043 o->data[o->length] = '\0';
1046 static void o_addQchr(o_string *o, int ch)
1049 if (o->o_quote && strchr("*?[\\", ch)) {
1051 o->data[o->length] = '\\';
1055 o->data[o->length] = ch;
1057 o->data[o->length] = '\0';
1060 static void o_addQstr(o_string *o, const char *str, int len)
1063 o_addstr(o, str, len);
1069 int ordinary_cnt = strcspn(str, "*?[\\");
1070 if (ordinary_cnt > len) /* paranoia */
1072 o_addstr(o, str, ordinary_cnt);
1073 if (ordinary_cnt == len)
1075 str += ordinary_cnt;
1076 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
1080 if (ch) { /* it is necessarily one of "*?[\\" */
1082 o->data[o->length] = '\\';
1086 o->data[o->length] = ch;
1088 o->data[o->length] = '\0';
1092 /* A special kind of o_string for $VAR and `cmd` expansion.
1093 * It contains char* list[] at the beginning, which is grown in 16 element
1094 * increments. Actual string data starts at the next multiple of 16 * (char*).
1095 * list[i] contains an INDEX (int!) into this string data.
1096 * It means that if list[] needs to grow, data needs to be moved higher up
1097 * but list[i]'s need not be modified.
1098 * NB: remembering how many list[i]'s you have there is crucial.
1099 * o_finalize_list() operation post-processes this structure - calculates
1100 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1102 #if DEBUG_EXPAND || DEBUG_GLOB
1103 static void debug_print_list(const char *prefix, o_string *o, int n)
1105 char **list = (char**)o->data;
1106 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1108 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1109 prefix, list, n, string_start, o->length, o->maxlen);
1111 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1112 o->data + (int)list[i] + string_start,
1113 o->data + (int)list[i] + string_start);
1117 const char *p = o->data + (int)list[n - 1] + string_start;
1118 fprintf(stderr, " total_sz:%d\n", (p + strlen(p) + 1) - o->data);
1122 #define debug_print_list(prefix, o, n) ((void)0)
1125 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1126 * in list[n] so that it points past last stored byte so far.
1127 * It returns n+1. */
1128 static int o_save_ptr_helper(o_string *o, int n)
1130 char **list = (char**)o->data;
1134 if (!o->has_empty_slot) {
1135 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1136 string_len = o->length - string_start;
1137 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1138 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
1139 /* list[n] points to string_start, make space for 16 more pointers */
1140 o->maxlen += 0x10 * sizeof(list[0]);
1141 o->data = xrealloc(o->data, o->maxlen + 1);
1142 list = (char**)o->data;
1143 memmove(list + n + 0x10, list + n, string_len);
1144 o->length += 0x10 * sizeof(list[0]);
1146 debug_printf_list("list[%d]=%d string_start=%d\n", n, string_len, string_start);
1148 /* We have empty slot at list[n], reuse without growth */
1149 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1150 string_len = o->length - string_start;
1151 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n", n, string_len, string_start);
1152 o->has_empty_slot = 0;
1154 list[n] = (char*)(ptrdiff_t)string_len;
1158 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
1159 static int o_get_last_ptr(o_string *o, int n)
1161 char **list = (char**)o->data;
1162 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1164 return ((int)(ptrdiff_t)list[n-1]) + string_start;
1167 /* o_glob performs globbing on last list[], saving each result
1168 * as a new list[]. */
1169 static int o_glob(o_string *o, int n)
1175 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
1177 return o_save_ptr_helper(o, n);
1178 pattern = o->data + o_get_last_ptr(o, n);
1179 debug_printf_glob("glob pattern '%s'\n", pattern);
1180 if (!glob_needed(pattern)) {
1182 o->length = unbackslash(pattern) - o->data;
1183 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
1184 return o_save_ptr_helper(o, n);
1187 memset(&globdata, 0, sizeof(globdata));
1188 gr = glob(pattern, 0, NULL, &globdata);
1189 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1190 if (gr == GLOB_NOSPACE)
1191 bb_error_msg_and_die("out of memory during glob");
1192 if (gr == GLOB_NOMATCH) {
1193 globfree(&globdata);
1196 if (gr != 0) { /* GLOB_ABORTED ? */
1197 //TODO: testcase for bad glob pattern behavior
1198 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1200 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1201 char **argv = globdata.gl_pathv;
1202 o->length = pattern - o->data; /* "forget" pattern */
1204 o_addstr(o, *argv, strlen(*argv) + 1);
1205 n = o_save_ptr_helper(o, n);
1211 globfree(&globdata);
1213 debug_print_list("o_glob returning", o, n);
1217 /* If o->o_glob == 1, glob the string so far remembered.
1218 * Otherwise, just finish current list[] and start new */
1219 static int o_save_ptr(o_string *o, int n)
1222 return o_glob(o, n); /* o_save_ptr_helper is inside */
1223 return o_save_ptr_helper(o, n);
1226 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
1227 static char **o_finalize_list(o_string *o, int n)
1232 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1234 debug_print_list("finalized", o, n);
1235 debug_printf_expand("finalized n:%d\n", n);
1236 list = (char**)o->data;
1237 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1241 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
1250 static int static_get(struct in_str *i)
1253 if (ch == '\0') return EOF;
1257 static int static_peek(struct in_str *i)
1262 #if ENABLE_HUSH_INTERACTIVE
1264 #if ENABLE_FEATURE_EDITING
1265 static void cmdedit_set_initial_prompt(void)
1267 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1270 G.PS1 = getenv("PS1");
1275 #endif /* EDITING */
1277 static const char* setup_prompt_string(int promptmode)
1279 const char *prompt_str;
1280 debug_printf("setup_prompt_string %d ", promptmode);
1281 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1282 /* Set up the prompt */
1283 if (promptmode == 0) { /* PS1 */
1285 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1291 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1293 debug_printf("result '%s'\n", prompt_str);
1297 static void get_user_input(struct in_str *i)
1300 const char *prompt_str;
1302 prompt_str = setup_prompt_string(i->promptmode);
1303 #if ENABLE_FEATURE_EDITING
1304 /* Enable command line editing only while a command line
1305 * is actually being read */
1307 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1308 } while (r == 0); /* repeat if Ctrl-C */
1309 i->eof_flag = (r < 0);
1310 if (i->eof_flag) { /* EOF/error detected */
1311 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1312 G.user_input_buf[1] = '\0';
1315 fputs(prompt_str, stdout);
1317 G.user_input_buf[0] = r = fgetc(i->file);
1318 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1319 i->eof_flag = (r == EOF);
1321 i->p = G.user_input_buf;
1324 #endif /* INTERACTIVE */
1326 /* This is the magic location that prints prompts
1327 * and gets data back from the user */
1328 static int file_get(struct in_str *i)
1332 /* If there is data waiting, eat it up */
1333 if (i->p && *i->p) {
1334 #if ENABLE_HUSH_INTERACTIVE
1338 if (i->eof_flag && !*i->p)
1341 /* need to double check i->file because we might be doing something
1342 * more complicated by now, like sourcing or substituting. */
1343 #if ENABLE_HUSH_INTERACTIVE
1344 if (G.interactive_fd && i->promptme && i->file == stdin) {
1347 } while (!*i->p); /* need non-empty line */
1348 i->promptmode = 1; /* PS2 */
1353 ch = fgetc(i->file);
1355 debug_printf("file_get: got a '%c' %d\n", ch, ch);
1356 #if ENABLE_HUSH_INTERACTIVE
1363 /* All the callers guarantee this routine will never be
1364 * used right after a newline, so prompting is not needed.
1366 static int file_peek(struct in_str *i)
1369 if (i->p && *i->p) {
1370 if (i->eof_flag && !i->p[1])
1374 ch = fgetc(i->file);
1375 i->eof_flag = (ch == EOF);
1376 i->peek_buf[0] = ch;
1377 i->peek_buf[1] = '\0';
1379 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
1383 static void setup_file_in_str(struct in_str *i, FILE *f)
1385 i->peek = file_peek;
1387 #if ENABLE_HUSH_INTERACTIVE
1389 i->promptmode = 0; /* PS1 */
1395 static void setup_string_in_str(struct in_str *i, const char *s)
1397 i->peek = static_peek;
1398 i->get = static_get;
1399 #if ENABLE_HUSH_INTERACTIVE
1401 i->promptmode = 0; /* PS1 */
1408 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
1409 * and stderr if they are redirected. */
1410 static int setup_redirects(struct command *prog, int squirrel[])
1413 struct redir_struct *redir;
1415 for (redir = prog->redirects; redir; redir = redir->next) {
1416 if (redir->dup == -1 && redir->rd_filename == NULL) {
1417 /* something went wrong in the parse. Pretend it didn't happen */
1420 if (redir->dup == -1) {
1422 mode = redir_table[redir->rd_type].mode;
1423 //TODO: check redir for names like '\\'
1424 p = expand_string_to_string(redir->rd_filename);
1425 openfd = open_or_warn(p, mode);
1428 /* this could get lost if stderr has been redirected, but
1429 bash and ash both lose it as well (though zsh doesn't!) */
1433 openfd = redir->dup;
1436 if (openfd != redir->fd) {
1437 if (squirrel && redir->fd < 3) {
1438 squirrel[redir->fd] = dup(redir->fd);
1441 //close(openfd); // close(-3) ??!
1443 dup2(openfd, redir->fd);
1444 if (redir->dup == -1)
1452 static void restore_redirects(int squirrel[])
1455 for (i = 0; i < 3; i++) {
1458 /* We simply die on error */
1464 static char **expand_assignments(char **argv, int count)
1468 /* Expand assignments into one string each */
1469 for (i = 0; i < count; i++) {
1470 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
1475 /* Called after [v]fork() in run_pipe(), or from builtin_exec().
1477 * XXX no exit() here. If you don't exec, use _exit instead.
1478 * The at_exit handlers apparently confuse the calling process,
1479 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
1480 static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded)
1484 const struct built_in_command *x;
1486 /* If a variable is assigned in a forest, and nobody listens,
1487 * was it ever really set?
1489 if (!argv[assignment_cnt])
1490 _exit(EXIT_SUCCESS);
1492 new_env = expand_assignments(argv, assignment_cnt);
1494 putenv_all(new_env);
1495 free(new_env); /* optional */
1497 nommu_save->new_env = new_env;
1498 nommu_save->old_env = putenv_all_and_save_old(new_env);
1500 if (argv_expanded) {
1501 argv = argv_expanded;
1503 argv = expand_strvec_to_strvec(argv);
1505 nommu_save->argv = argv;
1510 * Check if the command matches any of the builtins.
1511 * Depending on context, this might be redundant. But it's
1512 * easier to waste a few CPU cycles than it is to figure out
1513 * if this is one of those cases.
1515 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
1516 if (strcmp(argv[0], x->cmd) == 0) {
1517 debug_printf_exec("running builtin '%s'\n", argv[0]);
1518 rcode = x->function(argv);
1524 /* Check if the command matches any busybox applets */
1525 #if ENABLE_FEATURE_SH_STANDALONE
1526 if (strchr(argv[0], '/') == NULL) {
1527 int a = find_applet_by_name(argv[0]);
1529 if (APPLET_IS_NOEXEC(a)) {
1530 debug_printf_exec("running applet '%s'\n", argv[0]);
1531 // is it ok that run_applet_no_and_exit() does exit(), not _exit()?
1532 run_applet_no_and_exit(a, argv);
1534 /* re-exec ourselves with the new arguments */
1535 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
1536 execvp(bb_busybox_exec_path, argv);
1537 /* If they called chroot or otherwise made the binary no longer
1538 * executable, fall through */
1543 debug_printf_exec("execing '%s'\n", argv[0]);
1544 execvp(argv[0], argv);
1545 bb_perror_msg("can't exec '%s'", argv[0]);
1546 _exit(EXIT_FAILURE);
1549 /* Called after [v]fork() in run_pipe()
1551 static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded)
1554 pseudo_exec_argv(nommu_save, command->argv, command->assignment_cnt, argv_expanded);
1556 if (command->group) {
1558 bb_error_msg_and_die("nested lists are not supported on NOMMU");
1561 debug_printf_exec("pseudo_exec: run_list\n");
1562 rcode = run_list(command->group);
1563 /* OK to leak memory by not calling free_pipe_list,
1564 * since this process is about to exit */
1569 /* Can happen. See what bash does with ">foo" by itself. */
1570 debug_printf("trying to pseudo_exec null command\n");
1571 _exit(EXIT_SUCCESS);
1575 static const char *get_cmdtext(struct pipe *pi)
1581 /* This is subtle. ->cmdtext is created only on first backgrounding.
1582 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
1583 * On subsequent bg argv is trashed, but we won't use it */
1586 argv = pi->cmds[0].argv;
1587 if (!argv || !argv[0]) {
1588 pi->cmdtext = xzalloc(1);
1593 do len += strlen(*argv) + 1; while (*++argv);
1594 pi->cmdtext = p = xmalloc(len);
1595 argv = pi->cmds[0].argv;
1597 len = strlen(*argv);
1598 memcpy(p, *argv, len);
1606 static void insert_bg_job(struct pipe *pi)
1608 struct pipe *thejob;
1611 /* Linear search for the ID of the job to use */
1613 for (thejob = G.job_list; thejob; thejob = thejob->next)
1614 if (thejob->jobid >= pi->jobid)
1615 pi->jobid = thejob->jobid + 1;
1617 /* Add thejob to the list of running jobs */
1619 thejob = G.job_list = xmalloc(sizeof(*thejob));
1621 for (thejob = G.job_list; thejob->next; thejob = thejob->next)
1623 thejob->next = xmalloc(sizeof(*thejob));
1624 thejob = thejob->next;
1627 /* Physically copy the struct job */
1628 memcpy(thejob, pi, sizeof(struct pipe));
1629 thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
1630 /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
1631 for (i = 0; i < pi->num_cmds; i++) {
1632 // TODO: do we really need to have so many fields which are just dead weight
1633 // at execution stage?
1634 thejob->cmds[i].pid = pi->cmds[i].pid;
1635 /* all other fields are not used and stay zero */
1637 thejob->next = NULL;
1638 thejob->cmdtext = xstrdup(get_cmdtext(pi));
1640 /* We don't wait for background thejobs to return -- append it
1641 to the list of backgrounded thejobs and leave it alone */
1642 printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
1643 G.last_bg_pid = thejob->cmds[0].pid;
1644 G.last_jobid = thejob->jobid;
1647 static void remove_bg_job(struct pipe *pi)
1649 struct pipe *prev_pipe;
1651 if (pi == G.job_list) {
1652 G.job_list = pi->next;
1654 prev_pipe = G.job_list;
1655 while (prev_pipe->next != pi)
1656 prev_pipe = prev_pipe->next;
1657 prev_pipe->next = pi->next;
1660 G.last_jobid = G.job_list->jobid;
1665 /* Remove a backgrounded job */
1666 static void delete_finished_bg_job(struct pipe *pi)
1669 pi->stopped_cmds = 0;
1675 /* Check to see if any processes have exited -- if they
1676 * have, figure out why and see if a job has completed */
1677 static int checkjobs(struct pipe* fg_pipe)
1687 attributes = WUNTRACED;
1688 if (fg_pipe == NULL)
1689 attributes |= WNOHANG;
1691 /* Do we do this right?
1692 * bash-3.00# sleep 20 | false
1694 * [3]+ Stopped sleep 20 | false
1695 * bash-3.00# echo $?
1696 * 1 <========== bg pipe is not fully done, but exitcode is already known!
1699 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
1700 //are stopped. Testcase: "cat | cat" in a script (not on command line)
1701 // + killall -STOP cat
1704 // TODO: safe_waitpid?
1705 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
1707 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
1709 if (WIFSTOPPED(status))
1710 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
1711 childpid, WSTOPSIG(status), WEXITSTATUS(status));
1712 if (WIFSIGNALED(status))
1713 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
1714 childpid, WTERMSIG(status), WEXITSTATUS(status));
1715 if (WIFEXITED(status))
1716 debug_printf_jobs("pid %d exited, exitcode %d\n",
1717 childpid, WEXITSTATUS(status));
1719 /* Were we asked to wait for fg pipe? */
1721 for (i = 0; i < fg_pipe->num_cmds; i++) {
1722 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
1723 if (fg_pipe->cmds[i].pid != childpid)
1725 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
1727 fg_pipe->cmds[i].pid = 0;
1728 fg_pipe->alive_cmds--;
1729 if (i == fg_pipe->num_cmds - 1) {
1730 /* last process gives overall exitstatus */
1731 rcode = WEXITSTATUS(status);
1732 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
1735 fg_pipe->cmds[i].is_stopped = 1;
1736 fg_pipe->stopped_cmds++;
1738 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
1739 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
1740 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
1741 /* All processes in fg pipe have exited/stopped */
1743 if (fg_pipe->alive_cmds)
1744 insert_bg_job(fg_pipe);
1748 /* There are still running processes in the fg pipe */
1749 goto wait_more; /* do waitpid again */
1751 /* it wasnt fg_pipe, look for process in bg pipes */
1755 /* We asked to wait for bg or orphaned children */
1756 /* No need to remember exitcode in this case */
1757 for (pi = G.job_list; pi; pi = pi->next) {
1758 for (i = 0; i < pi->num_cmds; i++) {
1759 if (pi->cmds[i].pid == childpid)
1760 goto found_pi_and_prognum;
1763 /* Happens when shell is used as init process (init=/bin/sh) */
1764 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
1765 continue; /* do waitpid again */
1767 found_pi_and_prognum:
1770 pi->cmds[i].pid = 0;
1772 if (!pi->alive_cmds) {
1773 printf(JOB_STATUS_FORMAT, pi->jobid,
1774 "Done", pi->cmdtext);
1775 delete_finished_bg_job(pi);
1779 pi->cmds[i].is_stopped = 1;
1783 } /* while (waitpid succeeds)... */
1785 /* wait found no children or failed */
1787 if (childpid && errno != ECHILD)
1788 bb_perror_msg("waitpid");
1793 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1796 int rcode = checkjobs(fg_pipe);
1797 /* Job finished, move the shell to the foreground */
1798 p = getpgid(0); /* pgid of our process */
1799 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
1800 tcsetpgrp(G.interactive_fd, p);
1805 /* run_pipe() starts all the jobs, but doesn't wait for anything
1806 * to finish. See checkjobs().
1808 * return code is normally -1, when the caller has to wait for children
1809 * to finish to determine the exit status of the pipe. If the pipe
1810 * is a simple builtin command, however, the action is done by the
1811 * time run_pipe returns, and the exit code is provided as the
1814 * The input of the pipe is always stdin, the output is always
1815 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1816 * because it tries to avoid running the command substitution in
1817 * subshell, when that is in fact necessary. The subshell process
1818 * now has its stdout directed to the input of the appropriate pipe,
1819 * so this routine is noticeably simpler.
1821 * Returns -1 only if started some children. IOW: we have to
1822 * mask out retvals of builtins etc with 0xff!
1824 static int run_pipe(struct pipe *pi)
1828 int pipefds[2]; /* pipefds[0] is for reading */
1829 struct command *command;
1830 char **argv_expanded;
1832 const struct built_in_command *x;
1834 /* it is not always needed, but we aim to smaller code */
1835 int squirrel[] = { -1, -1, -1 };
1837 const int single_and_fg = (pi->num_cmds == 1 && pi->followup != PIPE_BG);
1839 debug_printf_exec("run_pipe start: single_and_fg=%d\n", single_and_fg);
1845 pi->stopped_cmds = 0;
1847 /* Check if this is a simple builtin (not part of a pipe).
1848 * Builtins within pipes have to fork anyway, and are handled in
1849 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1851 command = &(pi->cmds[0]);
1853 #if ENABLE_HUSH_FUNCTIONS
1854 if (single_and_fg && command->group && command->grp_type == GRP_FUNCTION) {
1855 /* We "execute" function definition */
1856 bb_error_msg("here we ought to remember function definition, and go on");
1857 return EXIT_SUCCESS;
1861 if (single_and_fg && command->group && command->grp_type == GRP_NORMAL) {
1862 debug_printf("non-subshell grouping\n");
1863 setup_redirects(command, squirrel);
1864 debug_printf_exec(": run_list\n");
1865 rcode = run_list(command->group) & 0xff;
1866 restore_redirects(squirrel);
1867 debug_printf_exec("run_pipe return %d\n", rcode);
1868 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
1872 argv = command->argv;
1873 argv_expanded = NULL;
1875 if (single_and_fg && argv != NULL) {
1876 char **new_env = NULL;
1877 char **old_env = NULL;
1879 i = command->assignment_cnt;
1880 if (i != 0 && argv[i] == NULL) {
1881 /* assignments, but no command: set local environment */
1882 for (i = 0; argv[i] != NULL; i++) {
1883 debug_printf("local environment set: %s\n", argv[i]);
1884 p = expand_string_to_string(argv[i]);
1885 set_local_var(p, 0);
1887 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1890 /* Expand the rest into (possibly) many strings each */
1891 argv_expanded = expand_strvec_to_strvec(argv + i);
1893 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
1894 if (strcmp(argv_expanded[0], x->cmd) != 0)
1896 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
1897 debug_printf("exec with redirects only\n");
1898 setup_redirects(command, NULL);
1899 rcode = EXIT_SUCCESS;
1900 goto clean_up_and_ret1;
1902 debug_printf("builtin inline %s\n", argv_expanded[0]);
1903 /* XXX setup_redirects acts on file descriptors, not FILEs.
1904 * This is perfect for work that comes after exec().
1905 * Is it really safe for inline use? Experimentally,
1906 * things seem to work with glibc. */
1907 setup_redirects(command, squirrel);
1908 new_env = expand_assignments(argv, command->assignment_cnt);
1909 old_env = putenv_all_and_save_old(new_env);
1910 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv_expanded[1]);
1911 rcode = x->function(argv_expanded) & 0xff;
1912 #if ENABLE_FEATURE_SH_STANDALONE
1915 restore_redirects(squirrel);
1916 free_strings_and_unsetenv(new_env, 1);
1917 putenv_all(old_env);
1918 free(old_env); /* not free_strings()! */
1920 free(argv_expanded);
1921 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
1922 debug_printf_exec("run_pipe return %d\n", rcode);
1925 #if ENABLE_FEATURE_SH_STANDALONE
1926 i = find_applet_by_name(argv_expanded[0]);
1927 if (i >= 0 && APPLET_IS_NOFORK(i)) {
1928 setup_redirects(command, squirrel);
1929 save_nofork_data(&G.nofork_save);
1930 new_env = expand_assignments(argv, command->assignment_cnt);
1931 old_env = putenv_all_and_save_old(new_env);
1932 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
1933 rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
1934 goto clean_up_and_ret;
1939 /* NB: argv_expanded may already be created, and that
1940 * might include `cmd` runs! Do not rerun it! We *must*
1941 * use argv_expanded if it's non-NULL */
1943 /* Disable job control signals for shell (parent) and
1944 * for initial child code after fork */
1945 set_jobctrl_sighandler(SIG_IGN);
1947 /* Going to fork a child per each pipe member */
1951 for (i = 0; i < pi->num_cmds; i++) {
1953 volatile nommu_save_t nommu_save;
1954 nommu_save.new_env = NULL;
1955 nommu_save.old_env = NULL;
1956 nommu_save.argv = NULL;
1958 command = &(pi->cmds[i]);
1959 if (command->argv) {
1960 debug_printf_exec(": pipe member '%s' '%s'...\n", command->argv[0], command->argv[1]);
1962 debug_printf_exec(": pipe member with no argv\n");
1964 /* pipes are inserted between pairs of commands */
1967 if ((i + 1) < pi->num_cmds)
1970 command->pid = BB_MMU ? fork() : vfork();
1971 if (!command->pid) { /* child */
1972 if (ENABLE_HUSH_JOB)
1973 die_sleep = 0; /* let nofork's xfuncs die */
1975 /* Every child adds itself to new process group
1976 * with pgid == pid_of_first_child_in_pipe */
1977 if (G.run_list_level == 1 && G.interactive_fd) {
1979 /* Don't do pgrp restore anymore on fatal signals */
1980 set_fatal_sighandler(SIG_DFL);
1982 if (pgrp < 0) /* true for 1st process only */
1984 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
1985 /* We do it in *every* child, not just first,
1987 tcsetpgrp(G.interactive_fd, pgrp);
1991 xmove_fd(nextin, 0);
1992 xmove_fd(pipefds[1], 1); /* write end */
1994 close(pipefds[0]); /* read end */
1995 /* Like bash, explicit redirects override pipes,
1996 * and the pipe fd is available for dup'ing. */
1997 setup_redirects(command, NULL);
1999 /* Restore default handlers just prior to exec */
2000 set_jobctrl_sighandler(SIG_DFL);
2001 set_misc_sighandler(SIG_DFL);
2002 signal(SIGCHLD, SIG_DFL);
2003 /* Stores to nommu_save list of env vars putenv'ed
2004 * (NOMMU, on MMU we don't need that) */
2005 /* cast away volatility... */
2006 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
2007 /* pseudo_exec() does not return */
2011 /* Clean up after vforked child */
2012 free(nommu_save.argv);
2013 free_strings_and_unsetenv(nommu_save.new_env, 1);
2014 putenv_all(nommu_save.old_env);
2016 free(argv_expanded);
2017 argv_expanded = NULL;
2018 if (command->pid < 0) { /* [v]fork failed */
2019 /* Clearly indicate, was it fork or vfork */
2020 bb_perror_msg(BB_MMU ? "fork" : "vfork");
2024 /* Second and next children need to know pid of first one */
2026 pi->pgrp = command->pid;
2032 if ((i + 1) < pi->num_cmds)
2033 close(pipefds[1]); /* write end */
2034 /* Pass read (output) pipe end to next iteration */
2035 nextin = pipefds[0];
2038 if (!pi->alive_cmds) {
2039 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
2043 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
2047 #ifndef debug_print_tree
2048 static void debug_print_tree(struct pipe *pi, int lvl)
2050 static const char *const PIPE[] = {
2056 static const char *RES[] = {
2057 [RES_NONE ] = "NONE" ,
2060 [RES_THEN ] = "THEN" ,
2061 [RES_ELIF ] = "ELIF" ,
2062 [RES_ELSE ] = "ELSE" ,
2065 #if ENABLE_HUSH_LOOPS
2066 [RES_FOR ] = "FOR" ,
2067 [RES_WHILE] = "WHILE",
2068 [RES_UNTIL] = "UNTIL",
2070 [RES_DONE ] = "DONE" ,
2072 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2075 #if ENABLE_HUSH_CASE
2076 [RES_CASE ] = "CASE" ,
2077 [RES_MATCH] = "MATCH",
2078 [RES_CASEI] = "CASEI",
2079 [RES_ESAC ] = "ESAC" ,
2081 [RES_XXXX ] = "XXXX" ,
2082 [RES_SNTX ] = "SNTX" ,
2084 static const char *const GRPTYPE[] = {
2087 #if ENABLE_HUSH_FUNCTIONS
2096 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2097 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2099 while (prn < pi->num_cmds) {
2100 struct command *command = &pi->cmds[prn];
2101 char **argv = command->argv;
2103 fprintf(stderr, "%*s prog %d assignment_cnt:%d", lvl*2, "", prn, command->assignment_cnt);
2104 if (command->group) {
2105 fprintf(stderr, " group %s: (argv=%p)\n",
2106 GRPTYPE[command->grp_type],
2108 debug_print_tree(command->group, lvl+1);
2112 if (argv) while (*argv) {
2113 fprintf(stderr, " '%s'", *argv);
2116 fprintf(stderr, "\n");
2125 /* NB: called by pseudo_exec, and therefore must not modify any
2126 * global data until exec/_exit (we can be a child after vfork!) */
2127 static int run_list(struct pipe *pi)
2129 #if ENABLE_HUSH_CASE
2130 char *case_word = NULL;
2132 #if ENABLE_HUSH_LOOPS
2133 struct pipe *loop_top = NULL;
2134 char *for_varname = NULL;
2135 char **for_lcur = NULL;
2136 char **for_list = NULL;
2138 smallint flag_skip = 1;
2139 smalluint rcode = 0; /* probably just for compiler */
2140 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
2141 smalluint cond_code = 0;
2143 enum { cond_code = 0, };
2145 /*enum reserved_style*/ smallint rword = RES_NONE;
2146 /*enum reserved_style*/ smallint skip_more_for_this_rword = RES_XXXX;
2148 debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
2150 #if ENABLE_HUSH_LOOPS
2151 /* Check syntax for "for" */
2152 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
2153 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
2155 /* current word is FOR or IN (BOLD in comments below) */
2156 if (cpipe->next == NULL) {
2157 syntax("malformed for");
2158 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
2161 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
2162 if (cpipe->next->res_word == RES_DO)
2164 /* next word is not "do". It must be "in" then ("FOR v in ...") */
2165 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
2166 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
2168 syntax("malformed for");
2169 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
2175 /* Past this point, all code paths should jump to ret: label
2176 * in order to return, no direct "return" statements please.
2177 * This helps to ensure that no memory is leaked. */
2180 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
2181 * We are saving state before entering outermost list ("while...done")
2182 * so that ctrl-Z will correctly background _entire_ outermost list,
2183 * not just a part of it (like "sleep 1 | exit 2") */
2184 if (++G.run_list_level == 1 && G.interactive_fd) {
2185 if (sigsetjmp(G.toplevel_jb, 1)) {
2186 /* ctrl-Z forked and we are parent; or ctrl-C.
2187 * Sighandler has longjmped us here */
2188 signal(SIGINT, SIG_IGN);
2189 signal(SIGTSTP, SIG_IGN);
2190 /* Restore level (we can be coming from deep inside
2192 G.run_list_level = 1;
2193 #if ENABLE_FEATURE_SH_STANDALONE
2194 if (G.nofork_save.saved) { /* if save area is valid */
2195 debug_printf_jobs("exiting nofork early\n");
2196 restore_nofork_data(&G.nofork_save);
2199 if (G.ctrl_z_flag) {
2200 /* ctrl-Z has forked and stored pid of the child in pi->pid.
2201 * Remember this child as background job */
2204 /* ctrl-C. We just stop doing whatever we were doing */
2207 USE_HUSH_LOOPS(loop_top = NULL;)
2208 USE_HUSH_LOOPS(G.depth_of_loop = 0;)
2212 /* ctrl-Z handler will store pid etc in pi */
2213 G.toplevel_list = pi;
2215 #if ENABLE_FEATURE_SH_STANDALONE
2216 G.nofork_save.saved = 0; /* in case we will run a nofork later */
2218 signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
2219 signal(SIGINT, handler_ctrl_c);
2223 /* Go through list of pipes, (maybe) executing them. */
2224 for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
2225 IF_HAS_KEYWORDS(rword = pi->res_word;)
2226 IF_HAS_NO_KEYWORDS(rword = RES_NONE;)
2227 debug_printf_exec(": rword=%d cond_code=%d skip_more=%d\n",
2228 rword, cond_code, skip_more_for_this_rword);
2229 #if ENABLE_HUSH_LOOPS
2230 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
2231 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
2233 /* start of a loop: remember where loop starts */
2238 if (rword == skip_more_for_this_rword && flag_skip) {
2239 if (pi->followup == PIPE_SEQ)
2241 /* it is "<false> && CMD" or "<true> || CMD"
2242 * and we should not execute CMD */
2246 skip_more_for_this_rword = RES_XXXX;
2249 if (rword == RES_THEN) {
2250 /* "if <false> THEN cmd": skip cmd */
2254 if (rword == RES_ELSE || rword == RES_ELIF) {
2255 /* "if <true> then ... ELSE/ELIF cmd":
2256 * skip cmd and all following ones */
2261 #if ENABLE_HUSH_LOOPS
2262 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
2264 /* first loop through for */
2266 static const char encoded_dollar_at[] ALIGN1 = {
2267 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
2268 }; /* encoded representation of "$@" */
2269 static const char *const encoded_dollar_at_argv[] = {
2270 encoded_dollar_at, NULL
2271 }; /* argv list with one element: "$@" */
2274 vals = (char**)encoded_dollar_at_argv;
2275 if (pi->next->res_word == RES_IN) {
2276 /* if no variable values after "in" we skip "for" */
2277 if (!pi->next->cmds[0].argv)
2279 vals = pi->next->cmds[0].argv;
2280 } /* else: "for var; do..." -> assume "$@" list */
2281 /* create list of variable values */
2282 debug_print_strings("for_list made from", vals);
2283 for_list = expand_strvec_to_strvec(vals);
2284 for_lcur = for_list;
2285 debug_print_strings("for_list", for_list);
2286 for_varname = pi->cmds[0].argv[0];
2287 pi->cmds[0].argv[0] = NULL;
2289 free(pi->cmds[0].argv[0]);
2291 /* "for" loop is over, clean up */
2295 pi->cmds[0].argv[0] = for_varname;
2298 /* insert next value from for_lcur */
2299 //TODO: does it need escaping?
2300 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
2301 pi->cmds[0].assignment_cnt = 1;
2303 if (rword == RES_IN) /* "for v IN list;..." - "in" has no cmds anyway */
2305 if (rword == RES_DONE) {
2306 continue; /* "done" has no cmds too */
2309 #if ENABLE_HUSH_CASE
2310 if (rword == RES_CASE) {
2311 case_word = expand_strvec_to_string(pi->cmds->argv);
2314 if (rword == RES_MATCH) {
2317 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
2319 /* all prev words didn't match, does this one match? */
2320 argv = pi->cmds->argv;
2322 char *pattern = expand_string_to_string(*argv);
2323 /* TODO: which FNM_xxx flags to use? */
2324 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
2326 if (cond_code == 0) { /* match! we will execute this branch */
2327 free(case_word); /* make future "word)" stop */
2335 if (rword == RES_CASEI) { /* inside of a case branch */
2337 continue; /* not matched yet, skip this pipe */
2340 if (pi->num_cmds == 0)
2343 /* After analyzing all keywords and conditions, we decided
2344 * to execute this pipe. NB: has to do checkjobs(NULL)
2345 * after run_pipe() to collect any background children,
2346 * even if list execution is to be stopped. */
2347 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
2350 #if ENABLE_HUSH_LOOPS
2351 G.flag_break_continue = 0;
2353 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
2355 /* we only ran a builtin: rcode is already known
2356 * and we don't need to wait for anything. */
2357 #if ENABLE_HUSH_LOOPS
2358 /* was it "break" or "continue"? */
2359 if (G.flag_break_continue) {
2360 smallint fbc = G.flag_break_continue;
2361 /* we might fall into outer *loop*,
2362 * don't want to break it too */
2364 G.depth_break_continue--;
2365 if (G.depth_break_continue == 0)
2366 G.flag_break_continue = 0;
2367 /* else: e.g. "continue 2" should *break* once, *then* continue */
2368 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
2369 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
2370 goto check_jobs_and_break;
2371 /* "continue": simulate end of loop */
2376 } else if (pi->followup == PIPE_BG) {
2377 /* what does bash do with attempts to background builtins? */
2378 /* even bash 3.2 doesn't do that well with nested bg:
2379 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
2380 * I'm NOT treating inner &'s as jobs */
2382 if (G.run_list_level == 1)
2385 rcode = 0; /* EXIT_SUCCESS */
2388 if (G.run_list_level == 1 && G.interactive_fd) {
2389 /* waits for completion, then fg's main shell */
2390 rcode = checkjobs_and_fg_shell(pi);
2391 debug_printf_exec(": checkjobs_and_fg_shell returned %d\n", rcode);
2394 { /* this one just waits for completion */
2395 rcode = checkjobs(pi);
2396 debug_printf_exec(": checkjobs returned %d\n", rcode);
2400 debug_printf_exec(": setting last_return_code=%d\n", rcode);
2401 G.last_return_code = rcode;
2403 /* Analyze how result affects subsequent commands */
2405 if (rword == RES_IF || rword == RES_ELIF)
2408 #if ENABLE_HUSH_LOOPS
2409 if (rword == RES_WHILE) {
2411 rcode = 0; /* "while false; do...done" - exitcode 0 */
2412 goto check_jobs_and_break;
2415 if (rword == RES_UNTIL) {
2417 check_jobs_and_break:
2423 if ((rcode == 0 && pi->followup == PIPE_OR)
2424 || (rcode != 0 && pi->followup == PIPE_AND)
2426 skip_more_for_this_rword = rword;
2432 if (G.ctrl_z_flag) {
2433 /* ctrl-Z forked somewhere in the past, we are the child,
2434 * and now we completed running the list. Exit. */
2439 if (!--G.run_list_level && G.interactive_fd) {
2440 signal(SIGTSTP, SIG_IGN);
2441 signal(SIGINT, SIG_IGN);
2444 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
2445 #if ENABLE_HUSH_LOOPS
2450 #if ENABLE_HUSH_CASE
2456 /* return code is the exit status of the pipe */
2457 static int free_pipe(struct pipe *pi, int indent)
2460 struct command *command;
2461 struct redir_struct *r, *rnext;
2462 int a, i, ret_code = 0;
2464 if (pi->stopped_cmds > 0)
2466 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2467 for (i = 0; i < pi->num_cmds; i++) {
2468 command = &pi->cmds[i];
2469 debug_printf_clean("%s command %d:\n", indenter(indent), i);
2470 if (command->argv) {
2471 for (a = 0, p = command->argv; *p; a++, p++) {
2472 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
2474 free_strings(command->argv);
2475 command->argv = NULL;
2476 } else if (command->group) {
2477 debug_printf_clean("%s begin group (grp_type:%d)\n", indenter(indent), command->grp_type);
2478 ret_code = free_pipe_list(command->group, indent+3);
2479 debug_printf_clean("%s end group\n", indenter(indent));
2481 debug_printf_clean("%s (nil)\n", indenter(indent));
2483 for (r = command->redirects; r; r = rnext) {
2484 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->rd_type].descrip);
2486 /* guard against the case >$FOO, where foo is unset or blank */
2487 if (r->rd_filename) {
2488 debug_printf_clean(" %s\n", r->rd_filename);
2489 free(r->rd_filename);
2490 r->rd_filename = NULL;
2493 debug_printf_clean("&%d\n", r->dup);
2498 command->redirects = NULL;
2500 free(pi->cmds); /* children are an array, they get freed all at once */
2509 static int free_pipe_list(struct pipe *head, int indent)
2511 int rcode = 0; /* if list has no members */
2512 struct pipe *pi, *next;
2514 for (pi = head; pi; pi = next) {
2516 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
2518 rcode = free_pipe(pi, indent);
2519 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
2521 /*pi->next = NULL;*/
2527 /* Select which version we will use */
2528 static int run_and_free_list(struct pipe *pi)
2531 debug_printf_exec("run_and_free_list entered\n");
2533 debug_printf_exec(": run_list with %d members\n", pi->num_cmds);
2534 rcode = run_list(pi);
2536 /* free_pipe_list has the side effect of clearing memory.
2537 * In the long run that function can be merged with run_list,
2538 * but doing that now would hobble the debugging effort. */
2539 free_pipe_list(pi, /* indent: */ 0);
2540 debug_printf_exec("run_and_free_list return %d\n", rcode);
2545 /* expand_strvec_to_strvec() takes a list of strings, expands
2546 * all variable references within and returns a pointer to
2547 * a list of expanded strings, possibly with larger number
2548 * of strings. (Think VAR="a b"; echo $VAR).
2549 * This new list is allocated as a single malloc block.
2550 * NULL-terminated list of char* pointers is at the beginning of it,
2551 * followed by strings themself.
2552 * Caller can deallocate entire list by single free(list). */
2554 /* Store given string, finalizing the word and starting new one whenever
2555 * we encounter IFS char(s). This is used for expanding variable values.
2556 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2557 static int expand_on_ifs(o_string *output, int n, const char *str)
2560 int word_len = strcspn(str, G.ifs);
2562 if (output->o_quote || !output->o_glob)
2563 o_addQstr(output, str, word_len);
2564 else /* protect backslashes against globbing up :) */
2565 o_addstr_duplicate_backslash(output, str, word_len);
2568 if (!*str) /* EOL - do not finalize word */
2570 o_addchr(output, '\0');
2571 debug_print_list("expand_on_ifs", output, n);
2572 n = o_save_ptr(output, n);
2573 str += strspn(str, G.ifs); /* skip ifs chars */
2575 debug_print_list("expand_on_ifs[1]", output, n);
2579 /* Expand all variable references in given string, adding words to list[]
2580 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2581 * to be filled). This routine is extremely tricky: has to deal with
2582 * variables/parameters with whitespace, $* and $@, and constructs like
2583 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2584 static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
2586 /* or_mask is either 0 (normal case) or 0x80
2587 * (expansion of right-hand side of assignment == 1-element expand.
2588 * It will also do no globbing, and thus we must not backslash-quote!) */
2590 char first_ch, ored_ch;
2597 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
2598 debug_print_list("expand_vars_to_list", output, n);
2599 n = o_save_ptr(output, n);
2600 debug_print_list("expand_vars_to_list[0]", output, n);
2602 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
2603 #if ENABLE_HUSH_TICK
2604 o_string subst_result = NULL_O_STRING;
2606 o_addstr(output, arg, p - arg);
2607 debug_print_list("expand_vars_to_list[1]", output, n);
2609 p = strchr(p, SPECIAL_VAR_SYMBOL);
2611 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2612 /* "$@" is special. Even if quoted, it can still
2613 * expand to nothing (not even an empty string) */
2614 if ((first_ch & 0x7f) != '@')
2615 ored_ch |= first_ch;
2617 switch (first_ch & 0x7f) {
2618 /* Highest bit in first_ch indicates that var is double-quoted */
2620 val = utoa(G.root_pid);
2622 case '!': /* bg pid */
2623 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2625 case '?': /* exitcode */
2626 val = utoa(G.last_return_code);
2628 case '#': /* argc */
2629 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2634 if (!G.global_argv[i])
2636 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2637 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2638 smallint sv = output->o_quote;
2639 /* unquoted var's contents should be globbed, so don't quote */
2640 output->o_quote = 0;
2641 while (G.global_argv[i]) {
2642 n = expand_on_ifs(output, n, G.global_argv[i]);
2643 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2644 if (G.global_argv[i++][0] && G.global_argv[i]) {
2645 /* this argv[] is not empty and not last:
2646 * put terminating NUL, start new word */
2647 o_addchr(output, '\0');
2648 debug_print_list("expand_vars_to_list[2]", output, n);
2649 n = o_save_ptr(output, n);
2650 debug_print_list("expand_vars_to_list[3]", output, n);
2653 output->o_quote = sv;
2655 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2656 * and in this case should treat it like '$*' - see 'else...' below */
2657 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2659 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2660 if (++i >= G.global_argc)
2662 o_addchr(output, '\0');
2663 debug_print_list("expand_vars_to_list[4]", output, n);
2664 n = o_save_ptr(output, n);
2666 } else { /* quoted $*: add as one word */
2668 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2669 if (!G.global_argv[++i])
2672 o_addchr(output, G.ifs[0]);
2676 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2677 /* "Empty variable", used to make "" etc to not disappear */
2681 #if ENABLE_HUSH_TICK
2682 case '`': { /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
2683 struct in_str input;
2686 //TODO: can we just stuff it into "output" directly?
2687 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
2688 setup_string_in_str(&input, arg);
2689 process_command_subs(&subst_result, &input, NULL);
2690 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
2691 val = subst_result.data;
2695 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
2697 arg[0] = first_ch & 0x7f;
2698 if (isdigit(arg[0])) {
2700 if (i < G.global_argc)
2701 val = G.global_argv[i];
2702 /* else val remains NULL: $N with too big N */
2704 val = lookup_param(arg);
2706 #if ENABLE_HUSH_TICK
2709 *p = SPECIAL_VAR_SYMBOL;
2710 if (!(first_ch & 0x80)) { /* unquoted $VAR */
2711 debug_printf_expand("unquoted '%s', output->o_quote:%d\n", val, output->o_quote);
2713 /* unquoted var's contents should be globbed, so don't quote */
2714 smallint sv = output->o_quote;
2715 output->o_quote = 0;
2716 n = expand_on_ifs(output, n, val);
2718 output->o_quote = sv;
2720 } else { /* quoted $VAR, val will be appended below */
2721 debug_printf_expand("quoted '%s', output->o_quote:%d\n", val, output->o_quote);
2725 o_addQstr(output, val, strlen(val));
2728 #if ENABLE_HUSH_TICK
2729 o_free(&subst_result);
2732 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2735 debug_print_list("expand_vars_to_list[a]", output, n);
2736 /* this part is literal, and it was already pre-quoted
2737 * if needed (much earlier), do not use o_addQstr here! */
2738 o_addstr(output, arg, strlen(arg) + 1);
2739 debug_print_list("expand_vars_to_list[b]", output, n);
2740 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2741 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2744 /* allow to reuse list[n] later without re-growth */
2745 output->has_empty_slot = 1;
2747 o_addchr(output, '\0');
2752 static char **expand_variables(char **argv, int or_mask)
2757 o_string output = NULL_O_STRING;
2759 if (or_mask & 0x100) {
2760 output.o_quote = 1; /* protect against globbing for "$var" */
2761 /* (unquoted $var will temporarily switch it off) */
2768 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
2771 debug_print_list("expand_variables", &output, n);
2773 /* output.data (malloced in one block) gets returned in "list" */
2774 list = o_finalize_list(&output, n);
2775 debug_print_strings("expand_variables[1]", list);
2779 static char **expand_strvec_to_strvec(char **argv)
2781 return expand_variables(argv, 0x100);
2784 /* Used for expansion of right hand of assignments */
2785 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2787 static char *expand_string_to_string(const char *str)
2789 char *argv[2], **list;
2791 argv[0] = (char*)str;
2793 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2795 if (!list[0] || list[1])
2796 bb_error_msg_and_die("BUG in varexp2");
2797 /* actually, just move string 2*sizeof(char*) bytes back */
2798 strcpy((char*)list, list[0]);
2799 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2803 /* Used for "eval" builtin */
2804 static char* expand_strvec_to_string(char **argv)
2808 list = expand_variables(argv, 0x80);
2809 /* Convert all NULs to spaces */
2814 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2815 bb_error_msg_and_die("BUG in varexp3");
2816 list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
2820 strcpy((char*)list, list[0]);
2821 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2826 /* Used to get/check local shell variables */
2827 static struct variable *get_local_var(const char *name)
2829 struct variable *cur;
2835 for (cur = G.top_var; cur; cur = cur->next) {
2836 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
2842 /* str holds "NAME=VAL" and is expected to be malloced.
2843 * We take ownership of it. */
2844 static int set_local_var(char *str, int flg_export)
2846 struct variable *cur;
2850 value = strchr(str, '=');
2851 if (!value) { /* not expected to ever happen? */
2856 name_len = value - str + 1; /* including '=' */
2857 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
2859 if (strncmp(cur->varstr, str, name_len) != 0) {
2861 /* Bail out. Note that now cur points
2862 * to last var in linked list */
2868 /* We found an existing var with this name */
2870 if (cur->flg_read_only) {
2871 bb_error_msg("%s: readonly variable", str);
2875 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2876 unsetenv(str); /* just in case */
2878 if (strcmp(cur->varstr, str) == 0) {
2883 if (cur->max_len >= strlen(str)) {
2884 /* This one is from startup env, reuse space */
2885 strcpy(cur->varstr, str);
2888 /* max_len == 0 signifies "malloced" var, which we can
2889 * (and has to) free */
2893 goto set_str_and_exp;
2896 /* Not found - create next variable struct */
2897 cur->next = xzalloc(sizeof(*cur));
2904 cur->flg_export = 1;
2905 if (cur->flg_export) {
2906 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
2907 return putenv(cur->varstr);
2912 static void unset_local_var(const char *name)
2914 struct variable *cur;
2915 struct variable *prev = prev; /* for gcc */
2920 name_len = strlen(name);
2923 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2924 if (cur->flg_read_only) {
2925 bb_error_msg("%s: readonly variable", name);
2928 /* prev is ok to use here because 1st variable, HUSH_VERSION,
2929 * is ro, and we cannot reach this code on the 1st pass */
2930 prev->next = cur->next;
2931 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2932 bb_unsetenv(cur->varstr);
2943 /* The src parameter allows us to peek forward to a possible &n syntax
2944 * for file descriptor duplication, e.g., "2>&1".
2945 * Return code is 0 normally, 1 if a syntax error is detected in src.
2946 * Resource errors (in xmalloc) cause the process to exit */
2947 static int setup_redirect(struct parse_context *ctx, int fd, redir_type style,
2948 struct in_str *input)
2950 struct command *command = ctx->command;
2951 struct redir_struct *redir = command->redirects;
2952 struct redir_struct *last_redir = NULL;
2954 /* Create a new redir_struct and drop it onto the end of the linked list */
2957 redir = redir->next;
2959 redir = xzalloc(sizeof(struct redir_struct));
2960 /* redir->next = NULL; */
2961 /* redir->rd_filename = NULL; */
2963 last_redir->next = redir;
2965 command->redirects = redir;
2968 redir->rd_type = style;
2969 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
2971 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2973 /* Check for a '2>&1' type redirect */
2974 redir->dup = redirect_dup_num(input);
2975 if (redir->dup == -2)
2976 return 1; /* syntax error */
2977 if (redir->dup != -1) {
2978 /* Erik had a check here that the file descriptor in question
2979 * is legit; I postpone that to "run time"
2980 * A "-" representation of "close me" shows up as a -3 here */
2981 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2983 /* We do _not_ try to open the file that src points to,
2984 * since we need to return and let src be expanded first.
2985 * Set ctx->pending_redirect, so we know what to do at the
2986 * end of the next parsed word. */
2987 ctx->pending_redirect = redir;
2992 static struct pipe *new_pipe(void)
2995 pi = xzalloc(sizeof(struct pipe));
2996 /*pi->followup = 0; - deliberately invalid value */
2997 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3001 static void initialize_context(struct parse_context *ctx)
3003 memset(ctx, 0, sizeof(*ctx));
3004 ctx->pipe = ctx->list_head = new_pipe();
3005 /* Create the memory for command, roughly:
3006 * ctx->pipe->cmds = new struct command;
3007 * ctx->command = &ctx->pipe->cmds[0];
3012 /* If a reserved word is found and processed, parse context is modified
3013 * and 1 is returned.
3014 * Handles if, then, elif, else, fi, for, while, until, do, done.
3015 * case, function, and select are obnoxious, save those for later.
3018 struct reserved_combo {
3021 unsigned char assignment_flag;
3025 FLAG_END = (1 << RES_NONE ),
3027 FLAG_IF = (1 << RES_IF ),
3028 FLAG_THEN = (1 << RES_THEN ),
3029 FLAG_ELIF = (1 << RES_ELIF ),
3030 FLAG_ELSE = (1 << RES_ELSE ),
3031 FLAG_FI = (1 << RES_FI ),
3033 #if ENABLE_HUSH_LOOPS
3034 FLAG_FOR = (1 << RES_FOR ),
3035 FLAG_WHILE = (1 << RES_WHILE),
3036 FLAG_UNTIL = (1 << RES_UNTIL),
3037 FLAG_DO = (1 << RES_DO ),
3038 FLAG_DONE = (1 << RES_DONE ),
3039 FLAG_IN = (1 << RES_IN ),
3041 #if ENABLE_HUSH_CASE
3042 FLAG_MATCH = (1 << RES_MATCH),
3043 FLAG_ESAC = (1 << RES_ESAC ),
3045 FLAG_START = (1 << RES_XXXX ),
3048 static const struct reserved_combo* match_reserved_word(o_string *word)
3050 /* Mostly a list of accepted follow-up reserved words.
3051 * FLAG_END means we are done with the sequence, and are ready
3052 * to turn the compound list into a command.
3053 * FLAG_START means the word must start a new compound list.
3055 static const struct reserved_combo reserved_list[] = {
3057 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3058 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
3059 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3060 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
3061 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
3062 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3064 #if ENABLE_HUSH_LOOPS
3065 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3066 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3067 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3068 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3069 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
3070 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3072 #if ENABLE_HUSH_CASE
3073 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3074 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3077 const struct reserved_combo *r;
3079 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3080 if (strcmp(word->data, r->literal) == 0)
3085 static int reserved_word(o_string *word, struct parse_context *ctx)
3087 #if ENABLE_HUSH_CASE
3088 static const struct reserved_combo reserved_match = {
3089 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3092 const struct reserved_combo *r;
3094 r = match_reserved_word(word);
3098 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3099 #if ENABLE_HUSH_CASE
3100 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
3101 /* "case word IN ..." - IN part starts first match part */
3102 r = &reserved_match;
3105 if (r->flag == 0) { /* '!' */
3106 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3108 IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
3110 ctx->ctx_inverted = 1;
3113 if (r->flag & FLAG_START) {
3114 struct parse_context *new;
3115 debug_printf("push stack\n");
3116 new = xmalloc(sizeof(*new));
3117 *new = *ctx; /* physical copy */
3118 initialize_context(ctx);
3120 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3122 ctx->ctx_res_w = RES_SNTX;
3125 ctx->ctx_res_w = r->res;
3126 ctx->old_flag = r->flag;
3127 if (ctx->old_flag & FLAG_END) {
3128 struct parse_context *old;
3129 debug_printf("pop stack\n");
3130 done_pipe(ctx, PIPE_SEQ);
3132 old->command->group = ctx->list_head;
3133 old->command->grp_type = GRP_NORMAL;
3134 *ctx = *old; /* physical copy */
3137 word->o_assignment = r->assignment_flag;
3142 //TODO: many, many callers don't check error from done_word()
3144 /* Word is complete, look at it and update parsing context.
3145 * Normal return is 0. Syntax errors return 1. */
3146 static int done_word(o_string *word, struct parse_context *ctx)
3148 struct command *command = ctx->command;
3150 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3151 if (word->length == 0 && word->nonnull == 0) {
3152 debug_printf_parse("done_word return 0: true null, ignored\n");
3155 /* If this word wasn't an assignment, next ones definitely
3156 * can't be assignments. Even if they look like ones. */
3157 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3158 && word->o_assignment != WORD_IS_KEYWORD
3160 word->o_assignment = NOT_ASSIGNMENT;
3162 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3163 command->assignment_cnt++;
3164 word->o_assignment = MAYBE_ASSIGNMENT;
3167 if (ctx->pending_redirect) {
3168 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3169 * only if run as "bash", not "sh" */
3170 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3171 word->o_assignment = NOT_ASSIGNMENT;
3172 debug_printf("word stored in rd_filename: '%s'\n", word->data);
3174 /* "{ echo foo; } echo bar" - bad */
3175 /* NB: bash allows e.g. "if true; then { echo foo; } fi". TODO? */
3176 if (command->group) {
3178 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
3182 #if ENABLE_HUSH_CASE
3183 if (ctx->ctx_dsemicolon
3184 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3186 /* already done when ctx_dsemicolon was set to 1: */
3187 /* ctx->ctx_res_w = RES_MATCH; */
3188 ctx->ctx_dsemicolon = 0;
3192 if (!command->argv /* if it's the first word... */
3193 #if ENABLE_HUSH_LOOPS
3194 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3195 && ctx->ctx_res_w != RES_IN
3198 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
3199 if (reserved_word(word, ctx)) {
3201 debug_printf_parse("done_word return %d\n", (ctx->ctx_res_w == RES_SNTX));
3202 return (ctx->ctx_res_w == RES_SNTX);
3206 if (word->nonnull /* word had "xx" or 'xx' at least as part of it. */
3207 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3208 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3209 /* (otherwise it's known to be not empty and is already safe) */
3211 /* exclude "$@" - it can expand to no word despite "" */
3212 char *p = word->data;
3213 while (p[0] == SPECIAL_VAR_SYMBOL
3214 && (p[1] & 0x7f) == '@'
3215 && p[2] == SPECIAL_VAR_SYMBOL
3219 if (p == word->data || p[0] != '\0') {
3220 /* saw no "$@", or not only "$@" but some
3221 * real text is there too */
3222 /* insert "empty variable" reference, this makes
3223 * e.g. "", $empty"" etc to not disappear */
3224 o_addchr(word, SPECIAL_VAR_SYMBOL);
3225 o_addchr(word, SPECIAL_VAR_SYMBOL);
3228 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3229 debug_print_strings("word appended to argv", command->argv);
3233 ctx->pending_redirect = NULL;
3235 #if ENABLE_HUSH_LOOPS
3236 /* Force FOR to have just one word (variable name) */
3237 /* NB: basically, this makes hush see "for v in ..." syntax as if
3238 * as it is "for v; in ...". FOR and IN become two pipe structs
3240 if (ctx->ctx_res_w == RES_FOR) {
3241 //TODO: check that command->argv[0] is a valid variable name!
3242 done_pipe(ctx, PIPE_SEQ);
3245 #if ENABLE_HUSH_CASE
3246 /* Force CASE to have just one word */
3247 if (ctx->ctx_res_w == RES_CASE) {
3248 done_pipe(ctx, PIPE_SEQ);
3251 debug_printf_parse("done_word return 0\n");
3255 /* Command (member of a pipe) is complete. The only possible error here
3256 * is out of memory, in which case xmalloc exits. */
3257 static int done_command(struct parse_context *ctx)
3259 /* The command is really already in the pipe structure, so
3260 * advance the pipe counter and make a new, null command. */
3261 struct pipe *pi = ctx->pipe;
3262 struct command *command = ctx->command;
3265 if (command->group == NULL
3266 && command->argv == NULL
3267 && command->redirects == NULL
3269 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3270 return pi->num_cmds;
3273 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3275 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3278 /* Only real trickiness here is that the uncommitted
3279 * command structure is not counted in pi->num_cmds. */
3280 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3281 command = &pi->cmds[pi->num_cmds];
3282 memset(command, 0, sizeof(*command));
3284 ctx->command = command;
3285 /* but ctx->pipe and ctx->list_head remain unchanged */
3287 return pi->num_cmds; /* used only for 0/nonzero check */
3290 static void done_pipe(struct parse_context *ctx, pipe_style type)
3294 debug_printf_parse("done_pipe entered, followup %d\n", type);
3295 /* Close previous command */
3296 not_null = done_command(ctx);
3297 ctx->pipe->followup = type;
3298 IF_HAS_KEYWORDS(ctx->pipe->pi_inverted = ctx->ctx_inverted;)
3299 IF_HAS_KEYWORDS(ctx->ctx_inverted = 0;)
3300 IF_HAS_KEYWORDS(ctx->pipe->res_word = ctx->ctx_res_w;)
3302 /* Without this check, even just <enter> on command line generates
3303 * tree of three NOPs (!). Which is harmless but annoying.
3304 * IOW: it is safe to do it unconditionally.
3305 * RES_NONE case is for "for a in; do ..." (empty IN set)
3306 * to work, possibly other cases too. */
3307 if (not_null IF_HAS_KEYWORDS(|| ctx->ctx_res_w != RES_NONE)) {
3309 debug_printf_parse("done_pipe: adding new pipe: "
3310 "not_null:%d ctx->ctx_res_w:%d\n",
3311 not_null, ctx->ctx_res_w);
3313 ctx->pipe->next = new_p;
3315 ctx->command = NULL; /* needed! */
3316 /* RES_THEN, RES_DO etc are "sticky" -
3317 * they remain set for commands inside if/while.
3318 * This is used to control execution.
3319 * RES_FOR and RES_IN are NOT sticky (needed to support
3320 * cases where variable or value happens to match a keyword):
3322 #if ENABLE_HUSH_LOOPS
3323 if (ctx->ctx_res_w == RES_FOR
3324 || ctx->ctx_res_w == RES_IN)
3325 ctx->ctx_res_w = RES_NONE;
3327 #if ENABLE_HUSH_CASE
3328 if (ctx->ctx_res_w == RES_MATCH)
3329 ctx->ctx_res_w = RES_CASEI;
3331 /* Create the memory for command, roughly:
3332 * ctx->pipe->cmds = new struct command;
3333 * ctx->command = &ctx->pipe->cmds[0];
3337 debug_printf_parse("done_pipe return\n");
3340 /* Peek ahead in the in_str to find out if we have a "&n" construct,
3341 * as in "2>&1", that represents duplicating a file descriptor.
3342 * Return either -2 (syntax error), -1 (no &), or the number found.
3344 static int redirect_dup_num(struct in_str *input)
3346 int ch, d = 0, ok = 0;
3348 if (ch != '&') return -1;
3350 i_getch(input); /* get the & */
3354 return -3; /* "-" represents "close me" */
3356 while (isdigit(ch)) {
3357 d = d*10 + (ch-'0');
3364 bb_error_msg("ambiguous redirect");
3368 /* If a redirect is immediately preceded by a number, that number is
3369 * supposed to tell which file descriptor to redirect. This routine
3370 * looks for such preceding numbers. In an ideal world this routine
3371 * needs to handle all the following classes of redirects...
3372 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3373 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3374 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3375 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3376 * A -1 output from this program means no valid number was found, so the
3377 * caller should use the appropriate default for this redirection.
3379 static int redirect_opt_num(o_string *o)
3385 for (num = 0; num < o->length; num++) {
3386 if (!isdigit(o->data[num])) {
3390 num = atoi(o->data);
3395 #if ENABLE_HUSH_TICK
3396 static FILE *generate_stream_from_list(struct pipe *head)
3399 int pid, channel[2];
3402 /* *** NOMMU WARNING *** */
3403 /* By using vfork here, we suspend parent till child exits or execs.
3404 * If child will not do it before it fills the pipe, it can block forever
3405 * in write(STDOUT_FILENO), and parent (shell) will be also stuck.
3407 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >TESTFILE
3408 * huge=`cat TESTFILE` # will block here forever
3411 pid = BB_MMU ? fork() : vfork();
3413 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
3414 if (pid == 0) { /* child */
3415 if (ENABLE_HUSH_JOB)
3416 die_sleep = 0; /* let nofork's xfuncs die */
3417 close(channel[0]); /* NB: close _first_, then move fd! */
3418 xmove_fd(channel[1], 1);
3419 /* Prevent it from trying to handle ctrl-z etc */
3421 G.run_list_level = 1;
3423 /* Process substitution is not considered to be usual
3424 * 'command execution'.
3425 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not. */
3426 /* Not needed, we are relying on it being disabled
3427 * everywhere outside actual command execution. */
3428 /*set_jobctrl_sighandler(SIG_IGN);*/
3429 set_misc_sighandler(SIG_DFL);
3430 /* Freeing 'head' here would break NOMMU. */
3431 _exit(run_list(head));
3434 pf = fdopen(channel[0], "r");
3436 /* 'head' is freed by the caller */
3439 /* Return code is exit status of the process that is run. */
3440 static int process_command_subs(o_string *dest,
3441 struct in_str *input,
3442 const char *subst_end)
3444 int retcode, ch, eol_cnt;
3445 o_string result = NULL_O_STRING;
3446 struct parse_context inner;
3448 struct in_str pipe_str;
3450 initialize_context(&inner);
3452 /* Recursion to generate command */
3453 retcode = parse_stream(&result, &inner, input, subst_end);
3455 return retcode; /* syntax error or EOF */
3456 done_word(&result, &inner);
3457 done_pipe(&inner, PIPE_SEQ);
3460 p = generate_stream_from_list(inner.list_head);
3463 close_on_exec_on(fileno(p));
3464 setup_file_in_str(&pipe_str, p);
3466 /* Now send results of command back into original context */
3468 while ((ch = i_getch(&pipe_str)) != EOF) {
3474 o_addchr(dest, '\n');
3477 o_addQchr(dest, ch);
3480 debug_printf("done reading from pipe, pclose()ing\n");
3481 /* This is the step that wait()s for the child. Should be pretty
3482 * safe, since we just read an EOF from its stdout. We could try
3483 * to do better, by using wait(), and keeping track of background jobs
3484 * at the same time. That would be a lot of work, and contrary
3485 * to the KISS philosophy of this program. */
3486 retcode = fclose(p);
3487 free_pipe_list(inner.list_head, /* indent: */ 0);
3488 debug_printf("closed FILE from child, retcode=%d\n", retcode);
3493 static int parse_group(o_string *dest, struct parse_context *ctx,
3494 struct in_str *input, int ch)
3496 /* dest contains characters seen prior to ( or {.
3497 * Typically it's empty, but for functions defs,
3498 * it contains function name (without '()'). */
3500 const char *endch = NULL;
3501 struct parse_context sub;
3502 struct command *command = ctx->command;
3504 debug_printf_parse("parse_group entered\n");
3505 #if ENABLE_HUSH_FUNCTIONS
3506 if (ch == 'F') { /* function definition? */
3507 bb_error_msg("aha '%s' is a function, parsing it...", dest->data);
3508 //command->fname = dest->data;
3509 command->grp_type = GRP_FUNCTION;
3510 //TODO: review every o_reset() location... do they handle all o_string fields correctly?
3511 memset(dest, 0, sizeof(*dest));
3514 if (command->argv /* word [word](... */
3515 || dest->length /* word(... */
3516 || dest->nonnull /* ""(... */
3519 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3522 initialize_context(&sub);
3526 command->grp_type = GRP_SUBSHELL;
3528 rcode = parse_stream(dest, &sub, input, endch);
3530 done_word(dest, &sub); /* finish off the final word in the subcontext */
3531 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
3532 command->group = sub.list_head;
3534 debug_printf_parse("parse_group return %d\n", rcode);
3536 /* command remains "open", available for possible redirects */
3539 /* Basically useful version until someone wants to get fancier,
3540 * see the bash man page under "Parameter Expansion" */
3541 static const char *lookup_param(const char *src)
3543 struct variable *var = get_local_var(src);
3545 return strchr(var->varstr, '=') + 1;
3549 #if ENABLE_HUSH_TICK
3550 /* Subroutines for copying $(...) and `...` things */
3551 static void add_till_backquote(o_string *dest, struct in_str *input);
3553 static void add_till_single_quote(o_string *dest, struct in_str *input)
3556 int ch = i_getch(input);
3564 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3565 static void add_till_double_quote(o_string *dest, struct in_str *input)
3568 int ch = i_getch(input);
3571 if (ch == '\\') { /* \x. Copy both chars. */
3573 ch = i_getch(input);
3579 add_till_backquote(dest, input);
3583 //if (ch == '$') ...
3586 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3588 * "Within the backquoted style of command substitution, backslash
3589 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3590 * The search for the matching backquote shall be satisfied by the first
3591 * backquote found without a preceding backslash; during this search,
3592 * if a non-escaped backquote is encountered within a shell comment,
3593 * a here-document, an embedded command substitution of the $(command)
3594 * form, or a quoted string, undefined results occur. A single-quoted
3595 * or double-quoted string that begins, but does not end, within the
3596 * "`...`" sequence produces undefined results."
3598 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3600 static void add_till_backquote(o_string *dest, struct in_str *input)
3603 int ch = i_getch(input);
3606 if (ch == '\\') { /* \x. Copy both chars unless it is \` */
3607 int ch2 = i_getch(input);
3608 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
3617 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3618 * quoting and nested ()s.
3619 * "With the $(command) style of command substitution, all characters
3620 * following the open parenthesis to the matching closing parenthesis
3621 * constitute the command. Any valid shell script can be used for command,
3622 * except a script consisting solely of redirections which produces
3623 * unspecified results."
3625 * echo $(echo '(TEST)' BEST) (TEST) BEST
3626 * echo $(echo 'TEST)' BEST) TEST) BEST
3627 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3629 static void add_till_closing_curly_brace(o_string *dest, struct in_str *input)
3633 int ch = i_getch(input);
3643 add_till_single_quote(dest, input);
3648 add_till_double_quote(dest, input);
3652 if (ch == '\\') { /* \x. Copy verbatim. Important for \(, \) */
3653 ch = i_getch(input);
3661 #endif /* ENABLE_HUSH_TICK */
3663 /* Return code: 0 for OK, 1 for syntax error */
3664 static int handle_dollar(o_string *dest, struct in_str *input)
3666 int ch = i_peek(input); /* first character after the $ */
3667 unsigned char quote_mask = dest->o_quote ? 0x80 : 0;
3669 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
3673 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3675 debug_printf_parse(": '%c'\n", ch);
3676 o_addchr(dest, ch | quote_mask);
3679 if (!isalnum(ch) && ch != '_')
3683 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3684 } else if (isdigit(ch)) {
3687 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3688 debug_printf_parse(": '%c'\n", ch);
3689 o_addchr(dest, ch | quote_mask);
3690 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3691 } else switch (ch) {
3693 case '!': /* last bg pid */
3694 case '?': /* last exit code */
3695 case '#': /* number of args */
3696 case '*': /* args */
3697 case '@': /* args */
3698 goto make_one_char_var;
3700 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3702 /* XXX maybe someone will try to escape the '}' */
3704 ch = i_getch(input);
3707 if (!isalnum(ch) && ch != '_') {
3708 syntax("unterminated ${name}");
3709 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3712 debug_printf_parse(": '%c'\n", ch);
3713 o_addchr(dest, ch | quote_mask);
3716 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3718 #if ENABLE_HUSH_TICK
3720 //int pos = dest->length;
3722 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3723 o_addchr(dest, quote_mask | '`');
3724 add_till_closing_curly_brace(dest, input);
3725 //debug_printf_subst("SUBST RES2 '%s'\n", dest->data + pos);
3726 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3733 if (isalnum(ch)) { /* it's $_name or $_123 */
3739 /* still unhandled, but should be eventually */
3740 bb_error_msg("unhandled syntax: $%c", ch);
3744 o_addQchr(dest, '$');
3746 debug_printf_parse("handle_dollar return 0\n");
3750 /* Scan input, call done_word() whenever full IFS delimited word was seen.
3751 * Call done_pipe if '\n' was seen (and end_trigger != NULL).
3752 * Return code is 0 if end_trigger char is met,
3753 * -1 on EOF (but if end_trigger == NULL then return 0),
3754 * 1 for syntax error */
3755 static int parse_stream(o_string *dest, struct parse_context *ctx,
3756 struct in_str *input, const char *end_trigger)
3760 redir_type redir_style;
3761 int shadow_quote = dest->o_quote;
3764 /* Only double-quote state is handled in the state variable dest->o_quote.
3765 * A single-quote triggers a bypass of the main loop until its mate is
3766 * found. When recursing, quote state is passed in via dest->o_quote. */
3768 debug_printf_parse("parse_stream entered, end_trigger='%s' dest->o_assignment:%d\n", end_trigger, dest->o_assignment);
3773 ch = i_getch(input);
3777 next = i_peek(input);
3780 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
3781 ch, ch, m, dest->o_quote);
3782 if (m == CHAR_ORDINARY
3783 || (m != CHAR_SPECIAL && shadow_quote)
3786 syntax("unterminated \"");
3787 debug_printf_parse("parse_stream return 1: unterminated \"\n");
3790 o_addQchr(dest, ch);
3791 if ((dest->o_assignment == MAYBE_ASSIGNMENT
3792 || dest->o_assignment == WORD_IS_KEYWORD)
3794 && is_assignment(dest->data)
3796 dest->o_assignment = DEFINITELY_ASSIGNMENT;
3800 if (m == CHAR_IFS) {
3801 if (done_word(dest, ctx)) {
3802 debug_printf_parse("parse_stream return 1: done_word!=0\n");
3807 /* If we aren't performing a substitution, treat
3808 * a newline as a command separator.
3809 * [why we don't handle it exactly like ';'? --vda] */
3810 if (end_trigger && ch == '\n') {
3811 #if ENABLE_HUSH_CASE
3812 /* "case ... in <newline> word) ..." -
3813 * newlines are ignored (but ';' wouldn't be) */
3814 if (dest->length == 0 // && argv[0] == NULL
3815 && ctx->ctx_res_w == RES_MATCH
3820 done_pipe(ctx, PIPE_SEQ);
3821 dest->o_assignment = MAYBE_ASSIGNMENT;
3825 if (!shadow_quote && strchr(end_trigger, ch)) {
3826 /* Special case: (...word) makes last word terminate,
3827 * as if ';' is seen */
3829 done_word(dest, ctx);
3831 done_pipe(ctx, PIPE_SEQ);
3832 dest->o_assignment = MAYBE_ASSIGNMENT;
3835 IF_HAS_KEYWORDS(|| (ctx->ctx_res_w == RES_NONE && ctx->old_flag == 0))
3837 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
3845 if (dest->o_assignment == MAYBE_ASSIGNMENT) {
3846 /* ch is a special char and thus this word
3847 * cannot be an assignment: */
3848 dest->o_assignment = NOT_ASSIGNMENT;
3853 if (dest->length == 0 && !shadow_quote) {
3856 if (ch == EOF || ch == '\n')
3861 o_addQchr(dest, ch);
3867 debug_printf_parse("parse_stream return 1: \\<eof>\n");
3871 * "The backslash retains its special meaning [in "..."]
3872 * only when followed by one of the following characters:
3873 * $, `, ", \, or <newline>. A double quote may be quoted
3874 * within double quotes by preceding it with a backslash.
3875 * If enabled, history expansion will be performed unless
3876 * an ! appearing in double quotes is escaped using
3877 * a backslash. The backslash preceding the ! is not removed."
3879 if (shadow_quote) { //NOT SURE dest->o_quote) {
3880 if (strchr("$`\"\\", next) != NULL) {
3881 o_addqchr(dest, i_getch(input));
3883 o_addqchr(dest, '\\');
3886 o_addchr(dest, '\\');
3887 o_addchr(dest, i_getch(input));
3891 if (handle_dollar(dest, input) != 0) {
3892 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3899 ch = i_getch(input);
3901 syntax("unterminated '");
3902 debug_printf_parse("parse_stream return 1: unterminated '\n");
3907 if (dest->o_assignment == NOT_ASSIGNMENT)
3908 o_addqchr(dest, ch);
3915 shadow_quote ^= 1; /* invert */
3916 if (dest->o_assignment == NOT_ASSIGNMENT)
3919 #if ENABLE_HUSH_TICK
3921 //int pos = dest->length;
3922 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3923 o_addchr(dest, shadow_quote /*or dest->o_quote??*/ ? 0x80 | '`' : '`');
3924 add_till_backquote(dest, input);
3925 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3926 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
3931 redir_fd = redirect_opt_num(dest);
3932 done_word(dest, ctx);
3933 redir_style = REDIRECT_OVERWRITE;
3935 redir_style = REDIRECT_APPEND;
3939 else if (next == '(') {
3940 syntax(">(process) not supported");
3941 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
3945 setup_redirect(ctx, redir_fd, redir_style, input);
3948 redir_fd = redirect_opt_num(dest);
3949 done_word(dest, ctx);
3950 redir_style = REDIRECT_INPUT;
3952 redir_style = REDIRECT_HEREIS;
3954 } else if (next == '>') {
3955 redir_style = REDIRECT_IO;
3959 else if (next == '(') {
3960 syntax("<(process) not supported");
3961 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
3965 setup_redirect(ctx, redir_fd, redir_style, input);
3968 #if ENABLE_HUSH_CASE
3971 done_word(dest, ctx);
3972 done_pipe(ctx, PIPE_SEQ);
3973 #if ENABLE_HUSH_CASE
3974 /* Eat multiple semicolons, detect
3975 * whether it means something special */
3981 if (ctx->ctx_res_w == RES_CASEI) {
3982 ctx->ctx_dsemicolon = 1;
3983 ctx->ctx_res_w = RES_MATCH;
3989 /* We just finished a cmd. New one may start
3990 * with an assignment */
3991 dest->o_assignment = MAYBE_ASSIGNMENT;
3994 done_word(dest, ctx);
3997 done_pipe(ctx, PIPE_AND);
3999 done_pipe(ctx, PIPE_BG);
4003 done_word(dest, ctx);
4004 #if ENABLE_HUSH_CASE
4005 if (ctx->ctx_res_w == RES_MATCH)
4006 break; /* we are in case's "word | word)" */
4008 if (next == '|') { /* || */
4010 done_pipe(ctx, PIPE_OR);
4012 /* we could pick up a file descriptor choice here
4013 * with redirect_opt_num(), but bash doesn't do it.
4014 * "echo foo 2| cat" yields "foo 2". */
4019 #if ENABLE_HUSH_CASE
4020 /* "case... in [(]word)..." - skip '(' */
4021 if (ctx->ctx_res_w == RES_MATCH
4022 && ctx->command->argv == NULL /* not (word|(... */
4023 && dest->length == 0 /* not word(... */
4024 && dest->nonnull == 0 /* not ""(... */
4029 #if ENABLE_HUSH_FUNCTIONS
4030 if (dest->length != 0 /* not just () but word() */
4031 && dest->nonnull == 0 /* not a"b"c() */
4032 && ctx->command->argv == NULL /* it's the first word */
4033 //TODO: "func ( ) {...}" - note spaces - is valid format too in bash
4034 && i_peek(input) == ')'
4035 && !match_reserved_word(dest)
4037 bb_error_msg("seems like a function definition");
4040 //TODO: do it properly.
4041 ch = i_getch(input);
4042 } while (ch == ' ' || ch == '\n');
4044 syntax("was expecting {");
4045 debug_printf_parse("parse_stream return 1\n");
4048 ch = 'F'; /* magic value */
4052 if (parse_group(dest, ctx, input, ch) != 0) {
4053 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
4058 #if ENABLE_HUSH_CASE
4059 if (ctx->ctx_res_w == RES_MATCH)
4063 /* proper use of this character is caught by end_trigger:
4064 * if we see {, we call parse_group(..., end_trigger='}')
4065 * and it will match } earlier (not here). */
4066 syntax("unexpected } or )");
4067 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
4071 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4074 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
4080 static void set_in_charmap(const char *set, int code)
4083 G.charmap[(unsigned char)*set++] = code;
4086 static void update_charmap(void)
4088 G.ifs = getenv("IFS");
4091 /* Precompute a list of 'flow through' behavior so it can be treated
4092 * quickly up front. Computation is necessary because of IFS.
4093 * Special case handling of IFS == " \t\n" is not implemented.
4094 * The charmap[] array only really needs two bits each,
4095 * and on most machines that would be faster (reduced L1 cache use).
4097 memset(G.charmap, CHAR_ORDINARY, sizeof(G.charmap));
4098 #if ENABLE_HUSH_TICK
4099 set_in_charmap("\\$\"`", CHAR_SPECIAL);
4101 set_in_charmap("\\$\"", CHAR_SPECIAL);
4103 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
4104 set_in_charmap(G.ifs, CHAR_IFS); /* are ordinary if quoted */
4107 /* Most recursion does not come through here, the exception is
4108 * from builtin_source() and builtin_eval() */
4109 static int parse_and_run_stream(struct in_str *inp, int parse_flag)
4111 struct parse_context ctx;
4112 o_string temp = NULL_O_STRING;
4116 initialize_context(&ctx);
4118 #if ENABLE_HUSH_INTERACTIVE
4119 inp->promptmode = 0; /* PS1 */
4121 /* We will stop & execute after each ';' or '\n'.
4122 * Example: "sleep 9999; echo TEST" + ctrl-C:
4123 * TEST should be printed */
4124 temp.o_assignment = MAYBE_ASSIGNMENT;
4125 rcode = parse_stream(&temp, &ctx, inp, ";\n");
4127 if (rcode != 1 && ctx.old_flag != 0) {
4131 if (rcode != 1 IF_HAS_KEYWORDS(&& ctx.old_flag == 0)) {
4132 done_word(&temp, &ctx);
4133 done_pipe(&ctx, PIPE_SEQ);
4134 debug_print_tree(ctx.list_head, 0);
4135 debug_printf_exec("parse_stream_outer: run_and_free_list\n");
4136 run_and_free_list(ctx.list_head);
4138 /* We arrive here also if rcode == 1 (error in parse_stream) */
4140 if (ctx.old_flag != 0) {
4145 /*temp.nonnull = 0; - o_free does it below */
4146 /*temp.o_quote = 0; - o_free does it below */
4147 free_pipe_list(ctx.list_head, /* indent: */ 0);
4148 /* Discard all unprocessed line input, force prompt on */
4150 #if ENABLE_HUSH_INTERACTIVE
4155 /* loop on syntax errors, return on EOF: */
4156 } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP));
4160 static int parse_and_run_string(const char *s, int parse_flag)
4162 struct in_str input;
4163 setup_string_in_str(&input, s);
4164 return parse_and_run_stream(&input, parse_flag);
4167 static int parse_and_run_file(FILE *f)
4170 struct in_str input;
4171 setup_file_in_str(&input, f);
4172 rcode = parse_and_run_stream(&input, 0 /* parse_flag */);
4177 /* Make sure we have a controlling tty. If we get started under a job
4178 * aware app (like bash for example), make sure we are now in charge so
4179 * we don't fight over who gets the foreground */
4180 static void setup_job_control(void)
4184 shell_pgrp = getpgrp();
4185 close_on_exec_on(G.interactive_fd);
4187 /* If we were ran as 'hush &',
4188 * sleep until we are in the foreground. */
4189 while (tcgetpgrp(G.interactive_fd) != shell_pgrp) {
4190 /* Send TTIN to ourself (should stop us) */
4191 kill(- shell_pgrp, SIGTTIN);
4192 shell_pgrp = getpgrp();
4195 /* Ignore job-control and misc signals. */
4196 set_jobctrl_sighandler(SIG_IGN);
4197 set_misc_sighandler(SIG_IGN);
4198 //huh? signal(SIGCHLD, SIG_IGN);
4200 /* We _must_ restore tty pgrp on fatal signals */
4201 set_fatal_sighandler(sigexit);
4203 /* Put ourselves in our own process group. */
4204 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
4205 /* Grab control of the terminal. */
4206 tcsetpgrp(G.interactive_fd, getpid());
4211 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4212 int hush_main(int argc, char **argv)
4214 static const struct variable const_shell_ver = {
4216 .varstr = (char*)hush_version_str,
4217 .max_len = 1, /* 0 can provoke free(name) */
4225 struct variable *cur_var;
4229 G.root_pid = getpid();
4231 /* Deal with HUSH_VERSION */
4232 G.shell_ver = const_shell_ver; /* copying struct here */
4233 G.top_var = &G.shell_ver;
4234 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
4235 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
4236 /* Initialize our shell local variables with the values
4237 * currently living in the environment */
4238 cur_var = G.top_var;
4241 char *value = strchr(*e, '=');
4242 if (value) { /* paranoia */
4243 cur_var->next = xzalloc(sizeof(*cur_var));
4244 cur_var = cur_var->next;
4245 cur_var->varstr = *e;
4246 cur_var->max_len = strlen(*e);
4247 cur_var->flg_export = 1;
4251 debug_printf_env("putenv '%s'\n", hush_version_str);
4252 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
4254 #if ENABLE_FEATURE_EDITING
4255 G.line_input_state = new_line_input_t(FOR_SHELL);
4257 /* XXX what should these be while sourcing /etc/profile? */
4258 G.global_argc = argc;
4259 G.global_argv = argv;
4260 /* Initialize some more globals to non-zero values */
4262 #if ENABLE_HUSH_INTERACTIVE
4263 #if ENABLE_FEATURE_EDITING
4264 cmdedit_set_initial_prompt();
4269 if (EXIT_SUCCESS) /* otherwise is already done */
4270 G.last_return_code = EXIT_SUCCESS;
4272 if (argv[0] && argv[0][0] == '-') {
4273 debug_printf("sourcing /etc/profile\n");
4274 input = fopen_for_read("/etc/profile");
4275 if (input != NULL) {
4276 close_on_exec_on(fileno(input));
4277 parse_and_run_file(input);
4283 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
4286 G.global_argv = argv + optind;
4287 G.global_argc = argc - optind;
4288 opt = parse_and_run_string(optarg, 0 /* parse_flag */);
4291 /* Well, we cannot just declare interactiveness,
4292 * we have to have some stuff (ctty, etc) */
4293 /* G.interactive_fd++; */
4300 fprintf(stderr, "Usage: sh [FILE]...\n"
4301 " or: sh -c command [args]...\n\n");
4309 /* A shell is interactive if the '-i' flag was given, or if all of
4310 * the following conditions are met:
4312 * no arguments remaining or the -s flag given
4313 * standard input is a terminal
4314 * standard output is a terminal
4315 * Refer to Posix.2, the description of the 'sh' utility. */
4316 if (argv[optind] == NULL && input == stdin
4317 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4319 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
4320 debug_printf("saved_tty_pgrp=%d\n", G.saved_tty_pgrp);
4321 if (G.saved_tty_pgrp >= 0) {
4322 /* try to dup to high fd#, >= 255 */
4323 G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4324 if (G.interactive_fd < 0) {
4325 /* try to dup to any fd */
4326 G.interactive_fd = dup(STDIN_FILENO);
4327 if (G.interactive_fd < 0)
4329 G.interactive_fd = 0;
4331 // TODO: track & disallow any attempts of user
4332 // to (inadvertently) close/redirect it
4335 debug_printf("G.interactive_fd=%d\n", G.interactive_fd);
4336 if (G.interactive_fd) {
4337 fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
4338 /* Looks like they want an interactive shell */
4339 setup_job_control();
4340 /* -1 is special - makes xfuncs longjmp, not exit
4341 * (we reset die_sleep = 0 whereever we [v]fork) */
4343 if (setjmp(die_jmp)) {
4344 /* xfunc has failed! die die die */
4345 hush_exit(xfunc_error_retval);
4347 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
4348 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
4349 printf("Enter 'help' for a list of built-in commands.\n\n");
4352 #elif ENABLE_HUSH_INTERACTIVE
4353 /* no job control compiled, only prompt/line editing */
4354 if (argv[optind] == NULL && input == stdin
4355 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4357 G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4358 if (G.interactive_fd < 0) {
4359 /* try to dup to any fd */
4360 G.interactive_fd = dup(STDIN_FILENO);
4361 if (G.interactive_fd < 0)
4363 G.interactive_fd = 0;
4365 if (G.interactive_fd) {
4366 fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
4367 set_misc_sighandler(SIG_IGN);
4372 if (argv[optind] == NULL) {
4373 opt = parse_and_run_file(stdin);
4375 debug_printf("\nrunning script '%s'\n", argv[optind]);
4376 G.global_argv = argv + optind;
4377 G.global_argc = argc - optind;
4378 input = xfopen_for_read(argv[optind]);
4379 fcntl(fileno(input), F_SETFD, FD_CLOEXEC);
4380 opt = parse_and_run_file(input);
4385 #if ENABLE_FEATURE_CLEAN_UP
4387 if (G.cwd != bb_msg_unknown)
4389 cur_var = G.top_var->next;
4391 struct variable *tmp = cur_var;
4392 if (!cur_var->max_len)
4393 free(cur_var->varstr);
4394 cur_var = cur_var->next;
4398 hush_exit(opt ? opt : G.last_return_code);
4403 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4404 int lash_main(int argc, char **argv)
4406 //bb_error_msg("lash is deprecated, please use hush instead");
4407 return hush_main(argc, argv);
4415 static int builtin_true(char **argv UNUSED_PARAM)
4420 static int builtin_test(char **argv)
4427 return test_main(argc, argv - argc);
4430 static int builtin_echo(char **argv)
4437 return echo_main(argc, argv - argc);
4440 static int builtin_eval(char **argv)
4442 int rcode = EXIT_SUCCESS;
4445 char *str = expand_strvec_to_string(argv + 1);
4446 parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP);
4448 rcode = G.last_return_code;
4453 static int builtin_cd(char **argv)
4456 if (argv[1] == NULL) {
4457 // bash does nothing (exitcode 0) if HOME is ""; if it's unset,
4458 // bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
4459 newdir = getenv("HOME") ? : "/";
4462 if (chdir(newdir)) {
4463 printf("cd: %s: %s\n", newdir, strerror(errno));
4464 return EXIT_FAILURE;
4467 return EXIT_SUCCESS;
4470 static int builtin_exec(char **argv)
4472 if (argv[1] == NULL)
4473 return EXIT_SUCCESS; /* bash does this */
4478 // FIXME: if exec fails, bash does NOT exit! We do...
4479 pseudo_exec_argv(&dummy, argv + 1, 0, NULL);
4484 static int builtin_exit(char **argv)
4486 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
4487 //puts("exit"); /* bash does it */
4488 // TODO: warn if we have background jobs: "There are stopped jobs"
4489 // On second consecutive 'exit', exit anyway.
4490 if (argv[1] == NULL)
4491 hush_exit(G.last_return_code);
4492 /* mimic bash: exit 123abc == exit 255 + error msg */
4493 xfunc_error_retval = 255;
4494 /* bash: exit -2 == exit 254, no error msg */
4495 hush_exit(xatoi(argv[1]) & 0xff);
4498 static int builtin_export(char **argv)
4501 char *name = argv[1];
4505 // ash emits: export VAR='VAL'
4506 // bash: declare -x VAR="VAL"
4507 // (both also escape as needed (quotes, $, etc))
4512 return EXIT_SUCCESS;
4515 value = strchr(name, '=');
4517 /* They are exporting something without a =VALUE */
4518 struct variable *var;
4520 var = get_local_var(name);
4522 var->flg_export = 1;
4523 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
4524 putenv(var->varstr);
4526 /* bash does not return an error when trying to export
4527 * an undefined variable. Do likewise. */
4528 return EXIT_SUCCESS;
4531 set_local_var(xstrdup(name), 1);
4532 return EXIT_SUCCESS;
4536 /* built-in 'fg' and 'bg' handler */
4537 static int builtin_fg_bg(char **argv)
4542 if (!G.interactive_fd)
4543 return EXIT_FAILURE;
4544 /* If they gave us no args, assume they want the last backgrounded task */
4546 for (pi = G.job_list; pi; pi = pi->next) {
4547 if (pi->jobid == G.last_jobid) {
4551 bb_error_msg("%s: no current job", argv[0]);
4552 return EXIT_FAILURE;
4554 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
4555 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
4556 return EXIT_FAILURE;
4558 for (pi = G.job_list; pi; pi = pi->next) {
4559 if (pi->jobid == jobnum) {
4563 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
4564 return EXIT_FAILURE;
4566 // TODO: bash prints a string representation
4567 // of job being foregrounded (like "sleep 1 | cat")
4568 if (*argv[0] == 'f') {
4569 /* Put the job into the foreground. */
4570 tcsetpgrp(G.interactive_fd, pi->pgrp);
4573 /* Restart the processes in the job */
4574 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
4575 for (i = 0; i < pi->num_cmds; i++) {
4576 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
4577 pi->cmds[i].is_stopped = 0;
4579 pi->stopped_cmds = 0;
4581 i = kill(- pi->pgrp, SIGCONT);
4583 if (errno == ESRCH) {
4584 delete_finished_bg_job(pi);
4585 return EXIT_SUCCESS;
4587 bb_perror_msg("kill (SIGCONT)");
4591 if (*argv[0] == 'f') {
4593 return checkjobs_and_fg_shell(pi);
4595 return EXIT_SUCCESS;
4599 #if ENABLE_HUSH_HELP
4600 static int builtin_help(char **argv UNUSED_PARAM)
4602 const struct built_in_command *x;
4604 printf("\nBuilt-in commands:\n");
4605 printf("-------------------\n");
4606 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
4607 printf("%s\t%s\n", x->cmd, x->descr);
4610 return EXIT_SUCCESS;
4615 static int builtin_jobs(char **argv UNUSED_PARAM)
4618 const char *status_string;
4620 for (job = G.job_list; job; job = job->next) {
4621 if (job->alive_cmds == job->stopped_cmds)
4622 status_string = "Stopped";
4624 status_string = "Running";
4626 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
4628 return EXIT_SUCCESS;
4632 static int builtin_pwd(char **argv UNUSED_PARAM)
4635 return EXIT_SUCCESS;
4638 static int builtin_read(char **argv)
4641 const char *name = argv[1] ? argv[1] : "REPLY";
4643 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
4644 return set_local_var(string, 0);
4647 /* built-in 'set [VAR=value]' handler */
4648 static int builtin_set(char **argv)
4650 char *temp = argv[1];
4654 for (e = G.top_var; e; e = e->next)
4657 set_local_var(xstrdup(temp), 0);
4659 return EXIT_SUCCESS;
4662 static int builtin_shift(char **argv)
4668 if (n >= 0 && n < G.global_argc) {
4669 G.global_argv[n] = G.global_argv[0];
4672 return EXIT_SUCCESS;
4674 return EXIT_FAILURE;
4677 static int builtin_source(char **argv)
4682 if (argv[1] == NULL)
4683 return EXIT_FAILURE;
4685 /* XXX search through $PATH is missing */
4686 input = fopen_for_read(argv[1]);
4688 bb_error_msg("can't open '%s'", argv[1]);
4689 return EXIT_FAILURE;
4691 close_on_exec_on(fileno(input));
4693 /* Now run the file */
4694 /* XXX argv and argc are broken; need to save old G.global_argv
4695 * (pointer only is OK!) on this stack frame,
4696 * set G.global_argv=argv+1, recurse, and restore. */
4697 status = parse_and_run_file(input);
4702 static int builtin_umask(char **argv)
4705 const char *arg = argv[1];
4708 new_umask = strtoul(arg, &end, 8);
4709 if (*end != '\0' || end == arg) {
4710 return EXIT_FAILURE;
4713 new_umask = umask(0);
4714 printf("%.3o\n", (unsigned) new_umask);
4717 return EXIT_SUCCESS;
4720 static int builtin_unset(char **argv)
4722 /* bash always returns true */
4723 unset_local_var(argv[1]);
4724 return EXIT_SUCCESS;
4727 #if ENABLE_HUSH_LOOPS
4728 static int builtin_break(char **argv)
4730 if (G.depth_of_loop == 0) {
4731 bb_error_msg("%s: only meaningful in a loop", argv[0]);
4732 return EXIT_SUCCESS; /* bash compat */
4734 G.flag_break_continue++; /* BC_BREAK = 1 */
4735 G.depth_break_continue = 1;
4737 G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
4738 if (errno || !G.depth_break_continue || argv[2]) {
4739 bb_error_msg("%s: bad arguments", argv[0]);
4740 G.flag_break_continue = BC_BREAK;
4741 G.depth_break_continue = UINT_MAX;
4744 if (G.depth_of_loop < G.depth_break_continue)
4745 G.depth_break_continue = G.depth_of_loop;
4746 return EXIT_SUCCESS;
4749 static int builtin_continue(char **argv)
4751 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
4752 return builtin_break(argv);