Changes for kernel and Busybox
[tomato.git] / release / src / router / busybox / shell / hush.c
blob51d38d3aef65220a751b9d56c53d6c737025407d
1 /* vi: set sw=4 ts=4: */
2 /*
3 * 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>
9 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
11 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
13 * Credits:
14 * The parser routines proper are all original material, first
15 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
16 * execution engine, the builtins, and much of the underlying
17 * support has been adapted from busybox-0.49pre's lash, which is
18 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
19 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
20 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
21 * Troan, which they placed in the public domain. I don't know
22 * how much of the Johnson/Troan code has survived the repeated
23 * rewrites.
25 * Other credits:
26 * o_addchr derived from similar w_addchar function in glibc-2.2.
27 * parse_redirect, redirect_opt_num, and big chunks of main
28 * and many builtins derived from contributions by Erik Andersen.
29 * Miscellaneous bugfixes from Matt Kraai.
31 * There are two big (and related) architecture differences between
32 * this parser and the lash parser. One is that this version is
33 * actually designed from the ground up to understand nearly all
34 * of the Bourne grammar. The second, consequential change is that
35 * the parser and input reader have been turned inside out. Now,
36 * the parser is in control, and asks for input as needed. The old
37 * way had the input reader in control, and it asked for parsing to
38 * take place as needed. The new way makes it much easier to properly
39 * handle the recursion implicit in the various substitutions, especially
40 * across continuation lines.
42 * TODOs:
43 * grep for "TODO" and fix (some of them are easy)
44 * special variables (done: PWD, PPID, RANDOM)
45 * tilde expansion
46 * aliases
47 * follow IFS rules more precisely, including update semantics
48 * builtins mandated by standards we don't support:
49 * [un]alias, command, fc, getopts, newgrp, readonly, times
50 * make complex ${var%...} constructs support optional
51 * make here documents optional
53 * Bash compat TODO:
54 * redirection of stdout+stderr: &> and >&
55 * reserved words: function select
56 * advanced test: [[ ]]
57 * process substitution: <(list) and >(list)
58 * =~: regex operator
59 * let EXPR [EXPR...]
60 * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
61 * If the last arg evaluates to 0, let returns 1; 0 otherwise.
62 * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
63 * ((EXPR))
64 * The EXPR is evaluated according to ARITHMETIC EVALUATION.
65 * This is exactly equivalent to let "EXPR".
66 * $[EXPR]: synonym for $((EXPR))
68 * Won't do:
69 * In bash, export builtin is special, its arguments are assignments
70 * and therefore expansion of them should be "one-word" expansion:
71 * $ export i=`echo 'a b'` # export has one arg: "i=a b"
72 * compare with:
73 * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
74 * ls: cannot access i=a: No such file or directory
75 * ls: cannot access b: No such file or directory
76 * Note1: same applies to local builtin.
77 * Note2: bash 3.2.33(1) does this only if export word itself
78 * is not quoted:
79 * $ export i=`echo 'aaa bbb'`; echo "$i"
80 * aaa bbb
81 * $ "export" i=`echo 'aaa bbb'`; echo "$i"
82 * aaa
84 #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
85 || defined(__APPLE__) \
87 # include <malloc.h> /* for malloc_trim */
88 #endif
89 #include <glob.h>
90 /* #include <dmalloc.h> */
91 #if ENABLE_HUSH_CASE
92 # include <fnmatch.h>
93 #endif
95 #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
96 #include "unicode.h"
97 #include "shell_common.h"
98 #include "math.h"
99 #include "match.h"
100 #if ENABLE_HUSH_RANDOM_SUPPORT
101 # include "random.h"
102 #else
103 # define CLEAR_RANDOM_T(rnd) ((void)0)
104 #endif
105 #ifndef PIPE_BUF
106 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
107 #endif
109 /* Not every libc has sighandler_t. Fix it */
110 typedef void (*hush_sighandler_t)(int);
111 #define sighandler_t hush_sighandler_t
113 //config:config HUSH
114 //config: bool "hush"
115 //config: default y
116 //config: help
117 //config: hush is a small shell (25k). It handles the normal flow control
118 //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
119 //config: case/esac. Redirections, here documents, $((arithmetic))
120 //config: and functions are supported.
121 //config:
122 //config: It will compile and work on no-mmu systems.
123 //config:
124 //config: It does not handle select, aliases, tilde expansion,
125 //config: &>file and >&file redirection of stdout+stderr.
126 //config:
127 //config:config HUSH_BASH_COMPAT
128 //config: bool "bash-compatible extensions"
129 //config: default y
130 //config: depends on HUSH
131 //config: help
132 //config: Enable bash-compatible extensions.
133 //config:
134 //config:config HUSH_BRACE_EXPANSION
135 //config: bool "Brace expansion"
136 //config: default y
137 //config: depends on HUSH_BASH_COMPAT
138 //config: help
139 //config: Enable {abc,def} extension.
140 //config:
141 //config:config HUSH_HELP
142 //config: bool "help builtin"
143 //config: default y
144 //config: depends on HUSH
145 //config: help
146 //config: Enable help builtin in hush. Code size + ~1 kbyte.
147 //config:
148 //config:config HUSH_INTERACTIVE
149 //config: bool "Interactive mode"
150 //config: default y
151 //config: depends on HUSH
152 //config: help
153 //config: Enable interactive mode (prompt and command editing).
154 //config: Without this, hush simply reads and executes commands
155 //config: from stdin just like a shell script from a file.
156 //config: No prompt, no PS1/PS2 magic shell variables.
157 //config:
158 //config:config HUSH_SAVEHISTORY
159 //config: bool "Save command history to .hush_history"
160 //config: default y
161 //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
162 //config: help
163 //config: Enable history saving in hush.
164 //config:
165 //config:config HUSH_JOB
166 //config: bool "Job control"
167 //config: default y
168 //config: depends on HUSH_INTERACTIVE
169 //config: help
170 //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
171 //config: command (not entire shell), fg/bg builtins work. Without this option,
172 //config: "cmd &" still works by simply spawning a process and immediately
173 //config: prompting for next command (or executing next command in a script),
174 //config: but no separate process group is formed.
175 //config:
176 //config:config HUSH_TICK
177 //config: bool "Process substitution"
178 //config: default y
179 //config: depends on HUSH
180 //config: help
181 //config: Enable process substitution `command` and $(command) in hush.
182 //config:
183 //config:config HUSH_IF
184 //config: bool "Support if/then/elif/else/fi"
185 //config: default y
186 //config: depends on HUSH
187 //config: help
188 //config: Enable if/then/elif/else/fi in hush.
189 //config:
190 //config:config HUSH_LOOPS
191 //config: bool "Support for, while and until loops"
192 //config: default y
193 //config: depends on HUSH
194 //config: help
195 //config: Enable for, while and until loops in hush.
196 //config:
197 //config:config HUSH_CASE
198 //config: bool "Support case ... esac statement"
199 //config: default y
200 //config: depends on HUSH
201 //config: help
202 //config: Enable case ... esac statement in hush. +400 bytes.
203 //config:
204 //config:config HUSH_FUNCTIONS
205 //config: bool "Support funcname() { commands; } syntax"
206 //config: default y
207 //config: depends on HUSH
208 //config: help
209 //config: Enable support for shell functions in hush. +800 bytes.
210 //config:
211 //config:config HUSH_LOCAL
212 //config: bool "Support local builtin"
213 //config: default y
214 //config: depends on HUSH_FUNCTIONS
215 //config: help
216 //config: Enable support for local variables in functions.
217 //config:
218 //config:config HUSH_RANDOM_SUPPORT
219 //config: bool "Pseudorandom generator and $RANDOM variable"
220 //config: default y
221 //config: depends on HUSH
222 //config: help
223 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
224 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
225 //config:
226 //config:config HUSH_EXPORT_N
227 //config: bool "Support 'export -n' option"
228 //config: default y
229 //config: depends on HUSH
230 //config: help
231 //config: export -n unexports variables. It is a bash extension.
232 //config:
233 //config:config HUSH_MODE_X
234 //config: bool "Support 'hush -x' option and 'set -x' command"
235 //config: default y
236 //config: depends on HUSH
237 //config: help
238 //config: This instructs hush to print commands before execution.
239 //config: Adds ~300 bytes.
240 //config:
241 //config:config MSH
242 //config: bool "msh (deprecated: aliased to hush)"
243 //config: default n
244 //config: select HUSH
245 //config: help
246 //config: msh is deprecated and will be removed, please migrate to hush.
247 //config:
249 //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
250 //applet:IF_MSH(APPLET(msh, BB_DIR_BIN, BB_SUID_DROP))
251 //applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, sh))
252 //applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, bash))
254 //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
255 //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
257 /* -i (interactive) and -s (read stdin) are also accepted,
258 * but currently do nothing, therefore aren't shown in help.
259 * NOMMU-specific options are not meant to be used by users,
260 * therefore we don't show them either.
262 //usage:#define hush_trivial_usage
263 //usage: "[-nxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
264 //usage:#define hush_full_usage "\n\n"
265 //usage: "Unix shell interpreter"
267 //usage:#define msh_trivial_usage hush_trivial_usage
268 //usage:#define msh_full_usage hush_full_usage
270 //usage:#if ENABLE_FEATURE_SH_IS_HUSH
271 //usage:# define sh_trivial_usage hush_trivial_usage
272 //usage:# define sh_full_usage hush_full_usage
273 //usage:#endif
274 //usage:#if ENABLE_FEATURE_BASH_IS_HUSH
275 //usage:# define bash_trivial_usage hush_trivial_usage
276 //usage:# define bash_full_usage hush_full_usage
277 //usage:#endif
280 /* Build knobs */
281 #define LEAK_HUNTING 0
282 #define BUILD_AS_NOMMU 0
283 /* Enable/disable sanity checks. Ok to enable in production,
284 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
285 * Keeping 1 for now even in released versions.
287 #define HUSH_DEBUG 1
288 /* Slightly bigger (+200 bytes), but faster hush.
289 * So far it only enables a trick with counting SIGCHLDs and forks,
290 * which allows us to do fewer waitpid's.
291 * (we can detect a case where neither forks were done nor SIGCHLDs happened
292 * and therefore waitpid will return the same result as last time)
294 #define ENABLE_HUSH_FAST 0
295 /* TODO: implement simplified code for users which do not need ${var%...} ops
296 * So far ${var%...} ops are always enabled:
298 #define ENABLE_HUSH_DOLLAR_OPS 1
301 #if BUILD_AS_NOMMU
302 # undef BB_MMU
303 # undef USE_FOR_NOMMU
304 # undef USE_FOR_MMU
305 # define BB_MMU 0
306 # define USE_FOR_NOMMU(...) __VA_ARGS__
307 # define USE_FOR_MMU(...)
308 #endif
310 #include "NUM_APPLETS.h"
311 #if NUM_APPLETS == 1
312 /* STANDALONE does not make sense, and won't compile */
313 # undef CONFIG_FEATURE_SH_STANDALONE
314 # undef ENABLE_FEATURE_SH_STANDALONE
315 # undef IF_FEATURE_SH_STANDALONE
316 # undef IF_NOT_FEATURE_SH_STANDALONE
317 # define ENABLE_FEATURE_SH_STANDALONE 0
318 # define IF_FEATURE_SH_STANDALONE(...)
319 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
320 #endif
322 #if !ENABLE_HUSH_INTERACTIVE
323 # undef ENABLE_FEATURE_EDITING
324 # define ENABLE_FEATURE_EDITING 0
325 # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
326 # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
327 # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
328 # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
329 #endif
331 /* Do we support ANY keywords? */
332 #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
333 # define HAS_KEYWORDS 1
334 # define IF_HAS_KEYWORDS(...) __VA_ARGS__
335 # define IF_HAS_NO_KEYWORDS(...)
336 #else
337 # define HAS_KEYWORDS 0
338 # define IF_HAS_KEYWORDS(...)
339 # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
340 #endif
342 /* If you comment out one of these below, it will be #defined later
343 * to perform debug printfs to stderr: */
344 #define debug_printf(...) do {} while (0)
345 /* Finer-grained debug switches */
346 #define debug_printf_parse(...) do {} while (0)
347 #define debug_print_tree(a, b) do {} while (0)
348 #define debug_printf_exec(...) do {} while (0)
349 #define debug_printf_env(...) do {} while (0)
350 #define debug_printf_jobs(...) do {} while (0)
351 #define debug_printf_expand(...) do {} while (0)
352 #define debug_printf_varexp(...) do {} while (0)
353 #define debug_printf_glob(...) do {} while (0)
354 #define debug_printf_list(...) do {} while (0)
355 #define debug_printf_subst(...) do {} while (0)
356 #define debug_printf_clean(...) do {} while (0)
358 #define ERR_PTR ((void*)(long)1)
360 #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
362 #define _SPECIAL_VARS_STR "_*@$!?#"
363 #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
364 #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
365 #if ENABLE_HUSH_BASH_COMPAT
366 /* Support / and // replace ops */
367 /* Note that // is stored as \ in "encoded" string representation */
368 # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
369 # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
370 # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
371 #else
372 # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
373 # define VAR_SUBST_OPS "%#:-=+?"
374 # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
375 #endif
377 #define SPECIAL_VAR_SYMBOL 3
379 struct variable;
381 static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
383 /* This supports saving pointers malloced in vfork child,
384 * to be freed in the parent.
386 #if !BB_MMU
387 typedef struct nommu_save_t {
388 char **new_env;
389 struct variable *old_vars;
390 char **argv;
391 char **argv_from_re_execing;
392 } nommu_save_t;
393 #endif
395 enum {
396 RES_NONE = 0,
397 #if ENABLE_HUSH_IF
398 RES_IF ,
399 RES_THEN ,
400 RES_ELIF ,
401 RES_ELSE ,
402 RES_FI ,
403 #endif
404 #if ENABLE_HUSH_LOOPS
405 RES_FOR ,
406 RES_WHILE ,
407 RES_UNTIL ,
408 RES_DO ,
409 RES_DONE ,
410 #endif
411 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
412 RES_IN ,
413 #endif
414 #if ENABLE_HUSH_CASE
415 RES_CASE ,
416 /* three pseudo-keywords support contrived "case" syntax: */
417 RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
418 RES_MATCH , /* "word)" */
419 RES_CASE_BODY, /* "this command is inside CASE" */
420 RES_ESAC ,
421 #endif
422 RES_XXXX ,
423 RES_SNTX
426 typedef struct o_string {
427 char *data;
428 int length; /* position where data is appended */
429 int maxlen;
430 int o_expflags;
431 /* At least some part of the string was inside '' or "",
432 * possibly empty one: word"", wo''rd etc. */
433 smallint has_quoted_part;
434 smallint has_empty_slot;
435 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
436 } o_string;
437 enum {
438 EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
439 EXP_FLAG_GLOB = 0x2,
440 /* Protect newly added chars against globbing
441 * by prepending \ to *, ?, [, \ */
442 EXP_FLAG_ESC_GLOB_CHARS = 0x1,
444 enum {
445 MAYBE_ASSIGNMENT = 0,
446 DEFINITELY_ASSIGNMENT = 1,
447 NOT_ASSIGNMENT = 2,
448 /* Not an assigment, but next word may be: "if v=xyz cmd;" */
449 WORD_IS_KEYWORD = 3,
451 /* Used for initialization: o_string foo = NULL_O_STRING; */
452 #define NULL_O_STRING { NULL }
454 #ifndef debug_printf_parse
455 static const char *const assignment_flag[] = {
456 "MAYBE_ASSIGNMENT",
457 "DEFINITELY_ASSIGNMENT",
458 "NOT_ASSIGNMENT",
459 "WORD_IS_KEYWORD",
461 #endif
463 typedef struct in_str {
464 const char *p;
465 /* eof_flag=1: last char in ->p is really an EOF */
466 char eof_flag; /* meaningless if ->p == NULL */
467 char peek_buf[2];
468 #if ENABLE_HUSH_INTERACTIVE
469 smallint promptmode; /* 0: PS1, 1: PS2 */
470 #endif
471 int last_char;
472 FILE *file;
473 int (*get) (struct in_str *) FAST_FUNC;
474 int (*peek) (struct in_str *) FAST_FUNC;
475 } in_str;
476 #define i_getch(input) ((input)->get(input))
477 #define i_peek(input) ((input)->peek(input))
479 /* The descrip member of this structure is only used to make
480 * debugging output pretty */
481 static const struct {
482 int mode;
483 signed char default_fd;
484 char descrip[3];
485 } redir_table[] = {
486 { O_RDONLY, 0, "<" },
487 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
488 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
489 { O_CREAT|O_RDWR, 1, "<>" },
490 { O_RDONLY, 0, "<<" },
491 /* Should not be needed. Bogus default_fd helps in debugging */
492 /* { O_RDONLY, 77, "<<" }, */
495 struct redir_struct {
496 struct redir_struct *next;
497 char *rd_filename; /* filename */
498 int rd_fd; /* fd to redirect */
499 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
500 int rd_dup;
501 smallint rd_type; /* (enum redir_type) */
502 /* note: for heredocs, rd_filename contains heredoc delimiter,
503 * and subsequently heredoc itself; and rd_dup is a bitmask:
504 * bit 0: do we need to trim leading tabs?
505 * bit 1: is heredoc quoted (<<'delim' syntax) ?
508 typedef enum redir_type {
509 REDIRECT_INPUT = 0,
510 REDIRECT_OVERWRITE = 1,
511 REDIRECT_APPEND = 2,
512 REDIRECT_IO = 3,
513 REDIRECT_HEREDOC = 4,
514 REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
516 REDIRFD_CLOSE = -3,
517 REDIRFD_SYNTAX_ERR = -2,
518 REDIRFD_TO_FILE = -1,
519 /* otherwise, rd_fd is redirected to rd_dup */
521 HEREDOC_SKIPTABS = 1,
522 HEREDOC_QUOTED = 2,
523 } redir_type;
526 struct command {
527 pid_t pid; /* 0 if exited */
528 int assignment_cnt; /* how many argv[i] are assignments? */
529 smallint cmd_type; /* CMD_xxx */
530 #define CMD_NORMAL 0
531 #define CMD_SUBSHELL 1
532 #if ENABLE_HUSH_BASH_COMPAT
533 /* used for "[[ EXPR ]]" */
534 # define CMD_SINGLEWORD_NOGLOB 2
535 #endif
536 #if ENABLE_HUSH_FUNCTIONS
537 # define CMD_FUNCDEF 3
538 #endif
540 smalluint cmd_exitcode;
541 /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
542 struct pipe *group;
543 #if !BB_MMU
544 char *group_as_string;
545 #endif
546 #if ENABLE_HUSH_FUNCTIONS
547 struct function *child_func;
548 /* This field is used to prevent a bug here:
549 * while...do f1() {a;}; f1; f1() {b;}; f1; done
550 * When we execute "f1() {a;}" cmd, we create new function and clear
551 * cmd->group, cmd->group_as_string, cmd->argv[0].
552 * When we execute "f1() {b;}", we notice that f1 exists,
553 * and that its "parent cmd" struct is still "alive",
554 * we put those fields back into cmd->xxx
555 * (struct function has ->parent_cmd ptr to facilitate that).
556 * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
557 * Without this trick, loop would execute a;b;b;b;...
558 * instead of correct sequence a;b;a;b;...
559 * When command is freed, it severs the link
560 * (sets ->child_func->parent_cmd to NULL).
562 #endif
563 char **argv; /* command name and arguments */
564 /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
565 * and on execution these are substituted with their values.
566 * Substitution can make _several_ words out of one argv[n]!
567 * Example: argv[0]=='.^C*^C.' here: echo .$*.
568 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
570 struct redir_struct *redirects; /* I/O redirections */
572 /* Is there anything in this command at all? */
573 #define IS_NULL_CMD(cmd) \
574 (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
576 struct pipe {
577 struct pipe *next;
578 int num_cmds; /* total number of commands in pipe */
579 int alive_cmds; /* number of commands running (not exited) */
580 int stopped_cmds; /* number of commands alive, but stopped */
581 #if ENABLE_HUSH_JOB
582 int jobid; /* job number */
583 pid_t pgrp; /* process group ID for the job */
584 char *cmdtext; /* name of job */
585 #endif
586 struct command *cmds; /* array of commands in pipe */
587 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
588 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
589 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
591 typedef enum pipe_style {
592 PIPE_SEQ = 1,
593 PIPE_AND = 2,
594 PIPE_OR = 3,
595 PIPE_BG = 4,
596 } pipe_style;
597 /* Is there anything in this pipe at all? */
598 #define IS_NULL_PIPE(pi) \
599 ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
601 /* This holds pointers to the various results of parsing */
602 struct parse_context {
603 /* linked list of pipes */
604 struct pipe *list_head;
605 /* last pipe (being constructed right now) */
606 struct pipe *pipe;
607 /* last command in pipe (being constructed right now) */
608 struct command *command;
609 /* last redirect in command->redirects list */
610 struct redir_struct *pending_redirect;
611 #if !BB_MMU
612 o_string as_string;
613 #endif
614 #if HAS_KEYWORDS
615 smallint ctx_res_w;
616 smallint ctx_inverted; /* "! cmd | cmd" */
617 #if ENABLE_HUSH_CASE
618 smallint ctx_dsemicolon; /* ";;" seen */
619 #endif
620 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
621 int old_flag;
622 /* group we are enclosed in:
623 * example: "if pipe1; pipe2; then pipe3; fi"
624 * when we see "if" or "then", we malloc and copy current context,
625 * and make ->stack point to it. then we parse pipeN.
626 * when closing "then" / fi" / whatever is found,
627 * we move list_head into ->stack->command->group,
628 * copy ->stack into current context, and delete ->stack.
629 * (parsing of { list } and ( list ) doesn't use this method)
631 struct parse_context *stack;
632 #endif
635 /* On program start, environ points to initial environment.
636 * putenv adds new pointers into it, unsetenv removes them.
637 * Neither of these (de)allocates the strings.
638 * setenv allocates new strings in malloc space and does putenv,
639 * and thus setenv is unusable (leaky) for shell's purposes */
640 #define setenv(...) setenv_is_leaky_dont_use()
641 struct variable {
642 struct variable *next;
643 char *varstr; /* points to "name=" portion */
644 #if ENABLE_HUSH_LOCAL
645 unsigned func_nest_level;
646 #endif
647 int max_len; /* if > 0, name is part of initial env; else name is malloced */
648 smallint flg_export; /* putenv should be done on this var */
649 smallint flg_read_only;
652 enum {
653 BC_BREAK = 1,
654 BC_CONTINUE = 2,
657 #if ENABLE_HUSH_FUNCTIONS
658 struct function {
659 struct function *next;
660 char *name;
661 struct command *parent_cmd;
662 struct pipe *body;
663 # if !BB_MMU
664 char *body_as_string;
665 # endif
667 #endif
670 /* set -/+o OPT support. (TODO: make it optional)
671 * bash supports the following opts:
672 * allexport off
673 * braceexpand on
674 * emacs on
675 * errexit off
676 * errtrace off
677 * functrace off
678 * hashall on
679 * histexpand off
680 * history on
681 * ignoreeof off
682 * interactive-comments on
683 * keyword off
684 * monitor on
685 * noclobber off
686 * noexec off
687 * noglob off
688 * nolog off
689 * notify off
690 * nounset off
691 * onecmd off
692 * physical off
693 * pipefail off
694 * posix off
695 * privileged off
696 * verbose off
697 * vi off
698 * xtrace off
700 static const char o_opt_strings[] ALIGN1 =
701 "pipefail\0"
702 "noexec\0"
703 #if ENABLE_HUSH_MODE_X
704 "xtrace\0"
705 #endif
707 enum {
708 OPT_O_PIPEFAIL,
709 OPT_O_NOEXEC,
710 #if ENABLE_HUSH_MODE_X
711 OPT_O_XTRACE,
712 #endif
713 NUM_OPT_O
717 /* "Globals" within this file */
718 /* Sorted roughly by size (smaller offsets == smaller code) */
719 struct globals {
720 /* interactive_fd != 0 means we are an interactive shell.
721 * If we are, then saved_tty_pgrp can also be != 0, meaning
722 * that controlling tty is available. With saved_tty_pgrp == 0,
723 * job control still works, but terminal signals
724 * (^C, ^Z, ^Y, ^\) won't work at all, and background
725 * process groups can only be created with "cmd &".
726 * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
727 * to give tty to the foreground process group,
728 * and will take it back when the group is stopped (^Z)
729 * or killed (^C).
731 #if ENABLE_HUSH_INTERACTIVE
732 /* 'interactive_fd' is a fd# open to ctty, if we have one
733 * _AND_ if we decided to act interactively */
734 int interactive_fd;
735 const char *PS1;
736 const char *PS2;
737 # define G_interactive_fd (G.interactive_fd)
738 #else
739 # define G_interactive_fd 0
740 #endif
741 #if ENABLE_FEATURE_EDITING
742 line_input_t *line_input_state;
743 #endif
744 pid_t root_pid;
745 pid_t root_ppid;
746 pid_t last_bg_pid;
747 #if ENABLE_HUSH_RANDOM_SUPPORT
748 random_t random_gen;
749 #endif
750 #if ENABLE_HUSH_JOB
751 int run_list_level;
752 int last_jobid;
753 pid_t saved_tty_pgrp;
754 struct pipe *job_list;
755 # define G_saved_tty_pgrp (G.saved_tty_pgrp)
756 #else
757 # define G_saved_tty_pgrp 0
758 #endif
759 char o_opt[NUM_OPT_O];
760 #if ENABLE_HUSH_MODE_X
761 # define G_x_mode (G.o_opt[OPT_O_XTRACE])
762 #else
763 # define G_x_mode 0
764 #endif
765 smallint flag_SIGINT;
766 #if ENABLE_HUSH_LOOPS
767 smallint flag_break_continue;
768 #endif
769 #if ENABLE_HUSH_FUNCTIONS
770 /* 0: outside of a function (or sourced file)
771 * -1: inside of a function, ok to use return builtin
772 * 1: return is invoked, skip all till end of func
774 smallint flag_return_in_progress;
775 #endif
776 smallint exiting; /* used to prevent EXIT trap recursion */
777 /* These four support $?, $#, and $1 */
778 smalluint last_exitcode;
779 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
780 smalluint global_args_malloced;
781 /* how many non-NULL argv's we have. NB: $# + 1 */
782 int global_argc;
783 char **global_argv;
784 #if !BB_MMU
785 char *argv0_for_re_execing;
786 #endif
787 #if ENABLE_HUSH_LOOPS
788 unsigned depth_break_continue;
789 unsigned depth_of_loop;
790 #endif
791 const char *ifs;
792 const char *cwd;
793 struct variable *top_var;
794 char **expanded_assignments;
795 #if ENABLE_HUSH_FUNCTIONS
796 struct function *top_func;
797 # if ENABLE_HUSH_LOCAL
798 struct variable **shadowed_vars_pp;
799 unsigned func_nest_level;
800 # endif
801 #endif
802 /* Signal and trap handling */
803 #if ENABLE_HUSH_FAST
804 unsigned count_SIGCHLD;
805 unsigned handled_SIGCHLD;
806 smallint we_have_children;
807 #endif
808 /* Which signals have non-DFL handler (even with no traps set)?
809 * Set at the start to:
810 * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
811 * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
812 * The rest is cleared right before execv syscalls.
813 * Other than these two times, never modified.
815 unsigned special_sig_mask;
816 #if ENABLE_HUSH_JOB
817 unsigned fatal_sig_mask;
818 # define G_fatal_sig_mask G.fatal_sig_mask
819 #else
820 # define G_fatal_sig_mask 0
821 #endif
822 char **traps; /* char *traps[NSIG] */
823 sigset_t pending_set;
824 #if HUSH_DEBUG
825 unsigned long memleak_value;
826 int debug_indent;
827 #endif
828 struct sigaction sa;
829 char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
831 #define G (*ptr_to_globals)
832 /* Not #defining name to G.name - this quickly gets unwieldy
833 * (too many defines). Also, I actually prefer to see when a variable
834 * is global, thus "G." prefix is a useful hint */
835 #define INIT_G() do { \
836 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
837 /* memset(&G.sa, 0, sizeof(G.sa)); */ \
838 sigfillset(&G.sa.sa_mask); \
839 G.sa.sa_flags = SA_RESTART; \
840 } while (0)
843 /* Function prototypes for builtins */
844 static int builtin_cd(char **argv) FAST_FUNC;
845 static int builtin_echo(char **argv) FAST_FUNC;
846 static int builtin_eval(char **argv) FAST_FUNC;
847 static int builtin_exec(char **argv) FAST_FUNC;
848 static int builtin_exit(char **argv) FAST_FUNC;
849 static int builtin_export(char **argv) FAST_FUNC;
850 #if ENABLE_HUSH_JOB
851 static int builtin_fg_bg(char **argv) FAST_FUNC;
852 static int builtin_jobs(char **argv) FAST_FUNC;
853 #endif
854 #if ENABLE_HUSH_HELP
855 static int builtin_help(char **argv) FAST_FUNC;
856 #endif
857 #if ENABLE_HUSH_LOCAL
858 static int builtin_local(char **argv) FAST_FUNC;
859 #endif
860 #if HUSH_DEBUG
861 static int builtin_memleak(char **argv) FAST_FUNC;
862 #endif
863 #if ENABLE_PRINTF
864 static int builtin_printf(char **argv) FAST_FUNC;
865 #endif
866 static int builtin_pwd(char **argv) FAST_FUNC;
867 static int builtin_read(char **argv) FAST_FUNC;
868 static int builtin_set(char **argv) FAST_FUNC;
869 static int builtin_shift(char **argv) FAST_FUNC;
870 static int builtin_source(char **argv) FAST_FUNC;
871 static int builtin_test(char **argv) FAST_FUNC;
872 static int builtin_trap(char **argv) FAST_FUNC;
873 static int builtin_type(char **argv) FAST_FUNC;
874 static int builtin_true(char **argv) FAST_FUNC;
875 static int builtin_umask(char **argv) FAST_FUNC;
876 static int builtin_unset(char **argv) FAST_FUNC;
877 static int builtin_wait(char **argv) FAST_FUNC;
878 #if ENABLE_HUSH_LOOPS
879 static int builtin_break(char **argv) FAST_FUNC;
880 static int builtin_continue(char **argv) FAST_FUNC;
881 #endif
882 #if ENABLE_HUSH_FUNCTIONS
883 static int builtin_return(char **argv) FAST_FUNC;
884 #endif
886 /* Table of built-in functions. They can be forked or not, depending on
887 * context: within pipes, they fork. As simple commands, they do not.
888 * When used in non-forking context, they can change global variables
889 * in the parent shell process. If forked, of course they cannot.
890 * For example, 'unset foo | whatever' will parse and run, but foo will
891 * still be set at the end. */
892 struct built_in_command {
893 const char *b_cmd;
894 int (*b_function)(char **argv) FAST_FUNC;
895 #if ENABLE_HUSH_HELP
896 const char *b_descr;
897 # define BLTIN(cmd, func, help) { cmd, func, help }
898 #else
899 # define BLTIN(cmd, func, help) { cmd, func }
900 #endif
903 static const struct built_in_command bltins1[] = {
904 BLTIN("." , builtin_source , "Run commands in a file"),
905 BLTIN(":" , builtin_true , NULL),
906 #if ENABLE_HUSH_JOB
907 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
908 #endif
909 #if ENABLE_HUSH_LOOPS
910 BLTIN("break" , builtin_break , "Exit from a loop"),
911 #endif
912 BLTIN("cd" , builtin_cd , "Change directory"),
913 #if ENABLE_HUSH_LOOPS
914 BLTIN("continue" , builtin_continue, "Start new loop iteration"),
915 #endif
916 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
917 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
918 BLTIN("exit" , builtin_exit , "Exit"),
919 BLTIN("export" , builtin_export , "Set environment variables"),
920 #if ENABLE_HUSH_JOB
921 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
922 #endif
923 #if ENABLE_HUSH_HELP
924 BLTIN("help" , builtin_help , NULL),
925 #endif
926 #if ENABLE_HUSH_JOB
927 BLTIN("jobs" , builtin_jobs , "List jobs"),
928 #endif
929 #if ENABLE_HUSH_LOCAL
930 BLTIN("local" , builtin_local , "Set local variables"),
931 #endif
932 #if HUSH_DEBUG
933 BLTIN("memleak" , builtin_memleak , NULL),
934 #endif
935 BLTIN("read" , builtin_read , "Input into variable"),
936 #if ENABLE_HUSH_FUNCTIONS
937 BLTIN("return" , builtin_return , "Return from a function"),
938 #endif
939 BLTIN("set" , builtin_set , "Set/unset positional parameters"),
940 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
941 #if ENABLE_HUSH_BASH_COMPAT
942 BLTIN("source" , builtin_source , "Run commands in a file"),
943 #endif
944 BLTIN("trap" , builtin_trap , "Trap signals"),
945 BLTIN("type" , builtin_type , "Show command type"),
946 BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
947 BLTIN("umask" , builtin_umask , "Set file creation mask"),
948 BLTIN("unset" , builtin_unset , "Unset variables"),
949 BLTIN("wait" , builtin_wait , "Wait for process"),
951 /* For now, echo and test are unconditionally enabled.
952 * Maybe make it configurable? */
953 static const struct built_in_command bltins2[] = {
954 BLTIN("[" , builtin_test , NULL),
955 BLTIN("echo" , builtin_echo , NULL),
956 #if ENABLE_PRINTF
957 BLTIN("printf" , builtin_printf , NULL),
958 #endif
959 BLTIN("pwd" , builtin_pwd , NULL),
960 BLTIN("test" , builtin_test , NULL),
964 /* Debug printouts.
966 #if HUSH_DEBUG
967 /* prevent disasters with G.debug_indent < 0 */
968 # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
969 # define debug_enter() (G.debug_indent++)
970 # define debug_leave() (G.debug_indent--)
971 #else
972 # define indent() ((void)0)
973 # define debug_enter() ((void)0)
974 # define debug_leave() ((void)0)
975 #endif
977 #ifndef debug_printf
978 # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
979 #endif
981 #ifndef debug_printf_parse
982 # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
983 #endif
985 #ifndef debug_printf_exec
986 #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
987 #endif
989 #ifndef debug_printf_env
990 # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
991 #endif
993 #ifndef debug_printf_jobs
994 # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
995 # define DEBUG_JOBS 1
996 #else
997 # define DEBUG_JOBS 0
998 #endif
1000 #ifndef debug_printf_expand
1001 # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
1002 # define DEBUG_EXPAND 1
1003 #else
1004 # define DEBUG_EXPAND 0
1005 #endif
1007 #ifndef debug_printf_varexp
1008 # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
1009 #endif
1011 #ifndef debug_printf_glob
1012 # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
1013 # define DEBUG_GLOB 1
1014 #else
1015 # define DEBUG_GLOB 0
1016 #endif
1018 #ifndef debug_printf_list
1019 # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
1020 #endif
1022 #ifndef debug_printf_subst
1023 # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
1024 #endif
1026 #ifndef debug_printf_clean
1027 # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
1028 # define DEBUG_CLEAN 1
1029 #else
1030 # define DEBUG_CLEAN 0
1031 #endif
1033 #if DEBUG_EXPAND
1034 static void debug_print_strings(const char *prefix, char **vv)
1036 indent();
1037 fdprintf(2, "%s:\n", prefix);
1038 while (*vv)
1039 fdprintf(2, " '%s'\n", *vv++);
1041 #else
1042 # define debug_print_strings(prefix, vv) ((void)0)
1043 #endif
1046 /* Leak hunting. Use hush_leaktool.sh for post-processing.
1048 #if LEAK_HUNTING
1049 static void *xxmalloc(int lineno, size_t size)
1051 void *ptr = xmalloc((size + 0xff) & ~0xff);
1052 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
1053 return ptr;
1055 static void *xxrealloc(int lineno, void *ptr, size_t size)
1057 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
1058 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
1059 return ptr;
1061 static char *xxstrdup(int lineno, const char *str)
1063 char *ptr = xstrdup(str);
1064 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
1065 return ptr;
1067 static void xxfree(void *ptr)
1069 fdprintf(2, "free %p\n", ptr);
1070 free(ptr);
1072 # define xmalloc(s) xxmalloc(__LINE__, s)
1073 # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
1074 # define xstrdup(s) xxstrdup(__LINE__, s)
1075 # define free(p) xxfree(p)
1076 #endif
1079 /* Syntax and runtime errors. They always abort scripts.
1080 * In interactive use they usually discard unparsed and/or unexecuted commands
1081 * and return to the prompt.
1082 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
1084 #if HUSH_DEBUG < 2
1085 # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
1086 # define syntax_error(lineno, msg) syntax_error(msg)
1087 # define syntax_error_at(lineno, msg) syntax_error_at(msg)
1088 # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
1089 # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
1090 # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
1091 #endif
1093 static void die_if_script(unsigned lineno, const char *fmt, ...)
1095 va_list p;
1097 #if HUSH_DEBUG >= 2
1098 bb_error_msg("hush.c:%u", lineno);
1099 #endif
1100 va_start(p, fmt);
1101 bb_verror_msg(fmt, p, NULL);
1102 va_end(p);
1103 if (!G_interactive_fd)
1104 xfunc_die();
1107 static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
1109 if (msg)
1110 bb_error_msg("syntax error: %s", msg);
1111 else
1112 bb_error_msg("syntax error");
1115 static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
1117 bb_error_msg("syntax error at '%s'", msg);
1120 static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
1122 bb_error_msg("syntax error: unterminated %s", s);
1125 static void syntax_error_unterm_ch(unsigned lineno, char ch)
1127 char msg[2] = { ch, '\0' };
1128 syntax_error_unterm_str(lineno, msg);
1131 static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
1133 char msg[2];
1134 msg[0] = ch;
1135 msg[1] = '\0';
1136 bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
1139 #if HUSH_DEBUG < 2
1140 # undef die_if_script
1141 # undef syntax_error
1142 # undef syntax_error_at
1143 # undef syntax_error_unterm_ch
1144 # undef syntax_error_unterm_str
1145 # undef syntax_error_unexpected_ch
1146 #else
1147 # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
1148 # define syntax_error(msg) syntax_error(__LINE__, msg)
1149 # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
1150 # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
1151 # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
1152 # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
1153 #endif
1156 #if ENABLE_HUSH_INTERACTIVE
1157 static void cmdedit_update_prompt(void);
1158 #else
1159 # define cmdedit_update_prompt() ((void)0)
1160 #endif
1163 /* Utility functions
1165 /* Replace each \x with x in place, return ptr past NUL. */
1166 static char *unbackslash(char *src)
1168 char *dst = src = strchrnul(src, '\\');
1169 while (1) {
1170 if (*src == '\\')
1171 src++;
1172 if ((*dst++ = *src++) == '\0')
1173 break;
1175 return dst;
1178 static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
1180 int i;
1181 unsigned count1;
1182 unsigned count2;
1183 char **v;
1185 v = strings;
1186 count1 = 0;
1187 if (v) {
1188 while (*v) {
1189 count1++;
1190 v++;
1193 count2 = 0;
1194 v = add;
1195 while (*v) {
1196 count2++;
1197 v++;
1199 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
1200 v[count1 + count2] = NULL;
1201 i = count2;
1202 while (--i >= 0)
1203 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
1204 return v;
1206 #if LEAK_HUNTING
1207 static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
1209 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
1210 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
1211 return ptr;
1213 #define add_strings_to_strings(strings, add, need_to_dup) \
1214 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
1215 #endif
1217 /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
1218 static char **add_string_to_strings(char **strings, char *add)
1220 char *v[2];
1221 v[0] = add;
1222 v[1] = NULL;
1223 return add_strings_to_strings(strings, v, /*dup:*/ 0);
1225 #if LEAK_HUNTING
1226 static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
1228 char **ptr = add_string_to_strings(strings, add);
1229 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
1230 return ptr;
1232 #define add_string_to_strings(strings, add) \
1233 xx_add_string_to_strings(__LINE__, strings, add)
1234 #endif
1236 static void free_strings(char **strings)
1238 char **v;
1240 if (!strings)
1241 return;
1242 v = strings;
1243 while (*v) {
1244 free(*v);
1245 v++;
1247 free(strings);
1251 /* Helpers for setting new $n and restoring them back
1253 typedef struct save_arg_t {
1254 char *sv_argv0;
1255 char **sv_g_argv;
1256 int sv_g_argc;
1257 smallint sv_g_malloced;
1258 } save_arg_t;
1260 static void save_and_replace_G_args(save_arg_t *sv, char **argv)
1262 int n;
1264 sv->sv_argv0 = argv[0];
1265 sv->sv_g_argv = G.global_argv;
1266 sv->sv_g_argc = G.global_argc;
1267 sv->sv_g_malloced = G.global_args_malloced;
1269 argv[0] = G.global_argv[0]; /* retain $0 */
1270 G.global_argv = argv;
1271 G.global_args_malloced = 0;
1273 n = 1;
1274 while (*++argv)
1275 n++;
1276 G.global_argc = n;
1279 static void restore_G_args(save_arg_t *sv, char **argv)
1281 char **pp;
1283 if (G.global_args_malloced) {
1284 /* someone ran "set -- arg1 arg2 ...", undo */
1285 pp = G.global_argv;
1286 while (*++pp) /* note: does not free $0 */
1287 free(*pp);
1288 free(G.global_argv);
1290 argv[0] = sv->sv_argv0;
1291 G.global_argv = sv->sv_g_argv;
1292 G.global_argc = sv->sv_g_argc;
1293 G.global_args_malloced = sv->sv_g_malloced;
1297 /* Basic theory of signal handling in shell
1298 * ========================================
1299 * This does not describe what hush does, rather, it is current understanding
1300 * what it _should_ do. If it doesn't, it's a bug.
1301 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
1303 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
1304 * is finished or backgrounded. It is the same in interactive and
1305 * non-interactive shells, and is the same regardless of whether
1306 * a user trap handler is installed or a shell special one is in effect.
1307 * ^C or ^Z from keyboard seems to execute "at once" because it usually
1308 * backgrounds (i.e. stops) or kills all members of currently running
1309 * pipe.
1311 * Wait builtin in interruptible by signals for which user trap is set
1312 * or by SIGINT in interactive shell.
1314 * Trap handlers will execute even within trap handlers. (right?)
1316 * User trap handlers are forgotten when subshell ("(cmd)") is entered,
1317 * except for handlers set to '' (empty string).
1319 * If job control is off, backgrounded commands ("cmd &")
1320 * have SIGINT, SIGQUIT set to SIG_IGN.
1322 * Commands which are run in command substitution ("`cmd`")
1323 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
1325 * Ordinary commands have signals set to SIG_IGN/DFL as inherited
1326 * by the shell from its parent.
1328 * Signals which differ from SIG_DFL action
1329 * (note: child (i.e., [v]forked) shell is not an interactive shell):
1331 * SIGQUIT: ignore
1332 * SIGTERM (interactive): ignore
1333 * SIGHUP (interactive):
1334 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
1335 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
1336 * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
1337 * that all pipe members are stopped. Try this in bash:
1338 * while :; do :; done - ^Z does not background it
1339 * (while :; do :; done) - ^Z backgrounds it
1340 * SIGINT (interactive): wait for last pipe, ignore the rest
1341 * of the command line, show prompt. NB: ^C does not send SIGINT
1342 * to interactive shell while shell is waiting for a pipe,
1343 * since shell is bg'ed (is not in foreground process group).
1344 * Example 1: this waits 5 sec, but does not execute ls:
1345 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
1346 * Example 2: this does not wait and does not execute ls:
1347 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
1348 * Example 3: this does not wait 5 sec, but executes ls:
1349 * "sleep 5; ls -l" + press ^C
1350 * Example 4: this does not wait and does not execute ls:
1351 * "sleep 5 & wait; ls -l" + press ^C
1353 * (What happens to signals which are IGN on shell start?)
1354 * (What happens with signal mask on shell start?)
1356 * Old implementation
1357 * ==================
1358 * We use in-kernel pending signal mask to determine which signals were sent.
1359 * We block all signals which we don't want to take action immediately,
1360 * i.e. we block all signals which need to have special handling as described
1361 * above, and all signals which have traps set.
1362 * After each pipe execution, we extract any pending signals via sigtimedwait()
1363 * and act on them.
1365 * unsigned special_sig_mask: a mask of such "special" signals
1366 * sigset_t blocked_set: current blocked signal set
1368 * "trap - SIGxxx":
1369 * clear bit in blocked_set unless it is also in special_sig_mask
1370 * "trap 'cmd' SIGxxx":
1371 * set bit in blocked_set (even if 'cmd' is '')
1372 * after [v]fork, if we plan to be a shell:
1373 * unblock signals with special interactive handling
1374 * (child shell is not interactive),
1375 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1376 * after [v]fork, if we plan to exec:
1377 * POSIX says fork clears pending signal mask in child - no need to clear it.
1378 * Restore blocked signal set to one inherited by shell just prior to exec.
1380 * Note: as a result, we do not use signal handlers much. The only uses
1381 * are to count SIGCHLDs
1382 * and to restore tty pgrp on signal-induced exit.
1384 * Note 2 (compat):
1385 * Standard says "When a subshell is entered, traps that are not being ignored
1386 * are set to the default actions". bash interprets it so that traps which
1387 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1389 * Problem: the above approach makes it unwieldy to catch signals while
1390 * we are in read builtin, of while we read commands from stdin:
1391 * masked signals are not visible!
1393 * New implementation
1394 * ==================
1395 * We record each signal we are interested in by installing signal handler
1396 * for them - a bit like emulating kernel pending signal mask in userspace.
1397 * We are interested in: signals which need to have special handling
1398 * as described above, and all signals which have traps set.
1399 * Signals are rocorded in pending_set.
1400 * After each pipe execution, we extract any pending signals
1401 * and act on them.
1403 * unsigned special_sig_mask: a mask of shell-special signals.
1404 * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
1405 * char *traps[sig] if trap for sig is set (even if it's '').
1406 * sigset_t pending_set: set of sigs we received.
1408 * "trap - SIGxxx":
1409 * if sig is in special_sig_mask, set handler back to:
1410 * record_pending_signo, or to IGN if it's a tty stop signal
1411 * if sig is in fatal_sig_mask, set handler back to sigexit.
1412 * else: set handler back to SIG_DFL
1413 * "trap 'cmd' SIGxxx":
1414 * set handler to record_pending_signo.
1415 * "trap '' SIGxxx":
1416 * set handler to SIG_IGN.
1417 * after [v]fork, if we plan to be a shell:
1418 * set signals with special interactive handling to SIG_DFL
1419 * (because child shell is not interactive),
1420 * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
1421 * after [v]fork, if we plan to exec:
1422 * POSIX says fork clears pending signal mask in child - no need to clear it.
1424 * To make wait builtin interruptible, we handle SIGCHLD as special signal,
1425 * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
1427 * Note (compat):
1428 * Standard says "When a subshell is entered, traps that are not being ignored
1429 * are set to the default actions". bash interprets it so that traps which
1430 * are set to '' (ignore) are NOT reset to defaults. We do the same.
1432 enum {
1433 SPECIAL_INTERACTIVE_SIGS = 0
1434 | (1 << SIGTERM)
1435 | (1 << SIGINT)
1436 | (1 << SIGHUP)
1438 SPECIAL_JOBSTOP_SIGS = 0
1439 #if ENABLE_HUSH_JOB
1440 | (1 << SIGTTIN)
1441 | (1 << SIGTTOU)
1442 | (1 << SIGTSTP)
1443 #endif
1447 static void record_pending_signo(int sig)
1449 sigaddset(&G.pending_set, sig);
1450 #if ENABLE_HUSH_FAST
1451 if (sig == SIGCHLD) {
1452 G.count_SIGCHLD++;
1453 //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1455 #endif
1458 static sighandler_t install_sighandler(int sig, sighandler_t handler)
1460 struct sigaction old_sa;
1462 /* We could use signal() to install handlers... almost:
1463 * except that we need to mask ALL signals while handlers run.
1464 * I saw signal nesting in strace, race window isn't small.
1465 * SA_RESTART is also needed, but in Linux, signal()
1466 * sets SA_RESTART too.
1468 /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
1469 /* sigfillset(&G.sa.sa_mask); - already done */
1470 /* G.sa.sa_flags = SA_RESTART; - already done */
1471 G.sa.sa_handler = handler;
1472 sigaction(sig, &G.sa, &old_sa);
1473 return old_sa.sa_handler;
1476 #if ENABLE_HUSH_JOB
1478 /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1479 # define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
1480 /* After [v]fork, in parent: restore tty pgrp on xfunc death */
1481 # define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1483 /* Restores tty foreground process group, and exits.
1484 * May be called as signal handler for fatal signal
1485 * (will resend signal to itself, producing correct exit state)
1486 * or called directly with -EXITCODE.
1487 * We also call it if xfunc is exiting. */
1488 static void sigexit(int sig) NORETURN;
1489 static void sigexit(int sig)
1491 /* Careful: we can end up here after [v]fork. Do not restore
1492 * tty pgrp then, only top-level shell process does that */
1493 if (G_saved_tty_pgrp && getpid() == G.root_pid) {
1494 /* Disable all signals: job control, SIGPIPE, etc.
1495 * Mostly paranoid measure, to prevent infinite SIGTTOU.
1497 sigprocmask_allsigs(SIG_BLOCK);
1498 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
1501 /* Not a signal, just exit */
1502 if (sig <= 0)
1503 _exit(- sig);
1505 kill_myself_with_sig(sig); /* does not return */
1507 #else
1509 # define disable_restore_tty_pgrp_on_exit() ((void)0)
1510 # define enable_restore_tty_pgrp_on_exit() ((void)0)
1512 #endif
1514 static sighandler_t pick_sighandler(unsigned sig)
1516 sighandler_t handler = SIG_DFL;
1517 if (sig < sizeof(unsigned)*8) {
1518 unsigned sigmask = (1 << sig);
1520 #if ENABLE_HUSH_JOB
1521 /* is sig fatal? */
1522 if (G_fatal_sig_mask & sigmask)
1523 handler = sigexit;
1524 else
1525 #endif
1526 /* sig has special handling? */
1527 if (G.special_sig_mask & sigmask) {
1528 handler = record_pending_signo;
1529 /* TTIN/TTOU/TSTP can't be set to record_pending_signo
1530 * in order to ignore them: they will be raised
1531 * in an endless loop when we try to do some
1532 * terminal ioctls! We do have to _ignore_ these.
1534 if (SPECIAL_JOBSTOP_SIGS & sigmask)
1535 handler = SIG_IGN;
1538 return handler;
1541 /* Restores tty foreground process group, and exits. */
1542 static void hush_exit(int exitcode) NORETURN;
1543 static void hush_exit(int exitcode)
1545 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
1546 save_history(G.line_input_state);
1547 #endif
1549 fflush_all();
1550 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1551 char *argv[3];
1552 /* argv[0] is unused */
1553 argv[1] = G.traps[0];
1554 argv[2] = NULL;
1555 G.exiting = 1; /* prevent EXIT trap recursion */
1556 /* Note: G.traps[0] is not cleared!
1557 * "trap" will still show it, if executed
1558 * in the handler */
1559 builtin_eval(argv);
1562 #if ENABLE_FEATURE_CLEAN_UP
1564 struct variable *cur_var;
1565 if (G.cwd != bb_msg_unknown)
1566 free((char*)G.cwd);
1567 cur_var = G.top_var;
1568 while (cur_var) {
1569 struct variable *tmp = cur_var;
1570 if (!cur_var->max_len)
1571 free(cur_var->varstr);
1572 cur_var = cur_var->next;
1573 free(tmp);
1576 #endif
1578 #if ENABLE_HUSH_JOB
1579 fflush_all();
1580 sigexit(- (exitcode & 0xff));
1581 #else
1582 exit(exitcode);
1583 #endif
1587 //TODO: return a mask of ALL handled sigs?
1588 static int check_and_run_traps(void)
1590 int last_sig = 0;
1592 while (1) {
1593 int sig;
1595 if (sigisemptyset(&G.pending_set))
1596 break;
1597 sig = 0;
1598 do {
1599 sig++;
1600 if (sigismember(&G.pending_set, sig)) {
1601 sigdelset(&G.pending_set, sig);
1602 goto got_sig;
1604 } while (sig < NSIG);
1605 break;
1606 got_sig:
1607 if (G.traps && G.traps[sig]) {
1608 if (G.traps[sig][0]) {
1609 /* We have user-defined handler */
1610 smalluint save_rcode;
1611 char *argv[3];
1612 /* argv[0] is unused */
1613 argv[1] = G.traps[sig];
1614 argv[2] = NULL;
1615 save_rcode = G.last_exitcode;
1616 builtin_eval(argv);
1617 G.last_exitcode = save_rcode;
1618 last_sig = sig;
1619 } /* else: "" trap, ignoring signal */
1620 continue;
1622 /* not a trap: special action */
1623 switch (sig) {
1624 case SIGINT:
1625 /* Builtin was ^C'ed, make it look prettier: */
1626 bb_putchar('\n');
1627 G.flag_SIGINT = 1;
1628 last_sig = sig;
1629 break;
1630 #if ENABLE_HUSH_JOB
1631 case SIGHUP: {
1632 struct pipe *job;
1633 /* bash is observed to signal whole process groups,
1634 * not individual processes */
1635 for (job = G.job_list; job; job = job->next) {
1636 if (job->pgrp <= 0)
1637 continue;
1638 debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
1639 if (kill(- job->pgrp, SIGHUP) == 0)
1640 kill(- job->pgrp, SIGCONT);
1642 sigexit(SIGHUP);
1644 #endif
1645 #if ENABLE_HUSH_FAST
1646 case SIGCHLD:
1647 G.count_SIGCHLD++;
1648 //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
1649 /* Note:
1650 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1651 * This simplifies wait builtin a bit.
1653 break;
1654 #endif
1655 default: /* ignored: */
1656 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
1657 /* Note:
1658 * We dont do 'last_sig = sig' here -> NOT returning this sig.
1659 * Example: wait is not interrupted by TERM
1660 * in interactive shell, because TERM is ignored.
1662 break;
1665 return last_sig;
1669 static const char *get_cwd(int force)
1671 if (force || G.cwd == NULL) {
1672 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1673 * we must not try to free(bb_msg_unknown) */
1674 if (G.cwd == bb_msg_unknown)
1675 G.cwd = NULL;
1676 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1677 if (!G.cwd)
1678 G.cwd = bb_msg_unknown;
1680 return G.cwd;
1685 * Shell and environment variable support
1687 static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
1689 struct variable **pp;
1690 struct variable *cur;
1692 pp = &G.top_var;
1693 while ((cur = *pp) != NULL) {
1694 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1695 return pp;
1696 pp = &cur->next;
1698 return NULL;
1701 static const char* FAST_FUNC get_local_var_value(const char *name)
1703 struct variable **vpp;
1704 unsigned len = strlen(name);
1706 if (G.expanded_assignments) {
1707 char **cpp = G.expanded_assignments;
1708 while (*cpp) {
1709 char *cp = *cpp;
1710 if (strncmp(cp, name, len) == 0 && cp[len] == '=')
1711 return cp + len + 1;
1712 cpp++;
1716 vpp = get_ptr_to_local_var(name, len);
1717 if (vpp)
1718 return (*vpp)->varstr + len + 1;
1720 if (strcmp(name, "PPID") == 0)
1721 return utoa(G.root_ppid);
1722 // bash compat: UID? EUID?
1723 #if ENABLE_HUSH_RANDOM_SUPPORT
1724 if (strcmp(name, "RANDOM") == 0)
1725 return utoa(next_random(&G.random_gen));
1726 #endif
1727 return NULL;
1730 /* str holds "NAME=VAL" and is expected to be malloced.
1731 * We take ownership of it.
1732 * flg_export:
1733 * 0: do not change export flag
1734 * (if creating new variable, flag will be 0)
1735 * 1: set export flag and putenv the variable
1736 * -1: clear export flag and unsetenv the variable
1737 * flg_read_only is set only when we handle -R var=val
1739 #if !BB_MMU && ENABLE_HUSH_LOCAL
1740 /* all params are used */
1741 #elif BB_MMU && ENABLE_HUSH_LOCAL
1742 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1743 set_local_var(str, flg_export, local_lvl)
1744 #elif BB_MMU && !ENABLE_HUSH_LOCAL
1745 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1746 set_local_var(str, flg_export)
1747 #elif !BB_MMU && !ENABLE_HUSH_LOCAL
1748 #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
1749 set_local_var(str, flg_export, flg_read_only)
1750 #endif
1751 static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
1753 struct variable **var_pp;
1754 struct variable *cur;
1755 char *eq_sign;
1756 int name_len;
1758 eq_sign = strchr(str, '=');
1759 if (!eq_sign) { /* not expected to ever happen? */
1760 free(str);
1761 return -1;
1764 name_len = eq_sign - str + 1; /* including '=' */
1765 var_pp = &G.top_var;
1766 while ((cur = *var_pp) != NULL) {
1767 if (strncmp(cur->varstr, str, name_len) != 0) {
1768 var_pp = &cur->next;
1769 continue;
1771 /* We found an existing var with this name */
1772 if (cur->flg_read_only) {
1773 #if !BB_MMU
1774 if (!flg_read_only)
1775 #endif
1776 bb_error_msg("%s: readonly variable", str);
1777 free(str);
1778 return -1;
1780 if (flg_export == -1) { // "&& cur->flg_export" ?
1781 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1782 *eq_sign = '\0';
1783 unsetenv(str);
1784 *eq_sign = '=';
1786 #if ENABLE_HUSH_LOCAL
1787 if (cur->func_nest_level < local_lvl) {
1788 /* New variable is declared as local,
1789 * and existing one is global, or local
1790 * from enclosing function.
1791 * Remove and save old one: */
1792 *var_pp = cur->next;
1793 cur->next = *G.shadowed_vars_pp;
1794 *G.shadowed_vars_pp = cur;
1795 /* bash 3.2.33(1) and exported vars:
1796 * # export z=z
1797 * # f() { local z=a; env | grep ^z; }
1798 * # f
1799 * z=a
1800 * # env | grep ^z
1801 * z=z
1803 if (cur->flg_export)
1804 flg_export = 1;
1805 break;
1807 #endif
1808 if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
1809 free_and_exp:
1810 free(str);
1811 goto exp;
1813 if (cur->max_len != 0) {
1814 if (cur->max_len >= strlen(str)) {
1815 /* This one is from startup env, reuse space */
1816 strcpy(cur->varstr, str);
1817 goto free_and_exp;
1819 } else {
1820 /* max_len == 0 signifies "malloced" var, which we can
1821 * (and has to) free */
1822 free(cur->varstr);
1824 cur->max_len = 0;
1825 goto set_str_and_exp;
1828 /* Not found - create new variable struct */
1829 cur = xzalloc(sizeof(*cur));
1830 #if ENABLE_HUSH_LOCAL
1831 cur->func_nest_level = local_lvl;
1832 #endif
1833 cur->next = *var_pp;
1834 *var_pp = cur;
1836 set_str_and_exp:
1837 cur->varstr = str;
1838 #if !BB_MMU
1839 cur->flg_read_only = flg_read_only;
1840 #endif
1841 exp:
1842 if (flg_export == 1)
1843 cur->flg_export = 1;
1844 if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1845 cmdedit_update_prompt();
1846 if (cur->flg_export) {
1847 if (flg_export == -1) {
1848 cur->flg_export = 0;
1849 /* unsetenv was already done */
1850 } else {
1851 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1852 return putenv(cur->varstr);
1855 return 0;
1858 /* Used at startup and after each cd */
1859 static void set_pwd_var(int exp)
1861 set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
1862 /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
1865 static int unset_local_var_len(const char *name, int name_len)
1867 struct variable *cur;
1868 struct variable **var_pp;
1870 if (!name)
1871 return EXIT_SUCCESS;
1872 var_pp = &G.top_var;
1873 while ((cur = *var_pp) != NULL) {
1874 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1875 if (cur->flg_read_only) {
1876 bb_error_msg("%s: readonly variable", name);
1877 return EXIT_FAILURE;
1879 *var_pp = cur->next;
1880 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1881 bb_unsetenv(cur->varstr);
1882 if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
1883 cmdedit_update_prompt();
1884 if (!cur->max_len)
1885 free(cur->varstr);
1886 free(cur);
1887 return EXIT_SUCCESS;
1889 var_pp = &cur->next;
1891 return EXIT_SUCCESS;
1894 static int unset_local_var(const char *name)
1896 return unset_local_var_len(name, strlen(name));
1899 static void unset_vars(char **strings)
1901 char **v;
1903 if (!strings)
1904 return;
1905 v = strings;
1906 while (*v) {
1907 const char *eq = strchrnul(*v, '=');
1908 unset_local_var_len(*v, (int)(eq - *v));
1909 v++;
1911 free(strings);
1914 static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
1916 char *var = xasprintf("%s=%s", name, val);
1917 set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
1922 * Helpers for "var1=val1 var2=val2 cmd" feature
1924 static void add_vars(struct variable *var)
1926 struct variable *next;
1928 while (var) {
1929 next = var->next;
1930 var->next = G.top_var;
1931 G.top_var = var;
1932 if (var->flg_export) {
1933 debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
1934 putenv(var->varstr);
1935 } else {
1936 debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
1938 var = next;
1942 static struct variable *set_vars_and_save_old(char **strings)
1944 char **s;
1945 struct variable *old = NULL;
1947 if (!strings)
1948 return old;
1949 s = strings;
1950 while (*s) {
1951 struct variable *var_p;
1952 struct variable **var_pp;
1953 char *eq;
1955 eq = strchr(*s, '=');
1956 if (eq) {
1957 var_pp = get_ptr_to_local_var(*s, eq - *s);
1958 if (var_pp) {
1959 /* Remove variable from global linked list */
1960 var_p = *var_pp;
1961 debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
1962 *var_pp = var_p->next;
1963 /* Add it to returned list */
1964 var_p->next = old;
1965 old = var_p;
1967 set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
1969 s++;
1971 return old;
1976 * in_str support
1978 static int FAST_FUNC static_get(struct in_str *i)
1980 int ch = *i->p;
1981 if (ch != '\0') {
1982 i->p++;
1983 i->last_char = ch;
1984 return ch;
1986 return EOF;
1989 static int FAST_FUNC static_peek(struct in_str *i)
1991 return *i->p;
1994 #if ENABLE_HUSH_INTERACTIVE
1996 static void cmdedit_update_prompt(void)
1998 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1999 G.PS1 = get_local_var_value("PS1");
2000 if (G.PS1 == NULL)
2001 G.PS1 = "\\w \\$ ";
2002 G.PS2 = get_local_var_value("PS2");
2003 } else {
2004 G.PS1 = NULL;
2006 if (G.PS2 == NULL)
2007 G.PS2 = "> ";
2010 static const char *setup_prompt_string(int promptmode)
2012 const char *prompt_str;
2013 debug_printf("setup_prompt_string %d ", promptmode);
2014 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
2015 /* Set up the prompt */
2016 if (promptmode == 0) { /* PS1 */
2017 free((char*)G.PS1);
2018 /* bash uses $PWD value, even if it is set by user.
2019 * It uses current dir only if PWD is unset.
2020 * We always use current dir. */
2021 G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
2022 prompt_str = G.PS1;
2023 } else
2024 prompt_str = G.PS2;
2025 } else
2026 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
2027 debug_printf("result '%s'\n", prompt_str);
2028 return prompt_str;
2031 static void get_user_input(struct in_str *i)
2033 int r;
2034 const char *prompt_str;
2036 prompt_str = setup_prompt_string(i->promptmode);
2037 # if ENABLE_FEATURE_EDITING
2038 /* Enable command line editing only while a command line
2039 * is actually being read */
2040 do {
2041 /* Unicode support should be activated even if LANG is set
2042 * _during_ shell execution, not only if it was set when
2043 * shell was started. Therefore, re-check LANG every time:
2045 reinit_unicode(get_local_var_value("LANG"));
2047 G.flag_SIGINT = 0;
2048 /* buglet: SIGINT will not make new prompt to appear _at once_,
2049 * only after <Enter>. (^C will work) */
2050 r = read_line_input(G.line_input_state, prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, /*timeout*/ -1);
2051 /* catch *SIGINT* etc (^C is handled by read_line_input) */
2052 check_and_run_traps();
2053 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
2054 i->eof_flag = (r < 0);
2055 if (i->eof_flag) { /* EOF/error detected */
2056 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
2057 G.user_input_buf[1] = '\0';
2059 # else
2060 do {
2061 G.flag_SIGINT = 0;
2062 if (i->last_char == '\0' || i->last_char == '\n') {
2063 /* Why check_and_run_traps here? Try this interactively:
2064 * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
2065 * $ <[enter], repeatedly...>
2066 * Without check_and_run_traps, handler never runs.
2068 check_and_run_traps();
2069 fputs(prompt_str, stdout);
2071 fflush_all();
2072 G.user_input_buf[0] = r = fgetc(i->file);
2073 /*G.user_input_buf[1] = '\0'; - already is and never changed */
2074 } while (G.flag_SIGINT);
2075 i->eof_flag = (r == EOF);
2076 # endif
2077 i->p = G.user_input_buf;
2080 #endif /* INTERACTIVE */
2082 /* This is the magic location that prints prompts
2083 * and gets data back from the user */
2084 static int FAST_FUNC file_get(struct in_str *i)
2086 int ch;
2088 /* If there is data waiting, eat it up */
2089 if (i->p && *i->p) {
2090 #if ENABLE_HUSH_INTERACTIVE
2091 take_cached:
2092 #endif
2093 ch = *i->p++;
2094 if (i->eof_flag && !*i->p)
2095 ch = EOF;
2096 /* note: ch is never NUL */
2097 } else {
2098 /* need to double check i->file because we might be doing something
2099 * more complicated by now, like sourcing or substituting. */
2100 #if ENABLE_HUSH_INTERACTIVE
2101 if (G_interactive_fd && i->file == stdin) {
2102 do {
2103 get_user_input(i);
2104 } while (!*i->p); /* need non-empty line */
2105 i->promptmode = 1; /* PS2 */
2106 goto take_cached;
2108 #endif
2109 do ch = fgetc(i->file); while (ch == '\0');
2111 debug_printf("file_get: got '%c' %d\n", ch, ch);
2112 i->last_char = ch;
2113 return ch;
2116 /* All callers guarantee this routine will never
2117 * be used right after a newline, so prompting is not needed.
2119 static int FAST_FUNC file_peek(struct in_str *i)
2121 int ch;
2122 if (i->p && *i->p) {
2123 if (i->eof_flag && !i->p[1])
2124 return EOF;
2125 return *i->p;
2126 /* note: ch is never NUL */
2128 do ch = fgetc(i->file); while (ch == '\0');
2129 i->eof_flag = (ch == EOF);
2130 i->peek_buf[0] = ch;
2131 i->peek_buf[1] = '\0';
2132 i->p = i->peek_buf;
2133 debug_printf("file_peek: got '%c' %d\n", ch, ch);
2134 return ch;
2137 static void setup_file_in_str(struct in_str *i, FILE *f)
2139 memset(i, 0, sizeof(*i));
2140 i->peek = file_peek;
2141 i->get = file_get;
2142 /* i->promptmode = 0; - PS1 (memset did it) */
2143 i->file = f;
2144 /* i->p = NULL; */
2147 static void setup_string_in_str(struct in_str *i, const char *s)
2149 memset(i, 0, sizeof(*i));
2150 i->peek = static_peek;
2151 i->get = static_get;
2152 /* i->promptmode = 0; - PS1 (memset did it) */
2153 i->p = s;
2154 /* i->eof_flag = 0; */
2159 * o_string support
2161 #define B_CHUNK (32 * sizeof(char*))
2163 static void o_reset_to_empty_unquoted(o_string *o)
2165 o->length = 0;
2166 o->has_quoted_part = 0;
2167 if (o->data)
2168 o->data[0] = '\0';
2171 static void o_free(o_string *o)
2173 free(o->data);
2174 memset(o, 0, sizeof(*o));
2177 static ALWAYS_INLINE void o_free_unsafe(o_string *o)
2179 free(o->data);
2182 static void o_grow_by(o_string *o, int len)
2184 if (o->length + len > o->maxlen) {
2185 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
2186 o->data = xrealloc(o->data, 1 + o->maxlen);
2190 static void o_addchr(o_string *o, int ch)
2192 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
2193 o_grow_by(o, 1);
2194 o->data[o->length] = ch;
2195 o->length++;
2196 o->data[o->length] = '\0';
2199 static void o_addblock(o_string *o, const char *str, int len)
2201 o_grow_by(o, len);
2202 memcpy(&o->data[o->length], str, len);
2203 o->length += len;
2204 o->data[o->length] = '\0';
2207 static void o_addstr(o_string *o, const char *str)
2209 o_addblock(o, str, strlen(str));
2212 #if !BB_MMU
2213 static void nommu_addchr(o_string *o, int ch)
2215 if (o)
2216 o_addchr(o, ch);
2218 #else
2219 # define nommu_addchr(o, str) ((void)0)
2220 #endif
2222 static void o_addstr_with_NUL(o_string *o, const char *str)
2224 o_addblock(o, str, strlen(str) + 1);
2228 * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
2229 * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
2230 * Apparently, on unquoted $v bash still does globbing
2231 * ("v='*.txt'; echo $v" prints all .txt files),
2232 * but NOT brace expansion! Thus, there should be TWO independent
2233 * quoting mechanisms on $v expansion side: one protects
2234 * $v from brace expansion, and other additionally protects "$v" against globbing.
2235 * We have only second one.
2238 #if ENABLE_HUSH_BRACE_EXPANSION
2239 # define MAYBE_BRACES "{}"
2240 #else
2241 # define MAYBE_BRACES ""
2242 #endif
2244 /* My analysis of quoting semantics tells me that state information
2245 * is associated with a destination, not a source.
2247 static void o_addqchr(o_string *o, int ch)
2249 int sz = 1;
2250 char *found = strchr("*?[\\" MAYBE_BRACES, ch);
2251 if (found)
2252 sz++;
2253 o_grow_by(o, sz);
2254 if (found) {
2255 o->data[o->length] = '\\';
2256 o->length++;
2258 o->data[o->length] = ch;
2259 o->length++;
2260 o->data[o->length] = '\0';
2263 static void o_addQchr(o_string *o, int ch)
2265 int sz = 1;
2266 if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
2267 && strchr("*?[\\" MAYBE_BRACES, ch)
2269 sz++;
2270 o->data[o->length] = '\\';
2271 o->length++;
2273 o_grow_by(o, sz);
2274 o->data[o->length] = ch;
2275 o->length++;
2276 o->data[o->length] = '\0';
2279 static void o_addqblock(o_string *o, const char *str, int len)
2281 while (len) {
2282 char ch;
2283 int sz;
2284 int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
2285 if (ordinary_cnt > len) /* paranoia */
2286 ordinary_cnt = len;
2287 o_addblock(o, str, ordinary_cnt);
2288 if (ordinary_cnt == len)
2289 return; /* NUL is already added by o_addblock */
2290 str += ordinary_cnt;
2291 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
2293 ch = *str++;
2294 sz = 1;
2295 if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
2296 sz++;
2297 o->data[o->length] = '\\';
2298 o->length++;
2300 o_grow_by(o, sz);
2301 o->data[o->length] = ch;
2302 o->length++;
2304 o->data[o->length] = '\0';
2307 static void o_addQblock(o_string *o, const char *str, int len)
2309 if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
2310 o_addblock(o, str, len);
2311 return;
2313 o_addqblock(o, str, len);
2316 static void o_addQstr(o_string *o, const char *str)
2318 o_addQblock(o, str, strlen(str));
2321 /* A special kind of o_string for $VAR and `cmd` expansion.
2322 * It contains char* list[] at the beginning, which is grown in 16 element
2323 * increments. Actual string data starts at the next multiple of 16 * (char*).
2324 * list[i] contains an INDEX (int!) into this string data.
2325 * It means that if list[] needs to grow, data needs to be moved higher up
2326 * but list[i]'s need not be modified.
2327 * NB: remembering how many list[i]'s you have there is crucial.
2328 * o_finalize_list() operation post-processes this structure - calculates
2329 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
2331 #if DEBUG_EXPAND || DEBUG_GLOB
2332 static void debug_print_list(const char *prefix, o_string *o, int n)
2334 char **list = (char**)o->data;
2335 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2336 int i = 0;
2338 indent();
2339 fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
2340 prefix, list, n, string_start, o->length, o->maxlen,
2341 !!(o->o_expflags & EXP_FLAG_GLOB),
2342 o->has_quoted_part,
2343 !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
2344 while (i < n) {
2345 indent();
2346 fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
2347 o->data + (int)(uintptr_t)list[i] + string_start,
2348 o->data + (int)(uintptr_t)list[i] + string_start);
2349 i++;
2351 if (n) {
2352 const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
2353 indent();
2354 fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
2357 #else
2358 # define debug_print_list(prefix, o, n) ((void)0)
2359 #endif
2361 /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
2362 * in list[n] so that it points past last stored byte so far.
2363 * It returns n+1. */
2364 static int o_save_ptr_helper(o_string *o, int n)
2366 char **list = (char**)o->data;
2367 int string_start;
2368 int string_len;
2370 if (!o->has_empty_slot) {
2371 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2372 string_len = o->length - string_start;
2373 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
2374 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
2375 /* list[n] points to string_start, make space for 16 more pointers */
2376 o->maxlen += 0x10 * sizeof(list[0]);
2377 o->data = xrealloc(o->data, o->maxlen + 1);
2378 list = (char**)o->data;
2379 memmove(list + n + 0x10, list + n, string_len);
2380 o->length += 0x10 * sizeof(list[0]);
2381 } else {
2382 debug_printf_list("list[%d]=%d string_start=%d\n",
2383 n, string_len, string_start);
2385 } else {
2386 /* We have empty slot at list[n], reuse without growth */
2387 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
2388 string_len = o->length - string_start;
2389 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
2390 n, string_len, string_start);
2391 o->has_empty_slot = 0;
2393 o->has_quoted_part = 0;
2394 list[n] = (char*)(uintptr_t)string_len;
2395 return n + 1;
2398 /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
2399 static int o_get_last_ptr(o_string *o, int n)
2401 char **list = (char**)o->data;
2402 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2404 return ((int)(uintptr_t)list[n-1]) + string_start;
2407 #if ENABLE_HUSH_BRACE_EXPANSION
2408 /* There in a GNU extension, GLOB_BRACE, but it is not usable:
2409 * first, it processes even {a} (no commas), second,
2410 * I didn't manage to make it return strings when they don't match
2411 * existing files. Need to re-implement it.
2414 /* Helper */
2415 static int glob_needed(const char *s)
2417 while (*s) {
2418 if (*s == '\\') {
2419 if (!s[1])
2420 return 0;
2421 s += 2;
2422 continue;
2424 if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
2425 return 1;
2426 s++;
2428 return 0;
2430 /* Return pointer to next closing brace or to comma */
2431 static const char *next_brace_sub(const char *cp)
2433 unsigned depth = 0;
2434 cp++;
2435 while (*cp != '\0') {
2436 if (*cp == '\\') {
2437 if (*++cp == '\0')
2438 break;
2439 cp++;
2440 continue;
2442 if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
2443 break;
2444 if (*cp++ == '{')
2445 depth++;
2448 return *cp != '\0' ? cp : NULL;
2450 /* Recursive brace globber. Note: may garble pattern[]. */
2451 static int glob_brace(char *pattern, o_string *o, int n)
2453 char *new_pattern_buf;
2454 const char *begin;
2455 const char *next;
2456 const char *rest;
2457 const char *p;
2458 size_t rest_len;
2460 debug_printf_glob("glob_brace('%s')\n", pattern);
2462 begin = pattern;
2463 while (1) {
2464 if (*begin == '\0')
2465 goto simple_glob;
2466 if (*begin == '{') {
2467 /* Find the first sub-pattern and at the same time
2468 * find the rest after the closing brace */
2469 next = next_brace_sub(begin);
2470 if (next == NULL) {
2471 /* An illegal expression */
2472 goto simple_glob;
2474 if (*next == '}') {
2475 /* "{abc}" with no commas - illegal
2476 * brace expr, disregard and skip it */
2477 begin = next + 1;
2478 continue;
2480 break;
2482 if (*begin == '\\' && begin[1] != '\0')
2483 begin++;
2484 begin++;
2486 debug_printf_glob("begin:%s\n", begin);
2487 debug_printf_glob("next:%s\n", next);
2489 /* Now find the end of the whole brace expression */
2490 rest = next;
2491 while (*rest != '}') {
2492 rest = next_brace_sub(rest);
2493 if (rest == NULL) {
2494 /* An illegal expression */
2495 goto simple_glob;
2497 debug_printf_glob("rest:%s\n", rest);
2499 rest_len = strlen(++rest) + 1;
2501 /* We are sure the brace expression is well-formed */
2503 /* Allocate working buffer large enough for our work */
2504 new_pattern_buf = xmalloc(strlen(pattern));
2506 /* We have a brace expression. BEGIN points to the opening {,
2507 * NEXT points past the terminator of the first element, and REST
2508 * points past the final }. We will accumulate result names from
2509 * recursive runs for each brace alternative in the buffer using
2510 * GLOB_APPEND. */
2512 p = begin + 1;
2513 while (1) {
2514 /* Construct the new glob expression */
2515 memcpy(
2516 mempcpy(
2517 mempcpy(new_pattern_buf,
2518 /* We know the prefix for all sub-patterns */
2519 pattern, begin - pattern),
2520 p, next - p),
2521 rest, rest_len);
2523 /* Note: glob_brace() may garble new_pattern_buf[].
2524 * That's why we re-copy prefix every time (1st memcpy above).
2526 n = glob_brace(new_pattern_buf, o, n);
2527 if (*next == '}') {
2528 /* We saw the last entry */
2529 break;
2531 p = next + 1;
2532 next = next_brace_sub(next);
2534 free(new_pattern_buf);
2535 return n;
2537 simple_glob:
2539 int gr;
2540 glob_t globdata;
2542 memset(&globdata, 0, sizeof(globdata));
2543 gr = glob(pattern, 0, NULL, &globdata);
2544 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2545 if (gr != 0) {
2546 if (gr == GLOB_NOMATCH) {
2547 globfree(&globdata);
2548 /* NB: garbles parameter */
2549 unbackslash(pattern);
2550 o_addstr_with_NUL(o, pattern);
2551 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2552 return o_save_ptr_helper(o, n);
2554 if (gr == GLOB_NOSPACE)
2555 bb_error_msg_and_die(bb_msg_memory_exhausted);
2556 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2557 * but we didn't specify it. Paranoia again. */
2558 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2560 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2561 char **argv = globdata.gl_pathv;
2562 while (1) {
2563 o_addstr_with_NUL(o, *argv);
2564 n = o_save_ptr_helper(o, n);
2565 argv++;
2566 if (!*argv)
2567 break;
2570 globfree(&globdata);
2572 return n;
2574 /* Performs globbing on last list[],
2575 * saving each result as a new list[].
2577 static int perform_glob(o_string *o, int n)
2579 char *pattern, *copy;
2581 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2582 if (!o->data)
2583 return o_save_ptr_helper(o, n);
2584 pattern = o->data + o_get_last_ptr(o, n);
2585 debug_printf_glob("glob pattern '%s'\n", pattern);
2586 if (!glob_needed(pattern)) {
2587 /* unbackslash last string in o in place, fix length */
2588 o->length = unbackslash(pattern) - o->data;
2589 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2590 return o_save_ptr_helper(o, n);
2593 copy = xstrdup(pattern);
2594 /* "forget" pattern in o */
2595 o->length = pattern - o->data;
2596 n = glob_brace(copy, o, n);
2597 free(copy);
2598 if (DEBUG_GLOB)
2599 debug_print_list("perform_glob returning", o, n);
2600 return n;
2603 #else /* !HUSH_BRACE_EXPANSION */
2605 /* Helper */
2606 static int glob_needed(const char *s)
2608 while (*s) {
2609 if (*s == '\\') {
2610 if (!s[1])
2611 return 0;
2612 s += 2;
2613 continue;
2615 if (*s == '*' || *s == '[' || *s == '?')
2616 return 1;
2617 s++;
2619 return 0;
2621 /* Performs globbing on last list[],
2622 * saving each result as a new list[].
2624 static int perform_glob(o_string *o, int n)
2626 glob_t globdata;
2627 int gr;
2628 char *pattern;
2630 debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
2631 if (!o->data)
2632 return o_save_ptr_helper(o, n);
2633 pattern = o->data + o_get_last_ptr(o, n);
2634 debug_printf_glob("glob pattern '%s'\n", pattern);
2635 if (!glob_needed(pattern)) {
2636 literal:
2637 /* unbackslash last string in o in place, fix length */
2638 o->length = unbackslash(pattern) - o->data;
2639 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
2640 return o_save_ptr_helper(o, n);
2643 memset(&globdata, 0, sizeof(globdata));
2644 /* Can't use GLOB_NOCHECK: it does not unescape the string.
2645 * If we glob "*.\*" and don't find anything, we need
2646 * to fall back to using literal "*.*", but GLOB_NOCHECK
2647 * will return "*.\*"!
2649 gr = glob(pattern, 0, NULL, &globdata);
2650 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
2651 if (gr != 0) {
2652 if (gr == GLOB_NOMATCH) {
2653 globfree(&globdata);
2654 goto literal;
2656 if (gr == GLOB_NOSPACE)
2657 bb_error_msg_and_die(bb_msg_memory_exhausted);
2658 /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
2659 * but we didn't specify it. Paranoia again. */
2660 bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
2662 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
2663 char **argv = globdata.gl_pathv;
2664 /* "forget" pattern in o */
2665 o->length = pattern - o->data;
2666 while (1) {
2667 o_addstr_with_NUL(o, *argv);
2668 n = o_save_ptr_helper(o, n);
2669 argv++;
2670 if (!*argv)
2671 break;
2674 globfree(&globdata);
2675 if (DEBUG_GLOB)
2676 debug_print_list("perform_glob returning", o, n);
2677 return n;
2680 #endif /* !HUSH_BRACE_EXPANSION */
2682 /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
2683 * Otherwise, just finish current list[] and start new */
2684 static int o_save_ptr(o_string *o, int n)
2686 if (o->o_expflags & EXP_FLAG_GLOB) {
2687 /* If o->has_empty_slot, list[n] was already globbed
2688 * (if it was requested back then when it was filled)
2689 * so don't do that again! */
2690 if (!o->has_empty_slot)
2691 return perform_glob(o, n); /* o_save_ptr_helper is inside */
2693 return o_save_ptr_helper(o, n);
2696 /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
2697 static char **o_finalize_list(o_string *o, int n)
2699 char **list;
2700 int string_start;
2702 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
2703 if (DEBUG_EXPAND)
2704 debug_print_list("finalized", o, n);
2705 debug_printf_expand("finalized n:%d\n", n);
2706 list = (char**)o->data;
2707 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
2708 list[--n] = NULL;
2709 while (n) {
2710 n--;
2711 list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
2713 return list;
2716 static void free_pipe_list(struct pipe *pi);
2718 /* Returns pi->next - next pipe in the list */
2719 static struct pipe *free_pipe(struct pipe *pi)
2721 struct pipe *next;
2722 int i;
2724 debug_printf_clean("free_pipe (pid %d)\n", getpid());
2725 for (i = 0; i < pi->num_cmds; i++) {
2726 struct command *command;
2727 struct redir_struct *r, *rnext;
2729 command = &pi->cmds[i];
2730 debug_printf_clean(" command %d:\n", i);
2731 if (command->argv) {
2732 if (DEBUG_CLEAN) {
2733 int a;
2734 char **p;
2735 for (a = 0, p = command->argv; *p; a++, p++) {
2736 debug_printf_clean(" argv[%d] = %s\n", a, *p);
2739 free_strings(command->argv);
2740 //command->argv = NULL;
2742 /* not "else if": on syntax error, we may have both! */
2743 if (command->group) {
2744 debug_printf_clean(" begin group (cmd_type:%d)\n",
2745 command->cmd_type);
2746 free_pipe_list(command->group);
2747 debug_printf_clean(" end group\n");
2748 //command->group = NULL;
2750 /* else is crucial here.
2751 * If group != NULL, child_func is meaningless */
2752 #if ENABLE_HUSH_FUNCTIONS
2753 else if (command->child_func) {
2754 debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
2755 command->child_func->parent_cmd = NULL;
2757 #endif
2758 #if !BB_MMU
2759 free(command->group_as_string);
2760 //command->group_as_string = NULL;
2761 #endif
2762 for (r = command->redirects; r; r = rnext) {
2763 debug_printf_clean(" redirect %d%s",
2764 r->rd_fd, redir_table[r->rd_type].descrip);
2765 /* guard against the case >$FOO, where foo is unset or blank */
2766 if (r->rd_filename) {
2767 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2768 free(r->rd_filename);
2769 //r->rd_filename = NULL;
2771 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
2772 rnext = r->next;
2773 free(r);
2775 //command->redirects = NULL;
2777 free(pi->cmds); /* children are an array, they get freed all at once */
2778 //pi->cmds = NULL;
2779 #if ENABLE_HUSH_JOB
2780 free(pi->cmdtext);
2781 //pi->cmdtext = NULL;
2782 #endif
2784 next = pi->next;
2785 free(pi);
2786 return next;
2789 static void free_pipe_list(struct pipe *pi)
2791 while (pi) {
2792 #if HAS_KEYWORDS
2793 debug_printf_clean("pipe reserved word %d\n", pi->res_word);
2794 #endif
2795 debug_printf_clean("pipe followup code %d\n", pi->followup);
2796 pi = free_pipe(pi);
2801 /*** Parsing routines ***/
2803 #ifndef debug_print_tree
2804 static void debug_print_tree(struct pipe *pi, int lvl)
2806 static const char *const PIPE[] = {
2807 [PIPE_SEQ] = "SEQ",
2808 [PIPE_AND] = "AND",
2809 [PIPE_OR ] = "OR" ,
2810 [PIPE_BG ] = "BG" ,
2812 static const char *RES[] = {
2813 [RES_NONE ] = "NONE" ,
2814 # if ENABLE_HUSH_IF
2815 [RES_IF ] = "IF" ,
2816 [RES_THEN ] = "THEN" ,
2817 [RES_ELIF ] = "ELIF" ,
2818 [RES_ELSE ] = "ELSE" ,
2819 [RES_FI ] = "FI" ,
2820 # endif
2821 # if ENABLE_HUSH_LOOPS
2822 [RES_FOR ] = "FOR" ,
2823 [RES_WHILE] = "WHILE",
2824 [RES_UNTIL] = "UNTIL",
2825 [RES_DO ] = "DO" ,
2826 [RES_DONE ] = "DONE" ,
2827 # endif
2828 # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
2829 [RES_IN ] = "IN" ,
2830 # endif
2831 # if ENABLE_HUSH_CASE
2832 [RES_CASE ] = "CASE" ,
2833 [RES_CASE_IN ] = "CASE_IN" ,
2834 [RES_MATCH] = "MATCH",
2835 [RES_CASE_BODY] = "CASE_BODY",
2836 [RES_ESAC ] = "ESAC" ,
2837 # endif
2838 [RES_XXXX ] = "XXXX" ,
2839 [RES_SNTX ] = "SNTX" ,
2841 static const char *const CMDTYPE[] = {
2842 "{}",
2843 "()",
2844 "[noglob]",
2845 # if ENABLE_HUSH_FUNCTIONS
2846 "func()",
2847 # endif
2850 int pin, prn;
2852 pin = 0;
2853 while (pi) {
2854 fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
2855 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
2856 prn = 0;
2857 while (prn < pi->num_cmds) {
2858 struct command *command = &pi->cmds[prn];
2859 char **argv = command->argv;
2861 fdprintf(2, "%*s cmd %d assignment_cnt:%d",
2862 lvl*2, "", prn,
2863 command->assignment_cnt);
2864 if (command->group) {
2865 fdprintf(2, " group %s: (argv=%p)%s%s\n",
2866 CMDTYPE[command->cmd_type],
2867 argv
2868 # if !BB_MMU
2869 , " group_as_string:", command->group_as_string
2870 # else
2871 , "", ""
2872 # endif
2874 debug_print_tree(command->group, lvl+1);
2875 prn++;
2876 continue;
2878 if (argv) while (*argv) {
2879 fdprintf(2, " '%s'", *argv);
2880 argv++;
2882 fdprintf(2, "\n");
2883 prn++;
2885 pi = pi->next;
2886 pin++;
2889 #endif /* debug_print_tree */
2891 static struct pipe *new_pipe(void)
2893 struct pipe *pi;
2894 pi = xzalloc(sizeof(struct pipe));
2895 /*pi->followup = 0; - deliberately invalid value */
2896 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
2897 return pi;
2900 /* Command (member of a pipe) is complete, or we start a new pipe
2901 * if ctx->command is NULL.
2902 * No errors possible here.
2904 static int done_command(struct parse_context *ctx)
2906 /* The command is really already in the pipe structure, so
2907 * advance the pipe counter and make a new, null command. */
2908 struct pipe *pi = ctx->pipe;
2909 struct command *command = ctx->command;
2911 if (command) {
2912 if (IS_NULL_CMD(command)) {
2913 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
2914 goto clear_and_ret;
2916 pi->num_cmds++;
2917 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
2918 //debug_print_tree(ctx->list_head, 20);
2919 } else {
2920 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
2923 /* Only real trickiness here is that the uncommitted
2924 * command structure is not counted in pi->num_cmds. */
2925 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
2926 ctx->command = command = &pi->cmds[pi->num_cmds];
2927 clear_and_ret:
2928 memset(command, 0, sizeof(*command));
2929 return pi->num_cmds; /* used only for 0/nonzero check */
2932 static void done_pipe(struct parse_context *ctx, pipe_style type)
2934 int not_null;
2936 debug_printf_parse("done_pipe entered, followup %d\n", type);
2937 /* Close previous command */
2938 not_null = done_command(ctx);
2939 ctx->pipe->followup = type;
2940 #if HAS_KEYWORDS
2941 ctx->pipe->pi_inverted = ctx->ctx_inverted;
2942 ctx->ctx_inverted = 0;
2943 ctx->pipe->res_word = ctx->ctx_res_w;
2944 #endif
2946 /* Without this check, even just <enter> on command line generates
2947 * tree of three NOPs (!). Which is harmless but annoying.
2948 * IOW: it is safe to do it unconditionally. */
2949 if (not_null
2950 #if ENABLE_HUSH_IF
2951 || ctx->ctx_res_w == RES_FI
2952 #endif
2953 #if ENABLE_HUSH_LOOPS
2954 || ctx->ctx_res_w == RES_DONE
2955 || ctx->ctx_res_w == RES_FOR
2956 || ctx->ctx_res_w == RES_IN
2957 #endif
2958 #if ENABLE_HUSH_CASE
2959 || ctx->ctx_res_w == RES_ESAC
2960 #endif
2962 struct pipe *new_p;
2963 debug_printf_parse("done_pipe: adding new pipe: "
2964 "not_null:%d ctx->ctx_res_w:%d\n",
2965 not_null, ctx->ctx_res_w);
2966 new_p = new_pipe();
2967 ctx->pipe->next = new_p;
2968 ctx->pipe = new_p;
2969 /* RES_THEN, RES_DO etc are "sticky" -
2970 * they remain set for pipes inside if/while.
2971 * This is used to control execution.
2972 * RES_FOR and RES_IN are NOT sticky (needed to support
2973 * cases where variable or value happens to match a keyword):
2975 #if ENABLE_HUSH_LOOPS
2976 if (ctx->ctx_res_w == RES_FOR
2977 || ctx->ctx_res_w == RES_IN)
2978 ctx->ctx_res_w = RES_NONE;
2979 #endif
2980 #if ENABLE_HUSH_CASE
2981 if (ctx->ctx_res_w == RES_MATCH)
2982 ctx->ctx_res_w = RES_CASE_BODY;
2983 if (ctx->ctx_res_w == RES_CASE)
2984 ctx->ctx_res_w = RES_CASE_IN;
2985 #endif
2986 ctx->command = NULL; /* trick done_command below */
2987 /* Create the memory for command, roughly:
2988 * ctx->pipe->cmds = new struct command;
2989 * ctx->command = &ctx->pipe->cmds[0];
2991 done_command(ctx);
2992 //debug_print_tree(ctx->list_head, 10);
2994 debug_printf_parse("done_pipe return\n");
2997 static void initialize_context(struct parse_context *ctx)
2999 memset(ctx, 0, sizeof(*ctx));
3000 ctx->pipe = ctx->list_head = new_pipe();
3001 /* Create the memory for command, roughly:
3002 * ctx->pipe->cmds = new struct command;
3003 * ctx->command = &ctx->pipe->cmds[0];
3005 done_command(ctx);
3008 /* If a reserved word is found and processed, parse context is modified
3009 * and 1 is returned.
3011 #if HAS_KEYWORDS
3012 struct reserved_combo {
3013 char literal[6];
3014 unsigned char res;
3015 unsigned char assignment_flag;
3016 int flag;
3018 enum {
3019 FLAG_END = (1 << RES_NONE ),
3020 # if ENABLE_HUSH_IF
3021 FLAG_IF = (1 << RES_IF ),
3022 FLAG_THEN = (1 << RES_THEN ),
3023 FLAG_ELIF = (1 << RES_ELIF ),
3024 FLAG_ELSE = (1 << RES_ELSE ),
3025 FLAG_FI = (1 << RES_FI ),
3026 # endif
3027 # if ENABLE_HUSH_LOOPS
3028 FLAG_FOR = (1 << RES_FOR ),
3029 FLAG_WHILE = (1 << RES_WHILE),
3030 FLAG_UNTIL = (1 << RES_UNTIL),
3031 FLAG_DO = (1 << RES_DO ),
3032 FLAG_DONE = (1 << RES_DONE ),
3033 FLAG_IN = (1 << RES_IN ),
3034 # endif
3035 # if ENABLE_HUSH_CASE
3036 FLAG_MATCH = (1 << RES_MATCH),
3037 FLAG_ESAC = (1 << RES_ESAC ),
3038 # endif
3039 FLAG_START = (1 << RES_XXXX ),
3042 static const struct reserved_combo* match_reserved_word(o_string *word)
3044 /* Mostly a list of accepted follow-up reserved words.
3045 * FLAG_END means we are done with the sequence, and are ready
3046 * to turn the compound list into a command.
3047 * FLAG_START means the word must start a new compound list.
3049 static const struct reserved_combo reserved_list[] = {
3050 # if ENABLE_HUSH_IF
3051 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3052 { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
3053 { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3054 { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
3055 { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
3056 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
3057 # endif
3058 # if ENABLE_HUSH_LOOPS
3059 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3060 { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3061 { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
3062 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3063 { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
3064 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
3065 # endif
3066 # if ENABLE_HUSH_CASE
3067 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3068 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
3069 # endif
3071 const struct reserved_combo *r;
3073 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3074 if (strcmp(word->data, r->literal) == 0)
3075 return r;
3077 return NULL;
3079 /* Return 0: not a keyword, 1: keyword
3081 static int reserved_word(o_string *word, struct parse_context *ctx)
3083 # if ENABLE_HUSH_CASE
3084 static const struct reserved_combo reserved_match = {
3085 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
3087 # endif
3088 const struct reserved_combo *r;
3090 if (word->has_quoted_part)
3091 return 0;
3092 r = match_reserved_word(word);
3093 if (!r)
3094 return 0;
3096 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
3097 # if ENABLE_HUSH_CASE
3098 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
3099 /* "case word IN ..." - IN part starts first MATCH part */
3100 r = &reserved_match;
3101 } else
3102 # endif
3103 if (r->flag == 0) { /* '!' */
3104 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
3105 syntax_error("! ! command");
3106 ctx->ctx_res_w = RES_SNTX;
3108 ctx->ctx_inverted = 1;
3109 return 1;
3111 if (r->flag & FLAG_START) {
3112 struct parse_context *old;
3114 old = xmalloc(sizeof(*old));
3115 debug_printf_parse("push stack %p\n", old);
3116 *old = *ctx; /* physical copy */
3117 initialize_context(ctx);
3118 ctx->stack = old;
3119 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
3120 syntax_error_at(word->data);
3121 ctx->ctx_res_w = RES_SNTX;
3122 return 1;
3123 } else {
3124 /* "{...} fi" is ok. "{...} if" is not
3125 * Example:
3126 * if { echo foo; } then { echo bar; } fi */
3127 if (ctx->command->group)
3128 done_pipe(ctx, PIPE_SEQ);
3131 ctx->ctx_res_w = r->res;
3132 ctx->old_flag = r->flag;
3133 word->o_assignment = r->assignment_flag;
3134 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3136 if (ctx->old_flag & FLAG_END) {
3137 struct parse_context *old;
3139 done_pipe(ctx, PIPE_SEQ);
3140 debug_printf_parse("pop stack %p\n", ctx->stack);
3141 old = ctx->stack;
3142 old->command->group = ctx->list_head;
3143 old->command->cmd_type = CMD_NORMAL;
3144 # if !BB_MMU
3145 o_addstr(&old->as_string, ctx->as_string.data);
3146 o_free_unsafe(&ctx->as_string);
3147 old->command->group_as_string = xstrdup(old->as_string.data);
3148 debug_printf_parse("pop, remembering as:'%s'\n",
3149 old->command->group_as_string);
3150 # endif
3151 *ctx = *old; /* physical copy */
3152 free(old);
3154 return 1;
3156 #endif /* HAS_KEYWORDS */
3158 /* Word is complete, look at it and update parsing context.
3159 * Normal return is 0. Syntax errors return 1.
3160 * Note: on return, word is reset, but not o_free'd!
3162 static int done_word(o_string *word, struct parse_context *ctx)
3164 struct command *command = ctx->command;
3166 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
3167 if (word->length == 0 && !word->has_quoted_part) {
3168 debug_printf_parse("done_word return 0: true null, ignored\n");
3169 return 0;
3172 if (ctx->pending_redirect) {
3173 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3174 * only if run as "bash", not "sh" */
3175 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3176 * "2.7 Redirection
3177 * ...the word that follows the redirection operator
3178 * shall be subjected to tilde expansion, parameter expansion,
3179 * command substitution, arithmetic expansion, and quote
3180 * removal. Pathname expansion shall not be performed
3181 * on the word by a non-interactive shell; an interactive
3182 * shell may perform it, but shall do so only when
3183 * the expansion would result in one word."
3185 ctx->pending_redirect->rd_filename = xstrdup(word->data);
3186 /* Cater for >\file case:
3187 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3188 * Same with heredocs:
3189 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3191 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
3192 unbackslash(ctx->pending_redirect->rd_filename);
3193 /* Is it <<"HEREDOC"? */
3194 if (word->has_quoted_part) {
3195 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3198 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
3199 ctx->pending_redirect = NULL;
3200 } else {
3201 #if HAS_KEYWORDS
3202 # if ENABLE_HUSH_CASE
3203 if (ctx->ctx_dsemicolon
3204 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
3206 /* already done when ctx_dsemicolon was set to 1: */
3207 /* ctx->ctx_res_w = RES_MATCH; */
3208 ctx->ctx_dsemicolon = 0;
3209 } else
3210 # endif
3211 if (!command->argv /* if it's the first word... */
3212 # if ENABLE_HUSH_LOOPS
3213 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
3214 && ctx->ctx_res_w != RES_IN
3215 # endif
3216 # if ENABLE_HUSH_CASE
3217 && ctx->ctx_res_w != RES_CASE
3218 # endif
3220 int reserved = reserved_word(word, ctx);
3221 debug_printf_parse("checking for reserved-ness: %d\n", reserved);
3222 if (reserved) {
3223 o_reset_to_empty_unquoted(word);
3224 debug_printf_parse("done_word return %d\n",
3225 (ctx->ctx_res_w == RES_SNTX));
3226 return (ctx->ctx_res_w == RES_SNTX);
3228 # if ENABLE_HUSH_BASH_COMPAT
3229 if (strcmp(word->data, "[[") == 0) {
3230 command->cmd_type = CMD_SINGLEWORD_NOGLOB;
3232 /* fall through */
3233 # endif
3235 #endif
3236 if (command->group) {
3237 /* "{ echo foo; } echo bar" - bad */
3238 syntax_error_at(word->data);
3239 debug_printf_parse("done_word return 1: syntax error, "
3240 "groups and arglists don't mix\n");
3241 return 1;
3244 /* If this word wasn't an assignment, next ones definitely
3245 * can't be assignments. Even if they look like ones. */
3246 if (word->o_assignment != DEFINITELY_ASSIGNMENT
3247 && word->o_assignment != WORD_IS_KEYWORD
3249 word->o_assignment = NOT_ASSIGNMENT;
3250 } else {
3251 if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
3252 command->assignment_cnt++;
3253 debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
3255 debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
3256 word->o_assignment = MAYBE_ASSIGNMENT;
3258 debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
3260 if (word->has_quoted_part
3261 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
3262 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
3263 /* (otherwise it's known to be not empty and is already safe) */
3265 /* exclude "$@" - it can expand to no word despite "" */
3266 char *p = word->data;
3267 while (p[0] == SPECIAL_VAR_SYMBOL
3268 && (p[1] & 0x7f) == '@'
3269 && p[2] == SPECIAL_VAR_SYMBOL
3271 p += 3;
3274 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
3275 debug_print_strings("word appended to argv", command->argv);
3278 #if ENABLE_HUSH_LOOPS
3279 if (ctx->ctx_res_w == RES_FOR) {
3280 if (word->has_quoted_part
3281 || !is_well_formed_var_name(command->argv[0], '\0')
3283 /* bash says just "not a valid identifier" */
3284 syntax_error("not a valid identifier in for");
3285 return 1;
3287 /* Force FOR to have just one word (variable name) */
3288 /* NB: basically, this makes hush see "for v in ..."
3289 * syntax as if it is "for v; in ...". FOR and IN become
3290 * two pipe structs in parse tree. */
3291 done_pipe(ctx, PIPE_SEQ);
3293 #endif
3294 #if ENABLE_HUSH_CASE
3295 /* Force CASE to have just one word */
3296 if (ctx->ctx_res_w == RES_CASE) {
3297 done_pipe(ctx, PIPE_SEQ);
3299 #endif
3301 o_reset_to_empty_unquoted(word);
3303 debug_printf_parse("done_word return 0\n");
3304 return 0;
3308 /* Peek ahead in the input to find out if we have a "&n" construct,
3309 * as in "2>&1", that represents duplicating a file descriptor.
3310 * Return:
3311 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
3312 * REDIRFD_SYNTAX_ERR if syntax error,
3313 * REDIRFD_TO_FILE if no & was seen,
3314 * or the number found.
3316 #if BB_MMU
3317 #define parse_redir_right_fd(as_string, input) \
3318 parse_redir_right_fd(input)
3319 #endif
3320 static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
3322 int ch, d, ok;
3324 ch = i_peek(input);
3325 if (ch != '&')
3326 return REDIRFD_TO_FILE;
3328 ch = i_getch(input); /* get the & */
3329 nommu_addchr(as_string, ch);
3330 ch = i_peek(input);
3331 if (ch == '-') {
3332 ch = i_getch(input);
3333 nommu_addchr(as_string, ch);
3334 return REDIRFD_CLOSE;
3336 d = 0;
3337 ok = 0;
3338 while (ch != EOF && isdigit(ch)) {
3339 d = d*10 + (ch-'0');
3340 ok = 1;
3341 ch = i_getch(input);
3342 nommu_addchr(as_string, ch);
3343 ch = i_peek(input);
3345 if (ok) return d;
3347 //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
3349 bb_error_msg("ambiguous redirect");
3350 return REDIRFD_SYNTAX_ERR;
3353 /* Return code is 0 normal, 1 if a syntax error is detected
3355 static int parse_redirect(struct parse_context *ctx,
3356 int fd,
3357 redir_type style,
3358 struct in_str *input)
3360 struct command *command = ctx->command;
3361 struct redir_struct *redir;
3362 struct redir_struct **redirp;
3363 int dup_num;
3365 dup_num = REDIRFD_TO_FILE;
3366 if (style != REDIRECT_HEREDOC) {
3367 /* Check for a '>&1' type redirect */
3368 dup_num = parse_redir_right_fd(&ctx->as_string, input);
3369 if (dup_num == REDIRFD_SYNTAX_ERR)
3370 return 1;
3371 } else {
3372 int ch = i_peek(input);
3373 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
3374 if (dup_num) { /* <<-... */
3375 ch = i_getch(input);
3376 nommu_addchr(&ctx->as_string, ch);
3377 ch = i_peek(input);
3381 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
3382 int ch = i_peek(input);
3383 if (ch == '|') {
3384 /* >|FILE redirect ("clobbering" >).
3385 * Since we do not support "set -o noclobber" yet,
3386 * >| and > are the same for now. Just eat |.
3388 ch = i_getch(input);
3389 nommu_addchr(&ctx->as_string, ch);
3393 /* Create a new redir_struct and append it to the linked list */
3394 redirp = &command->redirects;
3395 while ((redir = *redirp) != NULL) {
3396 redirp = &(redir->next);
3398 *redirp = redir = xzalloc(sizeof(*redir));
3399 /* redir->next = NULL; */
3400 /* redir->rd_filename = NULL; */
3401 redir->rd_type = style;
3402 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
3404 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
3405 redir_table[style].descrip);
3407 redir->rd_dup = dup_num;
3408 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
3409 /* Erik had a check here that the file descriptor in question
3410 * is legit; I postpone that to "run time"
3411 * A "-" representation of "close me" shows up as a -3 here */
3412 debug_printf_parse("duplicating redirect '%d>&%d'\n",
3413 redir->rd_fd, redir->rd_dup);
3414 } else {
3415 /* Set ctx->pending_redirect, so we know what to do at the
3416 * end of the next parsed word. */
3417 ctx->pending_redirect = redir;
3419 return 0;
3422 /* If a redirect is immediately preceded by a number, that number is
3423 * supposed to tell which file descriptor to redirect. This routine
3424 * looks for such preceding numbers. In an ideal world this routine
3425 * needs to handle all the following classes of redirects...
3426 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3427 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3428 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3429 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3431 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3432 * "2.7 Redirection
3433 * ... If n is quoted, the number shall not be recognized as part of
3434 * the redirection expression. For example:
3435 * echo \2>a
3436 * writes the character 2 into file a"
3437 * We are getting it right by setting ->has_quoted_part on any \<char>
3439 * A -1 return means no valid number was found,
3440 * the caller should use the appropriate default for this redirection.
3442 static int redirect_opt_num(o_string *o)
3444 int num;
3446 if (o->data == NULL)
3447 return -1;
3448 num = bb_strtou(o->data, NULL, 10);
3449 if (errno || num < 0)
3450 return -1;
3451 o_reset_to_empty_unquoted(o);
3452 return num;
3455 #if BB_MMU
3456 #define fetch_till_str(as_string, input, word, skip_tabs) \
3457 fetch_till_str(input, word, skip_tabs)
3458 #endif
3459 static char *fetch_till_str(o_string *as_string,
3460 struct in_str *input,
3461 const char *word,
3462 int heredoc_flags)
3464 o_string heredoc = NULL_O_STRING;
3465 unsigned past_EOL;
3466 int prev = 0; /* not \ */
3467 int ch;
3469 goto jump_in;
3471 while (1) {
3472 ch = i_getch(input);
3473 if (ch != EOF)
3474 nommu_addchr(as_string, ch);
3475 if ((ch == '\n' || ch == EOF)
3476 && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
3478 if (strcmp(heredoc.data + past_EOL, word) == 0) {
3479 heredoc.data[past_EOL] = '\0';
3480 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
3481 return heredoc.data;
3483 while (ch == '\n') {
3484 o_addchr(&heredoc, ch);
3485 prev = ch;
3486 jump_in:
3487 past_EOL = heredoc.length;
3488 do {
3489 ch = i_getch(input);
3490 if (ch != EOF)
3491 nommu_addchr(as_string, ch);
3492 } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
3495 if (ch == EOF) {
3496 o_free_unsafe(&heredoc);
3497 return NULL;
3499 o_addchr(&heredoc, ch);
3500 nommu_addchr(as_string, ch);
3501 if (prev == '\\' && ch == '\\')
3502 /* Correctly handle foo\\<eol> (not a line cont.) */
3503 prev = 0; /* not \ */
3504 else
3505 prev = ch;
3509 /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
3510 * and load them all. There should be exactly heredoc_cnt of them.
3512 static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
3514 struct pipe *pi = ctx->list_head;
3516 while (pi && heredoc_cnt) {
3517 int i;
3518 struct command *cmd = pi->cmds;
3520 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
3521 pi->num_cmds,
3522 cmd->argv ? cmd->argv[0] : "NONE");
3523 for (i = 0; i < pi->num_cmds; i++) {
3524 struct redir_struct *redir = cmd->redirects;
3526 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
3527 i, cmd->argv ? cmd->argv[0] : "NONE");
3528 while (redir) {
3529 if (redir->rd_type == REDIRECT_HEREDOC) {
3530 char *p;
3532 redir->rd_type = REDIRECT_HEREDOC2;
3533 /* redir->rd_dup is (ab)used to indicate <<- */
3534 p = fetch_till_str(&ctx->as_string, input,
3535 redir->rd_filename, redir->rd_dup);
3536 if (!p) {
3537 syntax_error("unexpected EOF in here document");
3538 return 1;
3540 free(redir->rd_filename);
3541 redir->rd_filename = p;
3542 heredoc_cnt--;
3544 redir = redir->next;
3546 cmd++;
3548 pi = pi->next;
3550 #if 0
3551 /* Should be 0. If it isn't, it's a parse error */
3552 if (heredoc_cnt)
3553 bb_error_msg_and_die("heredoc BUG 2");
3554 #endif
3555 return 0;
3559 static int run_list(struct pipe *pi);
3560 #if BB_MMU
3561 #define parse_stream(pstring, input, end_trigger) \
3562 parse_stream(input, end_trigger)
3563 #endif
3564 static struct pipe *parse_stream(char **pstring,
3565 struct in_str *input,
3566 int end_trigger);
3569 #if !ENABLE_HUSH_FUNCTIONS
3570 #define parse_group(dest, ctx, input, ch) \
3571 parse_group(ctx, input, ch)
3572 #endif
3573 static int parse_group(o_string *dest, struct parse_context *ctx,
3574 struct in_str *input, int ch)
3576 /* dest contains characters seen prior to ( or {.
3577 * Typically it's empty, but for function defs,
3578 * it contains function name (without '()'). */
3579 struct pipe *pipe_list;
3580 int endch;
3581 struct command *command = ctx->command;
3583 debug_printf_parse("parse_group entered\n");
3584 #if ENABLE_HUSH_FUNCTIONS
3585 if (ch == '(' && !dest->has_quoted_part) {
3586 if (dest->length)
3587 if (done_word(dest, ctx))
3588 return 1;
3589 if (!command->argv)
3590 goto skip; /* (... */
3591 if (command->argv[1]) { /* word word ... (... */
3592 syntax_error_unexpected_ch('(');
3593 return 1;
3595 /* it is "word(..." or "word (..." */
3597 ch = i_getch(input);
3598 while (ch == ' ' || ch == '\t');
3599 if (ch != ')') {
3600 syntax_error_unexpected_ch(ch);
3601 return 1;
3603 nommu_addchr(&ctx->as_string, ch);
3605 ch = i_getch(input);
3606 while (ch == ' ' || ch == '\t' || ch == '\n');
3607 if (ch != '{') {
3608 syntax_error_unexpected_ch(ch);
3609 return 1;
3611 nommu_addchr(&ctx->as_string, ch);
3612 command->cmd_type = CMD_FUNCDEF;
3613 goto skip;
3615 #endif
3617 #if 0 /* Prevented by caller */
3618 if (command->argv /* word [word]{... */
3619 || dest->length /* word{... */
3620 || dest->has_quoted_part /* ""{... */
3622 syntax_error(NULL);
3623 debug_printf_parse("parse_group return 1: "
3624 "syntax error, groups and arglists don't mix\n");
3625 return 1;
3627 #endif
3629 #if ENABLE_HUSH_FUNCTIONS
3630 skip:
3631 #endif
3632 endch = '}';
3633 if (ch == '(') {
3634 endch = ')';
3635 command->cmd_type = CMD_SUBSHELL;
3636 } else {
3637 /* bash does not allow "{echo...", requires whitespace */
3638 ch = i_getch(input);
3639 if (ch != ' ' && ch != '\t' && ch != '\n') {
3640 syntax_error_unexpected_ch(ch);
3641 return 1;
3643 nommu_addchr(&ctx->as_string, ch);
3647 #if BB_MMU
3648 # define as_string NULL
3649 #else
3650 char *as_string = NULL;
3651 #endif
3652 pipe_list = parse_stream(&as_string, input, endch);
3653 #if !BB_MMU
3654 if (as_string)
3655 o_addstr(&ctx->as_string, as_string);
3656 #endif
3657 /* empty ()/{} or parse error? */
3658 if (!pipe_list || pipe_list == ERR_PTR) {
3659 /* parse_stream already emitted error msg */
3660 if (!BB_MMU)
3661 free(as_string);
3662 debug_printf_parse("parse_group return 1: "
3663 "parse_stream returned %p\n", pipe_list);
3664 return 1;
3666 command->group = pipe_list;
3667 #if !BB_MMU
3668 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
3669 command->group_as_string = as_string;
3670 debug_printf_parse("end of group, remembering as:'%s'\n",
3671 command->group_as_string);
3672 #endif
3673 #undef as_string
3675 debug_printf_parse("parse_group return 0\n");
3676 return 0;
3677 /* command remains "open", available for possible redirects */
3680 #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
3681 /* Subroutines for copying $(...) and `...` things */
3682 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
3683 /* '...' */
3684 static int add_till_single_quote(o_string *dest, struct in_str *input)
3686 while (1) {
3687 int ch = i_getch(input);
3688 if (ch == EOF) {
3689 syntax_error_unterm_ch('\'');
3690 return 0;
3692 if (ch == '\'')
3693 return 1;
3694 o_addchr(dest, ch);
3697 /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
3698 static int add_till_double_quote(o_string *dest, struct in_str *input)
3700 while (1) {
3701 int ch = i_getch(input);
3702 if (ch == EOF) {
3703 syntax_error_unterm_ch('"');
3704 return 0;
3706 if (ch == '"')
3707 return 1;
3708 if (ch == '\\') { /* \x. Copy both chars. */
3709 o_addchr(dest, ch);
3710 ch = i_getch(input);
3712 o_addchr(dest, ch);
3713 if (ch == '`') {
3714 if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
3715 return 0;
3716 o_addchr(dest, ch);
3717 continue;
3719 //if (ch == '$') ...
3722 /* Process `cmd` - copy contents until "`" is seen. Complicated by
3723 * \` quoting.
3724 * "Within the backquoted style of command substitution, backslash
3725 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
3726 * The search for the matching backquote shall be satisfied by the first
3727 * backquote found without a preceding backslash; during this search,
3728 * if a non-escaped backquote is encountered within a shell comment,
3729 * a here-document, an embedded command substitution of the $(command)
3730 * form, or a quoted string, undefined results occur. A single-quoted
3731 * or double-quoted string that begins, but does not end, within the
3732 * "`...`" sequence produces undefined results."
3733 * Example Output
3734 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
3736 static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
3738 while (1) {
3739 int ch = i_getch(input);
3740 if (ch == '`')
3741 return 1;
3742 if (ch == '\\') {
3743 /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
3744 ch = i_getch(input);
3745 if (ch != '`'
3746 && ch != '$'
3747 && ch != '\\'
3748 && (!in_dquote || ch != '"')
3750 o_addchr(dest, '\\');
3753 if (ch == EOF) {
3754 syntax_error_unterm_ch('`');
3755 return 0;
3757 o_addchr(dest, ch);
3760 /* Process $(cmd) - copy contents until ")" is seen. Complicated by
3761 * quoting and nested ()s.
3762 * "With the $(command) style of command substitution, all characters
3763 * following the open parenthesis to the matching closing parenthesis
3764 * constitute the command. Any valid shell script can be used for command,
3765 * except a script consisting solely of redirections which produces
3766 * unspecified results."
3767 * Example Output
3768 * echo $(echo '(TEST)' BEST) (TEST) BEST
3769 * echo $(echo 'TEST)' BEST) TEST) BEST
3770 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
3772 * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
3773 * can contain arbitrary constructs, just like $(cmd).
3774 * In bash compat mode, it needs to also be able to stop on ':' or '/'
3775 * for ${var:N[:M]} and ${var/P[/R]} parsing.
3777 #define DOUBLE_CLOSE_CHAR_FLAG 0x80
3778 static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
3780 int ch;
3781 char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
3782 # if ENABLE_HUSH_BASH_COMPAT
3783 char end_char2 = end_ch >> 8;
3784 # endif
3785 end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
3787 while (1) {
3788 ch = i_getch(input);
3789 if (ch == EOF) {
3790 syntax_error_unterm_ch(end_ch);
3791 return 0;
3793 if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
3794 if (!dbl)
3795 break;
3796 /* we look for closing )) of $((EXPR)) */
3797 if (i_peek(input) == end_ch) {
3798 i_getch(input); /* eat second ')' */
3799 break;
3802 o_addchr(dest, ch);
3803 if (ch == '(' || ch == '{') {
3804 ch = (ch == '(' ? ')' : '}');
3805 if (!add_till_closing_bracket(dest, input, ch))
3806 return 0;
3807 o_addchr(dest, ch);
3808 continue;
3810 if (ch == '\'') {
3811 if (!add_till_single_quote(dest, input))
3812 return 0;
3813 o_addchr(dest, ch);
3814 continue;
3816 if (ch == '"') {
3817 if (!add_till_double_quote(dest, input))
3818 return 0;
3819 o_addchr(dest, ch);
3820 continue;
3822 if (ch == '`') {
3823 if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
3824 return 0;
3825 o_addchr(dest, ch);
3826 continue;
3828 if (ch == '\\') {
3829 /* \x. Copy verbatim. Important for \(, \) */
3830 ch = i_getch(input);
3831 if (ch == EOF) {
3832 syntax_error_unterm_ch(')');
3833 return 0;
3835 o_addchr(dest, ch);
3836 continue;
3839 return ch;
3841 #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
3843 /* Return code: 0 for OK, 1 for syntax error */
3844 #if BB_MMU
3845 #define parse_dollar(as_string, dest, input, quote_mask) \
3846 parse_dollar(dest, input, quote_mask)
3847 #define as_string NULL
3848 #endif
3849 static int parse_dollar(o_string *as_string,
3850 o_string *dest,
3851 struct in_str *input, unsigned char quote_mask)
3853 int ch = i_peek(input); /* first character after the $ */
3855 debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
3856 if (isalpha(ch)) {
3857 ch = i_getch(input);
3858 nommu_addchr(as_string, ch);
3859 make_var:
3860 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3861 while (1) {
3862 debug_printf_parse(": '%c'\n", ch);
3863 o_addchr(dest, ch | quote_mask);
3864 quote_mask = 0;
3865 ch = i_peek(input);
3866 if (!isalnum(ch) && ch != '_')
3867 break;
3868 ch = i_getch(input);
3869 nommu_addchr(as_string, ch);
3871 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3872 } else if (isdigit(ch)) {
3873 make_one_char_var:
3874 ch = i_getch(input);
3875 nommu_addchr(as_string, ch);
3876 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3877 debug_printf_parse(": '%c'\n", ch);
3878 o_addchr(dest, ch | quote_mask);
3879 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3880 } else switch (ch) {
3881 case '$': /* pid */
3882 case '!': /* last bg pid */
3883 case '?': /* last exit code */
3884 case '#': /* number of args */
3885 case '*': /* args */
3886 case '@': /* args */
3887 goto make_one_char_var;
3888 case '{': {
3889 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3891 ch = i_getch(input); /* eat '{' */
3892 nommu_addchr(as_string, ch);
3894 ch = i_getch(input); /* first char after '{' */
3895 /* It should be ${?}, or ${#var},
3896 * or even ${?+subst} - operator acting on a special variable,
3897 * or the beginning of variable name.
3899 if (ch == EOF
3900 || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
3902 bad_dollar_syntax:
3903 syntax_error_unterm_str("${name}");
3904 debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
3905 return 0;
3907 nommu_addchr(as_string, ch);
3908 ch |= quote_mask;
3910 /* It's possible to just call add_till_closing_bracket() at this point.
3911 * However, this regresses some of our testsuite cases
3912 * which check invalid constructs like ${%}.
3913 * Oh well... let's check that the var name part is fine... */
3915 while (1) {
3916 unsigned pos;
3918 o_addchr(dest, ch);
3919 debug_printf_parse(": '%c'\n", ch);
3921 ch = i_getch(input);
3922 nommu_addchr(as_string, ch);
3923 if (ch == '}')
3924 break;
3926 if (!isalnum(ch) && ch != '_') {
3927 unsigned end_ch;
3928 unsigned char last_ch;
3929 /* handle parameter expansions
3930 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
3932 if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
3933 goto bad_dollar_syntax;
3935 /* Eat everything until closing '}' (or ':') */
3936 end_ch = '}';
3937 if (ENABLE_HUSH_BASH_COMPAT
3938 && ch == ':'
3939 && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
3941 /* It's ${var:N[:M]} thing */
3942 end_ch = '}' * 0x100 + ':';
3944 if (ENABLE_HUSH_BASH_COMPAT
3945 && ch == '/'
3947 /* It's ${var/[/]pattern[/repl]} thing */
3948 if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
3949 i_getch(input);
3950 nommu_addchr(as_string, '/');
3951 ch = '\\';
3953 end_ch = '}' * 0x100 + '/';
3955 o_addchr(dest, ch);
3956 again:
3957 if (!BB_MMU)
3958 pos = dest->length;
3959 #if ENABLE_HUSH_DOLLAR_OPS
3960 last_ch = add_till_closing_bracket(dest, input, end_ch);
3961 if (last_ch == 0) /* error? */
3962 return 0;
3963 #else
3964 #error Simple code to only allow ${var} is not implemented
3965 #endif
3966 if (as_string) {
3967 o_addstr(as_string, dest->data + pos);
3968 o_addchr(as_string, last_ch);
3971 if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
3972 /* close the first block: */
3973 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3974 /* while parsing N from ${var:N[:M]}
3975 * or pattern from ${var/[/]pattern[/repl]} */
3976 if ((end_ch & 0xff) == last_ch) {
3977 /* got ':' or '/'- parse the rest */
3978 end_ch = '}';
3979 goto again;
3981 /* got '}' */
3982 if (end_ch == '}' * 0x100 + ':') {
3983 /* it's ${var:N} - emulate :999999999 */
3984 o_addstr(dest, "999999999");
3985 } /* else: it's ${var/[/]pattern} */
3987 break;
3990 o_addchr(dest, SPECIAL_VAR_SYMBOL);
3991 break;
3993 #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
3994 case '(': {
3995 unsigned pos;
3997 ch = i_getch(input);
3998 nommu_addchr(as_string, ch);
3999 # if ENABLE_SH_MATH_SUPPORT
4000 if (i_peek(input) == '(') {
4001 ch = i_getch(input);
4002 nommu_addchr(as_string, ch);
4003 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4004 o_addchr(dest, /*quote_mask |*/ '+');
4005 if (!BB_MMU)
4006 pos = dest->length;
4007 if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
4008 return 0; /* error */
4009 if (as_string) {
4010 o_addstr(as_string, dest->data + pos);
4011 o_addchr(as_string, ')');
4012 o_addchr(as_string, ')');
4014 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4015 break;
4017 # endif
4018 # if ENABLE_HUSH_TICK
4019 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4020 o_addchr(dest, quote_mask | '`');
4021 if (!BB_MMU)
4022 pos = dest->length;
4023 if (!add_till_closing_bracket(dest, input, ')'))
4024 return 0; /* error */
4025 if (as_string) {
4026 o_addstr(as_string, dest->data + pos);
4027 o_addchr(as_string, ')');
4029 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4030 # endif
4031 break;
4033 #endif
4034 case '_':
4035 ch = i_getch(input);
4036 nommu_addchr(as_string, ch);
4037 ch = i_peek(input);
4038 if (isalnum(ch)) { /* it's $_name or $_123 */
4039 ch = '_';
4040 goto make_var;
4042 /* else: it's $_ */
4043 /* TODO: $_ and $-: */
4044 /* $_ Shell or shell script name; or last argument of last command
4045 * (if last command wasn't a pipe; if it was, bash sets $_ to "");
4046 * but in command's env, set to full pathname used to invoke it */
4047 /* $- Option flags set by set builtin or shell options (-i etc) */
4048 default:
4049 o_addQchr(dest, '$');
4051 debug_printf_parse("parse_dollar return 1 (ok)\n");
4052 return 1;
4053 #undef as_string
4056 #if BB_MMU
4057 # if ENABLE_HUSH_BASH_COMPAT
4058 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4059 encode_string(dest, input, dquote_end, process_bkslash)
4060 # else
4061 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4062 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4063 encode_string(dest, input, dquote_end)
4064 # endif
4065 #define as_string NULL
4067 #else /* !MMU */
4069 # if ENABLE_HUSH_BASH_COMPAT
4070 /* all parameters are needed, no macro tricks */
4071 # else
4072 #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
4073 encode_string(as_string, dest, input, dquote_end)
4074 # endif
4075 #endif
4076 static int encode_string(o_string *as_string,
4077 o_string *dest,
4078 struct in_str *input,
4079 int dquote_end,
4080 int process_bkslash)
4082 #if !ENABLE_HUSH_BASH_COMPAT
4083 const int process_bkslash = 1;
4084 #endif
4085 int ch;
4086 int next;
4088 again:
4089 ch = i_getch(input);
4090 if (ch != EOF)
4091 nommu_addchr(as_string, ch);
4092 if (ch == dquote_end) { /* may be only '"' or EOF */
4093 debug_printf_parse("encode_string return 1 (ok)\n");
4094 return 1;
4096 /* note: can't move it above ch == dquote_end check! */
4097 if (ch == EOF) {
4098 syntax_error_unterm_ch('"');
4099 return 0; /* error */
4101 next = '\0';
4102 if (ch != '\n') {
4103 next = i_peek(input);
4105 debug_printf_parse("\" ch=%c (%d) escape=%d\n",
4106 ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4107 if (process_bkslash && ch == '\\') {
4108 if (next == EOF) {
4109 syntax_error("\\<eof>");
4110 xfunc_die();
4112 /* bash:
4113 * "The backslash retains its special meaning [in "..."]
4114 * only when followed by one of the following characters:
4115 * $, `, ", \, or <newline>. A double quote may be quoted
4116 * within double quotes by preceding it with a backslash."
4117 * NB: in (unquoted) heredoc, above does not apply to ",
4118 * therefore we check for it by "next == dquote_end" cond.
4120 if (next == dquote_end || strchr("$`\\\n", next)) {
4121 ch = i_getch(input); /* eat next */
4122 if (ch == '\n')
4123 goto again; /* skip \<newline> */
4124 } /* else: ch remains == '\\', and we double it below: */
4125 o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
4126 nommu_addchr(as_string, ch);
4127 goto again;
4129 if (ch == '$') {
4130 if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
4131 debug_printf_parse("encode_string return 0: "
4132 "parse_dollar returned 0 (error)\n");
4133 return 0;
4135 goto again;
4137 #if ENABLE_HUSH_TICK
4138 if (ch == '`') {
4139 //unsigned pos = dest->length;
4140 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4141 o_addchr(dest, 0x80 | '`');
4142 if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
4143 return 0; /* error */
4144 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4145 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
4146 goto again;
4148 #endif
4149 o_addQchr(dest, ch);
4150 goto again;
4151 #undef as_string
4155 * Scan input until EOF or end_trigger char.
4156 * Return a list of pipes to execute, or NULL on EOF
4157 * or if end_trigger character is met.
4158 * On syntax error, exit if shell is not interactive,
4159 * reset parsing machinery and start parsing anew,
4160 * or return ERR_PTR.
4162 static struct pipe *parse_stream(char **pstring,
4163 struct in_str *input,
4164 int end_trigger)
4166 struct parse_context ctx;
4167 o_string dest = NULL_O_STRING;
4168 int heredoc_cnt;
4170 /* Single-quote triggers a bypass of the main loop until its mate is
4171 * found. When recursing, quote state is passed in via dest->o_expflags.
4173 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4174 end_trigger ? end_trigger : 'X');
4175 debug_enter();
4177 /* If very first arg is "" or '', dest.data may end up NULL.
4178 * Preventing this: */
4179 o_addchr(&dest, '\0');
4180 dest.length = 0;
4182 /* We used to separate words on $IFS here. This was wrong.
4183 * $IFS is used only for word splitting when $var is expanded,
4184 * here we should use blank chars as separators, not $IFS
4187 if (MAYBE_ASSIGNMENT != 0)
4188 dest.o_assignment = MAYBE_ASSIGNMENT;
4189 initialize_context(&ctx);
4190 heredoc_cnt = 0;
4191 while (1) {
4192 const char *is_blank;
4193 const char *is_special;
4194 int ch;
4195 int next;
4196 int redir_fd;
4197 redir_type redir_style;
4199 ch = i_getch(input);
4200 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4201 ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
4202 if (ch == EOF) {
4203 struct pipe *pi;
4205 if (heredoc_cnt) {
4206 syntax_error_unterm_str("here document");
4207 goto parse_error;
4209 /* end_trigger == '}' case errors out earlier,
4210 * checking only ')' */
4211 if (end_trigger == ')') {
4212 syntax_error_unterm_ch('(');
4213 goto parse_error;
4216 if (done_word(&dest, &ctx)) {
4217 goto parse_error;
4219 o_free(&dest);
4220 done_pipe(&ctx, PIPE_SEQ);
4221 pi = ctx.list_head;
4222 /* If we got nothing... */
4223 /* (this makes bare "&" cmd a no-op.
4224 * bash says: "syntax error near unexpected token '&'") */
4225 if (pi->num_cmds == 0
4226 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4228 free_pipe_list(pi);
4229 pi = NULL;
4231 #if !BB_MMU
4232 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4233 if (pstring)
4234 *pstring = ctx.as_string.data;
4235 else
4236 o_free_unsafe(&ctx.as_string);
4237 #endif
4238 debug_leave();
4239 debug_printf_parse("parse_stream return %p\n", pi);
4240 return pi;
4242 nommu_addchr(&ctx.as_string, ch);
4244 next = '\0';
4245 if (ch != '\n')
4246 next = i_peek(input);
4248 is_special = "{}<>;&|()#'" /* special outside of "str" */
4249 "\\$\"" IF_HUSH_TICK("`"); /* always special */
4250 /* Are { and } special here? */
4251 if (ctx.command->argv /* word [word]{... - non-special */
4252 || dest.length /* word{... - non-special */
4253 || dest.has_quoted_part /* ""{... - non-special */
4254 || (next != ';' /* }; - special */
4255 && next != ')' /* }) - special */
4256 && next != '&' /* }& and }&& ... - special */
4257 && next != '|' /* }|| ... - special */
4258 && !strchr(defifs, next) /* {word - non-special */
4261 /* They are not special, skip "{}" */
4262 is_special += 2;
4264 is_special = strchr(is_special, ch);
4265 is_blank = strchr(defifs, ch);
4267 if (!is_special && !is_blank) { /* ordinary char */
4268 ordinary_char:
4269 o_addQchr(&dest, ch);
4270 if ((dest.o_assignment == MAYBE_ASSIGNMENT
4271 || dest.o_assignment == WORD_IS_KEYWORD)
4272 && ch == '='
4273 && is_well_formed_var_name(dest.data, '=')
4275 dest.o_assignment = DEFINITELY_ASSIGNMENT;
4276 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4278 continue;
4281 if (is_blank) {
4282 if (done_word(&dest, &ctx)) {
4283 goto parse_error;
4285 if (ch == '\n') {
4286 /* Is this a case when newline is simply ignored?
4287 * Some examples:
4288 * "cmd | <newline> cmd ..."
4289 * "case ... in <newline> word) ..."
4291 if (IS_NULL_CMD(ctx.command)
4292 && dest.length == 0 && !dest.has_quoted_part
4294 /* This newline can be ignored. But...
4295 * Without check #1, interactive shell
4296 * ignores even bare <newline>,
4297 * and shows the continuation prompt:
4298 * ps1_prompt$ <enter>
4299 * ps2> _ <=== wrong, should be ps1
4300 * Without check #2, "cmd & <newline>"
4301 * is similarly mistreated.
4302 * (BTW, this makes "cmd & cmd"
4303 * and "cmd && cmd" non-orthogonal.
4304 * Really, ask yourself, why
4305 * "cmd && <newline>" doesn't start
4306 * cmd but waits for more input?
4307 * No reason...)
4309 struct pipe *pi = ctx.list_head;
4310 if (pi->num_cmds != 0 /* check #1 */
4311 && pi->followup != PIPE_BG /* check #2 */
4313 continue;
4316 /* Treat newline as a command separator. */
4317 done_pipe(&ctx, PIPE_SEQ);
4318 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
4319 if (heredoc_cnt) {
4320 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
4321 goto parse_error;
4323 heredoc_cnt = 0;
4325 dest.o_assignment = MAYBE_ASSIGNMENT;
4326 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4327 ch = ';';
4328 /* note: if (is_blank) continue;
4329 * will still trigger for us */
4333 /* "cmd}" or "cmd }..." without semicolon or &:
4334 * } is an ordinary char in this case, even inside { cmd; }
4335 * Pathological example: { ""}; } should exec "}" cmd
4337 if (ch == '}') {
4338 if (!IS_NULL_CMD(ctx.command) /* cmd } */
4339 || dest.length != 0 /* word} */
4340 || dest.has_quoted_part /* ""} */
4342 goto ordinary_char;
4344 if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
4345 goto skip_end_trigger;
4346 /* else: } does terminate a group */
4349 if (end_trigger && end_trigger == ch
4350 && (ch != ';' || heredoc_cnt == 0)
4351 #if ENABLE_HUSH_CASE
4352 && (ch != ')'
4353 || ctx.ctx_res_w != RES_MATCH
4354 || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
4356 #endif
4358 if (heredoc_cnt) {
4359 /* This is technically valid:
4360 * { cat <<HERE; }; echo Ok
4361 * heredoc
4362 * heredoc
4363 * HERE
4364 * but we don't support this.
4365 * We require heredoc to be in enclosing {}/(),
4366 * if any.
4368 syntax_error_unterm_str("here document");
4369 goto parse_error;
4371 if (done_word(&dest, &ctx)) {
4372 goto parse_error;
4374 done_pipe(&ctx, PIPE_SEQ);
4375 dest.o_assignment = MAYBE_ASSIGNMENT;
4376 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4377 /* Do we sit outside of any if's, loops or case's? */
4378 if (!HAS_KEYWORDS
4379 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
4381 o_free(&dest);
4382 #if !BB_MMU
4383 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
4384 if (pstring)
4385 *pstring = ctx.as_string.data;
4386 else
4387 o_free_unsafe(&ctx.as_string);
4388 #endif
4389 debug_leave();
4390 debug_printf_parse("parse_stream return %p: "
4391 "end_trigger char found\n",
4392 ctx.list_head);
4393 return ctx.list_head;
4396 skip_end_trigger:
4397 if (is_blank)
4398 continue;
4400 /* Catch <, > before deciding whether this word is
4401 * an assignment. a=1 2>z b=2: b=2 is still assignment */
4402 switch (ch) {
4403 case '>':
4404 redir_fd = redirect_opt_num(&dest);
4405 if (done_word(&dest, &ctx)) {
4406 goto parse_error;
4408 redir_style = REDIRECT_OVERWRITE;
4409 if (next == '>') {
4410 redir_style = REDIRECT_APPEND;
4411 ch = i_getch(input);
4412 nommu_addchr(&ctx.as_string, ch);
4414 #if 0
4415 else if (next == '(') {
4416 syntax_error(">(process) not supported");
4417 goto parse_error;
4419 #endif
4420 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4421 goto parse_error;
4422 continue; /* back to top of while (1) */
4423 case '<':
4424 redir_fd = redirect_opt_num(&dest);
4425 if (done_word(&dest, &ctx)) {
4426 goto parse_error;
4428 redir_style = REDIRECT_INPUT;
4429 if (next == '<') {
4430 redir_style = REDIRECT_HEREDOC;
4431 heredoc_cnt++;
4432 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
4433 ch = i_getch(input);
4434 nommu_addchr(&ctx.as_string, ch);
4435 } else if (next == '>') {
4436 redir_style = REDIRECT_IO;
4437 ch = i_getch(input);
4438 nommu_addchr(&ctx.as_string, ch);
4440 #if 0
4441 else if (next == '(') {
4442 syntax_error("<(process) not supported");
4443 goto parse_error;
4445 #endif
4446 if (parse_redirect(&ctx, redir_fd, redir_style, input))
4447 goto parse_error;
4448 continue; /* back to top of while (1) */
4449 case '#':
4450 if (dest.length == 0 && !dest.has_quoted_part) {
4451 /* skip "#comment" */
4452 while (1) {
4453 ch = i_peek(input);
4454 if (ch == EOF || ch == '\n')
4455 break;
4456 i_getch(input);
4457 /* note: we do not add it to &ctx.as_string */
4459 nommu_addchr(&ctx.as_string, '\n');
4460 continue; /* back to top of while (1) */
4462 break;
4463 case '\\':
4464 if (next == '\n') {
4465 /* It's "\<newline>" */
4466 #if !BB_MMU
4467 /* Remove trailing '\' from ctx.as_string */
4468 ctx.as_string.data[--ctx.as_string.length] = '\0';
4469 #endif
4470 ch = i_getch(input); /* eat it */
4471 continue; /* back to top of while (1) */
4473 break;
4476 if (dest.o_assignment == MAYBE_ASSIGNMENT
4477 /* check that we are not in word in "a=1 2>word b=1": */
4478 && !ctx.pending_redirect
4480 /* ch is a special char and thus this word
4481 * cannot be an assignment */
4482 dest.o_assignment = NOT_ASSIGNMENT;
4483 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4486 /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
4488 switch (ch) {
4489 case '#': /* non-comment #: "echo a#b" etc */
4490 o_addQchr(&dest, ch);
4491 break;
4492 case '\\':
4493 if (next == EOF) {
4494 syntax_error("\\<eof>");
4495 xfunc_die();
4497 ch = i_getch(input);
4498 /* note: ch != '\n' (that case does not reach this place) */
4499 o_addchr(&dest, '\\');
4500 /*nommu_addchr(&ctx.as_string, '\\'); - already done */
4501 o_addchr(&dest, ch);
4502 nommu_addchr(&ctx.as_string, ch);
4503 /* Example: echo Hello \2>file
4504 * we need to know that word 2 is quoted */
4505 dest.has_quoted_part = 1;
4506 break;
4507 case '$':
4508 if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
4509 debug_printf_parse("parse_stream parse error: "
4510 "parse_dollar returned 0 (error)\n");
4511 goto parse_error;
4513 break;
4514 case '\'':
4515 dest.has_quoted_part = 1;
4516 if (next == '\'' && !ctx.pending_redirect) {
4517 insert_empty_quoted_str_marker:
4518 nommu_addchr(&ctx.as_string, next);
4519 i_getch(input); /* eat second ' */
4520 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4521 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4522 } else {
4523 while (1) {
4524 ch = i_getch(input);
4525 if (ch == EOF) {
4526 syntax_error_unterm_ch('\'');
4527 goto parse_error;
4529 nommu_addchr(&ctx.as_string, ch);
4530 if (ch == '\'')
4531 break;
4532 o_addqchr(&dest, ch);
4535 break;
4536 case '"':
4537 dest.has_quoted_part = 1;
4538 if (next == '"' && !ctx.pending_redirect)
4539 goto insert_empty_quoted_str_marker;
4540 if (dest.o_assignment == NOT_ASSIGNMENT)
4541 dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
4542 if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
4543 goto parse_error;
4544 dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
4545 break;
4546 #if ENABLE_HUSH_TICK
4547 case '`': {
4548 USE_FOR_NOMMU(unsigned pos;)
4550 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4551 o_addchr(&dest, '`');
4552 USE_FOR_NOMMU(pos = dest.length;)
4553 if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
4554 goto parse_error;
4555 # if !BB_MMU
4556 o_addstr(&ctx.as_string, dest.data + pos);
4557 o_addchr(&ctx.as_string, '`');
4558 # endif
4559 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
4560 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
4561 break;
4563 #endif
4564 case ';':
4565 #if ENABLE_HUSH_CASE
4566 case_semi:
4567 #endif
4568 if (done_word(&dest, &ctx)) {
4569 goto parse_error;
4571 done_pipe(&ctx, PIPE_SEQ);
4572 #if ENABLE_HUSH_CASE
4573 /* Eat multiple semicolons, detect
4574 * whether it means something special */
4575 while (1) {
4576 ch = i_peek(input);
4577 if (ch != ';')
4578 break;
4579 ch = i_getch(input);
4580 nommu_addchr(&ctx.as_string, ch);
4581 if (ctx.ctx_res_w == RES_CASE_BODY) {
4582 ctx.ctx_dsemicolon = 1;
4583 ctx.ctx_res_w = RES_MATCH;
4584 break;
4587 #endif
4588 new_cmd:
4589 /* We just finished a cmd. New one may start
4590 * with an assignment */
4591 dest.o_assignment = MAYBE_ASSIGNMENT;
4592 debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
4593 break;
4594 case '&':
4595 if (done_word(&dest, &ctx)) {
4596 goto parse_error;
4598 if (next == '&') {
4599 ch = i_getch(input);
4600 nommu_addchr(&ctx.as_string, ch);
4601 done_pipe(&ctx, PIPE_AND);
4602 } else {
4603 done_pipe(&ctx, PIPE_BG);
4605 goto new_cmd;
4606 case '|':
4607 if (done_word(&dest, &ctx)) {
4608 goto parse_error;
4610 #if ENABLE_HUSH_CASE
4611 if (ctx.ctx_res_w == RES_MATCH)
4612 break; /* we are in case's "word | word)" */
4613 #endif
4614 if (next == '|') { /* || */
4615 ch = i_getch(input);
4616 nommu_addchr(&ctx.as_string, ch);
4617 done_pipe(&ctx, PIPE_OR);
4618 } else {
4619 /* we could pick up a file descriptor choice here
4620 * with redirect_opt_num(), but bash doesn't do it.
4621 * "echo foo 2| cat" yields "foo 2". */
4622 done_command(&ctx);
4623 #if !BB_MMU
4624 o_reset_to_empty_unquoted(&ctx.as_string);
4625 #endif
4627 goto new_cmd;
4628 case '(':
4629 #if ENABLE_HUSH_CASE
4630 /* "case... in [(]word)..." - skip '(' */
4631 if (ctx.ctx_res_w == RES_MATCH
4632 && ctx.command->argv == NULL /* not (word|(... */
4633 && dest.length == 0 /* not word(... */
4634 && dest.has_quoted_part == 0 /* not ""(... */
4636 continue;
4638 #endif
4639 case '{':
4640 if (parse_group(&dest, &ctx, input, ch) != 0) {
4641 goto parse_error;
4643 goto new_cmd;
4644 case ')':
4645 #if ENABLE_HUSH_CASE
4646 if (ctx.ctx_res_w == RES_MATCH)
4647 goto case_semi;
4648 #endif
4649 case '}':
4650 /* proper use of this character is caught by end_trigger:
4651 * if we see {, we call parse_group(..., end_trigger='}')
4652 * and it will match } earlier (not here). */
4653 syntax_error_unexpected_ch(ch);
4654 goto parse_error;
4655 default:
4656 if (HUSH_DEBUG)
4657 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
4659 } /* while (1) */
4661 parse_error:
4663 struct parse_context *pctx;
4664 IF_HAS_KEYWORDS(struct parse_context *p2;)
4666 /* Clean up allocated tree.
4667 * Sample for finding leaks on syntax error recovery path.
4668 * Run it from interactive shell, watch pmap `pidof hush`.
4669 * while if false; then false; fi; do break; fi
4670 * Samples to catch leaks at execution:
4671 * while if (true | {true;}); then echo ok; fi; do break; done
4672 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
4674 pctx = &ctx;
4675 do {
4676 /* Update pipe/command counts,
4677 * otherwise freeing may miss some */
4678 done_pipe(pctx, PIPE_SEQ);
4679 debug_printf_clean("freeing list %p from ctx %p\n",
4680 pctx->list_head, pctx);
4681 debug_print_tree(pctx->list_head, 0);
4682 free_pipe_list(pctx->list_head);
4683 debug_printf_clean("freed list %p\n", pctx->list_head);
4684 #if !BB_MMU
4685 o_free_unsafe(&pctx->as_string);
4686 #endif
4687 IF_HAS_KEYWORDS(p2 = pctx->stack;)
4688 if (pctx != &ctx) {
4689 free(pctx);
4691 IF_HAS_KEYWORDS(pctx = p2;)
4692 } while (HAS_KEYWORDS && pctx);
4694 o_free(&dest);
4695 G.last_exitcode = 1;
4696 #if !BB_MMU
4697 if (pstring)
4698 *pstring = NULL;
4699 #endif
4700 debug_leave();
4701 return ERR_PTR;
4706 /*** Execution routines ***/
4708 /* Expansion can recurse, need forward decls: */
4709 #if !ENABLE_HUSH_BASH_COMPAT
4710 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4711 #define expand_string_to_string(str, do_unbackslash) \
4712 expand_string_to_string(str)
4713 #endif
4714 static char *expand_string_to_string(const char *str, int do_unbackslash);
4715 #if ENABLE_HUSH_TICK
4716 static int process_command_subs(o_string *dest, const char *s);
4717 #endif
4719 /* expand_strvec_to_strvec() takes a list of strings, expands
4720 * all variable references within and returns a pointer to
4721 * a list of expanded strings, possibly with larger number
4722 * of strings. (Think VAR="a b"; echo $VAR).
4723 * This new list is allocated as a single malloc block.
4724 * NULL-terminated list of char* pointers is at the beginning of it,
4725 * followed by strings themselves.
4726 * Caller can deallocate entire list by single free(list). */
4728 /* A horde of its helpers come first: */
4730 static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
4732 while (--len >= 0) {
4733 char c = *str++;
4735 #if ENABLE_HUSH_BRACE_EXPANSION
4736 if (c == '{' || c == '}') {
4737 /* { -> \{, } -> \} */
4738 o_addchr(o, '\\');
4739 /* And now we want to add { or } and continue:
4740 * o_addchr(o, c);
4741 * continue;
4742 * luckily, just falling throught achieves this.
4745 #endif
4746 o_addchr(o, c);
4747 if (c == '\\') {
4748 /* \z -> \\\z; \<eol> -> \\<eol> */
4749 o_addchr(o, '\\');
4750 if (len) {
4751 len--;
4752 o_addchr(o, '\\');
4753 o_addchr(o, *str++);
4759 /* Store given string, finalizing the word and starting new one whenever
4760 * we encounter IFS char(s). This is used for expanding variable values.
4761 * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
4762 * Return in *ended_with_ifs:
4763 * 1 - ended with IFS char, else 0 (this includes case of empty str).
4765 static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
4767 int last_is_ifs = 0;
4769 while (1) {
4770 int word_len;
4772 if (!*str) /* EOL - do not finalize word */
4773 break;
4774 word_len = strcspn(str, G.ifs);
4775 if (word_len) {
4776 /* We have WORD_LEN leading non-IFS chars */
4777 if (!(output->o_expflags & EXP_FLAG_GLOB)) {
4778 o_addblock(output, str, word_len);
4779 } else {
4780 /* Protect backslashes against globbing up :)
4781 * Example: "v='\*'; echo b$v" prints "b\*"
4782 * (and does not try to glob on "*")
4784 o_addblock_duplicate_backslash(output, str, word_len);
4785 /*/ Why can't we do it easier? */
4786 /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
4787 /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
4789 last_is_ifs = 0;
4790 str += word_len;
4791 if (!*str) /* EOL - do not finalize word */
4792 break;
4795 /* We know str here points to at least one IFS char */
4796 last_is_ifs = 1;
4797 str += strspn(str, G.ifs); /* skip IFS chars */
4798 if (!*str) /* EOL - do not finalize word */
4799 break;
4801 /* Start new word... but not always! */
4802 /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
4803 if (output->has_quoted_part
4804 /* Case "v=' a'; echo $v":
4805 * here nothing precedes the space in $v expansion,
4806 * therefore we should not finish the word
4807 * (IOW: if there *is* word to finalize, only then do it):
4809 || (n > 0 && output->data[output->length - 1])
4811 o_addchr(output, '\0');
4812 debug_print_list("expand_on_ifs", output, n);
4813 n = o_save_ptr(output, n);
4817 if (ended_with_ifs)
4818 *ended_with_ifs = last_is_ifs;
4819 debug_print_list("expand_on_ifs[1]", output, n);
4820 return n;
4823 /* Helper to expand $((...)) and heredoc body. These act as if
4824 * they are in double quotes, with the exception that they are not :).
4825 * Just the rules are similar: "expand only $var and `cmd`"
4827 * Returns malloced string.
4828 * As an optimization, we return NULL if expansion is not needed.
4830 #if !ENABLE_HUSH_BASH_COMPAT
4831 /* only ${var/pattern/repl} (its pattern part) needs additional mode */
4832 #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
4833 encode_then_expand_string(str)
4834 #endif
4835 static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
4837 char *exp_str;
4838 struct in_str input;
4839 o_string dest = NULL_O_STRING;
4841 if (!strchr(str, '$')
4842 && !strchr(str, '\\')
4843 #if ENABLE_HUSH_TICK
4844 && !strchr(str, '`')
4845 #endif
4847 return NULL;
4850 /* We need to expand. Example:
4851 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
4853 setup_string_in_str(&input, str);
4854 encode_string(NULL, &dest, &input, EOF, process_bkslash);
4855 //TODO: error check (encode_string returns 0 on error)?
4856 //bb_error_msg("'%s' -> '%s'", str, dest.data);
4857 exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
4858 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
4859 o_free_unsafe(&dest);
4860 return exp_str;
4863 #if ENABLE_SH_MATH_SUPPORT
4864 static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
4866 arith_state_t math_state;
4867 arith_t res;
4868 char *exp_str;
4870 math_state.lookupvar = get_local_var_value;
4871 math_state.setvar = set_local_var_from_halves;
4872 //math_state.endofname = endofname;
4873 exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
4874 res = arith(&math_state, exp_str ? exp_str : arg);
4875 free(exp_str);
4876 if (errmsg_p)
4877 *errmsg_p = math_state.errmsg;
4878 if (math_state.errmsg)
4879 die_if_script(math_state.errmsg);
4880 return res;
4882 #endif
4884 #if ENABLE_HUSH_BASH_COMPAT
4885 /* ${var/[/]pattern[/repl]} helpers */
4886 static char *strstr_pattern(char *val, const char *pattern, int *size)
4888 while (1) {
4889 char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
4890 debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
4891 if (end) {
4892 *size = end - val;
4893 return val;
4895 if (*val == '\0')
4896 return NULL;
4897 /* Optimization: if "*pat" did not match the start of "string",
4898 * we know that "tring", "ring" etc will not match too:
4900 if (pattern[0] == '*')
4901 return NULL;
4902 val++;
4905 static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
4907 char *result = NULL;
4908 unsigned res_len = 0;
4909 unsigned repl_len = strlen(repl);
4911 while (1) {
4912 int size;
4913 char *s = strstr_pattern(val, pattern, &size);
4914 if (!s)
4915 break;
4917 result = xrealloc(result, res_len + (s - val) + repl_len + 1);
4918 memcpy(result + res_len, val, s - val);
4919 res_len += s - val;
4920 strcpy(result + res_len, repl);
4921 res_len += repl_len;
4922 debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
4924 val = s + size;
4925 if (exp_op == '/')
4926 break;
4928 if (val[0] && result) {
4929 result = xrealloc(result, res_len + strlen(val) + 1);
4930 strcpy(result + res_len, val);
4931 debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
4933 debug_printf_varexp("result:'%s'\n", result);
4934 return result;
4936 #endif
4938 /* Helper:
4939 * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
4941 static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
4943 const char *val = NULL;
4944 char *to_be_freed = NULL;
4945 char *p = *pp;
4946 char *var;
4947 char first_char;
4948 char exp_op;
4949 char exp_save = exp_save; /* for compiler */
4950 char *exp_saveptr; /* points to expansion operator */
4951 char *exp_word = exp_word; /* for compiler */
4952 char arg0;
4954 *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
4955 var = arg;
4956 exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
4957 arg0 = arg[0];
4958 first_char = arg[0] = arg0 & 0x7f;
4959 exp_op = 0;
4961 if (first_char == '#' /* ${#... */
4962 && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
4964 /* It must be length operator: ${#var} */
4965 var++;
4966 exp_op = 'L';
4967 } else {
4968 /* Maybe handle parameter expansion */
4969 if (exp_saveptr /* if 2nd char is one of expansion operators */
4970 && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
4972 /* ${?:0}, ${#[:]%0} etc */
4973 exp_saveptr = var + 1;
4974 } else {
4975 /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
4976 exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
4978 exp_op = exp_save = *exp_saveptr;
4979 if (exp_op) {
4980 exp_word = exp_saveptr + 1;
4981 if (exp_op == ':') {
4982 exp_op = *exp_word++;
4983 //TODO: try ${var:} and ${var:bogus} in non-bash config
4984 if (ENABLE_HUSH_BASH_COMPAT
4985 && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
4987 /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
4988 exp_op = ':';
4989 exp_word--;
4992 *exp_saveptr = '\0';
4993 } /* else: it's not an expansion op, but bare ${var} */
4996 /* Look up the variable in question */
4997 if (isdigit(var[0])) {
4998 /* parse_dollar should have vetted var for us */
4999 int n = xatoi_positive(var);
5000 if (n < G.global_argc)
5001 val = G.global_argv[n];
5002 /* else val remains NULL: $N with too big N */
5003 } else {
5004 switch (var[0]) {
5005 case '$': /* pid */
5006 val = utoa(G.root_pid);
5007 break;
5008 case '!': /* bg pid */
5009 val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
5010 break;
5011 case '?': /* exitcode */
5012 val = utoa(G.last_exitcode);
5013 break;
5014 case '#': /* argc */
5015 val = utoa(G.global_argc ? G.global_argc-1 : 0);
5016 break;
5017 default:
5018 val = get_local_var_value(var);
5022 /* Handle any expansions */
5023 if (exp_op == 'L') {
5024 debug_printf_expand("expand: length(%s)=", val);
5025 val = utoa(val ? strlen(val) : 0);
5026 debug_printf_expand("%s\n", val);
5027 } else if (exp_op) {
5028 if (exp_op == '%' || exp_op == '#') {
5029 /* Standard-mandated substring removal ops:
5030 * ${parameter%word} - remove smallest suffix pattern
5031 * ${parameter%%word} - remove largest suffix pattern
5032 * ${parameter#word} - remove smallest prefix pattern
5033 * ${parameter##word} - remove largest prefix pattern
5035 * Word is expanded to produce a glob pattern.
5036 * Then var's value is matched to it and matching part removed.
5038 if (val && val[0]) {
5039 char *t;
5040 char *exp_exp_word;
5041 char *loc;
5042 unsigned scan_flags = pick_scan(exp_op, *exp_word);
5043 if (exp_op == *exp_word) /* ## or %% */
5044 exp_word++;
5045 exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5046 if (exp_exp_word)
5047 exp_word = exp_exp_word;
5048 /* HACK ALERT. We depend here on the fact that
5049 * G.global_argv and results of utoa and get_local_var_value
5050 * are actually in writable memory:
5051 * scan_and_match momentarily stores NULs there. */
5052 t = (char*)val;
5053 loc = scan_and_match(t, exp_word, scan_flags);
5054 //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
5055 // exp_op, t, exp_word, loc);
5056 free(exp_exp_word);
5057 if (loc) { /* match was found */
5058 if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
5059 val = loc; /* take right part */
5060 else /* %[%] */
5061 val = to_be_freed = xstrndup(val, loc - val); /* left */
5065 #if ENABLE_HUSH_BASH_COMPAT
5066 else if (exp_op == '/' || exp_op == '\\') {
5067 /* It's ${var/[/]pattern[/repl]} thing.
5068 * Note that in encoded form it has TWO parts:
5069 * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5070 * and if // is used, it is encoded as \:
5071 * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
5073 /* Empty variable always gives nothing: */
5074 // "v=''; echo ${v/*/w}" prints "", not "w"
5075 if (val && val[0]) {
5076 /* pattern uses non-standard expansion.
5077 * repl should be unbackslashed and globbed
5078 * by the usual expansion rules:
5079 * >az; >bz;
5080 * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
5081 * v='a bz'; echo "${v/a*z/\z}" prints "\z"
5082 * v='a bz'; echo ${v/a*z/a*z} prints "az"
5083 * v='a bz'; echo ${v/a*z/\z} prints "z"
5084 * (note that a*z _pattern_ is never globbed!)
5086 char *pattern, *repl, *t;
5087 pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
5088 if (!pattern)
5089 pattern = xstrdup(exp_word);
5090 debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
5091 *p++ = SPECIAL_VAR_SYMBOL;
5092 exp_word = p;
5093 p = strchr(p, SPECIAL_VAR_SYMBOL);
5094 *p = '\0';
5095 repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
5096 debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
5097 /* HACK ALERT. We depend here on the fact that
5098 * G.global_argv and results of utoa and get_local_var_value
5099 * are actually in writable memory:
5100 * replace_pattern momentarily stores NULs there. */
5101 t = (char*)val;
5102 to_be_freed = replace_pattern(t,
5103 pattern,
5104 (repl ? repl : exp_word),
5105 exp_op);
5106 if (to_be_freed) /* at least one replace happened */
5107 val = to_be_freed;
5108 free(pattern);
5109 free(repl);
5112 #endif
5113 else if (exp_op == ':') {
5114 #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
5115 /* It's ${var:N[:M]} bashism.
5116 * Note that in encoded form it has TWO parts:
5117 * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
5119 arith_t beg, len;
5120 const char *errmsg;
5122 beg = expand_and_evaluate_arith(exp_word, &errmsg);
5123 if (errmsg)
5124 goto arith_err;
5125 debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
5126 *p++ = SPECIAL_VAR_SYMBOL;
5127 exp_word = p;
5128 p = strchr(p, SPECIAL_VAR_SYMBOL);
5129 *p = '\0';
5130 len = expand_and_evaluate_arith(exp_word, &errmsg);
5131 if (errmsg)
5132 goto arith_err;
5133 debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
5134 if (len >= 0) { /* bash compat: len < 0 is illegal */
5135 if (beg < 0) /* bash compat */
5136 beg = 0;
5137 debug_printf_varexp("from val:'%s'\n", val);
5138 if (len == 0 || !val || beg >= strlen(val)) {
5139 arith_err:
5140 val = NULL;
5141 } else {
5142 /* Paranoia. What if user entered 9999999999999
5143 * which fits in arith_t but not int? */
5144 if (len >= INT_MAX)
5145 len = INT_MAX;
5146 val = to_be_freed = xstrndup(val + beg, len);
5148 debug_printf_varexp("val:'%s'\n", val);
5149 } else
5150 #endif
5152 die_if_script("malformed ${%s:...}", var);
5153 val = NULL;
5155 } else { /* one of "-=+?" */
5156 /* Standard-mandated substitution ops:
5157 * ${var?word} - indicate error if unset
5158 * If var is unset, word (or a message indicating it is unset
5159 * if word is null) is written to standard error
5160 * and the shell exits with a non-zero exit status.
5161 * Otherwise, the value of var is substituted.
5162 * ${var-word} - use default value
5163 * If var is unset, word is substituted.
5164 * ${var=word} - assign and use default value
5165 * If var is unset, word is assigned to var.
5166 * In all cases, final value of var is substituted.
5167 * ${var+word} - use alternative value
5168 * If var is unset, null is substituted.
5169 * Otherwise, word is substituted.
5171 * Word is subjected to tilde expansion, parameter expansion,
5172 * command substitution, and arithmetic expansion.
5173 * If word is not needed, it is not expanded.
5175 * Colon forms (${var:-word}, ${var:=word} etc) do the same,
5176 * but also treat null var as if it is unset.
5178 int use_word = (!val || ((exp_save == ':') && !val[0]));
5179 if (exp_op == '+')
5180 use_word = !use_word;
5181 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
5182 (exp_save == ':') ? "true" : "false", use_word);
5183 if (use_word) {
5184 to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5185 if (to_be_freed)
5186 exp_word = to_be_freed;
5187 if (exp_op == '?') {
5188 /* mimic bash message */
5189 die_if_script("%s: %s",
5190 var,
5191 exp_word[0] ? exp_word : "parameter null or not set"
5193 //TODO: how interactive bash aborts expansion mid-command?
5194 } else {
5195 val = exp_word;
5198 if (exp_op == '=') {
5199 /* ${var=[word]} or ${var:=[word]} */
5200 if (isdigit(var[0]) || var[0] == '#') {
5201 /* mimic bash message */
5202 die_if_script("$%s: cannot assign in this way", var);
5203 val = NULL;
5204 } else {
5205 char *new_var = xasprintf("%s=%s", var, val);
5206 set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
5210 } /* one of "-=+?" */
5212 *exp_saveptr = exp_save;
5213 } /* if (exp_op) */
5215 arg[0] = arg0;
5217 *pp = p;
5218 *to_be_freed_pp = to_be_freed;
5219 return val;
5222 /* Expand all variable references in given string, adding words to list[]
5223 * at n, n+1,... positions. Return updated n (so that list[n] is next one
5224 * to be filled). This routine is extremely tricky: has to deal with
5225 * variables/parameters with whitespace, $* and $@, and constructs like
5226 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
5227 static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
5229 /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
5230 * expansion of right-hand side of assignment == 1-element expand.
5232 char cant_be_null = 0; /* only bit 0x80 matters */
5233 int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
5234 char *p;
5236 debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
5237 !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
5238 debug_print_list("expand_vars_to_list", output, n);
5239 n = o_save_ptr(output, n);
5240 debug_print_list("expand_vars_to_list[0]", output, n);
5242 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
5243 char first_ch;
5244 char *to_be_freed = NULL;
5245 const char *val = NULL;
5246 #if ENABLE_HUSH_TICK
5247 o_string subst_result = NULL_O_STRING;
5248 #endif
5249 #if ENABLE_SH_MATH_SUPPORT
5250 char arith_buf[sizeof(arith_t)*3 + 2];
5251 #endif
5253 if (ended_in_ifs) {
5254 o_addchr(output, '\0');
5255 n = o_save_ptr(output, n);
5256 ended_in_ifs = 0;
5259 o_addblock(output, arg, p - arg);
5260 debug_print_list("expand_vars_to_list[1]", output, n);
5261 arg = ++p;
5262 p = strchr(p, SPECIAL_VAR_SYMBOL);
5264 /* Fetch special var name (if it is indeed one of them)
5265 * and quote bit, force the bit on if singleword expansion -
5266 * important for not getting v=$@ expand to many words. */
5267 first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
5269 /* Is this variable quoted and thus expansion can't be null?
5270 * "$@" is special. Even if quoted, it can still
5271 * expand to nothing (not even an empty string),
5272 * thus it is excluded. */
5273 if ((first_ch & 0x7f) != '@')
5274 cant_be_null |= first_ch;
5276 switch (first_ch & 0x7f) {
5277 /* Highest bit in first_ch indicates that var is double-quoted */
5278 case '*':
5279 case '@': {
5280 int i;
5281 if (!G.global_argv[1])
5282 break;
5283 i = 1;
5284 cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
5285 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
5286 while (G.global_argv[i]) {
5287 n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
5288 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
5289 if (G.global_argv[i++][0] && G.global_argv[i]) {
5290 /* this argv[] is not empty and not last:
5291 * put terminating NUL, start new word */
5292 o_addchr(output, '\0');
5293 debug_print_list("expand_vars_to_list[2]", output, n);
5294 n = o_save_ptr(output, n);
5295 debug_print_list("expand_vars_to_list[3]", output, n);
5298 } else
5299 /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
5300 * and in this case should treat it like '$*' - see 'else...' below */
5301 if (first_ch == ('@'|0x80) /* quoted $@ */
5302 && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
5304 while (1) {
5305 o_addQstr(output, G.global_argv[i]);
5306 if (++i >= G.global_argc)
5307 break;
5308 o_addchr(output, '\0');
5309 debug_print_list("expand_vars_to_list[4]", output, n);
5310 n = o_save_ptr(output, n);
5312 } else { /* quoted $* (or v="$@" case): add as one word */
5313 while (1) {
5314 o_addQstr(output, G.global_argv[i]);
5315 if (!G.global_argv[++i])
5316 break;
5317 if (G.ifs[0])
5318 o_addchr(output, G.ifs[0]);
5320 output->has_quoted_part = 1;
5322 break;
5324 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
5325 /* "Empty variable", used to make "" etc to not disappear */
5326 output->has_quoted_part = 1;
5327 arg++;
5328 cant_be_null = 0x80;
5329 break;
5330 #if ENABLE_HUSH_TICK
5331 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
5332 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5333 arg++;
5334 /* Can't just stuff it into output o_string,
5335 * expanded result may need to be globbed
5336 * and $IFS-splitted */
5337 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
5338 G.last_exitcode = process_command_subs(&subst_result, arg);
5339 debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
5340 val = subst_result.data;
5341 goto store_val;
5342 #endif
5343 #if ENABLE_SH_MATH_SUPPORT
5344 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
5345 arith_t res;
5347 arg++; /* skip '+' */
5348 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
5349 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
5350 res = expand_and_evaluate_arith(arg, NULL);
5351 debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
5352 sprintf(arith_buf, ARITH_FMT, res);
5353 val = arith_buf;
5354 break;
5356 #endif
5357 default:
5358 val = expand_one_var(&to_be_freed, arg, &p);
5359 IF_HUSH_TICK(store_val:)
5360 if (!(first_ch & 0x80)) { /* unquoted $VAR */
5361 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
5362 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5363 if (val && val[0]) {
5364 n = expand_on_ifs(&ended_in_ifs, output, n, val);
5365 val = NULL;
5367 } else { /* quoted $VAR, val will be appended below */
5368 output->has_quoted_part = 1;
5369 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
5370 !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
5372 break;
5374 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
5376 if (val && val[0]) {
5377 o_addQstr(output, val);
5379 free(to_be_freed);
5381 /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
5382 * Do the check to avoid writing to a const string. */
5383 if (*p != SPECIAL_VAR_SYMBOL)
5384 *p = SPECIAL_VAR_SYMBOL;
5386 #if ENABLE_HUSH_TICK
5387 o_free(&subst_result);
5388 #endif
5389 arg = ++p;
5390 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
5392 if (arg[0]) {
5393 if (ended_in_ifs) {
5394 o_addchr(output, '\0');
5395 n = o_save_ptr(output, n);
5397 debug_print_list("expand_vars_to_list[a]", output, n);
5398 /* this part is literal, and it was already pre-quoted
5399 * if needed (much earlier), do not use o_addQstr here! */
5400 o_addstr_with_NUL(output, arg);
5401 debug_print_list("expand_vars_to_list[b]", output, n);
5402 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
5403 && !(cant_be_null & 0x80) /* and all vars were not quoted. */
5405 n--;
5406 /* allow to reuse list[n] later without re-growth */
5407 output->has_empty_slot = 1;
5408 } else {
5409 o_addchr(output, '\0');
5412 return n;
5415 static char **expand_variables(char **argv, unsigned expflags)
5417 int n;
5418 char **list;
5419 o_string output = NULL_O_STRING;
5421 output.o_expflags = expflags;
5423 n = 0;
5424 while (*argv) {
5425 n = expand_vars_to_list(&output, n, *argv);
5426 argv++;
5428 debug_print_list("expand_variables", &output, n);
5430 /* output.data (malloced in one block) gets returned in "list" */
5431 list = o_finalize_list(&output, n);
5432 debug_print_strings("expand_variables[1]", list);
5433 return list;
5436 static char **expand_strvec_to_strvec(char **argv)
5438 return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
5441 #if ENABLE_HUSH_BASH_COMPAT
5442 static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
5444 return expand_variables(argv, EXP_FLAG_SINGLEWORD);
5446 #endif
5448 /* Used for expansion of right hand of assignments,
5449 * $((...)), heredocs, variable espansion parts.
5451 * NB: should NOT do globbing!
5452 * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
5454 static char *expand_string_to_string(const char *str, int do_unbackslash)
5456 #if !ENABLE_HUSH_BASH_COMPAT
5457 const int do_unbackslash = 1;
5458 #endif
5459 char *argv[2], **list;
5461 debug_printf_expand("string_to_string<='%s'\n", str);
5462 /* This is generally an optimization, but it also
5463 * handles "", which otherwise trips over !list[0] check below.
5464 * (is this ever happens that we actually get str="" here?)
5466 if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
5467 //TODO: Can use on strings with \ too, just unbackslash() them?
5468 debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
5469 return xstrdup(str);
5472 argv[0] = (char*)str;
5473 argv[1] = NULL;
5474 list = expand_variables(argv, do_unbackslash
5475 ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
5476 : EXP_FLAG_SINGLEWORD
5478 if (HUSH_DEBUG)
5479 if (!list[0] || list[1])
5480 bb_error_msg_and_die("BUG in varexp2");
5481 /* actually, just move string 2*sizeof(char*) bytes back */
5482 overlapping_strcpy((char*)list, list[0]);
5483 if (do_unbackslash)
5484 unbackslash((char*)list);
5485 debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
5486 return (char*)list;
5489 /* Used for "eval" builtin */
5490 static char* expand_strvec_to_string(char **argv)
5492 char **list;
5494 list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
5495 /* Convert all NULs to spaces */
5496 if (list[0]) {
5497 int n = 1;
5498 while (list[n]) {
5499 if (HUSH_DEBUG)
5500 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
5501 bb_error_msg_and_die("BUG in varexp3");
5502 /* bash uses ' ' regardless of $IFS contents */
5503 list[n][-1] = ' ';
5504 n++;
5507 overlapping_strcpy((char*)list, list[0]);
5508 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
5509 return (char*)list;
5512 static char **expand_assignments(char **argv, int count)
5514 int i;
5515 char **p;
5517 G.expanded_assignments = p = NULL;
5518 /* Expand assignments into one string each */
5519 for (i = 0; i < count; i++) {
5520 G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
5522 G.expanded_assignments = NULL;
5523 return p;
5527 static void switch_off_special_sigs(unsigned mask)
5529 unsigned sig = 0;
5530 while ((mask >>= 1) != 0) {
5531 sig++;
5532 if (!(mask & 1))
5533 continue;
5534 if (G.traps) {
5535 if (G.traps[sig] && !G.traps[sig][0])
5536 /* trap is '', has to remain SIG_IGN */
5537 continue;
5538 free(G.traps[sig]);
5539 G.traps[sig] = NULL;
5541 /* We are here only if no trap or trap was not '' */
5542 install_sighandler(sig, SIG_DFL);
5546 #if BB_MMU
5547 /* never called */
5548 void re_execute_shell(char ***to_free, const char *s,
5549 char *g_argv0, char **g_argv,
5550 char **builtin_argv) NORETURN;
5552 static void reset_traps_to_defaults(void)
5554 /* This function is always called in a child shell
5555 * after fork (not vfork, NOMMU doesn't use this function).
5557 unsigned sig;
5558 unsigned mask;
5560 /* Child shells are not interactive.
5561 * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
5562 * Testcase: (while :; do :; done) + ^Z should background.
5563 * Same goes for SIGTERM, SIGHUP, SIGINT.
5565 mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
5566 if (!G.traps && !mask)
5567 return; /* already no traps and no special sigs */
5569 /* Switch off special sigs */
5570 switch_off_special_sigs(mask);
5571 #if ENABLE_HUSH_JOB
5572 G_fatal_sig_mask = 0;
5573 #endif
5574 G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
5575 /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
5576 * remain set in G.special_sig_mask */
5578 if (!G.traps)
5579 return;
5581 /* Reset all sigs to default except ones with empty traps */
5582 for (sig = 0; sig < NSIG; sig++) {
5583 if (!G.traps[sig])
5584 continue; /* no trap: nothing to do */
5585 if (!G.traps[sig][0])
5586 continue; /* empty trap: has to remain SIG_IGN */
5587 /* sig has non-empty trap, reset it: */
5588 free(G.traps[sig]);
5589 G.traps[sig] = NULL;
5590 /* There is no signal for trap 0 (EXIT) */
5591 if (sig == 0)
5592 continue;
5593 install_sighandler(sig, pick_sighandler(sig));
5597 #else /* !BB_MMU */
5599 static void re_execute_shell(char ***to_free, const char *s,
5600 char *g_argv0, char **g_argv,
5601 char **builtin_argv) NORETURN;
5602 static void re_execute_shell(char ***to_free, const char *s,
5603 char *g_argv0, char **g_argv,
5604 char **builtin_argv)
5606 # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
5607 /* delims + 2 * (number of bytes in printed hex numbers) */
5608 char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
5609 char *heredoc_argv[4];
5610 struct variable *cur;
5611 # if ENABLE_HUSH_FUNCTIONS
5612 struct function *funcp;
5613 # endif
5614 char **argv, **pp;
5615 unsigned cnt;
5616 unsigned long long empty_trap_mask;
5618 if (!g_argv0) { /* heredoc */
5619 argv = heredoc_argv;
5620 argv[0] = (char *) G.argv0_for_re_execing;
5621 argv[1] = (char *) "-<";
5622 argv[2] = (char *) s;
5623 argv[3] = NULL;
5624 pp = &argv[3]; /* used as pointer to empty environment */
5625 goto do_exec;
5628 cnt = 0;
5629 pp = builtin_argv;
5630 if (pp) while (*pp++)
5631 cnt++;
5633 empty_trap_mask = 0;
5634 if (G.traps) {
5635 int sig;
5636 for (sig = 1; sig < NSIG; sig++) {
5637 if (G.traps[sig] && !G.traps[sig][0])
5638 empty_trap_mask |= 1LL << sig;
5642 sprintf(param_buf, NOMMU_HACK_FMT
5643 , (unsigned) G.root_pid
5644 , (unsigned) G.root_ppid
5645 , (unsigned) G.last_bg_pid
5646 , (unsigned) G.last_exitcode
5647 , cnt
5648 , empty_trap_mask
5649 IF_HUSH_LOOPS(, G.depth_of_loop)
5651 # undef NOMMU_HACK_FMT
5652 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
5653 * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
5655 cnt += 6;
5656 for (cur = G.top_var; cur; cur = cur->next) {
5657 if (!cur->flg_export || cur->flg_read_only)
5658 cnt += 2;
5660 # if ENABLE_HUSH_FUNCTIONS
5661 for (funcp = G.top_func; funcp; funcp = funcp->next)
5662 cnt += 3;
5663 # endif
5664 pp = g_argv;
5665 while (*pp++)
5666 cnt++;
5667 *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
5668 *pp++ = (char *) G.argv0_for_re_execing;
5669 *pp++ = param_buf;
5670 for (cur = G.top_var; cur; cur = cur->next) {
5671 if (strcmp(cur->varstr, hush_version_str) == 0)
5672 continue;
5673 if (cur->flg_read_only) {
5674 *pp++ = (char *) "-R";
5675 *pp++ = cur->varstr;
5676 } else if (!cur->flg_export) {
5677 *pp++ = (char *) "-V";
5678 *pp++ = cur->varstr;
5681 # if ENABLE_HUSH_FUNCTIONS
5682 for (funcp = G.top_func; funcp; funcp = funcp->next) {
5683 *pp++ = (char *) "-F";
5684 *pp++ = funcp->name;
5685 *pp++ = funcp->body_as_string;
5687 # endif
5688 /* We can pass activated traps here. Say, -Tnn:trap_string
5690 * However, POSIX says that subshells reset signals with traps
5691 * to SIG_DFL.
5692 * I tested bash-3.2 and it not only does that with true subshells
5693 * of the form ( list ), but with any forked children shells.
5694 * I set trap "echo W" WINCH; and then tried:
5696 * { echo 1; sleep 20; echo 2; } &
5697 * while true; do echo 1; sleep 20; echo 2; break; done &
5698 * true | { echo 1; sleep 20; echo 2; } | cat
5700 * In all these cases sending SIGWINCH to the child shell
5701 * did not run the trap. If I add trap "echo V" WINCH;
5702 * _inside_ group (just before echo 1), it works.
5704 * I conclude it means we don't need to pass active traps here.
5706 *pp++ = (char *) "-c";
5707 *pp++ = (char *) s;
5708 if (builtin_argv) {
5709 while (*++builtin_argv)
5710 *pp++ = *builtin_argv;
5711 *pp++ = (char *) "";
5713 *pp++ = g_argv0;
5714 while (*g_argv)
5715 *pp++ = *g_argv++;
5716 /* *pp = NULL; - is already there */
5717 pp = environ;
5719 do_exec:
5720 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
5721 /* Don't propagate SIG_IGN to the child */
5722 if (SPECIAL_JOBSTOP_SIGS != 0)
5723 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
5724 execve(bb_busybox_exec_path, argv, pp);
5725 /* Fallback. Useful for init=/bin/hush usage etc */
5726 if (argv[0][0] == '/')
5727 execve(argv[0], argv, pp);
5728 xfunc_error_retval = 127;
5729 bb_error_msg_and_die("can't re-execute the shell");
5731 #endif /* !BB_MMU */
5734 static int run_and_free_list(struct pipe *pi);
5736 /* Executing from string: eval, sh -c '...'
5737 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5738 * end_trigger controls how often we stop parsing
5739 * NUL: parse all, execute, return
5740 * ';': parse till ';' or newline, execute, repeat till EOF
5742 static void parse_and_run_stream(struct in_str *inp, int end_trigger)
5744 /* Why we need empty flag?
5745 * An obscure corner case "false; ``; echo $?":
5746 * empty command in `` should still set $? to 0.
5747 * But we can't just set $? to 0 at the start,
5748 * this breaks "false; echo `echo $?`" case.
5750 bool empty = 1;
5751 while (1) {
5752 struct pipe *pipe_list;
5754 #if ENABLE_HUSH_INTERACTIVE
5755 if (end_trigger == ';')
5756 inp->promptmode = 0; /* PS1 */
5757 #endif
5758 pipe_list = parse_stream(NULL, inp, end_trigger);
5759 if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
5760 /* If we are in "big" script
5761 * (not in `cmd` or something similar)...
5763 if (pipe_list == ERR_PTR && end_trigger == ';') {
5764 /* Discard cached input (rest of line) */
5765 int ch = inp->last_char;
5766 while (ch != EOF && ch != '\n') {
5767 //bb_error_msg("Discarded:'%c'", ch);
5768 ch = i_getch(inp);
5770 /* Force prompt */
5771 inp->p = NULL;
5772 /* This stream isn't empty */
5773 empty = 0;
5774 continue;
5776 if (!pipe_list && empty)
5777 G.last_exitcode = 0;
5778 break;
5780 debug_print_tree(pipe_list, 0);
5781 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5782 run_and_free_list(pipe_list);
5783 empty = 0;
5784 #if ENABLE_HUSH_FUNCTIONS
5785 if (G.flag_return_in_progress == 1)
5786 break;
5787 #endif
5791 static void parse_and_run_string(const char *s)
5793 struct in_str input;
5794 setup_string_in_str(&input, s);
5795 parse_and_run_stream(&input, '\0');
5798 static void parse_and_run_file(FILE *f)
5800 struct in_str input;
5801 setup_file_in_str(&input, f);
5802 parse_and_run_stream(&input, ';');
5805 #if ENABLE_HUSH_TICK
5806 static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
5808 pid_t pid;
5809 int channel[2];
5810 # if !BB_MMU
5811 char **to_free = NULL;
5812 # endif
5814 xpipe(channel);
5815 pid = BB_MMU ? xfork() : xvfork();
5816 if (pid == 0) { /* child */
5817 disable_restore_tty_pgrp_on_exit();
5818 /* Process substitution is not considered to be usual
5819 * 'command execution'.
5820 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
5822 bb_signals(0
5823 + (1 << SIGTSTP)
5824 + (1 << SIGTTIN)
5825 + (1 << SIGTTOU)
5826 , SIG_IGN);
5827 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
5828 close(channel[0]); /* NB: close _first_, then move fd! */
5829 xmove_fd(channel[1], 1);
5830 /* Prevent it from trying to handle ctrl-z etc */
5831 IF_HUSH_JOB(G.run_list_level = 1;)
5832 /* Awful hack for `trap` or $(trap).
5834 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5835 * contains an example where "trap" is executed in a subshell:
5837 * save_traps=$(trap)
5838 * ...
5839 * eval "$save_traps"
5841 * Standard does not say that "trap" in subshell shall print
5842 * parent shell's traps. It only says that its output
5843 * must have suitable form, but then, in the above example
5844 * (which is not supposed to be normative), it implies that.
5846 * bash (and probably other shell) does implement it
5847 * (traps are reset to defaults, but "trap" still shows them),
5848 * but as a result, "trap" logic is hopelessly messed up:
5850 * # trap
5851 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5852 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5853 * # true | trap <--- trap is in subshell - no output (ditto)
5854 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5855 * trap -- 'echo Ho' SIGWINCH
5856 * # echo `(trap)` <--- in subshell in subshell - output
5857 * trap -- 'echo Ho' SIGWINCH
5858 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5859 * trap -- 'echo Ho' SIGWINCH
5861 * The rules when to forget and when to not forget traps
5862 * get really complex and nonsensical.
5864 * Our solution: ONLY bare $(trap) or `trap` is special.
5866 s = skip_whitespace(s);
5867 if (strncmp(s, "trap", 4) == 0
5868 && skip_whitespace(s + 4)[0] == '\0'
5870 static const char *const argv[] = { NULL, NULL };
5871 builtin_trap((char**)argv);
5872 exit(0); /* not _exit() - we need to fflush */
5874 # if BB_MMU
5875 reset_traps_to_defaults();
5876 parse_and_run_string(s);
5877 _exit(G.last_exitcode);
5878 # else
5879 /* We re-execute after vfork on NOMMU. This makes this script safe:
5880 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
5881 * huge=`cat BIG` # was blocking here forever
5882 * echo OK
5884 re_execute_shell(&to_free,
5886 G.global_argv[0],
5887 G.global_argv + 1,
5888 NULL);
5889 # endif
5892 /* parent */
5893 *pid_p = pid;
5894 # if ENABLE_HUSH_FAST
5895 G.count_SIGCHLD++;
5896 //bb_error_msg("[%d] fork in generate_stream_from_string:"
5897 // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
5898 // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
5899 # endif
5900 enable_restore_tty_pgrp_on_exit();
5901 # if !BB_MMU
5902 free(to_free);
5903 # endif
5904 close(channel[1]);
5905 close_on_exec_on(channel[0]);
5906 return xfdopen_for_read(channel[0]);
5909 /* Return code is exit status of the process that is run. */
5910 static int process_command_subs(o_string *dest, const char *s)
5912 FILE *fp;
5913 struct in_str pipe_str;
5914 pid_t pid;
5915 int status, ch, eol_cnt;
5917 fp = generate_stream_from_string(s, &pid);
5919 /* Now send results of command back into original context */
5920 setup_file_in_str(&pipe_str, fp);
5921 eol_cnt = 0;
5922 while ((ch = i_getch(&pipe_str)) != EOF) {
5923 if (ch == '\n') {
5924 eol_cnt++;
5925 continue;
5927 while (eol_cnt) {
5928 o_addchr(dest, '\n');
5929 eol_cnt--;
5931 o_addQchr(dest, ch);
5934 debug_printf("done reading from `cmd` pipe, closing it\n");
5935 fclose(fp);
5936 /* We need to extract exitcode. Test case
5937 * "true; echo `sleep 1; false` $?"
5938 * should print 1 */
5939 safe_waitpid(pid, &status, 0);
5940 debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
5941 return WEXITSTATUS(status);
5943 #endif /* ENABLE_HUSH_TICK */
5946 static void setup_heredoc(struct redir_struct *redir)
5948 struct fd_pair pair;
5949 pid_t pid;
5950 int len, written;
5951 /* the _body_ of heredoc (misleading field name) */
5952 const char *heredoc = redir->rd_filename;
5953 char *expanded;
5954 #if !BB_MMU
5955 char **to_free;
5956 #endif
5958 expanded = NULL;
5959 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
5960 expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
5961 if (expanded)
5962 heredoc = expanded;
5964 len = strlen(heredoc);
5966 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
5967 xpiped_pair(pair);
5968 xmove_fd(pair.rd, redir->rd_fd);
5970 /* Try writing without forking. Newer kernels have
5971 * dynamically growing pipes. Must use non-blocking write! */
5972 ndelay_on(pair.wr);
5973 while (1) {
5974 written = write(pair.wr, heredoc, len);
5975 if (written <= 0)
5976 break;
5977 len -= written;
5978 if (len == 0) {
5979 close(pair.wr);
5980 free(expanded);
5981 return;
5983 heredoc += written;
5985 ndelay_off(pair.wr);
5987 /* Okay, pipe buffer was not big enough */
5988 /* Note: we must not create a stray child (bastard? :)
5989 * for the unsuspecting parent process. Child creates a grandchild
5990 * and exits before parent execs the process which consumes heredoc
5991 * (that exec happens after we return from this function) */
5992 #if !BB_MMU
5993 to_free = NULL;
5994 #endif
5995 pid = xvfork();
5996 if (pid == 0) {
5997 /* child */
5998 disable_restore_tty_pgrp_on_exit();
5999 pid = BB_MMU ? xfork() : xvfork();
6000 if (pid != 0)
6001 _exit(0);
6002 /* grandchild */
6003 close(redir->rd_fd); /* read side of the pipe */
6004 #if BB_MMU
6005 full_write(pair.wr, heredoc, len); /* may loop or block */
6006 _exit(0);
6007 #else
6008 /* Delegate blocking writes to another process */
6009 xmove_fd(pair.wr, STDOUT_FILENO);
6010 re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
6011 #endif
6013 /* parent */
6014 #if ENABLE_HUSH_FAST
6015 G.count_SIGCHLD++;
6016 //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6017 #endif
6018 enable_restore_tty_pgrp_on_exit();
6019 #if !BB_MMU
6020 free(to_free);
6021 #endif
6022 close(pair.wr);
6023 free(expanded);
6024 wait(NULL); /* wait till child has died */
6027 /* squirrel != NULL means we squirrel away copies of stdin, stdout,
6028 * and stderr if they are redirected. */
6029 static int setup_redirects(struct command *prog, int squirrel[])
6031 int openfd, mode;
6032 struct redir_struct *redir;
6034 for (redir = prog->redirects; redir; redir = redir->next) {
6035 if (redir->rd_type == REDIRECT_HEREDOC2) {
6036 /* rd_fd<<HERE case */
6037 if (squirrel && redir->rd_fd < 3
6038 && squirrel[redir->rd_fd] < 0
6040 squirrel[redir->rd_fd] = dup(redir->rd_fd);
6042 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
6043 * of the heredoc */
6044 debug_printf_parse("set heredoc '%s'\n",
6045 redir->rd_filename);
6046 setup_heredoc(redir);
6047 continue;
6050 if (redir->rd_dup == REDIRFD_TO_FILE) {
6051 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
6052 char *p;
6053 if (redir->rd_filename == NULL) {
6054 /* Something went wrong in the parse.
6055 * Pretend it didn't happen */
6056 bb_error_msg("bug in redirect parse");
6057 continue;
6059 mode = redir_table[redir->rd_type].mode;
6060 p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
6061 openfd = open_or_warn(p, mode);
6062 free(p);
6063 if (openfd < 0) {
6064 /* this could get lost if stderr has been redirected, but
6065 * bash and ash both lose it as well (though zsh doesn't!) */
6066 //what the above comment tries to say?
6067 return 1;
6069 } else {
6070 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
6071 openfd = redir->rd_dup;
6074 if (openfd != redir->rd_fd) {
6075 if (squirrel && redir->rd_fd < 3
6076 && squirrel[redir->rd_fd] < 0
6078 squirrel[redir->rd_fd] = dup(redir->rd_fd);
6080 if (openfd == REDIRFD_CLOSE) {
6081 /* "n>-" means "close me" */
6082 close(redir->rd_fd);
6083 } else {
6084 xdup2(openfd, redir->rd_fd);
6085 if (redir->rd_dup == REDIRFD_TO_FILE)
6086 close(openfd);
6090 return 0;
6093 static void restore_redirects(int squirrel[])
6095 int i, fd;
6096 for (i = 0; i < 3; i++) {
6097 fd = squirrel[i];
6098 if (fd != -1) {
6099 /* We simply die on error */
6100 xmove_fd(fd, i);
6105 static char *find_in_path(const char *arg)
6107 char *ret = NULL;
6108 const char *PATH = get_local_var_value("PATH");
6110 if (!PATH)
6111 return NULL;
6113 while (1) {
6114 const char *end = strchrnul(PATH, ':');
6115 int sz = end - PATH; /* must be int! */
6117 free(ret);
6118 if (sz != 0) {
6119 ret = xasprintf("%.*s/%s", sz, PATH, arg);
6120 } else {
6121 /* We have xxx::yyyy in $PATH,
6122 * it means "use current dir" */
6123 ret = xstrdup(arg);
6125 if (access(ret, F_OK) == 0)
6126 break;
6128 if (*end == '\0') {
6129 free(ret);
6130 return NULL;
6132 PATH = end + 1;
6135 return ret;
6138 static const struct built_in_command *find_builtin_helper(const char *name,
6139 const struct built_in_command *x,
6140 const struct built_in_command *end)
6142 while (x != end) {
6143 if (strcmp(name, x->b_cmd) != 0) {
6144 x++;
6145 continue;
6147 debug_printf_exec("found builtin '%s'\n", name);
6148 return x;
6150 return NULL;
6152 static const struct built_in_command *find_builtin1(const char *name)
6154 return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
6156 static const struct built_in_command *find_builtin(const char *name)
6158 const struct built_in_command *x = find_builtin1(name);
6159 if (x)
6160 return x;
6161 return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
6164 #if ENABLE_HUSH_FUNCTIONS
6165 static struct function **find_function_slot(const char *name)
6167 struct function **funcpp = &G.top_func;
6168 while (*funcpp) {
6169 if (strcmp(name, (*funcpp)->name) == 0) {
6170 break;
6172 funcpp = &(*funcpp)->next;
6174 return funcpp;
6177 static const struct function *find_function(const char *name)
6179 const struct function *funcp = *find_function_slot(name);
6180 if (funcp)
6181 debug_printf_exec("found function '%s'\n", name);
6182 return funcp;
6185 /* Note: takes ownership on name ptr */
6186 static struct function *new_function(char *name)
6188 struct function **funcpp = find_function_slot(name);
6189 struct function *funcp = *funcpp;
6191 if (funcp != NULL) {
6192 struct command *cmd = funcp->parent_cmd;
6193 debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
6194 if (!cmd) {
6195 debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
6196 free(funcp->name);
6197 /* Note: if !funcp->body, do not free body_as_string!
6198 * This is a special case of "-F name body" function:
6199 * body_as_string was not malloced! */
6200 if (funcp->body) {
6201 free_pipe_list(funcp->body);
6202 # if !BB_MMU
6203 free(funcp->body_as_string);
6204 # endif
6206 } else {
6207 debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
6208 cmd->argv[0] = funcp->name;
6209 cmd->group = funcp->body;
6210 # if !BB_MMU
6211 cmd->group_as_string = funcp->body_as_string;
6212 # endif
6214 } else {
6215 debug_printf_exec("remembering new function '%s'\n", name);
6216 funcp = *funcpp = xzalloc(sizeof(*funcp));
6217 /*funcp->next = NULL;*/
6220 funcp->name = name;
6221 return funcp;
6224 static void unset_func(const char *name)
6226 struct function **funcpp = find_function_slot(name);
6227 struct function *funcp = *funcpp;
6229 if (funcp != NULL) {
6230 debug_printf_exec("freeing function '%s'\n", funcp->name);
6231 *funcpp = funcp->next;
6232 /* funcp is unlinked now, deleting it.
6233 * Note: if !funcp->body, the function was created by
6234 * "-F name body", do not free ->body_as_string
6235 * and ->name as they were not malloced. */
6236 if (funcp->body) {
6237 free_pipe_list(funcp->body);
6238 free(funcp->name);
6239 # if !BB_MMU
6240 free(funcp->body_as_string);
6241 # endif
6243 free(funcp);
6247 # if BB_MMU
6248 #define exec_function(to_free, funcp, argv) \
6249 exec_function(funcp, argv)
6250 # endif
6251 static void exec_function(char ***to_free,
6252 const struct function *funcp,
6253 char **argv) NORETURN;
6254 static void exec_function(char ***to_free,
6255 const struct function *funcp,
6256 char **argv)
6258 # if BB_MMU
6259 int n = 1;
6261 argv[0] = G.global_argv[0];
6262 G.global_argv = argv;
6263 while (*++argv)
6264 n++;
6265 G.global_argc = n;
6266 /* On MMU, funcp->body is always non-NULL */
6267 n = run_list(funcp->body);
6268 fflush_all();
6269 _exit(n);
6270 # else
6271 re_execute_shell(to_free,
6272 funcp->body_as_string,
6273 G.global_argv[0],
6274 argv + 1,
6275 NULL);
6276 # endif
6279 static int run_function(const struct function *funcp, char **argv)
6281 int rc;
6282 save_arg_t sv;
6283 smallint sv_flg;
6285 save_and_replace_G_args(&sv, argv);
6287 /* "we are in function, ok to use return" */
6288 sv_flg = G.flag_return_in_progress;
6289 G.flag_return_in_progress = -1;
6290 # if ENABLE_HUSH_LOCAL
6291 G.func_nest_level++;
6292 # endif
6294 /* On MMU, funcp->body is always non-NULL */
6295 # if !BB_MMU
6296 if (!funcp->body) {
6297 /* Function defined by -F */
6298 parse_and_run_string(funcp->body_as_string);
6299 rc = G.last_exitcode;
6300 } else
6301 # endif
6303 rc = run_list(funcp->body);
6306 # if ENABLE_HUSH_LOCAL
6308 struct variable *var;
6309 struct variable **var_pp;
6311 var_pp = &G.top_var;
6312 while ((var = *var_pp) != NULL) {
6313 if (var->func_nest_level < G.func_nest_level) {
6314 var_pp = &var->next;
6315 continue;
6317 /* Unexport */
6318 if (var->flg_export)
6319 bb_unsetenv(var->varstr);
6320 /* Remove from global list */
6321 *var_pp = var->next;
6322 /* Free */
6323 if (!var->max_len)
6324 free(var->varstr);
6325 free(var);
6327 G.func_nest_level--;
6329 # endif
6330 G.flag_return_in_progress = sv_flg;
6332 restore_G_args(&sv, argv);
6334 return rc;
6336 #endif /* ENABLE_HUSH_FUNCTIONS */
6339 #if BB_MMU
6340 #define exec_builtin(to_free, x, argv) \
6341 exec_builtin(x, argv)
6342 #else
6343 #define exec_builtin(to_free, x, argv) \
6344 exec_builtin(to_free, argv)
6345 #endif
6346 static void exec_builtin(char ***to_free,
6347 const struct built_in_command *x,
6348 char **argv) NORETURN;
6349 static void exec_builtin(char ***to_free,
6350 const struct built_in_command *x,
6351 char **argv)
6353 #if BB_MMU
6354 int rcode;
6355 fflush_all();
6356 rcode = x->b_function(argv);
6357 fflush_all();
6358 _exit(rcode);
6359 #else
6360 fflush_all();
6361 /* On NOMMU, we must never block!
6362 * Example: { sleep 99 | read line; } & echo Ok
6364 re_execute_shell(to_free,
6365 argv[0],
6366 G.global_argv[0],
6367 G.global_argv + 1,
6368 argv);
6369 #endif
6373 static void execvp_or_die(char **argv) NORETURN;
6374 static void execvp_or_die(char **argv)
6376 debug_printf_exec("execing '%s'\n", argv[0]);
6377 /* Don't propagate SIG_IGN to the child */
6378 if (SPECIAL_JOBSTOP_SIGS != 0)
6379 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6380 execvp(argv[0], argv);
6381 bb_perror_msg("can't execute '%s'", argv[0]);
6382 _exit(127); /* bash compat */
6385 #if ENABLE_HUSH_MODE_X
6386 static void dump_cmd_in_x_mode(char **argv)
6388 if (G_x_mode && argv) {
6389 /* We want to output the line in one write op */
6390 char *buf, *p;
6391 int len;
6392 int n;
6394 len = 3;
6395 n = 0;
6396 while (argv[n])
6397 len += strlen(argv[n++]) + 1;
6398 buf = xmalloc(len);
6399 buf[0] = '+';
6400 p = buf + 1;
6401 n = 0;
6402 while (argv[n])
6403 p += sprintf(p, " %s", argv[n++]);
6404 *p++ = '\n';
6405 *p = '\0';
6406 fputs(buf, stderr);
6407 free(buf);
6410 #else
6411 # define dump_cmd_in_x_mode(argv) ((void)0)
6412 #endif
6414 #if BB_MMU
6415 #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
6416 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
6417 #define pseudo_exec(nommu_save, command, argv_expanded) \
6418 pseudo_exec(command, argv_expanded)
6419 #endif
6421 /* Called after [v]fork() in run_pipe, or from builtin_exec.
6422 * Never returns.
6423 * Don't exit() here. If you don't exec, use _exit instead.
6424 * The at_exit handlers apparently confuse the calling process,
6425 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
6426 static void pseudo_exec_argv(nommu_save_t *nommu_save,
6427 char **argv, int assignment_cnt,
6428 char **argv_expanded) NORETURN;
6429 static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
6430 char **argv, int assignment_cnt,
6431 char **argv_expanded)
6433 char **new_env;
6435 new_env = expand_assignments(argv, assignment_cnt);
6436 dump_cmd_in_x_mode(new_env);
6438 if (!argv[assignment_cnt]) {
6439 /* Case when we are here: ... | var=val | ...
6440 * (note that we do not exit early, i.e., do not optimize out
6441 * expand_assignments(): think about ... | var=`sleep 1` | ...
6443 free_strings(new_env);
6444 _exit(EXIT_SUCCESS);
6447 #if BB_MMU
6448 set_vars_and_save_old(new_env);
6449 free(new_env); /* optional */
6450 /* we can also destroy set_vars_and_save_old's return value,
6451 * to save memory */
6452 #else
6453 nommu_save->new_env = new_env;
6454 nommu_save->old_vars = set_vars_and_save_old(new_env);
6455 #endif
6457 if (argv_expanded) {
6458 argv = argv_expanded;
6459 } else {
6460 argv = expand_strvec_to_strvec(argv + assignment_cnt);
6461 #if !BB_MMU
6462 nommu_save->argv = argv;
6463 #endif
6465 dump_cmd_in_x_mode(argv);
6467 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6468 if (strchr(argv[0], '/') != NULL)
6469 goto skip;
6470 #endif
6472 /* Check if the command matches any of the builtins.
6473 * Depending on context, this might be redundant. But it's
6474 * easier to waste a few CPU cycles than it is to figure out
6475 * if this is one of those cases.
6478 /* On NOMMU, it is more expensive to re-execute shell
6479 * just in order to run echo or test builtin.
6480 * It's better to skip it here and run corresponding
6481 * non-builtin later. */
6482 const struct built_in_command *x;
6483 x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
6484 if (x) {
6485 exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
6488 #if ENABLE_HUSH_FUNCTIONS
6489 /* Check if the command matches any functions */
6491 const struct function *funcp = find_function(argv[0]);
6492 if (funcp) {
6493 exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
6496 #endif
6498 #if ENABLE_FEATURE_SH_STANDALONE
6499 /* Check if the command matches any busybox applets */
6501 int a = find_applet_by_name(argv[0]);
6502 if (a >= 0) {
6503 # if BB_MMU /* see above why on NOMMU it is not allowed */
6504 if (APPLET_IS_NOEXEC(a)) {
6505 debug_printf_exec("running applet '%s'\n", argv[0]);
6506 run_applet_no_and_exit(a, argv);
6508 # endif
6509 /* Re-exec ourselves */
6510 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
6511 /* Don't propagate SIG_IGN to the child */
6512 if (SPECIAL_JOBSTOP_SIGS != 0)
6513 switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
6514 execv(bb_busybox_exec_path, argv);
6515 /* If they called chroot or otherwise made the binary no longer
6516 * executable, fall through */
6519 #endif
6521 #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
6522 skip:
6523 #endif
6524 execvp_or_die(argv);
6527 /* Called after [v]fork() in run_pipe
6529 static void pseudo_exec(nommu_save_t *nommu_save,
6530 struct command *command,
6531 char **argv_expanded) NORETURN;
6532 static void pseudo_exec(nommu_save_t *nommu_save,
6533 struct command *command,
6534 char **argv_expanded)
6536 if (command->argv) {
6537 pseudo_exec_argv(nommu_save, command->argv,
6538 command->assignment_cnt, argv_expanded);
6541 if (command->group) {
6542 /* Cases when we are here:
6543 * ( list )
6544 * { list } &
6545 * ... | ( list ) | ...
6546 * ... | { list } | ...
6548 #if BB_MMU
6549 int rcode;
6550 debug_printf_exec("pseudo_exec: run_list\n");
6551 reset_traps_to_defaults();
6552 rcode = run_list(command->group);
6553 /* OK to leak memory by not calling free_pipe_list,
6554 * since this process is about to exit */
6555 _exit(rcode);
6556 #else
6557 re_execute_shell(&nommu_save->argv_from_re_execing,
6558 command->group_as_string,
6559 G.global_argv[0],
6560 G.global_argv + 1,
6561 NULL);
6562 #endif
6565 /* Case when we are here: ... | >file */
6566 debug_printf_exec("pseudo_exec'ed null command\n");
6567 _exit(EXIT_SUCCESS);
6570 #if ENABLE_HUSH_JOB
6571 static const char *get_cmdtext(struct pipe *pi)
6573 char **argv;
6574 char *p;
6575 int len;
6577 /* This is subtle. ->cmdtext is created only on first backgrounding.
6578 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
6579 * On subsequent bg argv is trashed, but we won't use it */
6580 if (pi->cmdtext)
6581 return pi->cmdtext;
6582 argv = pi->cmds[0].argv;
6583 if (!argv || !argv[0]) {
6584 pi->cmdtext = xzalloc(1);
6585 return pi->cmdtext;
6588 len = 0;
6589 do {
6590 len += strlen(*argv) + 1;
6591 } while (*++argv);
6592 p = xmalloc(len);
6593 pi->cmdtext = p;
6594 argv = pi->cmds[0].argv;
6595 do {
6596 len = strlen(*argv);
6597 memcpy(p, *argv, len);
6598 p += len;
6599 *p++ = ' ';
6600 } while (*++argv);
6601 p[-1] = '\0';
6602 return pi->cmdtext;
6605 static void insert_bg_job(struct pipe *pi)
6607 struct pipe *job, **jobp;
6608 int i;
6610 /* Linear search for the ID of the job to use */
6611 pi->jobid = 1;
6612 for (job = G.job_list; job; job = job->next)
6613 if (job->jobid >= pi->jobid)
6614 pi->jobid = job->jobid + 1;
6616 /* Add job to the list of running jobs */
6617 jobp = &G.job_list;
6618 while ((job = *jobp) != NULL)
6619 jobp = &job->next;
6620 job = *jobp = xmalloc(sizeof(*job));
6622 *job = *pi; /* physical copy */
6623 job->next = NULL;
6624 job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
6625 /* Cannot copy entire pi->cmds[] vector! This causes double frees */
6626 for (i = 0; i < pi->num_cmds; i++) {
6627 job->cmds[i].pid = pi->cmds[i].pid;
6628 /* all other fields are not used and stay zero */
6630 job->cmdtext = xstrdup(get_cmdtext(pi));
6632 if (G_interactive_fd)
6633 printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
6634 G.last_jobid = job->jobid;
6637 static void remove_bg_job(struct pipe *pi)
6639 struct pipe *prev_pipe;
6641 if (pi == G.job_list) {
6642 G.job_list = pi->next;
6643 } else {
6644 prev_pipe = G.job_list;
6645 while (prev_pipe->next != pi)
6646 prev_pipe = prev_pipe->next;
6647 prev_pipe->next = pi->next;
6649 if (G.job_list)
6650 G.last_jobid = G.job_list->jobid;
6651 else
6652 G.last_jobid = 0;
6655 /* Remove a backgrounded job */
6656 static void delete_finished_bg_job(struct pipe *pi)
6658 remove_bg_job(pi);
6659 free_pipe(pi);
6661 #endif /* JOB */
6663 /* Check to see if any processes have exited -- if they
6664 * have, figure out why and see if a job has completed */
6665 static int checkjobs(struct pipe *fg_pipe)
6667 int attributes;
6668 int status;
6669 #if ENABLE_HUSH_JOB
6670 struct pipe *pi;
6671 #endif
6672 pid_t childpid;
6673 int rcode = 0;
6675 debug_printf_jobs("checkjobs %p\n", fg_pipe);
6677 attributes = WUNTRACED;
6678 if (fg_pipe == NULL)
6679 attributes |= WNOHANG;
6681 errno = 0;
6682 #if ENABLE_HUSH_FAST
6683 if (G.handled_SIGCHLD == G.count_SIGCHLD) {
6684 //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
6685 //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
6686 /* There was neither fork nor SIGCHLD since last waitpid */
6687 /* Avoid doing waitpid syscall if possible */
6688 if (!G.we_have_children) {
6689 errno = ECHILD;
6690 return -1;
6692 if (fg_pipe == NULL) { /* is WNOHANG set? */
6693 /* We have children, but they did not exit
6694 * or stop yet (we saw no SIGCHLD) */
6695 return 0;
6697 /* else: !WNOHANG, waitpid will block, can't short-circuit */
6699 #endif
6701 /* Do we do this right?
6702 * bash-3.00# sleep 20 | false
6703 * <ctrl-Z pressed>
6704 * [3]+ Stopped sleep 20 | false
6705 * bash-3.00# echo $?
6706 * 1 <========== bg pipe is not fully done, but exitcode is already known!
6707 * [hush 1.14.0: yes we do it right]
6709 wait_more:
6710 while (1) {
6711 int i;
6712 int dead;
6714 #if ENABLE_HUSH_FAST
6715 i = G.count_SIGCHLD;
6716 #endif
6717 childpid = waitpid(-1, &status, attributes);
6718 if (childpid <= 0) {
6719 if (childpid && errno != ECHILD)
6720 bb_perror_msg("waitpid");
6721 #if ENABLE_HUSH_FAST
6722 else { /* Until next SIGCHLD, waitpid's are useless */
6723 G.we_have_children = (childpid == 0);
6724 G.handled_SIGCHLD = i;
6725 //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
6727 #endif
6728 break;
6730 dead = WIFEXITED(status) || WIFSIGNALED(status);
6732 #if DEBUG_JOBS
6733 if (WIFSTOPPED(status))
6734 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
6735 childpid, WSTOPSIG(status), WEXITSTATUS(status));
6736 if (WIFSIGNALED(status))
6737 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
6738 childpid, WTERMSIG(status), WEXITSTATUS(status));
6739 if (WIFEXITED(status))
6740 debug_printf_jobs("pid %d exited, exitcode %d\n",
6741 childpid, WEXITSTATUS(status));
6742 #endif
6743 /* Were we asked to wait for fg pipe? */
6744 if (fg_pipe) {
6745 i = fg_pipe->num_cmds;
6746 while (--i >= 0) {
6747 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
6748 if (fg_pipe->cmds[i].pid != childpid)
6749 continue;
6750 if (dead) {
6751 int ex;
6752 fg_pipe->cmds[i].pid = 0;
6753 fg_pipe->alive_cmds--;
6754 ex = WEXITSTATUS(status);
6755 /* bash prints killer signal's name for *last*
6756 * process in pipe (prints just newline for SIGINT/SIGPIPE).
6757 * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
6759 if (WIFSIGNALED(status)) {
6760 int sig = WTERMSIG(status);
6761 if (i == fg_pipe->num_cmds-1)
6762 /* TODO: use strsignal() instead for bash compat? but that's bloat... */
6763 printf("%s\n", sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
6764 /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
6765 /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
6766 * Maybe we need to use sig | 128? */
6767 ex = sig + 128;
6769 fg_pipe->cmds[i].cmd_exitcode = ex;
6770 } else {
6771 fg_pipe->stopped_cmds++;
6773 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
6774 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
6775 if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
6776 /* All processes in fg pipe have exited or stopped */
6777 i = fg_pipe->num_cmds;
6778 while (--i >= 0) {
6779 rcode = fg_pipe->cmds[i].cmd_exitcode;
6780 /* usually last process gives overall exitstatus,
6781 * but with "set -o pipefail", last *failed* process does */
6782 if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
6783 break;
6785 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
6786 /* Note: *non-interactive* bash does not continue if all processes in fg pipe
6787 * are stopped. Testcase: "cat | cat" in a script (not on command line!)
6788 * and "killall -STOP cat" */
6789 if (G_interactive_fd) {
6790 #if ENABLE_HUSH_JOB
6791 if (fg_pipe->alive_cmds != 0)
6792 insert_bg_job(fg_pipe);
6793 #endif
6794 return rcode;
6796 if (fg_pipe->alive_cmds == 0)
6797 return rcode;
6799 /* There are still running processes in the fg pipe */
6800 goto wait_more; /* do waitpid again */
6802 /* it wasnt fg_pipe, look for process in bg pipes */
6805 #if ENABLE_HUSH_JOB
6806 /* We asked to wait for bg or orphaned children */
6807 /* No need to remember exitcode in this case */
6808 for (pi = G.job_list; pi; pi = pi->next) {
6809 for (i = 0; i < pi->num_cmds; i++) {
6810 if (pi->cmds[i].pid == childpid)
6811 goto found_pi_and_prognum;
6814 /* Happens when shell is used as init process (init=/bin/sh) */
6815 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
6816 continue; /* do waitpid again */
6818 found_pi_and_prognum:
6819 if (dead) {
6820 /* child exited */
6821 pi->cmds[i].pid = 0;
6822 pi->alive_cmds--;
6823 if (!pi->alive_cmds) {
6824 if (G_interactive_fd)
6825 printf(JOB_STATUS_FORMAT, pi->jobid,
6826 "Done", pi->cmdtext);
6827 delete_finished_bg_job(pi);
6829 } else {
6830 /* child stopped */
6831 pi->stopped_cmds++;
6833 #endif
6834 } /* while (waitpid succeeds)... */
6836 return rcode;
6839 #if ENABLE_HUSH_JOB
6840 static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
6842 pid_t p;
6843 int rcode = checkjobs(fg_pipe);
6844 if (G_saved_tty_pgrp) {
6845 /* Job finished, move the shell to the foreground */
6846 p = getpgrp(); /* our process group id */
6847 debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
6848 tcsetpgrp(G_interactive_fd, p);
6850 return rcode;
6852 #endif
6854 /* Start all the jobs, but don't wait for anything to finish.
6855 * See checkjobs().
6857 * Return code is normally -1, when the caller has to wait for children
6858 * to finish to determine the exit status of the pipe. If the pipe
6859 * is a simple builtin command, however, the action is done by the
6860 * time run_pipe returns, and the exit code is provided as the
6861 * return value.
6863 * Returns -1 only if started some children. IOW: we have to
6864 * mask out retvals of builtins etc with 0xff!
6866 * The only case when we do not need to [v]fork is when the pipe
6867 * is single, non-backgrounded, non-subshell command. Examples:
6868 * cmd ; ... { list } ; ...
6869 * cmd && ... { list } && ...
6870 * cmd || ... { list } || ...
6871 * If it is, then we can run cmd as a builtin, NOFORK,
6872 * or (if SH_STANDALONE) an applet, and we can run the { list }
6873 * with run_list. If it isn't one of these, we fork and exec cmd.
6875 * Cases when we must fork:
6876 * non-single: cmd | cmd
6877 * backgrounded: cmd & { list } &
6878 * subshell: ( list ) [&]
6880 #if !ENABLE_HUSH_MODE_X
6881 #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
6882 redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
6883 #endif
6884 static int redirect_and_varexp_helper(char ***new_env_p,
6885 struct variable **old_vars_p,
6886 struct command *command,
6887 int squirrel[3],
6888 char **argv_expanded)
6890 /* setup_redirects acts on file descriptors, not FILEs.
6891 * This is perfect for work that comes after exec().
6892 * Is it really safe for inline use? Experimentally,
6893 * things seem to work. */
6894 int rcode = setup_redirects(command, squirrel);
6895 if (rcode == 0) {
6896 char **new_env = expand_assignments(command->argv, command->assignment_cnt);
6897 *new_env_p = new_env;
6898 dump_cmd_in_x_mode(new_env);
6899 dump_cmd_in_x_mode(argv_expanded);
6900 if (old_vars_p)
6901 *old_vars_p = set_vars_and_save_old(new_env);
6903 return rcode;
6905 static NOINLINE int run_pipe(struct pipe *pi)
6907 static const char *const null_ptr = NULL;
6909 int cmd_no;
6910 int next_infd;
6911 struct command *command;
6912 char **argv_expanded;
6913 char **argv;
6914 /* it is not always needed, but we aim to smaller code */
6915 int squirrel[] = { -1, -1, -1 };
6916 int rcode;
6918 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
6919 debug_enter();
6921 /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
6922 * Result should be 3 lines: q w e, qwe, q w e
6924 G.ifs = get_local_var_value("IFS");
6925 if (!G.ifs)
6926 G.ifs = defifs;
6928 IF_HUSH_JOB(pi->pgrp = -1;)
6929 pi->stopped_cmds = 0;
6930 command = &pi->cmds[0];
6931 argv_expanded = NULL;
6933 if (pi->num_cmds != 1
6934 || pi->followup == PIPE_BG
6935 || command->cmd_type == CMD_SUBSHELL
6937 goto must_fork;
6940 pi->alive_cmds = 1;
6942 debug_printf_exec(": group:%p argv:'%s'\n",
6943 command->group, command->argv ? command->argv[0] : "NONE");
6945 if (command->group) {
6946 #if ENABLE_HUSH_FUNCTIONS
6947 if (command->cmd_type == CMD_FUNCDEF) {
6948 /* "executing" func () { list } */
6949 struct function *funcp;
6951 funcp = new_function(command->argv[0]);
6952 /* funcp->name is already set to argv[0] */
6953 funcp->body = command->group;
6954 # if !BB_MMU
6955 funcp->body_as_string = command->group_as_string;
6956 command->group_as_string = NULL;
6957 # endif
6958 command->group = NULL;
6959 command->argv[0] = NULL;
6960 debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
6961 funcp->parent_cmd = command;
6962 command->child_func = funcp;
6964 debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
6965 debug_leave();
6966 return EXIT_SUCCESS;
6968 #endif
6969 /* { list } */
6970 debug_printf("non-subshell group\n");
6971 rcode = 1; /* exitcode if redir failed */
6972 if (setup_redirects(command, squirrel) == 0) {
6973 debug_printf_exec(": run_list\n");
6974 rcode = run_list(command->group) & 0xff;
6976 restore_redirects(squirrel);
6977 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
6978 debug_leave();
6979 debug_printf_exec("run_pipe: return %d\n", rcode);
6980 return rcode;
6983 argv = command->argv ? command->argv : (char **) &null_ptr;
6985 const struct built_in_command *x;
6986 #if ENABLE_HUSH_FUNCTIONS
6987 const struct function *funcp;
6988 #else
6989 enum { funcp = 0 };
6990 #endif
6991 char **new_env = NULL;
6992 struct variable *old_vars = NULL;
6994 if (argv[command->assignment_cnt] == NULL) {
6995 /* Assignments, but no command */
6996 /* Ensure redirects take effect (that is, create files).
6997 * Try "a=t >file" */
6998 #if 0 /* A few cases in testsuite fail with this code. FIXME */
6999 rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
7000 /* Set shell variables */
7001 if (new_env) {
7002 argv = new_env;
7003 while (*argv) {
7004 set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7005 /* Do we need to flag set_local_var() errors?
7006 * "assignment to readonly var" and "putenv error"
7008 argv++;
7011 /* Redirect error sets $? to 1. Otherwise,
7012 * if evaluating assignment value set $?, retain it.
7013 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7014 if (rcode == 0)
7015 rcode = G.last_exitcode;
7016 /* Exit, _skipping_ variable restoring code: */
7017 goto clean_up_and_ret0;
7019 #else /* Older, bigger, but more correct code */
7021 rcode = setup_redirects(command, squirrel);
7022 restore_redirects(squirrel);
7023 /* Set shell variables */
7024 if (G_x_mode)
7025 bb_putchar_stderr('+');
7026 while (*argv) {
7027 char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7028 if (G_x_mode)
7029 fprintf(stderr, " %s", p);
7030 debug_printf_exec("set shell var:'%s'->'%s'\n",
7031 *argv, p);
7032 set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7033 /* Do we need to flag set_local_var() errors?
7034 * "assignment to readonly var" and "putenv error"
7036 argv++;
7038 if (G_x_mode)
7039 bb_putchar_stderr('\n');
7040 /* Redirect error sets $? to 1. Otherwise,
7041 * if evaluating assignment value set $?, retain it.
7042 * Try "false; q=`exit 2`; echo $?" - should print 2: */
7043 if (rcode == 0)
7044 rcode = G.last_exitcode;
7045 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7046 debug_leave();
7047 debug_printf_exec("run_pipe: return %d\n", rcode);
7048 return rcode;
7049 #endif
7052 /* Expand the rest into (possibly) many strings each */
7053 #if ENABLE_HUSH_BASH_COMPAT
7054 if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
7055 argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
7056 } else
7057 #endif
7059 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
7062 /* if someone gives us an empty string: `cmd with empty output` */
7063 if (!argv_expanded[0]) {
7064 free(argv_expanded);
7065 debug_leave();
7066 return G.last_exitcode;
7069 x = find_builtin(argv_expanded[0]);
7070 #if ENABLE_HUSH_FUNCTIONS
7071 funcp = NULL;
7072 if (!x)
7073 funcp = find_function(argv_expanded[0]);
7074 #endif
7075 if (x || funcp) {
7076 if (!funcp) {
7077 if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
7078 debug_printf("exec with redirects only\n");
7079 rcode = setup_redirects(command, NULL);
7080 goto clean_up_and_ret1;
7083 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7084 if (rcode == 0) {
7085 if (!funcp) {
7086 debug_printf_exec(": builtin '%s' '%s'...\n",
7087 x->b_cmd, argv_expanded[1]);
7088 fflush_all();
7089 rcode = x->b_function(argv_expanded) & 0xff;
7090 fflush_all();
7092 #if ENABLE_HUSH_FUNCTIONS
7093 else {
7094 # if ENABLE_HUSH_LOCAL
7095 struct variable **sv;
7096 sv = G.shadowed_vars_pp;
7097 G.shadowed_vars_pp = &old_vars;
7098 # endif
7099 debug_printf_exec(": function '%s' '%s'...\n",
7100 funcp->name, argv_expanded[1]);
7101 rcode = run_function(funcp, argv_expanded) & 0xff;
7102 # if ENABLE_HUSH_LOCAL
7103 G.shadowed_vars_pp = sv;
7104 # endif
7106 #endif
7108 clean_up_and_ret:
7109 unset_vars(new_env);
7110 add_vars(old_vars);
7111 /* clean_up_and_ret0: */
7112 restore_redirects(squirrel);
7113 clean_up_and_ret1:
7114 free(argv_expanded);
7115 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
7116 debug_leave();
7117 debug_printf_exec("run_pipe return %d\n", rcode);
7118 return rcode;
7121 if (ENABLE_FEATURE_SH_NOFORK) {
7122 int n = find_applet_by_name(argv_expanded[0]);
7123 if (n >= 0 && APPLET_IS_NOFORK(n)) {
7124 rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
7125 if (rcode == 0) {
7126 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
7127 argv_expanded[0], argv_expanded[1]);
7128 rcode = run_nofork_applet(n, argv_expanded);
7130 goto clean_up_and_ret;
7133 /* It is neither builtin nor applet. We must fork. */
7136 must_fork:
7137 /* NB: argv_expanded may already be created, and that
7138 * might include `cmd` runs! Do not rerun it! We *must*
7139 * use argv_expanded if it's non-NULL */
7141 /* Going to fork a child per each pipe member */
7142 pi->alive_cmds = 0;
7143 next_infd = 0;
7145 cmd_no = 0;
7146 while (cmd_no < pi->num_cmds) {
7147 struct fd_pair pipefds;
7148 #if !BB_MMU
7149 volatile nommu_save_t nommu_save;
7150 nommu_save.new_env = NULL;
7151 nommu_save.old_vars = NULL;
7152 nommu_save.argv = NULL;
7153 nommu_save.argv_from_re_execing = NULL;
7154 #endif
7155 command = &pi->cmds[cmd_no];
7156 cmd_no++;
7157 if (command->argv) {
7158 debug_printf_exec(": pipe member '%s' '%s'...\n",
7159 command->argv[0], command->argv[1]);
7160 } else {
7161 debug_printf_exec(": pipe member with no argv\n");
7164 /* pipes are inserted between pairs of commands */
7165 pipefds.rd = 0;
7166 pipefds.wr = 1;
7167 if (cmd_no < pi->num_cmds)
7168 xpiped_pair(pipefds);
7170 command->pid = BB_MMU ? fork() : vfork();
7171 if (!command->pid) { /* child */
7172 #if ENABLE_HUSH_JOB
7173 disable_restore_tty_pgrp_on_exit();
7174 CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
7176 /* Every child adds itself to new process group
7177 * with pgid == pid_of_first_child_in_pipe */
7178 if (G.run_list_level == 1 && G_interactive_fd) {
7179 pid_t pgrp;
7180 pgrp = pi->pgrp;
7181 if (pgrp < 0) /* true for 1st process only */
7182 pgrp = getpid();
7183 if (setpgid(0, pgrp) == 0
7184 && pi->followup != PIPE_BG
7185 && G_saved_tty_pgrp /* we have ctty */
7187 /* We do it in *every* child, not just first,
7188 * to avoid races */
7189 tcsetpgrp(G_interactive_fd, pgrp);
7192 #endif
7193 if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
7194 /* 1st cmd in backgrounded pipe
7195 * should have its stdin /dev/null'ed */
7196 close(0);
7197 if (open(bb_dev_null, O_RDONLY))
7198 xopen("/", O_RDONLY);
7199 } else {
7200 xmove_fd(next_infd, 0);
7202 xmove_fd(pipefds.wr, 1);
7203 if (pipefds.rd > 1)
7204 close(pipefds.rd);
7205 /* Like bash, explicit redirects override pipes,
7206 * and the pipe fd is available for dup'ing. */
7207 if (setup_redirects(command, NULL))
7208 _exit(1);
7210 /* Stores to nommu_save list of env vars putenv'ed
7211 * (NOMMU, on MMU we don't need that) */
7212 /* cast away volatility... */
7213 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
7214 /* pseudo_exec() does not return */
7217 /* parent or error */
7218 #if ENABLE_HUSH_FAST
7219 G.count_SIGCHLD++;
7220 //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
7221 #endif
7222 enable_restore_tty_pgrp_on_exit();
7223 #if !BB_MMU
7224 /* Clean up after vforked child */
7225 free(nommu_save.argv);
7226 free(nommu_save.argv_from_re_execing);
7227 unset_vars(nommu_save.new_env);
7228 add_vars(nommu_save.old_vars);
7229 #endif
7230 free(argv_expanded);
7231 argv_expanded = NULL;
7232 if (command->pid < 0) { /* [v]fork failed */
7233 /* Clearly indicate, was it fork or vfork */
7234 bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
7235 } else {
7236 pi->alive_cmds++;
7237 #if ENABLE_HUSH_JOB
7238 /* Second and next children need to know pid of first one */
7239 if (pi->pgrp < 0)
7240 pi->pgrp = command->pid;
7241 #endif
7244 if (cmd_no > 1)
7245 close(next_infd);
7246 if (cmd_no < pi->num_cmds)
7247 close(pipefds.wr);
7248 /* Pass read (output) pipe end to next iteration */
7249 next_infd = pipefds.rd;
7252 if (!pi->alive_cmds) {
7253 debug_leave();
7254 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
7255 return 1;
7258 debug_leave();
7259 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
7260 return -1;
7263 /* NB: called by pseudo_exec, and therefore must not modify any
7264 * global data until exec/_exit (we can be a child after vfork!) */
7265 static int run_list(struct pipe *pi)
7267 #if ENABLE_HUSH_CASE
7268 char *case_word = NULL;
7269 #endif
7270 #if ENABLE_HUSH_LOOPS
7271 struct pipe *loop_top = NULL;
7272 char **for_lcur = NULL;
7273 char **for_list = NULL;
7274 #endif
7275 smallint last_followup;
7276 smalluint rcode;
7277 #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
7278 smalluint cond_code = 0;
7279 #else
7280 enum { cond_code = 0 };
7281 #endif
7282 #if HAS_KEYWORDS
7283 smallint rword; /* RES_foo */
7284 smallint last_rword; /* ditto */
7285 #endif
7287 debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
7288 debug_enter();
7290 #if ENABLE_HUSH_LOOPS
7291 /* Check syntax for "for" */
7293 struct pipe *cpipe;
7294 for (cpipe = pi; cpipe; cpipe = cpipe->next) {
7295 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
7296 continue;
7297 /* current word is FOR or IN (BOLD in comments below) */
7298 if (cpipe->next == NULL) {
7299 syntax_error("malformed for");
7300 debug_leave();
7301 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7302 return 1;
7304 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
7305 if (cpipe->next->res_word == RES_DO)
7306 continue;
7307 /* next word is not "do". It must be "in" then ("FOR v in ...") */
7308 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
7309 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
7311 syntax_error("malformed for");
7312 debug_leave();
7313 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
7314 return 1;
7318 #endif
7320 /* Past this point, all code paths should jump to ret: label
7321 * in order to return, no direct "return" statements please.
7322 * This helps to ensure that no memory is leaked. */
7324 #if ENABLE_HUSH_JOB
7325 G.run_list_level++;
7326 #endif
7328 #if HAS_KEYWORDS
7329 rword = RES_NONE;
7330 last_rword = RES_XXXX;
7331 #endif
7332 last_followup = PIPE_SEQ;
7333 rcode = G.last_exitcode;
7335 /* Go through list of pipes, (maybe) executing them. */
7336 for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
7337 if (G.flag_SIGINT)
7338 break;
7340 IF_HAS_KEYWORDS(rword = pi->res_word;)
7341 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
7342 rword, cond_code, last_rword);
7343 #if ENABLE_HUSH_LOOPS
7344 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
7345 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
7347 /* start of a loop: remember where loop starts */
7348 loop_top = pi;
7349 G.depth_of_loop++;
7351 #endif
7352 /* Still in the same "if...", "then..." or "do..." branch? */
7353 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
7354 if ((rcode == 0 && last_followup == PIPE_OR)
7355 || (rcode != 0 && last_followup == PIPE_AND)
7357 /* It is "<true> || CMD" or "<false> && CMD"
7358 * and we should not execute CMD */
7359 debug_printf_exec("skipped cmd because of || or &&\n");
7360 last_followup = pi->followup;
7361 continue;
7364 last_followup = pi->followup;
7365 IF_HAS_KEYWORDS(last_rword = rword;)
7366 #if ENABLE_HUSH_IF
7367 if (cond_code) {
7368 if (rword == RES_THEN) {
7369 /* if false; then ... fi has exitcode 0! */
7370 G.last_exitcode = rcode = EXIT_SUCCESS;
7371 /* "if <false> THEN cmd": skip cmd */
7372 continue;
7374 } else {
7375 if (rword == RES_ELSE || rword == RES_ELIF) {
7376 /* "if <true> then ... ELSE/ELIF cmd":
7377 * skip cmd and all following ones */
7378 break;
7381 #endif
7382 #if ENABLE_HUSH_LOOPS
7383 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
7384 if (!for_lcur) {
7385 /* first loop through for */
7387 static const char encoded_dollar_at[] ALIGN1 = {
7388 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
7389 }; /* encoded representation of "$@" */
7390 static const char *const encoded_dollar_at_argv[] = {
7391 encoded_dollar_at, NULL
7392 }; /* argv list with one element: "$@" */
7393 char **vals;
7395 vals = (char**)encoded_dollar_at_argv;
7396 if (pi->next->res_word == RES_IN) {
7397 /* if no variable values after "in" we skip "for" */
7398 if (!pi->next->cmds[0].argv) {
7399 G.last_exitcode = rcode = EXIT_SUCCESS;
7400 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
7401 break;
7403 vals = pi->next->cmds[0].argv;
7404 } /* else: "for var; do..." -> assume "$@" list */
7405 /* create list of variable values */
7406 debug_print_strings("for_list made from", vals);
7407 for_list = expand_strvec_to_strvec(vals);
7408 for_lcur = for_list;
7409 debug_print_strings("for_list", for_list);
7411 if (!*for_lcur) {
7412 /* "for" loop is over, clean up */
7413 free(for_list);
7414 for_list = NULL;
7415 for_lcur = NULL;
7416 break;
7418 /* Insert next value from for_lcur */
7419 /* note: *for_lcur already has quotes removed, $var expanded, etc */
7420 set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
7421 continue;
7423 if (rword == RES_IN) {
7424 continue; /* "for v IN list;..." - "in" has no cmds anyway */
7426 if (rword == RES_DONE) {
7427 continue; /* "done" has no cmds too */
7429 #endif
7430 #if ENABLE_HUSH_CASE
7431 if (rword == RES_CASE) {
7432 case_word = expand_strvec_to_string(pi->cmds->argv);
7433 continue;
7435 if (rword == RES_MATCH) {
7436 char **argv;
7438 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
7439 break;
7440 /* all prev words didn't match, does this one match? */
7441 argv = pi->cmds->argv;
7442 while (*argv) {
7443 char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
7444 /* TODO: which FNM_xxx flags to use? */
7445 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
7446 free(pattern);
7447 if (cond_code == 0) { /* match! we will execute this branch */
7448 free(case_word); /* make future "word)" stop */
7449 case_word = NULL;
7450 break;
7452 argv++;
7454 continue;
7456 if (rword == RES_CASE_BODY) { /* inside of a case branch */
7457 if (cond_code != 0)
7458 continue; /* not matched yet, skip this pipe */
7460 #endif
7461 /* Just pressing <enter> in shell should check for jobs.
7462 * OTOH, in non-interactive shell this is useless
7463 * and only leads to extra job checks */
7464 if (pi->num_cmds == 0) {
7465 if (G_interactive_fd)
7466 goto check_jobs_and_continue;
7467 continue;
7470 /* After analyzing all keywords and conditions, we decided
7471 * to execute this pipe. NB: have to do checkjobs(NULL)
7472 * after run_pipe to collect any background children,
7473 * even if list execution is to be stopped. */
7474 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
7476 int r;
7477 #if ENABLE_HUSH_LOOPS
7478 G.flag_break_continue = 0;
7479 #endif
7480 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
7481 if (r != -1) {
7482 /* We ran a builtin, function, or group.
7483 * rcode is already known
7484 * and we don't need to wait for anything. */
7485 G.last_exitcode = rcode;
7486 debug_printf_exec(": builtin/func exitcode %d\n", rcode);
7487 check_and_run_traps();
7488 #if ENABLE_HUSH_LOOPS
7489 /* Was it "break" or "continue"? */
7490 if (G.flag_break_continue) {
7491 smallint fbc = G.flag_break_continue;
7492 /* We might fall into outer *loop*,
7493 * don't want to break it too */
7494 if (loop_top) {
7495 G.depth_break_continue--;
7496 if (G.depth_break_continue == 0)
7497 G.flag_break_continue = 0;
7498 /* else: e.g. "continue 2" should *break* once, *then* continue */
7499 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
7500 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
7501 goto check_jobs_and_break;
7502 /* "continue": simulate end of loop */
7503 rword = RES_DONE;
7504 continue;
7506 #endif
7507 #if ENABLE_HUSH_FUNCTIONS
7508 if (G.flag_return_in_progress == 1) {
7509 /* same as "goto check_jobs_and_break" */
7510 checkjobs(NULL);
7511 break;
7513 #endif
7514 } else if (pi->followup == PIPE_BG) {
7515 /* What does bash do with attempts to background builtins? */
7516 /* even bash 3.2 doesn't do that well with nested bg:
7517 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
7518 * I'm NOT treating inner &'s as jobs */
7519 check_and_run_traps();
7520 #if ENABLE_HUSH_JOB
7521 if (G.run_list_level == 1)
7522 insert_bg_job(pi);
7523 #endif
7524 /* Last command's pid goes to $! */
7525 G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
7526 G.last_exitcode = rcode = EXIT_SUCCESS;
7527 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
7528 } else {
7529 #if ENABLE_HUSH_JOB
7530 if (G.run_list_level == 1 && G_interactive_fd) {
7531 /* Waits for completion, then fg's main shell */
7532 rcode = checkjobs_and_fg_shell(pi);
7533 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
7534 check_and_run_traps();
7535 } else
7536 #endif
7537 { /* This one just waits for completion */
7538 rcode = checkjobs(pi);
7539 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
7540 check_and_run_traps();
7542 G.last_exitcode = rcode;
7546 /* Analyze how result affects subsequent commands */
7547 #if ENABLE_HUSH_IF
7548 if (rword == RES_IF || rword == RES_ELIF)
7549 cond_code = rcode;
7550 #endif
7551 #if ENABLE_HUSH_LOOPS
7552 /* Beware of "while false; true; do ..."! */
7553 if (pi->next
7554 && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
7555 /* check for RES_DONE is needed for "while ...; do \n done" case */
7557 if (rword == RES_WHILE) {
7558 if (rcode) {
7559 /* "while false; do...done" - exitcode 0 */
7560 G.last_exitcode = rcode = EXIT_SUCCESS;
7561 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
7562 goto check_jobs_and_break;
7565 if (rword == RES_UNTIL) {
7566 if (!rcode) {
7567 debug_printf_exec(": until expr is true: breaking\n");
7568 check_jobs_and_break:
7569 checkjobs(NULL);
7570 break;
7574 #endif
7576 check_jobs_and_continue:
7577 checkjobs(NULL);
7578 } /* for (pi) */
7580 #if ENABLE_HUSH_JOB
7581 G.run_list_level--;
7582 #endif
7583 #if ENABLE_HUSH_LOOPS
7584 if (loop_top)
7585 G.depth_of_loop--;
7586 free(for_list);
7587 #endif
7588 #if ENABLE_HUSH_CASE
7589 free(case_word);
7590 #endif
7591 debug_leave();
7592 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
7593 return rcode;
7596 /* Select which version we will use */
7597 static int run_and_free_list(struct pipe *pi)
7599 int rcode = 0;
7600 debug_printf_exec("run_and_free_list entered\n");
7601 if (!G.o_opt[OPT_O_NOEXEC]) {
7602 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
7603 rcode = run_list(pi);
7605 /* free_pipe_list has the side effect of clearing memory.
7606 * In the long run that function can be merged with run_list,
7607 * but doing that now would hobble the debugging effort. */
7608 free_pipe_list(pi);
7609 debug_printf_exec("run_and_free_list return %d\n", rcode);
7610 return rcode;
7614 static void install_sighandlers(unsigned mask)
7616 sighandler_t old_handler;
7617 unsigned sig = 0;
7618 while ((mask >>= 1) != 0) {
7619 sig++;
7620 if (!(mask & 1))
7621 continue;
7622 old_handler = install_sighandler(sig, pick_sighandler(sig));
7623 /* POSIX allows shell to re-enable SIGCHLD
7624 * even if it was SIG_IGN on entry.
7625 * Therefore we skip IGN check for it:
7627 if (sig == SIGCHLD)
7628 continue;
7629 if (old_handler == SIG_IGN) {
7630 /* oops... restore back to IGN, and record this fact */
7631 install_sighandler(sig, old_handler);
7632 if (!G.traps)
7633 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7634 free(G.traps[sig]);
7635 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7640 /* Called a few times only (or even once if "sh -c") */
7641 static void install_special_sighandlers(void)
7643 unsigned mask;
7645 /* Which signals are shell-special? */
7646 mask = (1 << SIGQUIT) | (1 << SIGCHLD);
7647 if (G_interactive_fd) {
7648 mask |= SPECIAL_INTERACTIVE_SIGS;
7649 if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
7650 mask |= SPECIAL_JOBSTOP_SIGS;
7652 /* Careful, do not re-install handlers we already installed */
7653 if (G.special_sig_mask != mask) {
7654 unsigned diff = mask & ~G.special_sig_mask;
7655 G.special_sig_mask = mask;
7656 install_sighandlers(diff);
7660 #if ENABLE_HUSH_JOB
7661 /* helper */
7662 /* Set handlers to restore tty pgrp and exit */
7663 static void install_fatal_sighandlers(void)
7665 unsigned mask;
7667 /* We will restore tty pgrp on these signals */
7668 mask = 0
7669 + (1 << SIGILL ) * HUSH_DEBUG
7670 + (1 << SIGFPE ) * HUSH_DEBUG
7671 + (1 << SIGBUS ) * HUSH_DEBUG
7672 + (1 << SIGSEGV) * HUSH_DEBUG
7673 + (1 << SIGTRAP) * HUSH_DEBUG
7674 + (1 << SIGABRT)
7675 /* bash 3.2 seems to handle these just like 'fatal' ones */
7676 + (1 << SIGPIPE)
7677 + (1 << SIGALRM)
7678 /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
7679 * if we aren't interactive... but in this case
7680 * we never want to restore pgrp on exit, and this fn is not called
7682 /*+ (1 << SIGHUP )*/
7683 /*+ (1 << SIGTERM)*/
7684 /*+ (1 << SIGINT )*/
7686 G_fatal_sig_mask = mask;
7688 install_sighandlers(mask);
7690 #endif
7692 static int set_mode(int state, char mode, const char *o_opt)
7694 int idx;
7695 switch (mode) {
7696 case 'n':
7697 G.o_opt[OPT_O_NOEXEC] = state;
7698 break;
7699 case 'x':
7700 IF_HUSH_MODE_X(G_x_mode = state;)
7701 break;
7702 case 'o':
7703 if (!o_opt) {
7704 /* "set -+o" without parameter.
7705 * in bash, set -o produces this output:
7706 * pipefail off
7707 * and set +o:
7708 * set +o pipefail
7709 * We always use the second form.
7711 const char *p = o_opt_strings;
7712 idx = 0;
7713 while (*p) {
7714 printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
7715 idx++;
7716 p += strlen(p) + 1;
7718 break;
7720 idx = index_in_strings(o_opt_strings, o_opt);
7721 if (idx >= 0) {
7722 G.o_opt[idx] = state;
7723 break;
7725 default:
7726 return EXIT_FAILURE;
7728 return EXIT_SUCCESS;
7731 int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
7732 int hush_main(int argc, char **argv)
7734 enum {
7735 OPT_login = (1 << 0),
7737 unsigned flags;
7738 int opt;
7739 unsigned builtin_argc;
7740 char **e;
7741 struct variable *cur_var;
7742 struct variable *shell_ver;
7744 INIT_G();
7745 if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
7746 G.last_exitcode = EXIT_SUCCESS;
7747 #if ENABLE_HUSH_FAST
7748 G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
7749 #endif
7750 #if !BB_MMU
7751 G.argv0_for_re_execing = argv[0];
7752 #endif
7753 /* Deal with HUSH_VERSION */
7754 shell_ver = xzalloc(sizeof(*shell_ver));
7755 shell_ver->flg_export = 1;
7756 shell_ver->flg_read_only = 1;
7757 /* Code which handles ${var<op>...} needs writable values for all variables,
7758 * therefore we xstrdup: */
7759 shell_ver->varstr = xstrdup(hush_version_str);
7760 /* Create shell local variables from the values
7761 * currently living in the environment */
7762 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
7763 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
7764 G.top_var = shell_ver;
7765 cur_var = G.top_var;
7766 e = environ;
7767 if (e) while (*e) {
7768 char *value = strchr(*e, '=');
7769 if (value) { /* paranoia */
7770 cur_var->next = xzalloc(sizeof(*cur_var));
7771 cur_var = cur_var->next;
7772 cur_var->varstr = *e;
7773 cur_var->max_len = strlen(*e);
7774 cur_var->flg_export = 1;
7776 e++;
7778 /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
7779 debug_printf_env("putenv '%s'\n", shell_ver->varstr);
7780 putenv(shell_ver->varstr);
7782 /* Export PWD */
7783 set_pwd_var(/*exp:*/ 1);
7784 /* bash also exports SHLVL and _,
7785 * and sets (but doesn't export) the following variables:
7786 * BASH=/bin/bash
7787 * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
7788 * BASH_VERSION='3.2.0(1)-release'
7789 * HOSTTYPE=i386
7790 * MACHTYPE=i386-pc-linux-gnu
7791 * OSTYPE=linux-gnu
7792 * HOSTNAME=<xxxxxxxxxx>
7793 * PPID=<NNNNN> - we also do it elsewhere
7794 * EUID=<NNNNN>
7795 * UID=<NNNNN>
7796 * GROUPS=()
7797 * LINES=<NNN>
7798 * COLUMNS=<NNN>
7799 * BASH_ARGC=()
7800 * BASH_ARGV=()
7801 * BASH_LINENO=()
7802 * BASH_SOURCE=()
7803 * DIRSTACK=()
7804 * PIPESTATUS=([0]="0")
7805 * HISTFILE=/<xxx>/.bash_history
7806 * HISTFILESIZE=500
7807 * HISTSIZE=500
7808 * MAILCHECK=60
7809 * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
7810 * SHELL=/bin/bash
7811 * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
7812 * TERM=dumb
7813 * OPTERR=1
7814 * OPTIND=1
7815 * IFS=$' \t\n'
7816 * PS1='\s-\v\$ '
7817 * PS2='> '
7818 * PS4='+ '
7821 #if ENABLE_FEATURE_EDITING
7822 G.line_input_state = new_line_input_t(FOR_SHELL);
7823 #endif
7825 /* Initialize some more globals to non-zero values */
7826 cmdedit_update_prompt();
7828 if (setjmp(die_jmp)) {
7829 /* xfunc has failed! die die die */
7830 /* no EXIT traps, this is an escape hatch! */
7831 G.exiting = 1;
7832 hush_exit(xfunc_error_retval);
7835 /* Shell is non-interactive at first. We need to call
7836 * install_special_sighandlers() if we are going to execute "sh <script>",
7837 * "sh -c <cmds>" or login shell's /etc/profile and friends.
7838 * If we later decide that we are interactive, we run install_special_sighandlers()
7839 * in order to intercept (more) signals.
7842 /* Parse options */
7843 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
7844 flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
7845 builtin_argc = 0;
7846 while (1) {
7847 opt = getopt(argc, argv, "+c:xinsl"
7848 #if !BB_MMU
7849 "<:$:R:V:"
7850 # if ENABLE_HUSH_FUNCTIONS
7851 "F:"
7852 # endif
7853 #endif
7855 if (opt <= 0)
7856 break;
7857 switch (opt) {
7858 case 'c':
7859 /* Possibilities:
7860 * sh ... -c 'script'
7861 * sh ... -c 'script' ARG0 [ARG1...]
7862 * On NOMMU, if builtin_argc != 0,
7863 * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
7864 * "" needs to be replaced with NULL
7865 * and BARGV vector fed to builtin function.
7866 * Note: the form without ARG0 never happens:
7867 * sh ... -c 'builtin' BARGV... ""
7869 if (!G.root_pid) {
7870 G.root_pid = getpid();
7871 G.root_ppid = getppid();
7873 G.global_argv = argv + optind;
7874 G.global_argc = argc - optind;
7875 if (builtin_argc) {
7876 /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
7877 const struct built_in_command *x;
7879 install_special_sighandlers();
7880 x = find_builtin(optarg);
7881 if (x) { /* paranoia */
7882 G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
7883 G.global_argv += builtin_argc;
7884 G.global_argv[-1] = NULL; /* replace "" */
7885 fflush_all();
7886 G.last_exitcode = x->b_function(argv + optind - 1);
7888 goto final_return;
7890 if (!G.global_argv[0]) {
7891 /* -c 'script' (no params): prevent empty $0 */
7892 G.global_argv--; /* points to argv[i] of 'script' */
7893 G.global_argv[0] = argv[0];
7894 G.global_argc++;
7895 } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
7896 install_special_sighandlers();
7897 parse_and_run_string(optarg);
7898 goto final_return;
7899 case 'i':
7900 /* Well, we cannot just declare interactiveness,
7901 * we have to have some stuff (ctty, etc) */
7902 /* G_interactive_fd++; */
7903 break;
7904 case 's':
7905 /* "-s" means "read from stdin", but this is how we always
7906 * operate, so simply do nothing here. */
7907 break;
7908 case 'l':
7909 flags |= OPT_login;
7910 break;
7911 #if !BB_MMU
7912 case '<': /* "big heredoc" support */
7913 full_write1_str(optarg);
7914 _exit(0);
7915 case '$': {
7916 unsigned long long empty_trap_mask;
7918 G.root_pid = bb_strtou(optarg, &optarg, 16);
7919 optarg++;
7920 G.root_ppid = bb_strtou(optarg, &optarg, 16);
7921 optarg++;
7922 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
7923 optarg++;
7924 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
7925 optarg++;
7926 builtin_argc = bb_strtou(optarg, &optarg, 16);
7927 optarg++;
7928 empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
7929 if (empty_trap_mask != 0) {
7930 int sig;
7931 install_special_sighandlers();
7932 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
7933 for (sig = 1; sig < NSIG; sig++) {
7934 if (empty_trap_mask & (1LL << sig)) {
7935 G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
7936 install_sighandler(sig, SIG_IGN);
7940 # if ENABLE_HUSH_LOOPS
7941 optarg++;
7942 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
7943 # endif
7944 break;
7946 case 'R':
7947 case 'V':
7948 set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
7949 break;
7950 # if ENABLE_HUSH_FUNCTIONS
7951 case 'F': {
7952 struct function *funcp = new_function(optarg);
7953 /* funcp->name is already set to optarg */
7954 /* funcp->body is set to NULL. It's a special case. */
7955 funcp->body_as_string = argv[optind];
7956 optind++;
7957 break;
7959 # endif
7960 #endif
7961 case 'n':
7962 case 'x':
7963 if (set_mode(1, opt, NULL) == 0) /* no error */
7964 break;
7965 default:
7966 #ifndef BB_VER
7967 fprintf(stderr, "Usage: sh [FILE]...\n"
7968 " or: sh -c command [args]...\n\n");
7969 exit(EXIT_FAILURE);
7970 #else
7971 bb_show_usage();
7972 #endif
7974 } /* option parsing loop */
7976 /* Skip options. Try "hush -l": $1 should not be "-l"! */
7977 G.global_argc = argc - (optind - 1);
7978 G.global_argv = argv + (optind - 1);
7979 G.global_argv[0] = argv[0];
7981 if (!G.root_pid) {
7982 G.root_pid = getpid();
7983 G.root_ppid = getppid();
7986 /* If we are login shell... */
7987 if (flags & OPT_login) {
7988 FILE *input;
7989 debug_printf("sourcing /etc/profile\n");
7990 input = fopen_for_read("/etc/profile");
7991 if (input != NULL) {
7992 close_on_exec_on(fileno(input));
7993 install_special_sighandlers();
7994 parse_and_run_file(input);
7995 fclose(input);
7997 /* bash: after sourcing /etc/profile,
7998 * tries to source (in the given order):
7999 * ~/.bash_profile, ~/.bash_login, ~/.profile,
8000 * stopping on first found. --noprofile turns this off.
8001 * bash also sources ~/.bash_logout on exit.
8002 * If called as sh, skips .bash_XXX files.
8006 if (G.global_argv[1]) {
8007 FILE *input;
8009 * "bash <script>" (which is never interactive (unless -i?))
8010 * sources $BASH_ENV here (without scanning $PATH).
8011 * If called as sh, does the same but with $ENV.
8013 G.global_argc--;
8014 G.global_argv++;
8015 debug_printf("running script '%s'\n", G.global_argv[0]);
8016 input = xfopen_for_read(G.global_argv[0]);
8017 close_on_exec_on(fileno(input));
8018 install_special_sighandlers();
8019 parse_and_run_file(input);
8020 #if ENABLE_FEATURE_CLEAN_UP
8021 fclose(input);
8022 #endif
8023 goto final_return;
8026 /* Up to here, shell was non-interactive. Now it may become one.
8027 * NB: don't forget to (re)run install_special_sighandlers() as needed.
8030 /* A shell is interactive if the '-i' flag was given,
8031 * or if all of the following conditions are met:
8032 * no -c command
8033 * no arguments remaining or the -s flag given
8034 * standard input is a terminal
8035 * standard output is a terminal
8036 * Refer to Posix.2, the description of the 'sh' utility.
8038 #if ENABLE_HUSH_JOB
8039 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
8040 G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
8041 debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
8042 if (G_saved_tty_pgrp < 0)
8043 G_saved_tty_pgrp = 0;
8045 /* try to dup stdin to high fd#, >= 255 */
8046 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8047 if (G_interactive_fd < 0) {
8048 /* try to dup to any fd */
8049 G_interactive_fd = dup(STDIN_FILENO);
8050 if (G_interactive_fd < 0) {
8051 /* give up */
8052 G_interactive_fd = 0;
8053 G_saved_tty_pgrp = 0;
8056 // TODO: track & disallow any attempts of user
8057 // to (inadvertently) close/redirect G_interactive_fd
8059 debug_printf("interactive_fd:%d\n", G_interactive_fd);
8060 if (G_interactive_fd) {
8061 close_on_exec_on(G_interactive_fd);
8063 if (G_saved_tty_pgrp) {
8064 /* If we were run as 'hush &', sleep until we are
8065 * in the foreground (tty pgrp == our pgrp).
8066 * If we get started under a job aware app (like bash),
8067 * make sure we are now in charge so we don't fight over
8068 * who gets the foreground */
8069 while (1) {
8070 pid_t shell_pgrp = getpgrp();
8071 G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
8072 if (G_saved_tty_pgrp == shell_pgrp)
8073 break;
8074 /* send TTIN to ourself (should stop us) */
8075 kill(- shell_pgrp, SIGTTIN);
8079 /* Install more signal handlers */
8080 install_special_sighandlers();
8082 if (G_saved_tty_pgrp) {
8083 /* Set other signals to restore saved_tty_pgrp */
8084 install_fatal_sighandlers();
8085 /* Put ourselves in our own process group
8086 * (bash, too, does this only if ctty is available) */
8087 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
8088 /* Grab control of the terminal */
8089 tcsetpgrp(G_interactive_fd, getpid());
8091 /* -1 is special - makes xfuncs longjmp, not exit
8092 * (we reset die_sleep = 0 whereever we [v]fork) */
8093 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
8095 # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
8097 const char *hp = get_local_var_value("HISTFILE");
8098 if (!hp) {
8099 hp = get_local_var_value("HOME");
8100 if (hp)
8101 hp = concat_path_file(hp, ".hush_history");
8102 } else {
8103 hp = xstrdup(hp);
8105 if (hp) {
8106 G.line_input_state->hist_file = hp;
8107 //set_local_var(xasprintf("HISTFILE=%s", ...));
8109 # if ENABLE_FEATURE_SH_HISTFILESIZE
8110 hp = get_local_var_value("HISTFILESIZE");
8111 G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
8112 # endif
8114 # endif
8115 } else {
8116 install_special_sighandlers();
8118 #elif ENABLE_HUSH_INTERACTIVE
8119 /* No job control compiled in, only prompt/line editing */
8120 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
8121 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
8122 if (G_interactive_fd < 0) {
8123 /* try to dup to any fd */
8124 G_interactive_fd = dup(STDIN_FILENO);
8125 if (G_interactive_fd < 0)
8126 /* give up */
8127 G_interactive_fd = 0;
8130 if (G_interactive_fd) {
8131 close_on_exec_on(G_interactive_fd);
8133 install_special_sighandlers();
8134 #else
8135 /* We have interactiveness code disabled */
8136 install_special_sighandlers();
8137 #endif
8138 /* bash:
8139 * if interactive but not a login shell, sources ~/.bashrc
8140 * (--norc turns this off, --rcfile <file> overrides)
8143 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
8144 /* note: ash and hush share this string */
8145 printf("\n\n%s %s\n"
8146 IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
8147 "\n",
8148 bb_banner,
8149 "hush - the humble shell"
8153 parse_and_run_file(stdin);
8155 final_return:
8156 hush_exit(G.last_exitcode);
8160 #if ENABLE_MSH
8161 int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
8162 int msh_main(int argc, char **argv)
8164 //bb_error_msg("msh is deprecated, please use hush instead");
8165 return hush_main(argc, argv);
8167 #endif
8171 * Built-ins
8173 static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
8175 return 0;
8178 static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
8180 int argc = 0;
8181 while (*argv) {
8182 argc++;
8183 argv++;
8185 return applet_main_func(argc, argv - argc);
8188 static int FAST_FUNC builtin_test(char **argv)
8190 return run_applet_main(argv, test_main);
8193 static int FAST_FUNC builtin_echo(char **argv)
8195 return run_applet_main(argv, echo_main);
8198 #if ENABLE_PRINTF
8199 static int FAST_FUNC builtin_printf(char **argv)
8201 return run_applet_main(argv, printf_main);
8203 #endif
8205 static char **skip_dash_dash(char **argv)
8207 argv++;
8208 if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
8209 argv++;
8210 return argv;
8213 static int FAST_FUNC builtin_eval(char **argv)
8215 int rcode = EXIT_SUCCESS;
8217 argv = skip_dash_dash(argv);
8218 if (*argv) {
8219 char *str = expand_strvec_to_string(argv);
8220 /* bash:
8221 * eval "echo Hi; done" ("done" is syntax error):
8222 * "echo Hi" will not execute too.
8224 parse_and_run_string(str);
8225 free(str);
8226 rcode = G.last_exitcode;
8228 return rcode;
8231 static int FAST_FUNC builtin_cd(char **argv)
8233 const char *newdir;
8235 argv = skip_dash_dash(argv);
8236 newdir = argv[0];
8237 if (newdir == NULL) {
8238 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
8239 * bash says "bash: cd: HOME not set" and does nothing
8240 * (exitcode 1)
8242 const char *home = get_local_var_value("HOME");
8243 newdir = home ? home : "/";
8245 if (chdir(newdir)) {
8246 /* Mimic bash message exactly */
8247 bb_perror_msg("cd: %s", newdir);
8248 return EXIT_FAILURE;
8250 /* Read current dir (get_cwd(1) is inside) and set PWD.
8251 * Note: do not enforce exporting. If PWD was unset or unexported,
8252 * set it again, but do not export. bash does the same.
8254 set_pwd_var(/*exp:*/ 0);
8255 return EXIT_SUCCESS;
8258 static int FAST_FUNC builtin_exec(char **argv)
8260 argv = skip_dash_dash(argv);
8261 if (argv[0] == NULL)
8262 return EXIT_SUCCESS; /* bash does this */
8264 /* Careful: we can end up here after [v]fork. Do not restore
8265 * tty pgrp then, only top-level shell process does that */
8266 if (G_saved_tty_pgrp && getpid() == G.root_pid)
8267 tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
8269 /* TODO: if exec fails, bash does NOT exit! We do.
8270 * We'll need to undo trap cleanup (it's inside execvp_or_die)
8271 * and tcsetpgrp, and this is inherently racy.
8273 execvp_or_die(argv);
8276 static int FAST_FUNC builtin_exit(char **argv)
8278 debug_printf_exec("%s()\n", __func__);
8280 /* interactive bash:
8281 * # trap "echo EEE" EXIT
8282 * # exit
8283 * exit
8284 * There are stopped jobs.
8285 * (if there are _stopped_ jobs, running ones don't count)
8286 * # exit
8287 * exit
8288 # EEE (then bash exits)
8290 * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
8293 /* note: EXIT trap is run by hush_exit */
8294 argv = skip_dash_dash(argv);
8295 if (argv[0] == NULL)
8296 hush_exit(G.last_exitcode);
8297 /* mimic bash: exit 123abc == exit 255 + error msg */
8298 xfunc_error_retval = 255;
8299 /* bash: exit -2 == exit 254, no error msg */
8300 hush_exit(xatoi(argv[0]) & 0xff);
8303 static void print_escaped(const char *s)
8305 if (*s == '\'')
8306 goto squote;
8307 do {
8308 const char *p = strchrnul(s, '\'');
8309 /* print 'xxxx', possibly just '' */
8310 printf("'%.*s'", (int)(p - s), s);
8311 if (*p == '\0')
8312 break;
8313 s = p;
8314 squote:
8315 /* s points to '; print "'''...'''" */
8316 putchar('"');
8317 do putchar('\''); while (*++s == '\'');
8318 putchar('"');
8319 } while (*s);
8322 #if !ENABLE_HUSH_LOCAL
8323 #define helper_export_local(argv, exp, lvl) \
8324 helper_export_local(argv, exp)
8325 #endif
8326 static void helper_export_local(char **argv, int exp, int lvl)
8328 do {
8329 char *name = *argv;
8330 char *name_end = strchrnul(name, '=');
8332 /* So far we do not check that name is valid (TODO?) */
8334 if (*name_end == '\0') {
8335 struct variable *var, **vpp;
8337 vpp = get_ptr_to_local_var(name, name_end - name);
8338 var = vpp ? *vpp : NULL;
8340 if (exp == -1) { /* unexporting? */
8341 /* export -n NAME (without =VALUE) */
8342 if (var) {
8343 var->flg_export = 0;
8344 debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
8345 unsetenv(name);
8346 } /* else: export -n NOT_EXISTING_VAR: no-op */
8347 continue;
8349 if (exp == 1) { /* exporting? */
8350 /* export NAME (without =VALUE) */
8351 if (var) {
8352 var->flg_export = 1;
8353 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
8354 putenv(var->varstr);
8355 continue;
8358 /* Exporting non-existing variable.
8359 * bash does not put it in environment,
8360 * but remembers that it is exported,
8361 * and does put it in env when it is set later.
8362 * We just set it to "" and export. */
8363 /* Or, it's "local NAME" (without =VALUE).
8364 * bash sets the value to "". */
8365 name = xasprintf("%s=", name);
8366 } else {
8367 /* (Un)exporting/making local NAME=VALUE */
8368 name = xstrdup(name);
8370 set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
8371 } while (*++argv);
8374 static int FAST_FUNC builtin_export(char **argv)
8376 unsigned opt_unexport;
8378 #if ENABLE_HUSH_EXPORT_N
8379 /* "!": do not abort on errors */
8380 opt_unexport = getopt32(argv, "!n");
8381 if (opt_unexport == (uint32_t)-1)
8382 return EXIT_FAILURE;
8383 argv += optind;
8384 #else
8385 opt_unexport = 0;
8386 argv++;
8387 #endif
8389 if (argv[0] == NULL) {
8390 char **e = environ;
8391 if (e) {
8392 while (*e) {
8393 #if 0
8394 puts(*e++);
8395 #else
8396 /* ash emits: export VAR='VAL'
8397 * bash: declare -x VAR="VAL"
8398 * we follow ash example */
8399 const char *s = *e++;
8400 const char *p = strchr(s, '=');
8402 if (!p) /* wtf? take next variable */
8403 continue;
8404 /* export var= */
8405 printf("export %.*s", (int)(p - s) + 1, s);
8406 print_escaped(p + 1);
8407 putchar('\n');
8408 #endif
8410 /*fflush_all(); - done after each builtin anyway */
8412 return EXIT_SUCCESS;
8415 helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
8417 return EXIT_SUCCESS;
8420 #if ENABLE_HUSH_LOCAL
8421 static int FAST_FUNC builtin_local(char **argv)
8423 if (G.func_nest_level == 0) {
8424 bb_error_msg("%s: not in a function", argv[0]);
8425 return EXIT_FAILURE; /* bash compat */
8427 helper_export_local(argv, 0, G.func_nest_level);
8428 return EXIT_SUCCESS;
8430 #endif
8432 static int FAST_FUNC builtin_trap(char **argv)
8434 int sig;
8435 char *new_cmd;
8437 if (!G.traps)
8438 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
8440 argv++;
8441 if (!*argv) {
8442 int i;
8443 /* No args: print all trapped */
8444 for (i = 0; i < NSIG; ++i) {
8445 if (G.traps[i]) {
8446 printf("trap -- ");
8447 print_escaped(G.traps[i]);
8448 /* note: bash adds "SIG", but only if invoked
8449 * as "bash". If called as "sh", or if set -o posix,
8450 * then it prints short signal names.
8451 * We are printing short names: */
8452 printf(" %s\n", get_signame(i));
8455 /*fflush_all(); - done after each builtin anyway */
8456 return EXIT_SUCCESS;
8459 new_cmd = NULL;
8460 /* If first arg is a number: reset all specified signals */
8461 sig = bb_strtou(*argv, NULL, 10);
8462 if (errno == 0) {
8463 int ret;
8464 process_sig_list:
8465 ret = EXIT_SUCCESS;
8466 while (*argv) {
8467 sighandler_t handler;
8469 sig = get_signum(*argv++);
8470 if (sig < 0 || sig >= NSIG) {
8471 ret = EXIT_FAILURE;
8472 /* Mimic bash message exactly */
8473 bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
8474 continue;
8477 free(G.traps[sig]);
8478 G.traps[sig] = xstrdup(new_cmd);
8480 debug_printf("trap: setting SIG%s (%i) to '%s'\n",
8481 get_signame(sig), sig, G.traps[sig]);
8483 /* There is no signal for 0 (EXIT) */
8484 if (sig == 0)
8485 continue;
8487 if (new_cmd)
8488 handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
8489 else
8490 /* We are removing trap handler */
8491 handler = pick_sighandler(sig);
8492 install_sighandler(sig, handler);
8494 return ret;
8497 if (!argv[1]) { /* no second arg */
8498 bb_error_msg("trap: invalid arguments");
8499 return EXIT_FAILURE;
8502 /* First arg is "-": reset all specified to default */
8503 /* First arg is "--": skip it, the rest is "handler SIGs..." */
8504 /* Everything else: set arg as signal handler
8505 * (includes "" case, which ignores signal) */
8506 if (argv[0][0] == '-') {
8507 if (argv[0][1] == '\0') { /* "-" */
8508 /* new_cmd remains NULL: "reset these sigs" */
8509 goto reset_traps;
8511 if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
8512 argv++;
8514 /* else: "-something", no special meaning */
8516 new_cmd = *argv;
8517 reset_traps:
8518 argv++;
8519 goto process_sig_list;
8522 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
8523 static int FAST_FUNC builtin_type(char **argv)
8525 int ret = EXIT_SUCCESS;
8527 while (*++argv) {
8528 const char *type;
8529 char *path = NULL;
8531 if (0) {} /* make conditional compile easier below */
8532 /*else if (find_alias(*argv))
8533 type = "an alias";*/
8534 #if ENABLE_HUSH_FUNCTIONS
8535 else if (find_function(*argv))
8536 type = "a function";
8537 #endif
8538 else if (find_builtin(*argv))
8539 type = "a shell builtin";
8540 else if ((path = find_in_path(*argv)) != NULL)
8541 type = path;
8542 else {
8543 bb_error_msg("type: %s: not found", *argv);
8544 ret = EXIT_FAILURE;
8545 continue;
8548 printf("%s is %s\n", *argv, type);
8549 free(path);
8552 return ret;
8555 #if ENABLE_HUSH_JOB
8556 /* built-in 'fg' and 'bg' handler */
8557 static int FAST_FUNC builtin_fg_bg(char **argv)
8559 int i, jobnum;
8560 struct pipe *pi;
8562 if (!G_interactive_fd)
8563 return EXIT_FAILURE;
8565 /* If they gave us no args, assume they want the last backgrounded task */
8566 if (!argv[1]) {
8567 for (pi = G.job_list; pi; pi = pi->next) {
8568 if (pi->jobid == G.last_jobid) {
8569 goto found;
8572 bb_error_msg("%s: no current job", argv[0]);
8573 return EXIT_FAILURE;
8575 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
8576 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
8577 return EXIT_FAILURE;
8579 for (pi = G.job_list; pi; pi = pi->next) {
8580 if (pi->jobid == jobnum) {
8581 goto found;
8584 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
8585 return EXIT_FAILURE;
8586 found:
8587 /* TODO: bash prints a string representation
8588 * of job being foregrounded (like "sleep 1 | cat") */
8589 if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
8590 /* Put the job into the foreground. */
8591 tcsetpgrp(G_interactive_fd, pi->pgrp);
8594 /* Restart the processes in the job */
8595 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
8596 for (i = 0; i < pi->num_cmds; i++) {
8597 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
8599 pi->stopped_cmds = 0;
8601 i = kill(- pi->pgrp, SIGCONT);
8602 if (i < 0) {
8603 if (errno == ESRCH) {
8604 delete_finished_bg_job(pi);
8605 return EXIT_SUCCESS;
8607 bb_perror_msg("kill (SIGCONT)");
8610 if (argv[0][0] == 'f') {
8611 remove_bg_job(pi);
8612 return checkjobs_and_fg_shell(pi);
8614 return EXIT_SUCCESS;
8616 #endif
8618 #if ENABLE_HUSH_HELP
8619 static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
8621 const struct built_in_command *x;
8623 printf(
8624 "Built-in commands:\n"
8625 "------------------\n");
8626 for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
8627 if (x->b_descr)
8628 printf("%-10s%s\n", x->b_cmd, x->b_descr);
8630 bb_putchar('\n');
8631 return EXIT_SUCCESS;
8633 #endif
8635 #if ENABLE_HUSH_JOB
8636 static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
8638 struct pipe *job;
8639 const char *status_string;
8641 for (job = G.job_list; job; job = job->next) {
8642 if (job->alive_cmds == job->stopped_cmds)
8643 status_string = "Stopped";
8644 else
8645 status_string = "Running";
8647 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
8649 return EXIT_SUCCESS;
8651 #endif
8653 #if HUSH_DEBUG
8654 static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
8656 void *p;
8657 unsigned long l;
8659 # ifdef M_TRIM_THRESHOLD
8660 /* Optional. Reduces probability of false positives */
8661 malloc_trim(0);
8662 # endif
8663 /* Crude attempt to find where "free memory" starts,
8664 * sans fragmentation. */
8665 p = malloc(240);
8666 l = (unsigned long)p;
8667 free(p);
8668 p = malloc(3400);
8669 if (l < (unsigned long)p) l = (unsigned long)p;
8670 free(p);
8672 if (!G.memleak_value)
8673 G.memleak_value = l;
8675 l -= G.memleak_value;
8676 if ((long)l < 0)
8677 l = 0;
8678 l /= 1024;
8679 if (l > 127)
8680 l = 127;
8682 /* Exitcode is "how many kilobytes we leaked since 1st call" */
8683 return l;
8685 #endif
8687 static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
8689 puts(get_cwd(0));
8690 return EXIT_SUCCESS;
8693 /* Interruptibility of read builtin in bash
8694 * (tested on bash-4.2.8 by sending signals (not by ^C)):
8696 * Empty trap makes read ignore corresponding signal, for any signal.
8698 * SIGINT:
8699 * - terminates non-interactive shell;
8700 * - interrupts read in interactive shell;
8701 * if it has non-empty trap:
8702 * - executes trap and returns to command prompt in interactive shell;
8703 * - executes trap and returns to read in non-interactive shell;
8704 * SIGTERM:
8705 * - is ignored (does not interrupt) read in interactive shell;
8706 * - terminates non-interactive shell;
8707 * if it has non-empty trap:
8708 * - executes trap and returns to read;
8709 * SIGHUP:
8710 * - terminates shell (regardless of interactivity);
8711 * if it has non-empty trap:
8712 * - executes trap and returns to read;
8714 static int FAST_FUNC builtin_read(char **argv)
8716 const char *r;
8717 char *opt_n = NULL;
8718 char *opt_p = NULL;
8719 char *opt_t = NULL;
8720 char *opt_u = NULL;
8721 const char *ifs;
8722 int read_flags;
8724 /* "!": do not abort on errors.
8725 * Option string must start with "sr" to match BUILTIN_READ_xxx
8727 read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
8728 if (read_flags == (uint32_t)-1)
8729 return EXIT_FAILURE;
8730 argv += optind;
8731 ifs = get_local_var_value("IFS"); /* can be NULL */
8733 again:
8734 r = shell_builtin_read(set_local_var_from_halves,
8735 argv,
8736 ifs,
8737 read_flags,
8738 opt_n,
8739 opt_p,
8740 opt_t,
8741 opt_u
8744 if ((uintptr_t)r == 1 && errno == EINTR) {
8745 unsigned sig = check_and_run_traps();
8746 if (sig && sig != SIGINT)
8747 goto again;
8750 if ((uintptr_t)r > 1) {
8751 bb_error_msg("%s", r);
8752 r = (char*)(uintptr_t)1;
8755 return (uintptr_t)r;
8758 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
8759 * built-in 'set' handler
8760 * SUSv3 says:
8761 * set [-abCefhmnuvx] [-o option] [argument...]
8762 * set [+abCefhmnuvx] [+o option] [argument...]
8763 * set -- [argument...]
8764 * set -o
8765 * set +o
8766 * Implementations shall support the options in both their hyphen and
8767 * plus-sign forms. These options can also be specified as options to sh.
8768 * Examples:
8769 * Write out all variables and their values: set
8770 * Set $1, $2, and $3 and set "$#" to 3: set c a b
8771 * Turn on the -x and -v options: set -xv
8772 * Unset all positional parameters: set --
8773 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
8774 * Set the positional parameters to the expansion of x, even if x expands
8775 * with a leading '-' or '+': set -- $x
8777 * So far, we only support "set -- [argument...]" and some of the short names.
8779 static int FAST_FUNC builtin_set(char **argv)
8781 int n;
8782 char **pp, **g_argv;
8783 char *arg = *++argv;
8785 if (arg == NULL) {
8786 struct variable *e;
8787 for (e = G.top_var; e; e = e->next)
8788 puts(e->varstr);
8789 return EXIT_SUCCESS;
8792 do {
8793 if (strcmp(arg, "--") == 0) {
8794 ++argv;
8795 goto set_argv;
8797 if (arg[0] != '+' && arg[0] != '-')
8798 break;
8799 for (n = 1; arg[n]; ++n) {
8800 if (set_mode((arg[0] == '-'), arg[n], argv[1]))
8801 goto error;
8802 if (arg[n] == 'o' && argv[1])
8803 argv++;
8805 } while ((arg = *++argv) != NULL);
8806 /* Now argv[0] is 1st argument */
8808 if (arg == NULL)
8809 return EXIT_SUCCESS;
8810 set_argv:
8812 /* NB: G.global_argv[0] ($0) is never freed/changed */
8813 g_argv = G.global_argv;
8814 if (G.global_args_malloced) {
8815 pp = g_argv;
8816 while (*++pp)
8817 free(*pp);
8818 g_argv[1] = NULL;
8819 } else {
8820 G.global_args_malloced = 1;
8821 pp = xzalloc(sizeof(pp[0]) * 2);
8822 pp[0] = g_argv[0]; /* retain $0 */
8823 g_argv = pp;
8825 /* This realloc's G.global_argv */
8826 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
8828 n = 1;
8829 while (*++pp)
8830 n++;
8831 G.global_argc = n;
8833 return EXIT_SUCCESS;
8835 /* Nothing known, so abort */
8836 error:
8837 bb_error_msg("set: %s: invalid option", arg);
8838 return EXIT_FAILURE;
8841 static int FAST_FUNC builtin_shift(char **argv)
8843 int n = 1;
8844 argv = skip_dash_dash(argv);
8845 if (argv[0]) {
8846 n = atoi(argv[0]);
8848 if (n >= 0 && n < G.global_argc) {
8849 if (G.global_args_malloced) {
8850 int m = 1;
8851 while (m <= n)
8852 free(G.global_argv[m++]);
8854 G.global_argc -= n;
8855 memmove(&G.global_argv[1], &G.global_argv[n+1],
8856 G.global_argc * sizeof(G.global_argv[0]));
8857 return EXIT_SUCCESS;
8859 return EXIT_FAILURE;
8862 static int FAST_FUNC builtin_source(char **argv)
8864 char *arg_path, *filename;
8865 FILE *input;
8866 save_arg_t sv;
8867 #if ENABLE_HUSH_FUNCTIONS
8868 smallint sv_flg;
8869 #endif
8871 argv = skip_dash_dash(argv);
8872 filename = argv[0];
8873 if (!filename) {
8874 /* bash says: "bash: .: filename argument required" */
8875 return 2; /* bash compat */
8877 arg_path = NULL;
8878 if (!strchr(filename, '/')) {
8879 arg_path = find_in_path(filename);
8880 if (arg_path)
8881 filename = arg_path;
8883 input = fopen_or_warn(filename, "r");
8884 free(arg_path);
8885 if (!input) {
8886 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
8887 return EXIT_FAILURE;
8889 close_on_exec_on(fileno(input));
8891 #if ENABLE_HUSH_FUNCTIONS
8892 sv_flg = G.flag_return_in_progress;
8893 /* "we are inside sourced file, ok to use return" */
8894 G.flag_return_in_progress = -1;
8895 #endif
8896 save_and_replace_G_args(&sv, argv);
8898 parse_and_run_file(input);
8899 fclose(input);
8901 restore_G_args(&sv, argv);
8902 #if ENABLE_HUSH_FUNCTIONS
8903 G.flag_return_in_progress = sv_flg;
8904 #endif
8906 return G.last_exitcode;
8909 static int FAST_FUNC builtin_umask(char **argv)
8911 int rc;
8912 mode_t mask;
8914 mask = umask(0);
8915 argv = skip_dash_dash(argv);
8916 if (argv[0]) {
8917 mode_t old_mask = mask;
8919 mask ^= 0777;
8920 rc = bb_parse_mode(argv[0], &mask);
8921 mask ^= 0777;
8922 if (rc == 0) {
8923 mask = old_mask;
8924 /* bash messages:
8925 * bash: umask: 'q': invalid symbolic mode operator
8926 * bash: umask: 999: octal number out of range
8928 bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
8930 } else {
8931 rc = 1;
8932 /* Mimic bash */
8933 printf("%04o\n", (unsigned) mask);
8934 /* fall through and restore mask which we set to 0 */
8936 umask(mask);
8938 return !rc; /* rc != 0 - success */
8941 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
8942 static int FAST_FUNC builtin_unset(char **argv)
8944 int ret;
8945 unsigned opts;
8947 /* "!": do not abort on errors */
8948 /* "+": stop at 1st non-option */
8949 opts = getopt32(argv, "!+vf");
8950 if (opts == (unsigned)-1)
8951 return EXIT_FAILURE;
8952 if (opts == 3) {
8953 bb_error_msg("unset: -v and -f are exclusive");
8954 return EXIT_FAILURE;
8956 argv += optind;
8958 ret = EXIT_SUCCESS;
8959 while (*argv) {
8960 if (!(opts & 2)) { /* not -f */
8961 if (unset_local_var(*argv)) {
8962 /* unset <nonexistent_var> doesn't fail.
8963 * Error is when one tries to unset RO var.
8964 * Message was printed by unset_local_var. */
8965 ret = EXIT_FAILURE;
8968 #if ENABLE_HUSH_FUNCTIONS
8969 else {
8970 unset_func(*argv);
8972 #endif
8973 argv++;
8975 return ret;
8978 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
8979 static int FAST_FUNC builtin_wait(char **argv)
8981 int ret = EXIT_SUCCESS;
8982 int status;
8984 argv = skip_dash_dash(argv);
8985 if (argv[0] == NULL) {
8986 /* Don't care about wait results */
8987 /* Note 1: must wait until there are no more children */
8988 /* Note 2: must be interruptible */
8989 /* Examples:
8990 * $ sleep 3 & sleep 6 & wait
8991 * [1] 30934 sleep 3
8992 * [2] 30935 sleep 6
8993 * [1] Done sleep 3
8994 * [2] Done sleep 6
8995 * $ sleep 3 & sleep 6 & wait
8996 * [1] 30936 sleep 3
8997 * [2] 30937 sleep 6
8998 * [1] Done sleep 3
8999 * ^C <-- after ~4 sec from keyboard
9002 while (1) {
9003 int sig;
9004 sigset_t oldset, allsigs;
9006 /* waitpid is not interruptible by SA_RESTARTed
9007 * signals which we use. Thus, this ugly dance:
9010 /* Make sure possible SIGCHLD is stored in kernel's
9011 * pending signal mask before we call waitpid.
9012 * Or else we may race with SIGCHLD, lose it,
9013 * and get stuck in sigwaitinfo...
9015 sigfillset(&allsigs);
9016 sigprocmask(SIG_SETMASK, &allsigs, &oldset);
9018 if (!sigisemptyset(&G.pending_set)) {
9019 /* Crap! we raced with some signal! */
9020 // sig = 0;
9021 goto restore;
9024 checkjobs(NULL); /* waitpid(WNOHANG) inside */
9025 if (errno == ECHILD) {
9026 sigprocmask(SIG_SETMASK, &oldset, NULL);
9027 break;
9030 /* Wait for SIGCHLD or any other signal */
9031 //sig = sigwaitinfo(&allsigs, NULL);
9032 /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
9033 /* Note: sigsuspend invokes signal handler */
9034 sigsuspend(&oldset);
9035 restore:
9036 sigprocmask(SIG_SETMASK, &oldset, NULL);
9038 /* So, did we get a signal? */
9039 //if (sig > 0)
9040 // raise(sig); /* run handler */
9041 sig = check_and_run_traps();
9042 if (sig /*&& sig != SIGCHLD - always true */) {
9043 /* see note 2 */
9044 ret = 128 + sig;
9045 break;
9047 /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
9049 return ret;
9052 /* This is probably buggy wrt interruptible-ness */
9053 while (*argv) {
9054 pid_t pid = bb_strtou(*argv, NULL, 10);
9055 if (errno) {
9056 /* mimic bash message */
9057 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
9058 return EXIT_FAILURE;
9060 if (waitpid(pid, &status, 0) == pid) {
9061 if (WIFSIGNALED(status))
9062 ret = 128 + WTERMSIG(status);
9063 else if (WIFEXITED(status))
9064 ret = WEXITSTATUS(status);
9065 else /* wtf? */
9066 ret = EXIT_FAILURE;
9067 } else {
9068 bb_perror_msg("wait %s", *argv);
9069 ret = 127;
9071 argv++;
9074 return ret;
9077 #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
9078 static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
9080 if (argv[1]) {
9081 def = bb_strtou(argv[1], NULL, 10);
9082 if (errno || def < def_min || argv[2]) {
9083 bb_error_msg("%s: bad arguments", argv[0]);
9084 def = UINT_MAX;
9087 return def;
9089 #endif
9091 #if ENABLE_HUSH_LOOPS
9092 static int FAST_FUNC builtin_break(char **argv)
9094 unsigned depth;
9095 if (G.depth_of_loop == 0) {
9096 bb_error_msg("%s: only meaningful in a loop", argv[0]);
9097 return EXIT_SUCCESS; /* bash compat */
9099 G.flag_break_continue++; /* BC_BREAK = 1 */
9101 G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
9102 if (depth == UINT_MAX)
9103 G.flag_break_continue = BC_BREAK;
9104 if (G.depth_of_loop < depth)
9105 G.depth_break_continue = G.depth_of_loop;
9107 return EXIT_SUCCESS;
9110 static int FAST_FUNC builtin_continue(char **argv)
9112 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
9113 return builtin_break(argv);
9115 #endif
9117 #if ENABLE_HUSH_FUNCTIONS
9118 static int FAST_FUNC builtin_return(char **argv)
9120 int rc;
9122 if (G.flag_return_in_progress != -1) {
9123 bb_error_msg("%s: not in a function or sourced script", argv[0]);
9124 return EXIT_FAILURE; /* bash compat */
9127 G.flag_return_in_progress = 1;
9129 /* bash:
9130 * out of range: wraps around at 256, does not error out
9131 * non-numeric param:
9132 * f() { false; return qwe; }; f; echo $?
9133 * bash: return: qwe: numeric argument required <== we do this
9134 * 255 <== we also do this
9136 rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
9137 return rc;
9139 #endif