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;
474 smalluint global_args_malloced;
475 int global_argc; /* NB: $# + 1 */
477 #if ENABLE_HUSH_LOOPS
478 unsigned depth_break_continue;
479 unsigned depth_of_loop;
483 struct variable *top_var; /* = &G.shell_ver (set in main()) */
484 struct variable shell_ver;
485 #if ENABLE_FEATURE_SH_STANDALONE
486 struct nofork_save_area nofork_save;
489 sigjmp_buf toplevel_jb;
491 unsigned char charmap[256];
492 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
495 #define G (*ptr_to_globals)
496 /* Not #defining name to G.name - this quickly gets unwieldy
497 * (too many defines). Also, I actually prefer to see when a variable
498 * is global, thus "G." prefix is a useful hint */
499 #define INIT_G() do { \
500 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
504 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
508 static void syntax(const char *msg)
510 #if ENABLE_HUSH_INTERACTIVE
511 /* Was using fancy stuff:
512 * (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
513 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
514 void FAST_FUNC (*fp)(const char *s, ...);
515 fp = (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die);
516 fp(msg ? "%s: %s" : "syntax error", "syntax error", msg);
518 bb_error_msg_and_die(msg ? "%s: %s" : "syntax error", "syntax error", msg);
524 static void syntax_lineno(int line)
526 #if ENABLE_HUSH_INTERACTIVE
527 void FAST_FUNC (*fp)(const char *s, ...);
528 fp = (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die);
529 fp("syntax error hush.c:%d", line);
531 bb_error_msg_and_die("syntax error hush.c:%d", line);
534 #define syntax(str) syntax_lineno(__LINE__)
537 /* Index of subroutines: */
538 /* in_str manipulations: */
539 static int static_get(struct in_str *i);
540 static int static_peek(struct in_str *i);
541 static int file_get(struct in_str *i);
542 static int file_peek(struct in_str *i);
543 static void setup_file_in_str(struct in_str *i, FILE *f);
544 static void setup_string_in_str(struct in_str *i, const char *s);
545 /* "run" the final data structures: */
546 #if !defined(DEBUG_CLEAN)
547 #define free_pipe_list(head, indent) free_pipe_list(head)
548 #define free_pipe(pi, indent) free_pipe(pi)
550 static int free_pipe_list(struct pipe *head, int indent);
551 static int free_pipe(struct pipe *pi, int indent);
552 /* really run the final data structures: */
553 typedef struct nommu_save_t {
559 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
560 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
561 #define pseudo_exec(nommu_save, command, argv_expanded) \
562 pseudo_exec(command, argv_expanded)
564 static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded) NORETURN;
565 static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded) NORETURN;
566 static int setup_redirects(struct command *prog, int squirrel[]);
567 static int run_list(struct pipe *pi);
568 static int run_pipe(struct pipe *pi);
569 /* data structure manipulation: */
570 static int setup_redirect(struct parse_context *ctx, int fd, redir_type style, struct in_str *input);
571 static void initialize_context(struct parse_context *ctx);
572 static int done_word(o_string *dest, struct parse_context *ctx);
573 static int done_command(struct parse_context *ctx);
574 static void done_pipe(struct parse_context *ctx, pipe_style type);
575 /* primary string parsing: */
576 static int redirect_dup_num(struct in_str *input);
577 static int redirect_opt_num(o_string *o);
579 static int process_command_subs(o_string *dest,
580 struct in_str *input, const char *subst_end);
582 static int parse_group(o_string *dest, struct parse_context *ctx, struct in_str *input, int ch);
583 static const char *lookup_param(const char *src);
584 static int handle_dollar(o_string *dest,
585 struct in_str *input);
586 static int parse_stream(o_string *dest, struct parse_context *ctx, struct in_str *input0, const char *end_trigger);
588 static int parse_and_run_stream(struct in_str *inp, int parse_flag);
589 static int parse_and_run_string(const char *s, int parse_flag);
590 static int parse_and_run_file(FILE *f);
591 /* job management: */
592 static int checkjobs(struct pipe* fg_pipe);
594 static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
595 static void insert_bg_job(struct pipe *pi);
596 static void remove_bg_job(struct pipe *pi);
597 static void delete_finished_bg_job(struct pipe *pi);
599 int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
601 /* local variable support */
602 static char **expand_strvec_to_strvec(char **argv);
604 static char *expand_strvec_to_string(char **argv);
605 /* used for expansion of right hand of assignments */
606 static char *expand_string_to_string(const char *str);
607 static struct variable *get_local_var(const char *name);
608 static int set_local_var(char *str, int flg_export);
609 static void unset_local_var(const char *name);
612 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="HUSH_VER_STR;
615 static int glob_needed(const char *s)
620 if (*s == '*' || *s == '[' || *s == '?')
627 static int is_assignment(const char *s)
629 if (!s || !(isalpha(*s) || *s == '_'))
632 while (isalnum(*s) || *s == '_')
637 /* Replace each \x with x in place, return ptr past NUL. */
638 static char *unbackslash(char *src)
644 if ((*dst++ = *src++) == '\0')
650 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
671 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
672 v[count1 + count2] = NULL;
675 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
679 static char **add_string_to_strings(char **strings, char *add)
684 return add_strings_to_strings(strings, v, /*dup:*/ 0);
687 static void putenv_all(char **strings)
692 debug_printf_env("putenv '%s'\n", *strings);
697 static char **putenv_all_and_save_old(char **strings)
707 eq = strchr(*strings, '=');
710 v = getenv(*strings);
713 /* v points to VAL in VAR=VAL, go back to VAR */
714 v -= (eq - *strings) + 1;
715 old = add_string_to_strings(old, v);
724 static void free_strings_and_unsetenv(char **strings, int unset)
734 debug_printf_env("unsetenv '%s'\n", *v);
742 static void free_strings(char **strings)
744 free_strings_and_unsetenv(strings, 0);
748 /* Function prototypes for builtins */
749 static int builtin_cd(char **argv);
750 static int builtin_echo(char **argv);
751 static int builtin_eval(char **argv);
752 static int builtin_exec(char **argv);
753 static int builtin_exit(char **argv);
754 static int builtin_export(char **argv);
756 static int builtin_fg_bg(char **argv);
757 static int builtin_jobs(char **argv);
760 static int builtin_help(char **argv);
762 static int builtin_pwd(char **argv);
763 static int builtin_read(char **argv);
764 static int builtin_test(char **argv);
765 static int builtin_true(char **argv);
766 static int builtin_set(char **argv);
767 static int builtin_shift(char **argv);
768 static int builtin_source(char **argv);
769 static int builtin_umask(char **argv);
770 static int builtin_unset(char **argv);
771 #if ENABLE_HUSH_LOOPS
772 static int builtin_break(char **argv);
773 static int builtin_continue(char **argv);
775 //static int builtin_not_written(char **argv);
777 /* Table of built-in functions. They can be forked or not, depending on
778 * context: within pipes, they fork. As simple commands, they do not.
779 * When used in non-forking context, they can change global variables
780 * in the parent shell process. If forked, of course they cannot.
781 * For example, 'unset foo | whatever' will parse and run, but foo will
782 * still be set at the end. */
783 struct built_in_command {
785 int (*function)(char **argv);
788 #define BLTIN(cmd, func, help) { cmd, func, help }
790 #define BLTIN(cmd, func, help) { cmd, func }
794 /* For now, echo and test are unconditionally enabled.
795 * Maybe make it configurable? */
796 static const struct built_in_command bltins[] = {
797 BLTIN("." , builtin_source, "Run commands in a file"),
798 BLTIN(":" , builtin_true, "No-op"),
799 BLTIN("[" , builtin_test, "Test condition"),
800 BLTIN("[[" , builtin_test, "Test condition"),
802 BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"),
804 #if ENABLE_HUSH_LOOPS
805 BLTIN("break" , builtin_break, "Exit from a loop"),
807 BLTIN("cd" , builtin_cd, "Change directory"),
808 #if ENABLE_HUSH_LOOPS
809 BLTIN("continue", builtin_continue, "Start new loop iteration"),
811 BLTIN("echo" , builtin_echo, "Write to stdout"),
812 BLTIN("eval" , builtin_eval, "Construct and run shell command"),
813 BLTIN("exec" , builtin_exec, "Execute command, don't return to shell"),
814 BLTIN("exit" , builtin_exit, "Exit"),
815 BLTIN("export", builtin_export, "Set environment variable"),
817 BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"),
818 BLTIN("jobs" , builtin_jobs, "List active jobs"),
820 BLTIN("pwd" , builtin_pwd, "Print current directory"),
821 BLTIN("read" , builtin_read, "Input environment variable"),
822 // BLTIN("return", builtin_not_written, "Return from a function"),
823 BLTIN("set" , builtin_set, "Set/unset shell local variables"),
824 BLTIN("shift" , builtin_shift, "Shift positional parameters"),
825 // BLTIN("trap" , builtin_not_written, "Trap signals"),
826 BLTIN("test" , builtin_test, "Test condition"),
827 // BLTIN("ulimit", builtin_not_written, "Control resource limits"),
828 BLTIN("umask" , builtin_umask, "Set file creation mask"),
829 BLTIN("unset" , builtin_unset, "Unset environment variable"),
831 BLTIN("help" , builtin_help, "List shell built-in commands"),
836 /* Signals are grouped, we handle them in batches */
837 static void set_misc_sighandler(void (*handler)(int))
848 static void set_fatal_sighandler(void (*handler)(int))
857 /* bash 3.2 seems to handle these just like 'fatal' ones */
863 static void set_jobctrl_sighandler(void (*handler)(int))
871 /* SIGCHLD is special and handled separately */
873 static void set_every_sighandler(void (*handler)(int))
875 set_fatal_sighandler(handler);
876 set_jobctrl_sighandler(handler);
877 set_misc_sighandler(handler);
878 signal(SIGCHLD, handler);
881 static void handler_ctrl_c(int sig UNUSED_PARAM)
883 debug_printf_jobs("got sig %d\n", sig);
884 // as usual we can have all kinds of nasty problems with leaked malloc data here
885 siglongjmp(G.toplevel_jb, 1);
888 static void handler_ctrl_z(int sig UNUSED_PARAM)
892 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
894 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
897 if (!pid) { /* child */
899 die_sleep = 0; /* let nofork's xfuncs die */
901 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
902 set_every_sighandler(SIG_DFL);
903 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
904 debug_printf_jobs("returning in child\n");
905 /* return to nofork, it will eventually exit now,
906 * not return back to shell */
910 /* finish filling up pipe info */
911 G.toplevel_list->pgrp = pid; /* child is in its own pgrp */
912 G.toplevel_list->cmds[0].pid = pid;
913 /* parent needs to longjmp out of running nofork.
914 * we will "return" exitcode 0, with child put in background */
915 // as usual we can have all kinds of nasty problems with leaked malloc data here
916 debug_printf_jobs("siglongjmp in parent\n");
917 siglongjmp(G.toplevel_jb, 1);
920 /* Restores tty foreground process group, and exits.
921 * May be called as signal handler for fatal signal
922 * (will faithfully resend signal to itself, producing correct exit state)
923 * or called directly with -EXITCODE.
924 * We also call it if xfunc is exiting. */
925 static void sigexit(int sig) NORETURN;
926 static void sigexit(int sig)
928 /* Disable all signals: job control, SIGPIPE, etc. */
929 sigprocmask_allsigs(SIG_BLOCK);
931 #if ENABLE_HUSH_INTERACTIVE
932 if (G.interactive_fd)
933 tcsetpgrp(G.interactive_fd, G.saved_tty_pgrp);
936 /* Not a signal, just exit */
940 kill_myself_with_sig(sig); /* does not return */
943 /* Restores tty foreground process group, and exits. */
944 static void hush_exit(int exitcode) NORETURN;
945 static void hush_exit(int exitcode)
947 fflush(NULL); /* flush all streams */
948 sigexit(- (exitcode & 0xff));
953 #define set_fatal_sighandler(handler) ((void)0)
954 #define set_jobctrl_sighandler(handler) ((void)0)
955 #define hush_exit(e) exit(e)
960 static const char *set_cwd(void)
962 if (G.cwd == bb_msg_unknown)
963 G.cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
964 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
966 G.cwd = bb_msg_unknown;
974 #define B_CHUNK (32 * sizeof(char*))
976 static void o_reset(o_string *o)
984 static void o_free(o_string *o)
987 memset(o, 0, sizeof(*o));
990 static void o_grow_by(o_string *o, int len)
992 if (o->length + len > o->maxlen) {
993 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
994 o->data = xrealloc(o->data, 1 + o->maxlen);
998 static void o_addchr(o_string *o, int ch)
1000 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1002 o->data[o->length] = ch;
1004 o->data[o->length] = '\0';
1007 static void o_addstr(o_string *o, const char *str, int len)
1010 memcpy(&o->data[o->length], str, len);
1012 o->data[o->length] = '\0';
1015 static void o_addstr_duplicate_backslash(o_string *o, const char *str, int len)
1020 && (*str != '*' && *str != '?' && *str != '[')
1028 /* My analysis of quoting semantics tells me that state information
1029 * is associated with a destination, not a source.
1031 static void o_addqchr(o_string *o, int ch)
1034 char *found = strchr("*?[\\", ch);
1039 o->data[o->length] = '\\';
1042 o->data[o->length] = ch;
1044 o->data[o->length] = '\0';
1047 static void o_addQchr(o_string *o, int ch)
1050 if (o->o_quote && strchr("*?[\\", ch)) {
1052 o->data[o->length] = '\\';
1056 o->data[o->length] = ch;
1058 o->data[o->length] = '\0';
1061 static void o_addQstr(o_string *o, const char *str, int len)
1064 o_addstr(o, str, len);
1070 int ordinary_cnt = strcspn(str, "*?[\\");
1071 if (ordinary_cnt > len) /* paranoia */
1073 o_addstr(o, str, ordinary_cnt);
1074 if (ordinary_cnt == len)
1076 str += ordinary_cnt;
1077 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
1081 if (ch) { /* it is necessarily one of "*?[\\" */
1083 o->data[o->length] = '\\';
1087 o->data[o->length] = ch;
1089 o->data[o->length] = '\0';
1093 /* A special kind of o_string for $VAR and `cmd` expansion.
1094 * It contains char* list[] at the beginning, which is grown in 16 element
1095 * increments. Actual string data starts at the next multiple of 16 * (char*).
1096 * list[i] contains an INDEX (int!) into this string data.
1097 * It means that if list[] needs to grow, data needs to be moved higher up
1098 * but list[i]'s need not be modified.
1099 * NB: remembering how many list[i]'s you have there is crucial.
1100 * o_finalize_list() operation post-processes this structure - calculates
1101 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1103 #if DEBUG_EXPAND || DEBUG_GLOB
1104 static void debug_print_list(const char *prefix, o_string *o, int n)
1106 char **list = (char**)o->data;
1107 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1109 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1110 prefix, list, n, string_start, o->length, o->maxlen);
1112 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1113 o->data + (int)list[i] + string_start,
1114 o->data + (int)list[i] + string_start);
1118 const char *p = o->data + (int)list[n - 1] + string_start;
1119 fprintf(stderr, " total_sz:%d\n", (p + strlen(p) + 1) - o->data);
1123 #define debug_print_list(prefix, o, n) ((void)0)
1126 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1127 * in list[n] so that it points past last stored byte so far.
1128 * It returns n+1. */
1129 static int o_save_ptr_helper(o_string *o, int n)
1131 char **list = (char**)o->data;
1135 if (!o->has_empty_slot) {
1136 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1137 string_len = o->length - string_start;
1138 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
1139 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
1140 /* list[n] points to string_start, make space for 16 more pointers */
1141 o->maxlen += 0x10 * sizeof(list[0]);
1142 o->data = xrealloc(o->data, o->maxlen + 1);
1143 list = (char**)o->data;
1144 memmove(list + n + 0x10, list + n, string_len);
1145 o->length += 0x10 * sizeof(list[0]);
1147 debug_printf_list("list[%d]=%d string_start=%d\n", n, string_len, string_start);
1149 /* We have empty slot at list[n], reuse without growth */
1150 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1151 string_len = o->length - string_start;
1152 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n", n, string_len, string_start);
1153 o->has_empty_slot = 0;
1155 list[n] = (char*)(ptrdiff_t)string_len;
1159 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
1160 static int o_get_last_ptr(o_string *o, int n)
1162 char **list = (char**)o->data;
1163 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1165 return ((int)(ptrdiff_t)list[n-1]) + string_start;
1168 /* o_glob performs globbing on last list[], saving each result
1169 * as a new list[]. */
1170 static int o_glob(o_string *o, int n)
1176 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
1178 return o_save_ptr_helper(o, n);
1179 pattern = o->data + o_get_last_ptr(o, n);
1180 debug_printf_glob("glob pattern '%s'\n", pattern);
1181 if (!glob_needed(pattern)) {
1183 o->length = unbackslash(pattern) - o->data;
1184 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
1185 return o_save_ptr_helper(o, n);
1188 memset(&globdata, 0, sizeof(globdata));
1189 gr = glob(pattern, 0, NULL, &globdata);
1190 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1191 if (gr == GLOB_NOSPACE)
1192 bb_error_msg_and_die("out of memory during glob");
1193 if (gr == GLOB_NOMATCH) {
1194 globfree(&globdata);
1197 if (gr != 0) { /* GLOB_ABORTED ? */
1198 //TODO: testcase for bad glob pattern behavior
1199 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1201 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1202 char **argv = globdata.gl_pathv;
1203 o->length = pattern - o->data; /* "forget" pattern */
1205 o_addstr(o, *argv, strlen(*argv) + 1);
1206 n = o_save_ptr_helper(o, n);
1212 globfree(&globdata);
1214 debug_print_list("o_glob returning", o, n);
1218 /* If o->o_glob == 1, glob the string so far remembered.
1219 * Otherwise, just finish current list[] and start new */
1220 static int o_save_ptr(o_string *o, int n)
1222 if (o->o_glob) { /* if globbing is requested */
1223 /* If o->has_empty_slot, list[n] was already globbed
1224 * (if it was requested back then when it was filled)
1225 * so don't do that again! */
1226 if (!o->has_empty_slot)
1227 return o_glob(o, n); /* o_save_ptr_helper is inside */
1229 return o_save_ptr_helper(o, n);
1232 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
1233 static char **o_finalize_list(o_string *o, int n)
1238 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1240 debug_print_list("finalized", o, n);
1241 debug_printf_expand("finalized n:%d\n", n);
1242 list = (char**)o->data;
1243 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1247 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
1256 static int static_get(struct in_str *i)
1259 if (ch == '\0') return EOF;
1263 static int static_peek(struct in_str *i)
1268 #if ENABLE_HUSH_INTERACTIVE
1270 #if ENABLE_FEATURE_EDITING
1271 static void cmdedit_set_initial_prompt(void)
1273 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1276 G.PS1 = getenv("PS1");
1281 #endif /* EDITING */
1283 static const char* setup_prompt_string(int promptmode)
1285 const char *prompt_str;
1286 debug_printf("setup_prompt_string %d ", promptmode);
1287 #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
1288 /* Set up the prompt */
1289 if (promptmode == 0) { /* PS1 */
1291 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1297 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
1299 debug_printf("result '%s'\n", prompt_str);
1303 static void get_user_input(struct in_str *i)
1306 const char *prompt_str;
1308 prompt_str = setup_prompt_string(i->promptmode);
1309 #if ENABLE_FEATURE_EDITING
1310 /* Enable command line editing only while a command line
1311 * is actually being read */
1313 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
1314 } while (r == 0); /* repeat if Ctrl-C */
1315 i->eof_flag = (r < 0);
1316 if (i->eof_flag) { /* EOF/error detected */
1317 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1318 G.user_input_buf[1] = '\0';
1321 fputs(prompt_str, stdout);
1323 G.user_input_buf[0] = r = fgetc(i->file);
1324 /*G.user_input_buf[1] = '\0'; - already is and never changed */
1325 i->eof_flag = (r == EOF);
1327 i->p = G.user_input_buf;
1330 #endif /* INTERACTIVE */
1332 /* This is the magic location that prints prompts
1333 * and gets data back from the user */
1334 static int file_get(struct in_str *i)
1338 /* If there is data waiting, eat it up */
1339 if (i->p && *i->p) {
1340 #if ENABLE_HUSH_INTERACTIVE
1344 if (i->eof_flag && !*i->p)
1347 /* need to double check i->file because we might be doing something
1348 * more complicated by now, like sourcing or substituting. */
1349 #if ENABLE_HUSH_INTERACTIVE
1350 if (G.interactive_fd && i->promptme && i->file == stdin) {
1353 } while (!*i->p); /* need non-empty line */
1354 i->promptmode = 1; /* PS2 */
1359 ch = fgetc(i->file);
1361 debug_printf("file_get: got a '%c' %d\n", ch, ch);
1362 #if ENABLE_HUSH_INTERACTIVE
1369 /* All the callers guarantee this routine will never be
1370 * used right after a newline, so prompting is not needed.
1372 static int file_peek(struct in_str *i)
1375 if (i->p && *i->p) {
1376 if (i->eof_flag && !i->p[1])
1380 ch = fgetc(i->file);
1381 i->eof_flag = (ch == EOF);
1382 i->peek_buf[0] = ch;
1383 i->peek_buf[1] = '\0';
1385 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
1389 static void setup_file_in_str(struct in_str *i, FILE *f)
1391 i->peek = file_peek;
1393 #if ENABLE_HUSH_INTERACTIVE
1395 i->promptmode = 0; /* PS1 */
1401 static void setup_string_in_str(struct in_str *i, const char *s)
1403 i->peek = static_peek;
1404 i->get = static_get;
1405 #if ENABLE_HUSH_INTERACTIVE
1407 i->promptmode = 0; /* PS1 */
1414 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
1415 * and stderr if they are redirected. */
1416 static int setup_redirects(struct command *prog, int squirrel[])
1419 struct redir_struct *redir;
1421 for (redir = prog->redirects; redir; redir = redir->next) {
1422 if (redir->dup == -1 && redir->rd_filename == NULL) {
1423 /* something went wrong in the parse. Pretend it didn't happen */
1426 if (redir->dup == -1) {
1428 mode = redir_table[redir->rd_type].mode;
1429 //TODO: check redir for names like '\\'
1430 p = expand_string_to_string(redir->rd_filename);
1431 openfd = open_or_warn(p, mode);
1434 /* this could get lost if stderr has been redirected, but
1435 bash and ash both lose it as well (though zsh doesn't!) */
1439 openfd = redir->dup;
1442 if (openfd != redir->fd) {
1443 if (squirrel && redir->fd < 3) {
1444 squirrel[redir->fd] = dup(redir->fd);
1447 //close(openfd); // close(-3) ??!
1449 dup2(openfd, redir->fd);
1450 if (redir->dup == -1)
1458 static void restore_redirects(int squirrel[])
1461 for (i = 0; i < 3; i++) {
1464 /* We simply die on error */
1470 static char **expand_assignments(char **argv, int count)
1474 /* Expand assignments into one string each */
1475 for (i = 0; i < count; i++) {
1476 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
1481 /* Called after [v]fork() in run_pipe(), or from builtin_exec().
1483 * XXX no exit() here. If you don't exec, use _exit instead.
1484 * The at_exit handlers apparently confuse the calling process,
1485 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
1486 static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded)
1490 const struct built_in_command *x;
1492 /* If a variable is assigned in a forest, and nobody listens,
1493 * was it ever really set?
1495 if (!argv[assignment_cnt])
1496 _exit(EXIT_SUCCESS);
1498 new_env = expand_assignments(argv, assignment_cnt);
1500 putenv_all(new_env);
1501 free(new_env); /* optional */
1503 nommu_save->new_env = new_env;
1504 nommu_save->old_env = putenv_all_and_save_old(new_env);
1506 if (argv_expanded) {
1507 argv = argv_expanded;
1509 argv = expand_strvec_to_strvec(argv);
1511 nommu_save->argv = argv;
1516 * Check if the command matches any of the builtins.
1517 * Depending on context, this might be redundant. But it's
1518 * easier to waste a few CPU cycles than it is to figure out
1519 * if this is one of those cases.
1521 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
1522 if (strcmp(argv[0], x->cmd) == 0) {
1523 debug_printf_exec("running builtin '%s'\n", argv[0]);
1524 rcode = x->function(argv);
1530 /* Check if the command matches any busybox applets */
1531 #if ENABLE_FEATURE_SH_STANDALONE
1532 if (strchr(argv[0], '/') == NULL) {
1533 int a = find_applet_by_name(argv[0]);
1535 if (APPLET_IS_NOEXEC(a)) {
1536 debug_printf_exec("running applet '%s'\n", argv[0]);
1537 // is it ok that run_applet_no_and_exit() does exit(), not _exit()?
1538 run_applet_no_and_exit(a, argv);
1540 /* re-exec ourselves with the new arguments */
1541 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
1542 execvp(bb_busybox_exec_path, argv);
1543 /* If they called chroot or otherwise made the binary no longer
1544 * executable, fall through */
1549 debug_printf_exec("execing '%s'\n", argv[0]);
1550 execvp(argv[0], argv);
1551 bb_perror_msg("can't exec '%s'", argv[0]);
1552 _exit(EXIT_FAILURE);
1555 /* Called after [v]fork() in run_pipe()
1557 static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded)
1560 pseudo_exec_argv(nommu_save, command->argv, command->assignment_cnt, argv_expanded);
1562 if (command->group) {
1564 bb_error_msg_and_die("nested lists are not supported on NOMMU");
1567 debug_printf_exec("pseudo_exec: run_list\n");
1568 rcode = run_list(command->group);
1569 /* OK to leak memory by not calling free_pipe_list,
1570 * since this process is about to exit */
1575 /* Can happen. See what bash does with ">foo" by itself. */
1576 debug_printf("trying to pseudo_exec null command\n");
1577 _exit(EXIT_SUCCESS);
1581 static const char *get_cmdtext(struct pipe *pi)
1587 /* This is subtle. ->cmdtext is created only on first backgrounding.
1588 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
1589 * On subsequent bg argv is trashed, but we won't use it */
1592 argv = pi->cmds[0].argv;
1593 if (!argv || !argv[0]) {
1594 pi->cmdtext = xzalloc(1);
1599 do len += strlen(*argv) + 1; while (*++argv);
1600 pi->cmdtext = p = xmalloc(len);
1601 argv = pi->cmds[0].argv;
1603 len = strlen(*argv);
1604 memcpy(p, *argv, len);
1612 static void insert_bg_job(struct pipe *pi)
1614 struct pipe *thejob;
1617 /* Linear search for the ID of the job to use */
1619 for (thejob = G.job_list; thejob; thejob = thejob->next)
1620 if (thejob->jobid >= pi->jobid)
1621 pi->jobid = thejob->jobid + 1;
1623 /* Add thejob to the list of running jobs */
1625 thejob = G.job_list = xmalloc(sizeof(*thejob));
1627 for (thejob = G.job_list; thejob->next; thejob = thejob->next)
1629 thejob->next = xmalloc(sizeof(*thejob));
1630 thejob = thejob->next;
1633 /* Physically copy the struct job */
1634 memcpy(thejob, pi, sizeof(struct pipe));
1635 thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
1636 /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
1637 for (i = 0; i < pi->num_cmds; i++) {
1638 // TODO: do we really need to have so many fields which are just dead weight
1639 // at execution stage?
1640 thejob->cmds[i].pid = pi->cmds[i].pid;
1641 /* all other fields are not used and stay zero */
1643 thejob->next = NULL;
1644 thejob->cmdtext = xstrdup(get_cmdtext(pi));
1646 /* We don't wait for background thejobs to return -- append it
1647 to the list of backgrounded thejobs and leave it alone */
1648 printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
1649 G.last_bg_pid = thejob->cmds[0].pid;
1650 G.last_jobid = thejob->jobid;
1653 static void remove_bg_job(struct pipe *pi)
1655 struct pipe *prev_pipe;
1657 if (pi == G.job_list) {
1658 G.job_list = pi->next;
1660 prev_pipe = G.job_list;
1661 while (prev_pipe->next != pi)
1662 prev_pipe = prev_pipe->next;
1663 prev_pipe->next = pi->next;
1666 G.last_jobid = G.job_list->jobid;
1671 /* Remove a backgrounded job */
1672 static void delete_finished_bg_job(struct pipe *pi)
1675 pi->stopped_cmds = 0;
1681 /* Check to see if any processes have exited -- if they
1682 * have, figure out why and see if a job has completed */
1683 static int checkjobs(struct pipe* fg_pipe)
1693 attributes = WUNTRACED;
1694 if (fg_pipe == NULL)
1695 attributes |= WNOHANG;
1697 /* Do we do this right?
1698 * bash-3.00# sleep 20 | false
1700 * [3]+ Stopped sleep 20 | false
1701 * bash-3.00# echo $?
1702 * 1 <========== bg pipe is not fully done, but exitcode is already known!
1705 //FIXME: non-interactive bash does not continue even if all processes in fg pipe
1706 //are stopped. Testcase: "cat | cat" in a script (not on command line)
1707 // + killall -STOP cat
1710 // TODO: safe_waitpid?
1711 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
1713 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
1715 if (WIFSTOPPED(status))
1716 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
1717 childpid, WSTOPSIG(status), WEXITSTATUS(status));
1718 if (WIFSIGNALED(status))
1719 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
1720 childpid, WTERMSIG(status), WEXITSTATUS(status));
1721 if (WIFEXITED(status))
1722 debug_printf_jobs("pid %d exited, exitcode %d\n",
1723 childpid, WEXITSTATUS(status));
1725 /* Were we asked to wait for fg pipe? */
1727 for (i = 0; i < fg_pipe->num_cmds; i++) {
1728 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
1729 if (fg_pipe->cmds[i].pid != childpid)
1731 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
1733 fg_pipe->cmds[i].pid = 0;
1734 fg_pipe->alive_cmds--;
1735 if (i == fg_pipe->num_cmds - 1) {
1736 /* last process gives overall exitstatus */
1737 rcode = WEXITSTATUS(status);
1738 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
1741 fg_pipe->cmds[i].is_stopped = 1;
1742 fg_pipe->stopped_cmds++;
1744 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
1745 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
1746 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
1747 /* All processes in fg pipe have exited/stopped */
1749 if (fg_pipe->alive_cmds)
1750 insert_bg_job(fg_pipe);
1754 /* There are still running processes in the fg pipe */
1755 goto wait_more; /* do waitpid again */
1757 /* it wasnt fg_pipe, look for process in bg pipes */
1761 /* We asked to wait for bg or orphaned children */
1762 /* No need to remember exitcode in this case */
1763 for (pi = G.job_list; pi; pi = pi->next) {
1764 for (i = 0; i < pi->num_cmds; i++) {
1765 if (pi->cmds[i].pid == childpid)
1766 goto found_pi_and_prognum;
1769 /* Happens when shell is used as init process (init=/bin/sh) */
1770 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
1771 continue; /* do waitpid again */
1773 found_pi_and_prognum:
1776 pi->cmds[i].pid = 0;
1778 if (!pi->alive_cmds) {
1779 printf(JOB_STATUS_FORMAT, pi->jobid,
1780 "Done", pi->cmdtext);
1781 delete_finished_bg_job(pi);
1785 pi->cmds[i].is_stopped = 1;
1789 } /* while (waitpid succeeds)... */
1791 /* wait found no children or failed */
1793 if (childpid && errno != ECHILD)
1794 bb_perror_msg("waitpid");
1799 static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1802 int rcode = checkjobs(fg_pipe);
1803 /* Job finished, move the shell to the foreground */
1804 p = getpgid(0); /* pgid of our process */
1805 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
1806 tcsetpgrp(G.interactive_fd, p);
1811 /* run_pipe() starts all the jobs, but doesn't wait for anything
1812 * to finish. See checkjobs().
1814 * return code is normally -1, when the caller has to wait for children
1815 * to finish to determine the exit status of the pipe. If the pipe
1816 * is a simple builtin command, however, the action is done by the
1817 * time run_pipe returns, and the exit code is provided as the
1820 * The input of the pipe is always stdin, the output is always
1821 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1822 * because it tries to avoid running the command substitution in
1823 * subshell, when that is in fact necessary. The subshell process
1824 * now has its stdout directed to the input of the appropriate pipe,
1825 * so this routine is noticeably simpler.
1827 * Returns -1 only if started some children. IOW: we have to
1828 * mask out retvals of builtins etc with 0xff!
1830 static int run_pipe(struct pipe *pi)
1834 int pipefds[2]; /* pipefds[0] is for reading */
1835 struct command *command;
1836 char **argv_expanded;
1838 const struct built_in_command *x;
1840 /* it is not always needed, but we aim to smaller code */
1841 int squirrel[] = { -1, -1, -1 };
1843 const int single_and_fg = (pi->num_cmds == 1 && pi->followup != PIPE_BG);
1845 debug_printf_exec("run_pipe start: single_and_fg=%d\n", single_and_fg);
1851 pi->stopped_cmds = 0;
1853 /* Check if this is a simple builtin (not part of a pipe).
1854 * Builtins within pipes have to fork anyway, and are handled in
1855 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1857 command = &(pi->cmds[0]);
1859 #if ENABLE_HUSH_FUNCTIONS
1860 if (single_and_fg && command->group && command->grp_type == GRP_FUNCTION) {
1861 /* We "execute" function definition */
1862 bb_error_msg("here we ought to remember function definition, and go on");
1863 return EXIT_SUCCESS;
1867 if (single_and_fg && command->group && command->grp_type == GRP_NORMAL) {
1868 debug_printf("non-subshell grouping\n");
1869 setup_redirects(command, squirrel);
1870 debug_printf_exec(": run_list\n");
1871 rcode = run_list(command->group) & 0xff;
1872 restore_redirects(squirrel);
1873 debug_printf_exec("run_pipe return %d\n", rcode);
1874 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
1878 argv = command->argv;
1879 argv_expanded = NULL;
1881 if (single_and_fg && argv != NULL) {
1882 char **new_env = NULL;
1883 char **old_env = NULL;
1885 i = command->assignment_cnt;
1886 if (i != 0 && argv[i] == NULL) {
1887 /* assignments, but no command: set local environment */
1888 for (i = 0; argv[i] != NULL; i++) {
1889 debug_printf("local environment set: %s\n", argv[i]);
1890 p = expand_string_to_string(argv[i]);
1891 set_local_var(p, 0);
1893 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1896 /* Expand the rest into (possibly) many strings each */
1897 argv_expanded = expand_strvec_to_strvec(argv + i);
1899 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
1900 if (strcmp(argv_expanded[0], x->cmd) != 0)
1902 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
1903 debug_printf("exec with redirects only\n");
1904 setup_redirects(command, NULL);
1905 rcode = EXIT_SUCCESS;
1906 goto clean_up_and_ret1;
1908 debug_printf("builtin inline %s\n", argv_expanded[0]);
1909 /* XXX setup_redirects acts on file descriptors, not FILEs.
1910 * This is perfect for work that comes after exec().
1911 * Is it really safe for inline use? Experimentally,
1912 * things seem to work with glibc. */
1913 setup_redirects(command, squirrel);
1914 new_env = expand_assignments(argv, command->assignment_cnt);
1915 old_env = putenv_all_and_save_old(new_env);
1916 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv_expanded[1]);
1917 rcode = x->function(argv_expanded) & 0xff;
1918 #if ENABLE_FEATURE_SH_STANDALONE
1921 restore_redirects(squirrel);
1922 free_strings_and_unsetenv(new_env, 1);
1923 putenv_all(old_env);
1924 free(old_env); /* not free_strings()! */
1926 free(argv_expanded);
1927 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
1928 debug_printf_exec("run_pipe return %d\n", rcode);
1931 #if ENABLE_FEATURE_SH_STANDALONE
1932 i = find_applet_by_name(argv_expanded[0]);
1933 if (i >= 0 && APPLET_IS_NOFORK(i)) {
1934 setup_redirects(command, squirrel);
1935 save_nofork_data(&G.nofork_save);
1936 new_env = expand_assignments(argv, command->assignment_cnt);
1937 old_env = putenv_all_and_save_old(new_env);
1938 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
1939 rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
1940 goto clean_up_and_ret;
1945 /* NB: argv_expanded may already be created, and that
1946 * might include `cmd` runs! Do not rerun it! We *must*
1947 * use argv_expanded if it's non-NULL */
1949 /* Disable job control signals for shell (parent) and
1950 * for initial child code after fork */
1951 set_jobctrl_sighandler(SIG_IGN);
1953 /* Going to fork a child per each pipe member */
1957 for (i = 0; i < pi->num_cmds; i++) {
1959 volatile nommu_save_t nommu_save;
1960 nommu_save.new_env = NULL;
1961 nommu_save.old_env = NULL;
1962 nommu_save.argv = NULL;
1964 command = &(pi->cmds[i]);
1965 if (command->argv) {
1966 debug_printf_exec(": pipe member '%s' '%s'...\n", command->argv[0], command->argv[1]);
1968 debug_printf_exec(": pipe member with no argv\n");
1970 /* pipes are inserted between pairs of commands */
1973 if ((i + 1) < pi->num_cmds)
1976 command->pid = BB_MMU ? fork() : vfork();
1977 if (!command->pid) { /* child */
1978 if (ENABLE_HUSH_JOB)
1979 die_sleep = 0; /* let nofork's xfuncs die */
1981 /* Every child adds itself to new process group
1982 * with pgid == pid_of_first_child_in_pipe */
1983 if (G.run_list_level == 1 && G.interactive_fd) {
1985 /* Don't do pgrp restore anymore on fatal signals */
1986 set_fatal_sighandler(SIG_DFL);
1988 if (pgrp < 0) /* true for 1st process only */
1990 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
1991 /* We do it in *every* child, not just first,
1993 tcsetpgrp(G.interactive_fd, pgrp);
1997 xmove_fd(nextin, 0);
1998 xmove_fd(pipefds[1], 1); /* write end */
2000 close(pipefds[0]); /* read end */
2001 /* Like bash, explicit redirects override pipes,
2002 * and the pipe fd is available for dup'ing. */
2003 setup_redirects(command, NULL);
2005 /* Restore default handlers just prior to exec */
2006 set_jobctrl_sighandler(SIG_DFL);
2007 set_misc_sighandler(SIG_DFL);
2008 signal(SIGCHLD, SIG_DFL);
2009 /* Stores to nommu_save list of env vars putenv'ed
2010 * (NOMMU, on MMU we don't need that) */
2011 /* cast away volatility... */
2012 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
2013 /* pseudo_exec() does not return */
2017 /* Clean up after vforked child */
2018 free(nommu_save.argv);
2019 free_strings_and_unsetenv(nommu_save.new_env, 1);
2020 putenv_all(nommu_save.old_env);
2022 free(argv_expanded);
2023 argv_expanded = NULL;
2024 if (command->pid < 0) { /* [v]fork failed */
2025 /* Clearly indicate, was it fork or vfork */
2026 bb_perror_msg(BB_MMU ? "fork" : "vfork");
2030 /* Second and next children need to know pid of first one */
2032 pi->pgrp = command->pid;
2038 if ((i + 1) < pi->num_cmds)
2039 close(pipefds[1]); /* write end */
2040 /* Pass read (output) pipe end to next iteration */
2041 nextin = pipefds[0];
2044 if (!pi->alive_cmds) {
2045 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
2049 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
2053 #ifndef debug_print_tree
2054 static void debug_print_tree(struct pipe *pi, int lvl)
2056 static const char *const PIPE[] = {
2062 static const char *RES[] = {
2063 [RES_NONE ] = "NONE" ,
2066 [RES_THEN ] = "THEN" ,
2067 [RES_ELIF ] = "ELIF" ,
2068 [RES_ELSE ] = "ELSE" ,
2071 #if ENABLE_HUSH_LOOPS
2072 [RES_FOR ] = "FOR" ,
2073 [RES_WHILE] = "WHILE",
2074 [RES_UNTIL] = "UNTIL",
2076 [RES_DONE ] = "DONE" ,
2078 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2081 #if ENABLE_HUSH_CASE
2082 [RES_CASE ] = "CASE" ,
2083 [RES_MATCH] = "MATCH",
2084 [RES_CASEI] = "CASEI",
2085 [RES_ESAC ] = "ESAC" ,
2087 [RES_XXXX ] = "XXXX" ,
2088 [RES_SNTX ] = "SNTX" ,
2090 static const char *const GRPTYPE[] = {
2093 #if ENABLE_HUSH_FUNCTIONS
2102 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2103 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2105 while (prn < pi->num_cmds) {
2106 struct command *command = &pi->cmds[prn];
2107 char **argv = command->argv;
2109 fprintf(stderr, "%*s prog %d assignment_cnt:%d", lvl*2, "", prn, command->assignment_cnt);
2110 if (command->group) {
2111 fprintf(stderr, " group %s: (argv=%p)\n",
2112 GRPTYPE[command->grp_type],
2114 debug_print_tree(command->group, lvl+1);
2118 if (argv) while (*argv) {
2119 fprintf(stderr, " '%s'", *argv);
2122 fprintf(stderr, "\n");
2131 /* NB: called by pseudo_exec, and therefore must not modify any
2132 * global data until exec/_exit (we can be a child after vfork!) */
2133 static int run_list(struct pipe *pi)
2135 #if ENABLE_HUSH_CASE
2136 char *case_word = NULL;
2138 #if ENABLE_HUSH_LOOPS
2139 struct pipe *loop_top = NULL;
2140 char *for_varname = NULL;
2141 char **for_lcur = NULL;
2142 char **for_list = NULL;
2144 smallint flag_skip = 1;
2145 smalluint rcode = 0; /* probably just for compiler */
2146 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
2147 smalluint cond_code = 0;
2149 enum { cond_code = 0, };
2151 /*enum reserved_style*/ smallint rword = RES_NONE;
2152 /*enum reserved_style*/ smallint skip_more_for_this_rword = RES_XXXX;
2154 debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
2156 #if ENABLE_HUSH_LOOPS
2157 /* Check syntax for "for" */
2158 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
2159 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
2161 /* current word is FOR or IN (BOLD in comments below) */
2162 if (cpipe->next == NULL) {
2163 syntax("malformed for");
2164 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
2167 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
2168 if (cpipe->next->res_word == RES_DO)
2170 /* next word is not "do". It must be "in" then ("FOR v in ...") */
2171 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
2172 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
2174 syntax("malformed for");
2175 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
2181 /* Past this point, all code paths should jump to ret: label
2182 * in order to return, no direct "return" statements please.
2183 * This helps to ensure that no memory is leaked. */
2186 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
2187 * We are saving state before entering outermost list ("while...done")
2188 * so that ctrl-Z will correctly background _entire_ outermost list,
2189 * not just a part of it (like "sleep 1 | exit 2") */
2190 if (++G.run_list_level == 1 && G.interactive_fd) {
2191 if (sigsetjmp(G.toplevel_jb, 1)) {
2192 /* ctrl-Z forked and we are parent; or ctrl-C.
2193 * Sighandler has longjmped us here */
2194 signal(SIGINT, SIG_IGN);
2195 signal(SIGTSTP, SIG_IGN);
2196 /* Restore level (we can be coming from deep inside
2198 G.run_list_level = 1;
2199 #if ENABLE_FEATURE_SH_STANDALONE
2200 if (G.nofork_save.saved) { /* if save area is valid */
2201 debug_printf_jobs("exiting nofork early\n");
2202 restore_nofork_data(&G.nofork_save);
2205 if (G.ctrl_z_flag) {
2206 /* ctrl-Z has forked and stored pid of the child in pi->pid.
2207 * Remember this child as background job */
2210 /* ctrl-C. We just stop doing whatever we were doing */
2213 USE_HUSH_LOOPS(loop_top = NULL;)
2214 USE_HUSH_LOOPS(G.depth_of_loop = 0;)
2218 /* ctrl-Z handler will store pid etc in pi */
2219 G.toplevel_list = pi;
2221 #if ENABLE_FEATURE_SH_STANDALONE
2222 G.nofork_save.saved = 0; /* in case we will run a nofork later */
2224 signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
2225 signal(SIGINT, handler_ctrl_c);
2229 /* Go through list of pipes, (maybe) executing them. */
2230 for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
2231 IF_HAS_KEYWORDS(rword = pi->res_word;)
2232 IF_HAS_NO_KEYWORDS(rword = RES_NONE;)
2233 debug_printf_exec(": rword=%d cond_code=%d skip_more=%d\n",
2234 rword, cond_code, skip_more_for_this_rword);
2235 #if ENABLE_HUSH_LOOPS
2236 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
2237 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
2239 /* start of a loop: remember where loop starts */
2244 if (rword == skip_more_for_this_rword && flag_skip) {
2245 if (pi->followup == PIPE_SEQ)
2247 /* it is "<false> && CMD" or "<true> || CMD"
2248 * and we should not execute CMD */
2252 skip_more_for_this_rword = RES_XXXX;
2255 if (rword == RES_THEN) {
2256 /* "if <false> THEN cmd": skip cmd */
2260 if (rword == RES_ELSE || rword == RES_ELIF) {
2261 /* "if <true> then ... ELSE/ELIF cmd":
2262 * skip cmd and all following ones */
2267 #if ENABLE_HUSH_LOOPS
2268 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
2270 /* first loop through for */
2272 static const char encoded_dollar_at[] ALIGN1 = {
2273 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
2274 }; /* encoded representation of "$@" */
2275 static const char *const encoded_dollar_at_argv[] = {
2276 encoded_dollar_at, NULL
2277 }; /* argv list with one element: "$@" */
2280 vals = (char**)encoded_dollar_at_argv;
2281 if (pi->next->res_word == RES_IN) {
2282 /* if no variable values after "in" we skip "for" */
2283 if (!pi->next->cmds[0].argv)
2285 vals = pi->next->cmds[0].argv;
2286 } /* else: "for var; do..." -> assume "$@" list */
2287 /* create list of variable values */
2288 debug_print_strings("for_list made from", vals);
2289 for_list = expand_strvec_to_strvec(vals);
2290 for_lcur = for_list;
2291 debug_print_strings("for_list", for_list);
2292 for_varname = pi->cmds[0].argv[0];
2293 pi->cmds[0].argv[0] = NULL;
2295 free(pi->cmds[0].argv[0]);
2297 /* "for" loop is over, clean up */
2301 pi->cmds[0].argv[0] = for_varname;
2304 /* insert next value from for_lcur */
2305 //TODO: does it need escaping?
2306 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
2307 pi->cmds[0].assignment_cnt = 1;
2309 if (rword == RES_IN) /* "for v IN list;..." - "in" has no cmds anyway */
2311 if (rword == RES_DONE) {
2312 continue; /* "done" has no cmds too */
2315 #if ENABLE_HUSH_CASE
2316 if (rword == RES_CASE) {
2317 case_word = expand_strvec_to_string(pi->cmds->argv);
2320 if (rword == RES_MATCH) {
2323 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
2325 /* all prev words didn't match, does this one match? */
2326 argv = pi->cmds->argv;
2328 char *pattern = expand_string_to_string(*argv);
2329 /* TODO: which FNM_xxx flags to use? */
2330 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
2332 if (cond_code == 0) { /* match! we will execute this branch */
2333 free(case_word); /* make future "word)" stop */
2341 if (rword == RES_CASEI) { /* inside of a case branch */
2343 continue; /* not matched yet, skip this pipe */
2346 if (pi->num_cmds == 0)
2349 /* After analyzing all keywords and conditions, we decided
2350 * to execute this pipe. NB: has to do checkjobs(NULL)
2351 * after run_pipe() to collect any background children,
2352 * even if list execution is to be stopped. */
2353 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
2356 #if ENABLE_HUSH_LOOPS
2357 G.flag_break_continue = 0;
2359 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
2361 /* we only ran a builtin: rcode is already known
2362 * and we don't need to wait for anything. */
2363 #if ENABLE_HUSH_LOOPS
2364 /* was it "break" or "continue"? */
2365 if (G.flag_break_continue) {
2366 smallint fbc = G.flag_break_continue;
2367 /* we might fall into outer *loop*,
2368 * don't want to break it too */
2370 G.depth_break_continue--;
2371 if (G.depth_break_continue == 0)
2372 G.flag_break_continue = 0;
2373 /* else: e.g. "continue 2" should *break* once, *then* continue */
2374 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
2375 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
2376 goto check_jobs_and_break;
2377 /* "continue": simulate end of loop */
2382 } else if (pi->followup == PIPE_BG) {
2383 /* what does bash do with attempts to background builtins? */
2384 /* even bash 3.2 doesn't do that well with nested bg:
2385 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
2386 * I'm NOT treating inner &'s as jobs */
2388 if (G.run_list_level == 1)
2391 rcode = 0; /* EXIT_SUCCESS */
2394 if (G.run_list_level == 1 && G.interactive_fd) {
2395 /* waits for completion, then fg's main shell */
2396 rcode = checkjobs_and_fg_shell(pi);
2397 debug_printf_exec(": checkjobs_and_fg_shell returned %d\n", rcode);
2400 { /* this one just waits for completion */
2401 rcode = checkjobs(pi);
2402 debug_printf_exec(": checkjobs returned %d\n", rcode);
2406 debug_printf_exec(": setting last_return_code=%d\n", rcode);
2407 G.last_return_code = rcode;
2409 /* Analyze how result affects subsequent commands */
2411 if (rword == RES_IF || rword == RES_ELIF)
2414 #if ENABLE_HUSH_LOOPS
2415 if (rword == RES_WHILE) {
2417 rcode = 0; /* "while false; do...done" - exitcode 0 */
2418 goto check_jobs_and_break;
2421 if (rword == RES_UNTIL) {
2423 check_jobs_and_break:
2429 if ((rcode == 0 && pi->followup == PIPE_OR)
2430 || (rcode != 0 && pi->followup == PIPE_AND)
2432 skip_more_for_this_rword = rword;
2438 if (G.ctrl_z_flag) {
2439 /* ctrl-Z forked somewhere in the past, we are the child,
2440 * and now we completed running the list. Exit. */
2445 if (!--G.run_list_level && G.interactive_fd) {
2446 signal(SIGTSTP, SIG_IGN);
2447 signal(SIGINT, SIG_IGN);
2450 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
2451 #if ENABLE_HUSH_LOOPS
2456 #if ENABLE_HUSH_CASE
2462 /* return code is the exit status of the pipe */
2463 static int free_pipe(struct pipe *pi, int indent)
2466 struct command *command;
2467 struct redir_struct *r, *rnext;
2468 int a, i, ret_code = 0;
2470 if (pi->stopped_cmds > 0)
2472 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2473 for (i = 0; i < pi->num_cmds; i++) {
2474 command = &pi->cmds[i];
2475 debug_printf_clean("%s command %d:\n", indenter(indent), i);
2476 if (command->argv) {
2477 for (a = 0, p = command->argv; *p; a++, p++) {
2478 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
2480 free_strings(command->argv);
2481 command->argv = NULL;
2482 } else if (command->group) {
2483 debug_printf_clean("%s begin group (grp_type:%d)\n", indenter(indent), command->grp_type);
2484 ret_code = free_pipe_list(command->group, indent+3);
2485 debug_printf_clean("%s end group\n", indenter(indent));
2487 debug_printf_clean("%s (nil)\n", indenter(indent));
2489 for (r = command->redirects; r; r = rnext) {
2490 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->rd_type].descrip);
2492 /* guard against the case >$FOO, where foo is unset or blank */
2493 if (r->rd_filename) {
2494 debug_printf_clean(" %s\n", r->rd_filename);
2495 free(r->rd_filename);
2496 r->rd_filename = NULL;
2499 debug_printf_clean("&%d\n", r->dup);
2504 command->redirects = NULL;
2506 free(pi->cmds); /* children are an array, they get freed all at once */
2515 static int free_pipe_list(struct pipe *head, int indent)
2517 int rcode = 0; /* if list has no members */
2518 struct pipe *pi, *next;
2520 for (pi = head; pi; pi = next) {
2522 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
2524 rcode = free_pipe(pi, indent);
2525 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
2527 /*pi->next = NULL;*/
2533 /* Select which version we will use */
2534 static int run_and_free_list(struct pipe *pi)
2537 debug_printf_exec("run_and_free_list entered\n");
2539 debug_printf_exec(": run_list with %d members\n", pi->num_cmds);
2540 rcode = run_list(pi);
2542 /* free_pipe_list has the side effect of clearing memory.
2543 * In the long run that function can be merged with run_list,
2544 * but doing that now would hobble the debugging effort. */
2545 free_pipe_list(pi, /* indent: */ 0);
2546 debug_printf_exec("run_and_free_list return %d\n", rcode);
2551 /* expand_strvec_to_strvec() takes a list of strings, expands
2552 * all variable references within and returns a pointer to
2553 * a list of expanded strings, possibly with larger number
2554 * of strings. (Think VAR="a b"; echo $VAR).
2555 * This new list is allocated as a single malloc block.
2556 * NULL-terminated list of char* pointers is at the beginning of it,
2557 * followed by strings themself.
2558 * Caller can deallocate entire list by single free(list). */
2560 /* Store given string, finalizing the word and starting new one whenever
2561 * we encounter IFS char(s). This is used for expanding variable values.
2562 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
2563 static int expand_on_ifs(o_string *output, int n, const char *str)
2566 int word_len = strcspn(str, G.ifs);
2568 if (output->o_quote || !output->o_glob)
2569 o_addQstr(output, str, word_len);
2570 else /* protect backslashes against globbing up :) */
2571 o_addstr_duplicate_backslash(output, str, word_len);
2574 if (!*str) /* EOL - do not finalize word */
2576 o_addchr(output, '\0');
2577 debug_print_list("expand_on_ifs", output, n);
2578 n = o_save_ptr(output, n);
2579 str += strspn(str, G.ifs); /* skip ifs chars */
2581 debug_print_list("expand_on_ifs[1]", output, n);
2585 /* Expand all variable references in given string, adding words to list[]
2586 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2587 * to be filled). This routine is extremely tricky: has to deal with
2588 * variables/parameters with whitespace, $* and $@, and constructs like
2589 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
2590 static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
2592 /* or_mask is either 0 (normal case) or 0x80
2593 * (expansion of right-hand side of assignment == 1-element expand.
2594 * It will also do no globbing, and thus we must not backslash-quote!) */
2596 char first_ch, ored_ch;
2603 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
2604 debug_print_list("expand_vars_to_list", output, n);
2605 n = o_save_ptr(output, n);
2606 debug_print_list("expand_vars_to_list[0]", output, n);
2608 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
2609 #if ENABLE_HUSH_TICK
2610 o_string subst_result = NULL_O_STRING;
2612 o_addstr(output, arg, p - arg);
2613 debug_print_list("expand_vars_to_list[1]", output, n);
2615 p = strchr(p, SPECIAL_VAR_SYMBOL);
2617 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
2618 /* "$@" is special. Even if quoted, it can still
2619 * expand to nothing (not even an empty string) */
2620 if ((first_ch & 0x7f) != '@')
2621 ored_ch |= first_ch;
2623 switch (first_ch & 0x7f) {
2624 /* Highest bit in first_ch indicates that var is double-quoted */
2626 val = utoa(G.root_pid);
2628 case '!': /* bg pid */
2629 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
2631 case '?': /* exitcode */
2632 val = utoa(G.last_return_code);
2634 case '#': /* argc */
2635 val = utoa(G.global_argc ? G.global_argc-1 : 0);
2640 if (!G.global_argv[i])
2642 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
2643 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
2644 smallint sv = output->o_quote;
2645 /* unquoted var's contents should be globbed, so don't quote */
2646 output->o_quote = 0;
2647 while (G.global_argv[i]) {
2648 n = expand_on_ifs(output, n, G.global_argv[i]);
2649 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
2650 if (G.global_argv[i++][0] && G.global_argv[i]) {
2651 /* this argv[] is not empty and not last:
2652 * put terminating NUL, start new word */
2653 o_addchr(output, '\0');
2654 debug_print_list("expand_vars_to_list[2]", output, n);
2655 n = o_save_ptr(output, n);
2656 debug_print_list("expand_vars_to_list[3]", output, n);
2659 output->o_quote = sv;
2661 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2662 * and in this case should treat it like '$*' - see 'else...' below */
2663 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
2665 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2666 if (++i >= G.global_argc)
2668 o_addchr(output, '\0');
2669 debug_print_list("expand_vars_to_list[4]", output, n);
2670 n = o_save_ptr(output, n);
2672 } else { /* quoted $*: add as one word */
2674 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
2675 if (!G.global_argv[++i])
2678 o_addchr(output, G.ifs[0]);
2682 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
2683 /* "Empty variable", used to make "" etc to not disappear */
2687 #if ENABLE_HUSH_TICK
2688 case '`': { /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
2689 struct in_str input;
2692 //TODO: can we just stuff it into "output" directly?
2693 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
2694 setup_string_in_str(&input, arg);
2695 process_command_subs(&subst_result, &input, NULL);
2696 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
2697 val = subst_result.data;
2701 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
2703 arg[0] = first_ch & 0x7f;
2704 if (isdigit(arg[0])) {
2706 if (i < G.global_argc)
2707 val = G.global_argv[i];
2708 /* else val remains NULL: $N with too big N */
2710 val = lookup_param(arg);
2712 #if ENABLE_HUSH_TICK
2715 *p = SPECIAL_VAR_SYMBOL;
2716 if (!(first_ch & 0x80)) { /* unquoted $VAR */
2717 debug_printf_expand("unquoted '%s', output->o_quote:%d\n", val, output->o_quote);
2719 /* unquoted var's contents should be globbed, so don't quote */
2720 smallint sv = output->o_quote;
2721 output->o_quote = 0;
2722 n = expand_on_ifs(output, n, val);
2724 output->o_quote = sv;
2726 } else { /* quoted $VAR, val will be appended below */
2727 debug_printf_expand("quoted '%s', output->o_quote:%d\n", val, output->o_quote);
2731 o_addQstr(output, val, strlen(val));
2734 #if ENABLE_HUSH_TICK
2735 o_free(&subst_result);
2738 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2741 debug_print_list("expand_vars_to_list[a]", output, n);
2742 /* this part is literal, and it was already pre-quoted
2743 * if needed (much earlier), do not use o_addQstr here! */
2744 o_addstr(output, arg, strlen(arg) + 1);
2745 debug_print_list("expand_vars_to_list[b]", output, n);
2746 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2747 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2750 /* allow to reuse list[n] later without re-growth */
2751 output->has_empty_slot = 1;
2753 o_addchr(output, '\0');
2758 static char **expand_variables(char **argv, int or_mask)
2763 o_string output = NULL_O_STRING;
2765 if (or_mask & 0x100) {
2766 output.o_quote = 1; /* protect against globbing for "$var" */
2767 /* (unquoted $var will temporarily switch it off) */
2774 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
2777 debug_print_list("expand_variables", &output, n);
2779 /* output.data (malloced in one block) gets returned in "list" */
2780 list = o_finalize_list(&output, n);
2781 debug_print_strings("expand_variables[1]", list);
2785 static char **expand_strvec_to_strvec(char **argv)
2787 return expand_variables(argv, 0x100);
2790 /* Used for expansion of right hand of assignments */
2791 /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2793 static char *expand_string_to_string(const char *str)
2795 char *argv[2], **list;
2797 argv[0] = (char*)str;
2799 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2801 if (!list[0] || list[1])
2802 bb_error_msg_and_die("BUG in varexp2");
2803 /* actually, just move string 2*sizeof(char*) bytes back */
2804 strcpy((char*)list, list[0]);
2805 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2809 /* Used for "eval" builtin */
2810 static char* expand_strvec_to_string(char **argv)
2814 list = expand_variables(argv, 0x80);
2815 /* Convert all NULs to spaces */
2820 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2821 bb_error_msg_and_die("BUG in varexp3");
2822 list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
2826 strcpy((char*)list, list[0]);
2827 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2832 /* Used to get/check local shell variables */
2833 static struct variable *get_local_var(const char *name)
2835 struct variable *cur;
2841 for (cur = G.top_var; cur; cur = cur->next) {
2842 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
2848 /* str holds "NAME=VAL" and is expected to be malloced.
2849 * We take ownership of it. */
2850 static int set_local_var(char *str, int flg_export)
2852 struct variable *cur;
2856 value = strchr(str, '=');
2857 if (!value) { /* not expected to ever happen? */
2862 name_len = value - str + 1; /* including '=' */
2863 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
2865 if (strncmp(cur->varstr, str, name_len) != 0) {
2867 /* Bail out. Note that now cur points
2868 * to last var in linked list */
2874 /* We found an existing var with this name */
2876 if (cur->flg_read_only) {
2877 bb_error_msg("%s: readonly variable", str);
2881 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
2882 unsetenv(str); /* just in case */
2884 if (strcmp(cur->varstr, str) == 0) {
2889 if (cur->max_len >= strlen(str)) {
2890 /* This one is from startup env, reuse space */
2891 strcpy(cur->varstr, str);
2894 /* max_len == 0 signifies "malloced" var, which we can
2895 * (and has to) free */
2899 goto set_str_and_exp;
2902 /* Not found - create next variable struct */
2903 cur->next = xzalloc(sizeof(*cur));
2910 cur->flg_export = 1;
2911 if (cur->flg_export) {
2912 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
2913 return putenv(cur->varstr);
2918 static void unset_local_var(const char *name)
2920 struct variable *cur;
2921 struct variable *prev = prev; /* for gcc */
2926 name_len = strlen(name);
2929 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
2930 if (cur->flg_read_only) {
2931 bb_error_msg("%s: readonly variable", name);
2934 /* prev is ok to use here because 1st variable, HUSH_VERSION,
2935 * is ro, and we cannot reach this code on the 1st pass */
2936 prev->next = cur->next;
2937 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
2938 bb_unsetenv(cur->varstr);
2949 /* The src parameter allows us to peek forward to a possible &n syntax
2950 * for file descriptor duplication, e.g., "2>&1".
2951 * Return code is 0 normally, 1 if a syntax error is detected in src.
2952 * Resource errors (in xmalloc) cause the process to exit */
2953 static int setup_redirect(struct parse_context *ctx, int fd, redir_type style,
2954 struct in_str *input)
2956 struct command *command = ctx->command;
2957 struct redir_struct *redir = command->redirects;
2958 struct redir_struct *last_redir = NULL;
2960 /* Create a new redir_struct and drop it onto the end of the linked list */
2963 redir = redir->next;
2965 redir = xzalloc(sizeof(struct redir_struct));
2966 /* redir->next = NULL; */
2967 /* redir->rd_filename = NULL; */
2969 last_redir->next = redir;
2971 command->redirects = redir;
2974 redir->rd_type = style;
2975 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
2977 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2979 /* Check for a '2>&1' type redirect */
2980 redir->dup = redirect_dup_num(input);
2981 if (redir->dup == -2)
2982 return 1; /* syntax error */
2983 if (redir->dup != -1) {
2984 /* Erik had a check here that the file descriptor in question
2985 * is legit; I postpone that to "run time"
2986 * A "-" representation of "close me" shows up as a -3 here */
2987 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2989 /* We do _not_ try to open the file that src points to,
2990 * since we need to return and let src be expanded first.
2991 * Set ctx->pending_redirect, so we know what to do at the
2992 * end of the next parsed word. */
2993 ctx->pending_redirect = redir;
2998 static struct pipe *new_pipe(void)
3001 pi = xzalloc(sizeof(struct pipe));
3002 /*pi->followup = 0; - deliberately invalid value */
3003 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
3007 static void initialize_context(struct parse_context *ctx)
3009 memset(ctx, 0, sizeof(*ctx));
3010 ctx->pipe = ctx->list_head = new_pipe();
3011 /* Create the memory for command, roughly:
3012 * ctx->pipe->cmds = new struct command;
3013 * ctx->command = &ctx->pipe->cmds[0];
3018 /* If a reserved word is found and processed, parse context is modified
3019 * and 1 is returned.
3020 * Handles if, then, elif, else, fi, for, while, until, do, done.
3021 * case, function, and select are obnoxious, save those for later.
3024 struct reserved_combo {
3027 unsigned char assignment_flag;
3031 FLAG_END = (1 << RES_NONE ),
3033 FLAG_IF = (1 << RES_IF ),
3034 FLAG_THEN = (1 << RES_THEN ),
3035 FLAG_ELIF = (1 << RES_ELIF ),
3036 FLAG_ELSE = (1 << RES_ELSE ),
3037 FLAG_FI = (1 << RES_FI ),
3039 #if ENABLE_HUSH_LOOPS
3040 FLAG_FOR = (1 << RES_FOR ),
3041 FLAG_WHILE = (1 << RES_WHILE),
3042 FLAG_UNTIL = (1 << RES_UNTIL),
3043 FLAG_DO = (1 << RES_DO ),
3044 FLAG_DONE = (1 << RES_DONE ),
3045 FLAG_IN = (1 << RES_IN ),
3047 #if ENABLE_HUSH_CASE
3048 FLAG_MATCH = (1 << RES_MATCH),
3049 FLAG_ESAC = (1 << RES_ESAC ),
3051 FLAG_START = (1 << RES_XXXX ),
3054 static const struct reserved_combo* match_reserved_word(o_string *word)
3056 /* Mostly a list of accepted follow-up reserved words.
3057 * FLAG_END means we are done with the sequence, and are ready
3058 * to turn the compound list into a command.
3059 * FLAG_START means the word must start a new compound list.
3061 static const struct reserved_combo reserved_list[] = {
3063 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3064 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
3065 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3066 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
3067 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
3068 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3070 #if ENABLE_HUSH_LOOPS
3071 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3072 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3073 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3074 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3075 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
3076 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3078 #if ENABLE_HUSH_CASE
3079 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3080 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3083 const struct reserved_combo *r;
3085 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3086 if (strcmp(word->data, r->literal) == 0)
3091 static int reserved_word(o_string *word, struct parse_context *ctx)
3093 #if ENABLE_HUSH_CASE
3094 static const struct reserved_combo reserved_match = {
3095 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3098 const struct reserved_combo *r;
3100 r = match_reserved_word(word);
3104 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3105 #if ENABLE_HUSH_CASE
3106 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
3107 /* "case word IN ..." - IN part starts first match part */
3108 r = &reserved_match;
3111 if (r->flag == 0) { /* '!' */
3112 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3114 IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
3116 ctx->ctx_inverted = 1;
3119 if (r->flag & FLAG_START) {
3120 struct parse_context *new;
3121 debug_printf("push stack\n");
3122 new = xmalloc(sizeof(*new));
3123 *new = *ctx; /* physical copy */
3124 initialize_context(ctx);
3126 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3128 ctx->ctx_res_w = RES_SNTX;
3131 ctx->ctx_res_w = r->res;
3132 ctx->old_flag = r->flag;
3133 if (ctx->old_flag & FLAG_END) {
3134 struct parse_context *old;
3135 debug_printf("pop stack\n");
3136 done_pipe(ctx, PIPE_SEQ);
3138 old->command->group = ctx->list_head;
3139 old->command->grp_type = GRP_NORMAL;
3140 *ctx = *old; /* physical copy */
3143 word->o_assignment = r->assignment_flag;
3148 //TODO: many, many callers don't check error from done_word()
3150 /* Word is complete, look at it and update parsing context.
3151 * Normal return is 0. Syntax errors return 1. */
3152 static int done_word(o_string *word, struct parse_context *ctx)
3154 struct command *command = ctx->command;
3156 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3157 if (word->length == 0 && word->nonnull == 0) {
3158 debug_printf_parse("done_word return 0: true null, ignored\n");
3161 /* If this word wasn't an assignment, next ones definitely
3162 * can't be assignments. Even if they look like ones. */
3163 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3164 && word->o_assignment != WORD_IS_KEYWORD
3166 word->o_assignment = NOT_ASSIGNMENT;
3168 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
3169 command->assignment_cnt++;
3170 word->o_assignment = MAYBE_ASSIGNMENT;
3173 if (ctx->pending_redirect) {
3174 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3175 * only if run as "bash", not "sh" */
3176 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3177 word->o_assignment = NOT_ASSIGNMENT;
3178 debug_printf("word stored in rd_filename: '%s'\n", word->data);
3180 /* "{ echo foo; } echo bar" - bad */
3181 /* NB: bash allows e.g. "if true; then { echo foo; } fi". TODO? */
3182 if (command->group) {
3184 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
3188 #if ENABLE_HUSH_CASE
3189 if (ctx->ctx_dsemicolon
3190 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3192 /* already done when ctx_dsemicolon was set to 1: */
3193 /* ctx->ctx_res_w = RES_MATCH; */
3194 ctx->ctx_dsemicolon = 0;
3198 if (!command->argv /* if it's the first word... */
3199 #if ENABLE_HUSH_LOOPS
3200 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3201 && ctx->ctx_res_w != RES_IN
3204 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
3205 if (reserved_word(word, ctx)) {
3207 debug_printf_parse("done_word return %d\n", (ctx->ctx_res_w == RES_SNTX));
3208 return (ctx->ctx_res_w == RES_SNTX);
3212 if (word->nonnull /* word had "xx" or 'xx' at least as part of it. */
3213 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3214 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3215 /* (otherwise it's known to be not empty and is already safe) */
3217 /* exclude "$@" - it can expand to no word despite "" */
3218 char *p = word->data;
3219 while (p[0] == SPECIAL_VAR_SYMBOL
3220 && (p[1] & 0x7f) == '@'
3221 && p[2] == SPECIAL_VAR_SYMBOL
3225 if (p == word->data || p[0] != '\0') {
3226 /* saw no "$@", or not only "$@" but some
3227 * real text is there too */
3228 /* insert "empty variable" reference, this makes
3229 * e.g. "", $empty"" etc to not disappear */
3230 o_addchr(word, SPECIAL_VAR_SYMBOL);
3231 o_addchr(word, SPECIAL_VAR_SYMBOL);
3234 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3235 debug_print_strings("word appended to argv", command->argv);
3239 ctx->pending_redirect = NULL;
3241 #if ENABLE_HUSH_LOOPS
3242 /* Force FOR to have just one word (variable name) */
3243 /* NB: basically, this makes hush see "for v in ..." syntax as if
3244 * as it is "for v; in ...". FOR and IN become two pipe structs
3246 if (ctx->ctx_res_w == RES_FOR) {
3247 //TODO: check that command->argv[0] is a valid variable name!
3248 done_pipe(ctx, PIPE_SEQ);
3251 #if ENABLE_HUSH_CASE
3252 /* Force CASE to have just one word */
3253 if (ctx->ctx_res_w == RES_CASE) {
3254 done_pipe(ctx, PIPE_SEQ);
3257 debug_printf_parse("done_word return 0\n");
3261 /* Command (member of a pipe) is complete. The only possible error here
3262 * is out of memory, in which case xmalloc exits. */
3263 static int done_command(struct parse_context *ctx)
3265 /* The command is really already in the pipe structure, so
3266 * advance the pipe counter and make a new, null command. */
3267 struct pipe *pi = ctx->pipe;
3268 struct command *command = ctx->command;
3271 if (command->group == NULL
3272 && command->argv == NULL
3273 && command->redirects == NULL
3275 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
3276 return pi->num_cmds;
3279 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
3281 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3284 /* Only real trickiness here is that the uncommitted
3285 * command structure is not counted in pi->num_cmds. */
3286 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3287 command = &pi->cmds[pi->num_cmds];
3288 memset(command, 0, sizeof(*command));
3290 ctx->command = command;
3291 /* but ctx->pipe and ctx->list_head remain unchanged */
3293 return pi->num_cmds; /* used only for 0/nonzero check */
3296 static void done_pipe(struct parse_context *ctx, pipe_style type)
3300 debug_printf_parse("done_pipe entered, followup %d\n", type);
3301 /* Close previous command */
3302 not_null = done_command(ctx);
3303 ctx->pipe->followup = type;
3304 IF_HAS_KEYWORDS(ctx->pipe->pi_inverted = ctx->ctx_inverted;)
3305 IF_HAS_KEYWORDS(ctx->ctx_inverted = 0;)
3306 IF_HAS_KEYWORDS(ctx->pipe->res_word = ctx->ctx_res_w;)
3308 /* Without this check, even just <enter> on command line generates
3309 * tree of three NOPs (!). Which is harmless but annoying.
3310 * IOW: it is safe to do it unconditionally.
3311 * RES_NONE case is for "for a in; do ..." (empty IN set)
3312 * to work, possibly other cases too. */
3313 if (not_null IF_HAS_KEYWORDS(|| ctx->ctx_res_w != RES_NONE)) {
3315 debug_printf_parse("done_pipe: adding new pipe: "
3316 "not_null:%d ctx->ctx_res_w:%d\n",
3317 not_null, ctx->ctx_res_w);
3319 ctx->pipe->next = new_p;
3321 ctx->command = NULL; /* needed! */
3322 /* RES_THEN, RES_DO etc are "sticky" -
3323 * they remain set for commands inside if/while.
3324 * This is used to control execution.
3325 * RES_FOR and RES_IN are NOT sticky (needed to support
3326 * cases where variable or value happens to match a keyword):
3328 #if ENABLE_HUSH_LOOPS
3329 if (ctx->ctx_res_w == RES_FOR
3330 || ctx->ctx_res_w == RES_IN)
3331 ctx->ctx_res_w = RES_NONE;
3333 #if ENABLE_HUSH_CASE
3334 if (ctx->ctx_res_w == RES_MATCH)
3335 ctx->ctx_res_w = RES_CASEI;
3337 /* Create the memory for command, roughly:
3338 * ctx->pipe->cmds = new struct command;
3339 * ctx->command = &ctx->pipe->cmds[0];
3343 debug_printf_parse("done_pipe return\n");
3346 /* Peek ahead in the in_str to find out if we have a "&n" construct,
3347 * as in "2>&1", that represents duplicating a file descriptor.
3348 * Return either -2 (syntax error), -1 (no &), or the number found.
3350 static int redirect_dup_num(struct in_str *input)
3352 int ch, d = 0, ok = 0;
3354 if (ch != '&') return -1;
3356 i_getch(input); /* get the & */
3360 return -3; /* "-" represents "close me" */
3362 while (isdigit(ch)) {
3363 d = d*10 + (ch-'0');
3370 bb_error_msg("ambiguous redirect");
3374 /* If a redirect is immediately preceded by a number, that number is
3375 * supposed to tell which file descriptor to redirect. This routine
3376 * looks for such preceding numbers. In an ideal world this routine
3377 * needs to handle all the following classes of redirects...
3378 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3379 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3380 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3381 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3382 * A -1 output from this program means no valid number was found, so the
3383 * caller should use the appropriate default for this redirection.
3385 static int redirect_opt_num(o_string *o)
3391 for (num = 0; num < o->length; num++) {
3392 if (!isdigit(o->data[num])) {
3396 num = atoi(o->data);
3401 #if ENABLE_HUSH_TICK
3402 static FILE *generate_stream_from_list(struct pipe *head)
3405 int pid, channel[2];
3408 /* *** NOMMU WARNING *** */
3409 /* By using vfork here, we suspend parent till child exits or execs.
3410 * If child will not do it before it fills the pipe, it can block forever
3411 * in write(STDOUT_FILENO), and parent (shell) will be also stuck.
3413 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >TESTFILE
3414 * huge=`cat TESTFILE` # will block here forever
3417 pid = BB_MMU ? fork() : vfork();
3419 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
3420 if (pid == 0) { /* child */
3421 if (ENABLE_HUSH_JOB)
3422 die_sleep = 0; /* let nofork's xfuncs die */
3423 close(channel[0]); /* NB: close _first_, then move fd! */
3424 xmove_fd(channel[1], 1);
3425 /* Prevent it from trying to handle ctrl-z etc */
3427 G.run_list_level = 1;
3429 /* Process substitution is not considered to be usual
3430 * 'command execution'.
3431 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not. */
3432 /* Not needed, we are relying on it being disabled
3433 * everywhere outside actual command execution. */
3434 /*set_jobctrl_sighandler(SIG_IGN);*/
3435 set_misc_sighandler(SIG_DFL);
3436 /* Freeing 'head' here would break NOMMU. */
3437 _exit(run_list(head));
3440 pf = fdopen(channel[0], "r");
3442 /* 'head' is freed by the caller */
3445 /* Return code is exit status of the process that is run. */
3446 static int process_command_subs(o_string *dest,
3447 struct in_str *input,
3448 const char *subst_end)
3450 int retcode, ch, eol_cnt;
3451 o_string result = NULL_O_STRING;
3452 struct parse_context inner;
3454 struct in_str pipe_str;
3456 initialize_context(&inner);
3458 /* Recursion to generate command */
3459 retcode = parse_stream(&result, &inner, input, subst_end);
3461 return retcode; /* syntax error or EOF */
3462 done_word(&result, &inner);
3463 done_pipe(&inner, PIPE_SEQ);
3466 p = generate_stream_from_list(inner.list_head);
3469 close_on_exec_on(fileno(p));
3470 setup_file_in_str(&pipe_str, p);
3472 /* Now send results of command back into original context */
3474 while ((ch = i_getch(&pipe_str)) != EOF) {
3480 o_addchr(dest, '\n');
3483 o_addQchr(dest, ch);
3486 debug_printf("done reading from pipe, pclose()ing\n");
3487 /* This is the step that wait()s for the child. Should be pretty
3488 * safe, since we just read an EOF from its stdout. We could try
3489 * to do better, by using wait(), and keeping track of background jobs
3490 * at the same time. That would be a lot of work, and contrary
3491 * to the KISS philosophy of this program. */
3492 retcode = fclose(p);
3493 free_pipe_list(inner.list_head, /* indent: */ 0);
3494 debug_printf("closed FILE from child, retcode=%d\n", retcode);
3499 static int parse_group(o_string *dest, struct parse_context *ctx,
3500 struct in_str *input, int ch)
3502 /* dest contains characters seen prior to ( or {.
3503 * Typically it's empty, but for functions defs,
3504 * it contains function name (without '()'). */
3506 const char *endch = NULL;
3507 struct parse_context sub;
3508 struct command *command = ctx->command;
3510 debug_printf_parse("parse_group entered\n");
3511 #if ENABLE_HUSH_FUNCTIONS
3512 if (ch == 'F') { /* function definition? */
3513 bb_error_msg("aha '%s' is a function, parsing it...", dest->data);
3514 //command->fname = dest->data;
3515 command->grp_type = GRP_FUNCTION;
3516 //TODO: review every o_reset() location... do they handle all o_string fields correctly?
3517 memset(dest, 0, sizeof(*dest));
3520 if (command->argv /* word [word](... */
3521 || dest->length /* word(... */
3522 || dest->nonnull /* ""(... */
3525 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3528 initialize_context(&sub);
3532 command->grp_type = GRP_SUBSHELL;
3534 rcode = parse_stream(dest, &sub, input, endch);
3536 done_word(dest, &sub); /* finish off the final word in the subcontext */
3537 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
3538 command->group = sub.list_head;
3540 debug_printf_parse("parse_group return %d\n", rcode);
3542 /* command remains "open", available for possible redirects */
3545 /* Basically useful version until someone wants to get fancier,
3546 * see the bash man page under "Parameter Expansion" */
3547 static const char *lookup_param(const char *src)
3549 struct variable *var = get_local_var(src);
3551 return strchr(var->varstr, '=') + 1;
3555 #if ENABLE_HUSH_TICK
3556 /* Subroutines for copying $(...) and `...` things */
3557 static void add_till_backquote(o_string *dest, struct in_str *input);
3559 static void add_till_single_quote(o_string *dest, struct in_str *input)
3562 int ch = i_getch(input);
3570 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3571 static void add_till_double_quote(o_string *dest, struct in_str *input)
3574 int ch = i_getch(input);
3577 if (ch == '\\') { /* \x. Copy both chars. */
3579 ch = i_getch(input);
3585 add_till_backquote(dest, input);
3589 //if (ch == '$') ...
3592 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3594 * "Within the backquoted style of command substitution, backslash
3595 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3596 * The search for the matching backquote shall be satisfied by the first
3597 * backquote found without a preceding backslash; during this search,
3598 * if a non-escaped backquote is encountered within a shell comment,
3599 * a here-document, an embedded command substitution of the $(command)
3600 * form, or a quoted string, undefined results occur. A single-quoted
3601 * or double-quoted string that begins, but does not end, within the
3602 * "`...`" sequence produces undefined results."
3604 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3606 static void add_till_backquote(o_string *dest, struct in_str *input)
3609 int ch = i_getch(input);
3612 if (ch == '\\') { /* \x. Copy both chars unless it is \` */
3613 int ch2 = i_getch(input);
3614 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
3623 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3624 * quoting and nested ()s.
3625 * "With the $(command) style of command substitution, all characters
3626 * following the open parenthesis to the matching closing parenthesis
3627 * constitute the command. Any valid shell script can be used for command,
3628 * except a script consisting solely of redirections which produces
3629 * unspecified results."
3631 * echo $(echo '(TEST)' BEST) (TEST) BEST
3632 * echo $(echo 'TEST)' BEST) TEST) BEST
3633 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3635 static void add_till_closing_curly_brace(o_string *dest, struct in_str *input)
3639 int ch = i_getch(input);
3649 add_till_single_quote(dest, input);
3654 add_till_double_quote(dest, input);
3658 if (ch == '\\') { /* \x. Copy verbatim. Important for \(, \) */
3659 ch = i_getch(input);
3667 #endif /* ENABLE_HUSH_TICK */
3669 /* Return code: 0 for OK, 1 for syntax error */
3670 static int handle_dollar(o_string *dest, struct in_str *input)
3672 int ch = i_peek(input); /* first character after the $ */
3673 unsigned char quote_mask = dest->o_quote ? 0x80 : 0;
3675 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
3679 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3681 debug_printf_parse(": '%c'\n", ch);
3682 o_addchr(dest, ch | quote_mask);
3685 if (!isalnum(ch) && ch != '_')
3689 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3690 } else if (isdigit(ch)) {
3693 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3694 debug_printf_parse(": '%c'\n", ch);
3695 o_addchr(dest, ch | quote_mask);
3696 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3697 } else switch (ch) {
3699 case '!': /* last bg pid */
3700 case '?': /* last exit code */
3701 case '#': /* number of args */
3702 case '*': /* args */
3703 case '@': /* args */
3704 goto make_one_char_var;
3706 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3708 /* XXX maybe someone will try to escape the '}' */
3710 ch = i_getch(input);
3713 if (!isalnum(ch) && ch != '_') {
3714 syntax("unterminated ${name}");
3715 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3718 debug_printf_parse(": '%c'\n", ch);
3719 o_addchr(dest, ch | quote_mask);
3722 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3724 #if ENABLE_HUSH_TICK
3726 //int pos = dest->length;
3728 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3729 o_addchr(dest, quote_mask | '`');
3730 add_till_closing_curly_brace(dest, input);
3731 //debug_printf_subst("SUBST RES2 '%s'\n", dest->data + pos);
3732 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3739 if (isalnum(ch)) { /* it's $_name or $_123 */
3745 /* still unhandled, but should be eventually */
3746 bb_error_msg("unhandled syntax: $%c", ch);
3750 o_addQchr(dest, '$');
3752 debug_printf_parse("handle_dollar return 0\n");
3756 /* Scan input, call done_word() whenever full IFS delimited word was seen.
3757 * Call done_pipe if '\n' was seen (and end_trigger != NULL).
3758 * Return code is 0 if end_trigger char is met,
3759 * -1 on EOF (but if end_trigger == NULL then return 0),
3760 * 1 for syntax error */
3761 static int parse_stream(o_string *dest, struct parse_context *ctx,
3762 struct in_str *input, const char *end_trigger)
3766 redir_type redir_style;
3767 int shadow_quote = dest->o_quote;
3770 /* Only double-quote state is handled in the state variable dest->o_quote.
3771 * A single-quote triggers a bypass of the main loop until its mate is
3772 * found. When recursing, quote state is passed in via dest->o_quote. */
3774 debug_printf_parse("parse_stream entered, end_trigger='%s' dest->o_assignment:%d\n", end_trigger, dest->o_assignment);
3779 ch = i_getch(input);
3783 next = i_peek(input);
3786 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
3787 ch, ch, m, dest->o_quote);
3788 if (m == CHAR_ORDINARY
3789 || (m != CHAR_SPECIAL && shadow_quote)
3792 syntax("unterminated \"");
3793 debug_printf_parse("parse_stream return 1: unterminated \"\n");
3796 o_addQchr(dest, ch);
3797 if ((dest->o_assignment == MAYBE_ASSIGNMENT
3798 || dest->o_assignment == WORD_IS_KEYWORD)
3800 && is_assignment(dest->data)
3802 dest->o_assignment = DEFINITELY_ASSIGNMENT;
3806 if (m == CHAR_IFS) {
3807 if (done_word(dest, ctx)) {
3808 debug_printf_parse("parse_stream return 1: done_word!=0\n");
3813 /* If we aren't performing a substitution, treat
3814 * a newline as a command separator.
3815 * [why we don't handle it exactly like ';'? --vda] */
3816 if (end_trigger && ch == '\n') {
3817 #if ENABLE_HUSH_CASE
3818 /* "case ... in <newline> word) ..." -
3819 * newlines are ignored (but ';' wouldn't be) */
3820 if (dest->length == 0 // && argv[0] == NULL
3821 && ctx->ctx_res_w == RES_MATCH
3826 done_pipe(ctx, PIPE_SEQ);
3827 dest->o_assignment = MAYBE_ASSIGNMENT;
3831 if (!shadow_quote && strchr(end_trigger, ch)) {
3832 /* Special case: (...word) makes last word terminate,
3833 * as if ';' is seen */
3835 done_word(dest, ctx);
3837 done_pipe(ctx, PIPE_SEQ);
3838 dest->o_assignment = MAYBE_ASSIGNMENT;
3841 IF_HAS_KEYWORDS(|| (ctx->ctx_res_w == RES_NONE && ctx->old_flag == 0))
3843 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
3851 if (dest->o_assignment == MAYBE_ASSIGNMENT) {
3852 /* ch is a special char and thus this word
3853 * cannot be an assignment: */
3854 dest->o_assignment = NOT_ASSIGNMENT;
3859 if (dest->length == 0 && !shadow_quote) {
3862 if (ch == EOF || ch == '\n')
3867 o_addQchr(dest, ch);
3873 debug_printf_parse("parse_stream return 1: \\<eof>\n");
3877 * "The backslash retains its special meaning [in "..."]
3878 * only when followed by one of the following characters:
3879 * $, `, ", \, or <newline>. A double quote may be quoted
3880 * within double quotes by preceding it with a backslash.
3881 * If enabled, history expansion will be performed unless
3882 * an ! appearing in double quotes is escaped using
3883 * a backslash. The backslash preceding the ! is not removed."
3885 if (shadow_quote) { //NOT SURE dest->o_quote) {
3886 if (strchr("$`\"\\", next) != NULL) {
3887 o_addqchr(dest, i_getch(input));
3889 o_addqchr(dest, '\\');
3892 o_addchr(dest, '\\');
3893 o_addchr(dest, i_getch(input));
3897 if (handle_dollar(dest, input) != 0) {
3898 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3905 ch = i_getch(input);
3907 syntax("unterminated '");
3908 debug_printf_parse("parse_stream return 1: unterminated '\n");
3913 if (dest->o_assignment == NOT_ASSIGNMENT)
3914 o_addqchr(dest, ch);
3921 shadow_quote ^= 1; /* invert */
3922 if (dest->o_assignment == NOT_ASSIGNMENT)
3925 #if ENABLE_HUSH_TICK
3927 //int pos = dest->length;
3928 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3929 o_addchr(dest, shadow_quote /*or dest->o_quote??*/ ? 0x80 | '`' : '`');
3930 add_till_backquote(dest, input);
3931 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3932 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
3937 redir_fd = redirect_opt_num(dest);
3938 done_word(dest, ctx);
3939 redir_style = REDIRECT_OVERWRITE;
3941 redir_style = REDIRECT_APPEND;
3945 else if (next == '(') {
3946 syntax(">(process) not supported");
3947 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
3951 setup_redirect(ctx, redir_fd, redir_style, input);
3954 redir_fd = redirect_opt_num(dest);
3955 done_word(dest, ctx);
3956 redir_style = REDIRECT_INPUT;
3958 redir_style = REDIRECT_HEREIS;
3960 } else if (next == '>') {
3961 redir_style = REDIRECT_IO;
3965 else if (next == '(') {
3966 syntax("<(process) not supported");
3967 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
3971 setup_redirect(ctx, redir_fd, redir_style, input);
3974 #if ENABLE_HUSH_CASE
3977 done_word(dest, ctx);
3978 done_pipe(ctx, PIPE_SEQ);
3979 #if ENABLE_HUSH_CASE
3980 /* Eat multiple semicolons, detect
3981 * whether it means something special */
3987 if (ctx->ctx_res_w == RES_CASEI) {
3988 ctx->ctx_dsemicolon = 1;
3989 ctx->ctx_res_w = RES_MATCH;
3995 /* We just finished a cmd. New one may start
3996 * with an assignment */
3997 dest->o_assignment = MAYBE_ASSIGNMENT;
4000 done_word(dest, ctx);
4003 done_pipe(ctx, PIPE_AND);
4005 done_pipe(ctx, PIPE_BG);
4009 done_word(dest, ctx);
4010 #if ENABLE_HUSH_CASE
4011 if (ctx->ctx_res_w == RES_MATCH)
4012 break; /* we are in case's "word | word)" */
4014 if (next == '|') { /* || */
4016 done_pipe(ctx, PIPE_OR);
4018 /* we could pick up a file descriptor choice here
4019 * with redirect_opt_num(), but bash doesn't do it.
4020 * "echo foo 2| cat" yields "foo 2". */
4025 #if ENABLE_HUSH_CASE
4026 /* "case... in [(]word)..." - skip '(' */
4027 if (ctx->ctx_res_w == RES_MATCH
4028 && ctx->command->argv == NULL /* not (word|(... */
4029 && dest->length == 0 /* not word(... */
4030 && dest->nonnull == 0 /* not ""(... */
4035 #if ENABLE_HUSH_FUNCTIONS
4036 if (dest->length != 0 /* not just () but word() */
4037 && dest->nonnull == 0 /* not a"b"c() */
4038 && ctx->command->argv == NULL /* it's the first word */
4039 //TODO: "func ( ) {...}" - note spaces - is valid format too in bash
4040 && i_peek(input) == ')'
4041 && !match_reserved_word(dest)
4043 bb_error_msg("seems like a function definition");
4046 //TODO: do it properly.
4047 ch = i_getch(input);
4048 } while (ch == ' ' || ch == '\n');
4050 syntax("was expecting {");
4051 debug_printf_parse("parse_stream return 1\n");
4054 ch = 'F'; /* magic value */
4058 if (parse_group(dest, ctx, input, ch) != 0) {
4059 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
4064 #if ENABLE_HUSH_CASE
4065 if (ctx->ctx_res_w == RES_MATCH)
4069 /* proper use of this character is caught by end_trigger:
4070 * if we see {, we call parse_group(..., end_trigger='}')
4071 * and it will match } earlier (not here). */
4072 syntax("unexpected } or )");
4073 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
4077 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4080 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
4086 static void set_in_charmap(const char *set, int code)
4089 G.charmap[(unsigned char)*set++] = code;
4092 static void update_charmap(void)
4094 G.ifs = getenv("IFS");
4097 /* Precompute a list of 'flow through' behavior so it can be treated
4098 * quickly up front. Computation is necessary because of IFS.
4099 * Special case handling of IFS == " \t\n" is not implemented.
4100 * The charmap[] array only really needs two bits each,
4101 * and on most machines that would be faster (reduced L1 cache use).
4103 memset(G.charmap, CHAR_ORDINARY, sizeof(G.charmap));
4104 #if ENABLE_HUSH_TICK
4105 set_in_charmap("\\$\"`", CHAR_SPECIAL);
4107 set_in_charmap("\\$\"", CHAR_SPECIAL);
4109 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
4110 set_in_charmap(G.ifs, CHAR_IFS); /* are ordinary if quoted */
4113 /* Most recursion does not come through here, the exception is
4114 * from builtin_source() and builtin_eval() */
4115 static int parse_and_run_stream(struct in_str *inp, int parse_flag)
4117 struct parse_context ctx;
4118 o_string temp = NULL_O_STRING;
4122 initialize_context(&ctx);
4124 #if ENABLE_HUSH_INTERACTIVE
4125 inp->promptmode = 0; /* PS1 */
4127 /* We will stop & execute after each ';' or '\n'.
4128 * Example: "sleep 9999; echo TEST" + ctrl-C:
4129 * TEST should be printed */
4130 temp.o_assignment = MAYBE_ASSIGNMENT;
4131 rcode = parse_stream(&temp, &ctx, inp, ";\n");
4133 if (rcode != 1 && ctx.old_flag != 0) {
4137 if (rcode != 1 IF_HAS_KEYWORDS(&& ctx.old_flag == 0)) {
4138 done_word(&temp, &ctx);
4139 done_pipe(&ctx, PIPE_SEQ);
4140 debug_print_tree(ctx.list_head, 0);
4141 debug_printf_exec("parse_stream_outer: run_and_free_list\n");
4142 run_and_free_list(ctx.list_head);
4144 /* We arrive here also if rcode == 1 (error in parse_stream) */
4146 if (ctx.old_flag != 0) {
4151 /*temp.nonnull = 0; - o_free does it below */
4152 /*temp.o_quote = 0; - o_free does it below */
4153 free_pipe_list(ctx.list_head, /* indent: */ 0);
4154 /* Discard all unprocessed line input, force prompt on */
4156 #if ENABLE_HUSH_INTERACTIVE
4161 /* loop on syntax errors, return on EOF: */
4162 } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP));
4166 static int parse_and_run_string(const char *s, int parse_flag)
4168 struct in_str input;
4169 setup_string_in_str(&input, s);
4170 return parse_and_run_stream(&input, parse_flag);
4173 static int parse_and_run_file(FILE *f)
4176 struct in_str input;
4177 setup_file_in_str(&input, f);
4178 rcode = parse_and_run_stream(&input, 0 /* parse_flag */);
4183 /* Make sure we have a controlling tty. If we get started under a job
4184 * aware app (like bash for example), make sure we are now in charge so
4185 * we don't fight over who gets the foreground */
4186 static void setup_job_control(void)
4190 shell_pgrp = getpgrp();
4191 close_on_exec_on(G.interactive_fd);
4193 /* If we were ran as 'hush &',
4194 * sleep until we are in the foreground. */
4195 while (tcgetpgrp(G.interactive_fd) != shell_pgrp) {
4196 /* Send TTIN to ourself (should stop us) */
4197 kill(- shell_pgrp, SIGTTIN);
4198 shell_pgrp = getpgrp();
4201 /* Ignore job-control and misc signals. */
4202 set_jobctrl_sighandler(SIG_IGN);
4203 set_misc_sighandler(SIG_IGN);
4204 //huh? signal(SIGCHLD, SIG_IGN);
4206 /* We _must_ restore tty pgrp on fatal signals */
4207 set_fatal_sighandler(sigexit);
4209 /* Put ourselves in our own process group. */
4210 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
4211 /* Grab control of the terminal. */
4212 tcsetpgrp(G.interactive_fd, getpid());
4217 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4218 int hush_main(int argc, char **argv)
4220 static const struct variable const_shell_ver = {
4222 .varstr = (char*)hush_version_str,
4223 .max_len = 1, /* 0 can provoke free(name) */
4231 struct variable *cur_var;
4235 G.root_pid = getpid();
4237 /* Deal with HUSH_VERSION */
4238 G.shell_ver = const_shell_ver; /* copying struct here */
4239 G.top_var = &G.shell_ver;
4240 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
4241 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
4242 /* Initialize our shell local variables with the values
4243 * currently living in the environment */
4244 cur_var = G.top_var;
4247 char *value = strchr(*e, '=');
4248 if (value) { /* paranoia */
4249 cur_var->next = xzalloc(sizeof(*cur_var));
4250 cur_var = cur_var->next;
4251 cur_var->varstr = *e;
4252 cur_var->max_len = strlen(*e);
4253 cur_var->flg_export = 1;
4257 debug_printf_env("putenv '%s'\n", hush_version_str);
4258 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
4260 #if ENABLE_FEATURE_EDITING
4261 G.line_input_state = new_line_input_t(FOR_SHELL);
4263 /* XXX what should these be while sourcing /etc/profile? */
4264 G.global_argc = argc;
4265 G.global_argv = argv;
4266 /* Initialize some more globals to non-zero values */
4268 #if ENABLE_HUSH_INTERACTIVE
4269 #if ENABLE_FEATURE_EDITING
4270 cmdedit_set_initial_prompt();
4275 if (EXIT_SUCCESS) /* otherwise is already done */
4276 G.last_return_code = EXIT_SUCCESS;
4278 if (argv[0] && argv[0][0] == '-') {
4279 debug_printf("sourcing /etc/profile\n");
4280 input = fopen_for_read("/etc/profile");
4281 if (input != NULL) {
4282 close_on_exec_on(fileno(input));
4283 parse_and_run_file(input);
4289 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
4292 G.global_argv = argv + optind;
4293 if (!argv[optind]) {
4294 /* -c 'script' (no params): prevent empty $0 */
4295 *--G.global_argv = argv[0];
4297 } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
4298 G.global_argc = argc - optind;
4299 opt = parse_and_run_string(optarg, 0 /* parse_flag */);
4302 /* Well, we cannot just declare interactiveness,
4303 * we have to have some stuff (ctty, etc) */
4304 /* G.interactive_fd++; */
4311 fprintf(stderr, "Usage: sh [FILE]...\n"
4312 " or: sh -c command [args]...\n\n");
4320 /* A shell is interactive if the '-i' flag was given, or if all of
4321 * the following conditions are met:
4323 * no arguments remaining or the -s flag given
4324 * standard input is a terminal
4325 * standard output is a terminal
4326 * Refer to Posix.2, the description of the 'sh' utility. */
4327 if (argv[optind] == NULL && input == stdin
4328 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4330 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
4331 debug_printf("saved_tty_pgrp=%d\n", G.saved_tty_pgrp);
4332 if (G.saved_tty_pgrp >= 0) {
4333 /* try to dup to high fd#, >= 255 */
4334 G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4335 if (G.interactive_fd < 0) {
4336 /* try to dup to any fd */
4337 G.interactive_fd = dup(STDIN_FILENO);
4338 if (G.interactive_fd < 0)
4340 G.interactive_fd = 0;
4342 // TODO: track & disallow any attempts of user
4343 // to (inadvertently) close/redirect it
4346 debug_printf("G.interactive_fd=%d\n", G.interactive_fd);
4347 if (G.interactive_fd) {
4348 fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
4349 /* Looks like they want an interactive shell */
4350 setup_job_control();
4351 /* -1 is special - makes xfuncs longjmp, not exit
4352 * (we reset die_sleep = 0 whereever we [v]fork) */
4354 if (setjmp(die_jmp)) {
4355 /* xfunc has failed! die die die */
4356 hush_exit(xfunc_error_retval);
4358 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
4359 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
4360 printf("Enter 'help' for a list of built-in commands.\n\n");
4363 #elif ENABLE_HUSH_INTERACTIVE
4364 /* no job control compiled, only prompt/line editing */
4365 if (argv[optind] == NULL && input == stdin
4366 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
4368 G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
4369 if (G.interactive_fd < 0) {
4370 /* try to dup to any fd */
4371 G.interactive_fd = dup(STDIN_FILENO);
4372 if (G.interactive_fd < 0)
4374 G.interactive_fd = 0;
4376 if (G.interactive_fd) {
4377 fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
4378 set_misc_sighandler(SIG_IGN);
4383 if (argv[optind] == NULL) {
4384 opt = parse_and_run_file(stdin);
4386 debug_printf("\nrunning script '%s'\n", argv[optind]);
4387 G.global_argv = argv + optind;
4388 G.global_argc = argc - optind;
4389 input = xfopen_for_read(argv[optind]);
4390 fcntl(fileno(input), F_SETFD, FD_CLOEXEC);
4391 opt = parse_and_run_file(input);
4396 #if ENABLE_FEATURE_CLEAN_UP
4398 if (G.cwd != bb_msg_unknown)
4400 cur_var = G.top_var->next;
4402 struct variable *tmp = cur_var;
4403 if (!cur_var->max_len)
4404 free(cur_var->varstr);
4405 cur_var = cur_var->next;
4409 hush_exit(opt ? opt : G.last_return_code);
4414 int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4415 int lash_main(int argc, char **argv)
4417 //bb_error_msg("lash is deprecated, please use hush instead");
4418 return hush_main(argc, argv);
4426 static int builtin_true(char **argv UNUSED_PARAM)
4431 static int builtin_test(char **argv)
4438 return test_main(argc, argv - argc);
4441 static int builtin_echo(char **argv)
4448 return echo_main(argc, argv - argc);
4451 static int builtin_eval(char **argv)
4453 int rcode = EXIT_SUCCESS;
4456 char *str = expand_strvec_to_string(argv + 1);
4457 parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP);
4459 rcode = G.last_return_code;
4464 static int builtin_cd(char **argv)
4467 if (argv[1] == NULL) {
4468 // bash does nothing (exitcode 0) if HOME is ""; if it's unset,
4469 // bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
4470 newdir = getenv("HOME") ? : "/";
4473 if (chdir(newdir)) {
4474 printf("cd: %s: %s\n", newdir, strerror(errno));
4475 return EXIT_FAILURE;
4478 return EXIT_SUCCESS;
4481 static int builtin_exec(char **argv)
4483 if (argv[1] == NULL)
4484 return EXIT_SUCCESS; /* bash does this */
4489 // FIXME: if exec fails, bash does NOT exit! We do...
4490 pseudo_exec_argv(&dummy, argv + 1, 0, NULL);
4495 static int builtin_exit(char **argv)
4497 // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
4498 //puts("exit"); /* bash does it */
4499 // TODO: warn if we have background jobs: "There are stopped jobs"
4500 // On second consecutive 'exit', exit anyway.
4501 if (argv[1] == NULL)
4502 hush_exit(G.last_return_code);
4503 /* mimic bash: exit 123abc == exit 255 + error msg */
4504 xfunc_error_retval = 255;
4505 /* bash: exit -2 == exit 254, no error msg */
4506 hush_exit(xatoi(argv[1]) & 0xff);
4509 static int builtin_export(char **argv)
4512 char *name = argv[1];
4516 // ash emits: export VAR='VAL'
4517 // bash: declare -x VAR="VAL"
4518 // (both also escape as needed (quotes, $, etc))
4523 return EXIT_SUCCESS;
4526 value = strchr(name, '=');
4528 /* They are exporting something without a =VALUE */
4529 struct variable *var;
4531 var = get_local_var(name);
4533 var->flg_export = 1;
4534 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
4535 putenv(var->varstr);
4537 /* bash does not return an error when trying to export
4538 * an undefined variable. Do likewise. */
4539 return EXIT_SUCCESS;
4542 set_local_var(xstrdup(name), 1);
4543 return EXIT_SUCCESS;
4547 /* built-in 'fg' and 'bg' handler */
4548 static int builtin_fg_bg(char **argv)
4553 if (!G.interactive_fd)
4554 return EXIT_FAILURE;
4555 /* If they gave us no args, assume they want the last backgrounded task */
4557 for (pi = G.job_list; pi; pi = pi->next) {
4558 if (pi->jobid == G.last_jobid) {
4562 bb_error_msg("%s: no current job", argv[0]);
4563 return EXIT_FAILURE;
4565 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
4566 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
4567 return EXIT_FAILURE;
4569 for (pi = G.job_list; pi; pi = pi->next) {
4570 if (pi->jobid == jobnum) {
4574 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
4575 return EXIT_FAILURE;
4577 // TODO: bash prints a string representation
4578 // of job being foregrounded (like "sleep 1 | cat")
4579 if (*argv[0] == 'f') {
4580 /* Put the job into the foreground. */
4581 tcsetpgrp(G.interactive_fd, pi->pgrp);
4584 /* Restart the processes in the job */
4585 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
4586 for (i = 0; i < pi->num_cmds; i++) {
4587 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
4588 pi->cmds[i].is_stopped = 0;
4590 pi->stopped_cmds = 0;
4592 i = kill(- pi->pgrp, SIGCONT);
4594 if (errno == ESRCH) {
4595 delete_finished_bg_job(pi);
4596 return EXIT_SUCCESS;
4598 bb_perror_msg("kill (SIGCONT)");
4602 if (*argv[0] == 'f') {
4604 return checkjobs_and_fg_shell(pi);
4606 return EXIT_SUCCESS;
4610 #if ENABLE_HUSH_HELP
4611 static int builtin_help(char **argv UNUSED_PARAM)
4613 const struct built_in_command *x;
4615 printf("\nBuilt-in commands:\n");
4616 printf("-------------------\n");
4617 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
4618 printf("%s\t%s\n", x->cmd, x->descr);
4621 return EXIT_SUCCESS;
4626 static int builtin_jobs(char **argv UNUSED_PARAM)
4629 const char *status_string;
4631 for (job = G.job_list; job; job = job->next) {
4632 if (job->alive_cmds == job->stopped_cmds)
4633 status_string = "Stopped";
4635 status_string = "Running";
4637 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
4639 return EXIT_SUCCESS;
4643 static int builtin_pwd(char **argv UNUSED_PARAM)
4646 return EXIT_SUCCESS;
4649 static int builtin_read(char **argv)
4652 const char *name = argv[1] ? argv[1] : "REPLY";
4654 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
4655 return set_local_var(string, 0);
4658 /* built-in 'set' handler
4660 * set [-abCefmnuvx] [-h] [-o option] [argument...]
4661 * set [+abCefmnuvx] [+h] [+o option] [argument...]
4662 * set -- [argument...]
4665 * Implementations shall support the options in both their hyphen and
4666 * plus-sign forms. These options can also be specified as options to sh.
4668 * Write out all variables and their values: set
4669 * Set $1, $2, and $3 and set "$#" to 3: set c a b
4670 * Turn on the -x and -v options: set -xv
4671 * Unset all positional parameters: set --
4672 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
4673 * Set the positional parameters to the expansion of x, even if x expands
4674 * with a leading '-' or '+': set -- $x
4676 * So far, we only support "set -- [argument...]" by ignoring all options
4677 * (also, "-o option" will be mishandled by taking "option" as parameter #1).
4679 static int builtin_set(char **argv)
4683 char *arg = *++argv;
4686 for (e = G.top_var; e; e = e->next)
4689 /* NB: G.global_argv[0] ($0) is never freed/changed */
4691 if (G.global_args_malloced) {
4695 G.global_argv[1] = NULL;
4697 G.global_args_malloced = 1;
4698 pp = xzalloc(sizeof(pp[0]) * 2);
4699 pp[0] = G.global_argv[0]; /* retain $0 */
4707 if (arg[1] == '-' && arg[2] == '\0') {
4711 } while ((arg = *++argv) != NULL);
4712 /* Now argv[0] is 1st argument */
4714 /* This realloc's G.global_argv */
4715 G.global_argv = pp = add_strings_to_strings(G.global_argv, argv, /*dup:*/ 1);
4721 return EXIT_SUCCESS;
4724 static int builtin_shift(char **argv)
4730 if (n >= 0 && n < G.global_argc) {
4731 G.global_argv[n] = G.global_argv[0];
4734 return EXIT_SUCCESS;
4736 return EXIT_FAILURE;
4739 static int builtin_source(char **argv)
4744 if (argv[1] == NULL)
4745 return EXIT_FAILURE;
4747 /* XXX search through $PATH is missing */
4748 input = fopen_for_read(argv[1]);
4750 bb_error_msg("can't open '%s'", argv[1]);
4751 return EXIT_FAILURE;
4753 close_on_exec_on(fileno(input));
4755 /* Now run the file */
4756 /* XXX argv and argc are broken; need to save old G.global_argv
4757 * (pointer only is OK!) on this stack frame,
4758 * set G.global_argv=argv+1, recurse, and restore. */
4759 status = parse_and_run_file(input);
4764 static int builtin_umask(char **argv)
4767 const char *arg = argv[1];
4770 new_umask = strtoul(arg, &end, 8);
4771 if (*end != '\0' || end == arg) {
4772 return EXIT_FAILURE;
4775 new_umask = umask(0);
4776 printf("%.3o\n", (unsigned) new_umask);
4779 return EXIT_SUCCESS;
4782 static int builtin_unset(char **argv)
4784 /* bash always returns true */
4785 unset_local_var(argv[1]);
4786 return EXIT_SUCCESS;
4789 #if ENABLE_HUSH_LOOPS
4790 static int builtin_break(char **argv)
4792 if (G.depth_of_loop == 0) {
4793 bb_error_msg("%s: only meaningful in a loop", argv[0]);
4794 return EXIT_SUCCESS; /* bash compat */
4796 G.flag_break_continue++; /* BC_BREAK = 1 */
4797 G.depth_break_continue = 1;
4799 G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
4800 if (errno || !G.depth_break_continue || argv[2]) {
4801 bb_error_msg("%s: bad arguments", argv[0]);
4802 G.flag_break_continue = BC_BREAK;
4803 G.depth_break_continue = UINT_MAX;
4806 if (G.depth_of_loop < G.depth_break_continue)
4807 G.depth_break_continue = G.depth_of_loop;
4808 return EXIT_SUCCESS;
4811 static int builtin_continue(char **argv)
4813 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
4814 return builtin_break(argv);