1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * This code is derived from software contributed to Berkeley by
8 * Original BSD copyright notice is retained at the end of this file.
10 * Copyright (c) 1989, 1991, 1993, 1994
11 * The Regents of the University of California. All rights reserved.
13 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
14 * was re-ported from NetBSD and debianized.
16 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
19 //config: bool "ash (78 kb)"
21 //config: depends on !NOMMU
23 //config: The most complete and most pedantically correct shell included with
24 //config: busybox. This shell is actually a derivative of the Debian 'dash'
25 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
26 //config: (written by Kenneth Almquist) from NetBSD.
28 //config:# ash options
29 //config:# note: Don't remove !NOMMU part in the next line; it would break
30 //config:# menuconfig's indenting.
31 //config:if !NOMMU && (ASH || SH_IS_ASH || BASH_IS_ASH)
33 //config:config ASH_OPTIMIZE_FOR_SIZE
34 //config: bool "Optimize for size instead of speed"
36 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
38 //config:config ASH_INTERNAL_GLOB
39 //config: bool "Use internal glob() implementation"
40 //config: default y # Y is bigger, but because of uclibc glob() bug, let Y be default for now
41 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
43 //config: Do not use glob() function from libc, use internal implementation.
44 //config: Use this if you are getting "glob.h: No such file or directory"
45 //config: or similar build errors.
46 //config: Note that as of now (2017-01), uclibc and musl glob() both have bugs
47 //config: which would break ash if you select N here.
49 //config:config ASH_BASH_COMPAT
50 //config: bool "bash-compatible extensions"
52 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
54 //config:config ASH_BASH_SOURCE_CURDIR
55 //config: bool "'source' and '.' builtins search current directory after $PATH"
56 //config: default n # do not encourage non-standard behavior
57 //config: depends on ASH_BASH_COMPAT
59 //config: This is not compliant with standards. Avoid if possible.
61 //config:config ASH_BASH_NOT_FOUND_HOOK
62 //config: bool "command_not_found_handle hook support"
64 //config: depends on ASH_BASH_COMPAT
66 //config: Enable support for the 'command_not_found_handle' hook function,
67 //config: from GNU bash, which allows for alternative command not found
70 //config:config ASH_JOB_CONTROL
71 //config: bool "Job control"
73 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
75 //config:config ASH_ALIAS
76 //config: bool "Alias support"
78 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
80 //config:config ASH_RANDOM_SUPPORT
81 //config: bool "Pseudorandom generator and $RANDOM variable"
83 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
85 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
86 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
87 //config: You can reset the generator by using a specified start value.
88 //config: After "unset RANDOM" the generator will switch off and this
89 //config: variable will no longer have special treatment.
91 //config:config ASH_EXPAND_PRMT
92 //config: bool "Expand prompt string"
94 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
96 //config: $PS# may contain volatile content, such as backquote commands.
97 //config: This option recreates the prompt string from the environment
98 //config: variable each time it is displayed.
100 //config:config ASH_IDLE_TIMEOUT
101 //config: bool "Idle timeout variable $TMOUT"
103 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
105 //config: Enable bash-like auto-logout after $TMOUT seconds of idle time.
107 //config:config ASH_MAIL
108 //config: bool "Check for new mail in interactive shell"
110 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
112 //config: Enable "check for new mail" function:
113 //config: if set, $MAIL file and $MAILPATH list of files
114 //config: are checked for mtime changes, and "you have mail"
115 //config: message is printed if change is detected.
117 //config:config ASH_ECHO
118 //config: bool "echo builtin"
120 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
122 //config:config ASH_PRINTF
123 //config: bool "printf builtin"
125 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
127 //config:config ASH_TEST
128 //config: bool "test builtin"
130 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
132 //config:config ASH_HELP
133 //config: bool "help builtin"
135 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
137 //config:config ASH_GETOPTS
138 //config: bool "getopts builtin"
140 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
142 //config:config ASH_CMDCMD
143 //config: bool "command builtin"
145 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
147 //config: Enable support for the 'command' builtin, which allows
148 //config: you to run the specified command or builtin,
149 //config: even when there is a function with the same name.
151 //config:endif # ash options
153 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
154 // APPLET_ODDNAME:name main location suid_type help
155 //applet:IF_SH_IS_ASH( APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
156 //applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
158 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
159 //kbuild:lib-$(CONFIG_SH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
160 //kbuild:lib-$(CONFIG_BASH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
161 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
164 * DEBUG=1 to compile in debugging ('set -o debug' turns on)
165 * DEBUG=2 to compile in and turn on debugging.
166 * When debugging is on ("set -o debug" was executed, or DEBUG=2),
167 * debugging info is written to ./trace, quit signal generates core dump.
170 /* Tweak debug output verbosity here */
174 #define DEBUG_INTONOFF 0
178 #define JOBS ENABLE_ASH_JOB_CONTROL
181 #include <sys/times.h>
182 #include <sys/utsname.h> /* for setting $HOSTNAME */
183 #include "busybox.h" /* for applet_names */
184 #if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS
185 # include "embedded_scripts.h"
187 # define NUM_SCRIPTS 0
190 /* So far, all bash compat is controlled by one config option */
191 /* Separate defines document which part of code implements what */
192 /* function keyword */
193 #define BASH_FUNCTION ENABLE_ASH_BASH_COMPAT
194 #define IF_BASH_FUNCTION IF_ASH_BASH_COMPAT
196 #define BASH_REDIR_OUTPUT ENABLE_ASH_BASH_COMPAT
197 #define IF_BASH_REDIR_OUTPUT IF_ASH_BASH_COMPAT
199 #define BASH_DOLLAR_SQUOTE ENABLE_ASH_BASH_COMPAT
200 #define IF_BASH_DOLLAR_SQUOTE IF_ASH_BASH_COMPAT
201 #define BASH_PATTERN_SUBST ENABLE_ASH_BASH_COMPAT
202 #define IF_BASH_PATTERN_SUBST IF_ASH_BASH_COMPAT
203 #define BASH_SUBSTR ENABLE_ASH_BASH_COMPAT
204 #define IF_BASH_SUBSTR IF_ASH_BASH_COMPAT
205 /* BASH_TEST2: [[ EXPR ]]
206 * Status of [[ support:
207 * We replace && and || with -a and -o
209 * singleword+noglob expansion:
210 * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
211 * [[ /bin/n* ]]; echo 0:$?
212 * -a/-o are not AND/OR ops! (they are just strings)
213 * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
214 * = is glob match operator, not equality operator: STR = GLOB
215 * (in GLOB, quoting is significant on char-by-char basis: a*cd"*")
217 * add =~ regex match operator: STR =~ REGEX
219 #define BASH_TEST2 (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)
220 #define BASH_SOURCE ENABLE_ASH_BASH_COMPAT
221 #define BASH_PIPEFAIL ENABLE_ASH_BASH_COMPAT
222 #define BASH_HOSTNAME_VAR ENABLE_ASH_BASH_COMPAT
223 #define BASH_EPOCH_VARS ENABLE_ASH_BASH_COMPAT
224 #define BASH_SHLVL_VAR ENABLE_ASH_BASH_COMPAT
225 #define BASH_XTRACEFD ENABLE_ASH_BASH_COMPAT
226 #define BASH_READ_D ENABLE_ASH_BASH_COMPAT
227 #define IF_BASH_READ_D IF_ASH_BASH_COMPAT
228 #define BASH_WAIT_N ENABLE_ASH_BASH_COMPAT
230 #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
231 /* Bionic at least up to version 24 has no glob() */
232 # undef ENABLE_ASH_INTERNAL_GLOB
233 # define ENABLE_ASH_INTERNAL_GLOB 1
236 #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
237 # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
238 # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
239 # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
240 # error glob() should unbackslash them and match. uClibc does not unbackslash,
241 # error fails to match dirname, subsequently not expanding <pattern> in it.
243 // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
244 // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
247 #if !ENABLE_ASH_INTERNAL_GLOB
252 #include "shell_common.h"
253 #if ENABLE_FEATURE_SH_MATH
256 typedef long arith_t;
257 # define ARITH_FMT "%ld"
259 #if ENABLE_ASH_RANDOM_SUPPORT
262 # define CLEAR_RANDOM_T(rnd) ((void)0)
265 #include "NUM_APPLETS.h"
267 /* STANDALONE does not make sense, and won't compile */
268 # undef CONFIG_FEATURE_SH_STANDALONE
269 # undef ENABLE_FEATURE_SH_STANDALONE
270 # undef IF_FEATURE_SH_STANDALONE
271 # undef IF_NOT_FEATURE_SH_STANDALONE
272 # define ENABLE_FEATURE_SH_STANDALONE 0
273 # define IF_FEATURE_SH_STANDALONE(...)
274 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
277 #ifndef F_DUPFD_CLOEXEC
278 # define F_DUPFD_CLOEXEC F_DUPFD
284 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
288 # error "Do not even bother, ash will not run on NOMMU machine"
291 /* We use a trick to have more optimized code (fewer pointer reloads):
292 * ash.c: extern struct globals *const ash_ptr_to_globals;
293 * ash_ptr_hack.c: struct globals *ash_ptr_to_globals;
294 * This way, compiler in ash.c knows the pointer can not change.
296 * However, this may break on weird arches or toolchains. In this case,
297 * set "-DBB_GLOBAL_CONST=''" in CONFIG_EXTRA_CFLAGS to disable
300 #ifndef BB_GLOBAL_CONST
301 # define BB_GLOBAL_CONST const
305 /* ============ Hash table sizes. Configurable. */
309 #define CMDTABLESIZE 31 /* should be prime */
312 /* ============ Shell options */
314 static const char *const optletters_optnames[] = {
318 /* The below allowed this invocation:
319 * ash -c 'set -i; echo $-; sleep 5; echo $-'
320 * to be ^C-ed and get to interactive ash prompt.
321 * bash does not support such "set -i".
322 * In our code, this is denoted by empty long name:
327 /* Ditto: bash has no "set -s" */
345 //bash 4.4.23 also has these opts (with these defaults):
353 //interactive-comments on
360 #define optletters(n) optletters_optnames[n][0]
361 #define optnames(n) (optletters_optnames[n] + 1)
363 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
366 /* ============ Misc data */
368 #define msg_illnum "Illegal number: %s"
371 * We enclose jmp_buf in a structure so that we can declare pointers to
372 * jump locations. The global variable handler contains the location to
373 * jump to when an exception occurs, and the global variable exception_type
374 * contains a code identifying the exception. To implement nested
375 * exception handlers, the user should save the value of handler on entry
376 * to an inner scope, set handler to point to a jmploc structure for the
377 * inner scope, and restore handler on exit from the scope.
383 struct globals_misc {
384 uint8_t exitstatus; /* exit status of last command */
385 uint8_t back_exitstatus;/* exit status of backquoted command */
386 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
387 int savestatus; /* exit status of last command outside traps */
388 int rootpid; /* pid of main shell */
389 /* shell level: 0 for the main shell, 1 for its children, and so on */
391 #define rootshell (!shlvl)
394 char *minusc; /* argument to -c option */
396 char *curdir; // = nullstr; /* current working directory */
397 char *physdir; // = nullstr; /* physical working directory */
399 char *arg0; /* value of $0 */
401 struct jmploc *exception_handler;
403 volatile int suppress_int; /* counter */
404 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
405 volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
406 volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
407 smallint exception_type; /* kind of exception (0..5) */
409 #define EXINT 0 /* SIGINT received */
410 #define EXERROR 1 /* a generic error */
411 #define EXEXIT 4 /* exit the shell */
413 char nullstr[1]; /* zero length string */
416 #define eflag optlist[0]
417 #define fflag optlist[1]
418 #define Iflag optlist[2]
419 #define iflag optlist[3]
420 #define mflag optlist[4]
421 #define nflag optlist[5]
422 #define sflag optlist[6]
423 #define cflag optlist[7]
424 #define xflag optlist[8]
425 #define vflag optlist[9]
426 #define Cflag optlist[10]
427 #define aflag optlist[11]
428 #define bflag optlist[12]
429 #define uflag optlist[13]
430 #define viflag optlist[14]
432 # define pipefail optlist[15]
437 # define nolog optlist[15 + BASH_PIPEFAIL]
438 # define debug optlist[16 + BASH_PIPEFAIL]
441 /* trap handler commands */
443 * Sigmode records the current value of the signal handlers for the various
444 * modes. A value of zero means that the current handler is not known.
445 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
447 char sigmode[NSIG - 1];
448 #define S_DFL 1 /* default signal handling (SIG_DFL) */
449 #define S_CATCH 2 /* signal is caught */
450 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
451 #define S_HARD_IGN 4 /* signal is ignored permanently (it was SIG_IGN on entry to shell) */
453 /* indicates specified signal received */
454 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
455 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
457 char **trap_ptr; /* used only by "trap hack" */
459 /* Rarely referenced stuff */
460 #if ENABLE_ASH_RANDOM_SUPPORT
463 pid_t backgndpid; /* pid of last background process */
465 extern struct globals_misc *BB_GLOBAL_CONST ash_ptr_to_globals_misc;
466 #define G_misc (*ash_ptr_to_globals_misc)
467 #define exitstatus (G_misc.exitstatus )
468 #define back_exitstatus (G_misc.back_exitstatus )
469 #define job_warning (G_misc.job_warning)
470 #define savestatus (G_misc.savestatus )
471 #define rootpid (G_misc.rootpid )
472 #define shlvl (G_misc.shlvl )
473 #define errlinno (G_misc.errlinno )
474 #define minusc (G_misc.minusc )
475 #define curdir (G_misc.curdir )
476 #define physdir (G_misc.physdir )
477 #define arg0 (G_misc.arg0 )
478 #define exception_handler (G_misc.exception_handler)
479 #define exception_type (G_misc.exception_type )
480 #define suppress_int (G_misc.suppress_int )
481 #define pending_int (G_misc.pending_int )
482 #define got_sigchld (G_misc.got_sigchld )
483 #define pending_sig (G_misc.pending_sig )
484 #define nullstr (G_misc.nullstr )
485 #define optlist (G_misc.optlist )
486 #define sigmode (G_misc.sigmode )
487 #define gotsig (G_misc.gotsig )
488 #define may_have_traps (G_misc.may_have_traps )
489 #define trap (G_misc.trap )
490 #define trap_ptr (G_misc.trap_ptr )
491 #define random_gen (G_misc.random_gen )
492 #define backgndpid (G_misc.backgndpid )
493 #define INIT_G_misc() do { \
494 (*(struct globals_misc**)not_const_pp(&ash_ptr_to_globals_misc)) = xzalloc(sizeof(G_misc)); \
503 /* ============ DEBUG */
505 static void trace_printf(const char *fmt, ...);
506 static void trace_vprintf(const char *fmt, va_list va);
507 # define TRACE(param) trace_printf param
508 # define TRACEV(param) trace_vprintf param
509 # define close(fd) do { \
511 if (close(dfd) < 0) \
512 bb_error_msg("bug on %d: closing %d(0x%x)", \
513 __LINE__, dfd, dfd); \
516 # define TRACE(param)
517 # define TRACEV(param)
521 /* ============ Utility functions */
522 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
523 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
526 isdigit_str9(const char *str)
528 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
529 while (--maxlen && isdigit(*str))
531 return (*str == '\0');
535 var_end(const char *var)
544 /* ============ Interrupts / exceptions */
546 static void exitshell(void) NORETURN;
549 * These macros allow the user to suspend the handling of interrupt signals
550 * over a period of time. This is similar to SIGHOLD or to sigblock, but
551 * much more efficient and portable. (But hacking the kernel is so much
552 * more fun than worrying about efficiency and portability. :-))
555 # define INT_OFF do { \
556 TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
561 # define INT_OFF do { \
568 * Called to raise an exception. Since C doesn't include exceptions, we
569 * just do a longjmp to the exception handler. The type of exception is
570 * stored in the global variable "exception_type".
572 static void raise_exception(int) NORETURN;
574 raise_exception(int e)
577 if (exception_handler == NULL)
582 longjmp(exception_handler->loc, 1);
585 #define raise_exception(e) do { \
586 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
587 raise_exception(e); \
592 * Called when a SIGINT is received. (If the user specifies
593 * that SIGINT is to be trapped or ignored using the trap builtin, then
594 * this routine is not called.) Suppressint is nonzero when interrupts
595 * are held using the INT_OFF macro. (The test for iflag is just
596 * defensive programming.)
598 static void raise_interrupt(void) NORETURN;
600 raise_interrupt(void)
603 /* Signal is not automatically unmasked after it is raised,
604 * do it ourself - unmask all signals */
605 sigprocmask_allsigs(SIG_UNBLOCK);
606 /* pending_sig = 0; - now done in signal_handler() */
608 if (!(rootshell && iflag)) {
609 /* Kill ourself with SIGINT */
610 signal(SIGINT, SIG_DFL);
613 /* bash: ^C even on empty command line sets $? */
614 exitstatus = SIGINT + 128;
615 raise_exception(EXINT);
619 #define raise_interrupt() do { \
620 TRACE(("raising interrupt on line %d\n", __LINE__)); \
625 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
629 if (--suppress_int == 0 && pending_int) {
634 # define INT_ON do { \
635 TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
639 # define INT_ON int_on()
641 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
649 #define FORCE_INT_ON force_int_on()
651 #define SAVE_INT(v) ((v) = suppress_int)
653 #define RESTORE_INT(v) do { \
655 suppress_int = (v); \
656 if (suppress_int == 0 && pending_int) \
661 /* ============ Stdout/stderr output */
664 outstr(const char *p, FILE *file)
672 flush_stdout_stderr(void)
679 /* Was called outcslow(c,FILE*), but c was always '\n' */
681 newline_and_flush(FILE *dest)
689 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
691 out1fmt(const char *fmt, ...)
698 r = vprintf(fmt, ap);
704 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
706 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
713 ret = vsnprintf(outbuf, length, fmt, ap);
716 return ret > (int)length ? length : ret;
720 out1str(const char *p)
726 out2str(const char *p)
729 flush_stdout_stderr();
733 /* ============ Parser structures */
735 /* control characters in argument strings */
736 #define CTL_FIRST CTLESC
737 #define CTLESC ((unsigned char)'\201') /* escape next character */
738 #define CTLVAR ((unsigned char)'\202') /* variable defn */
739 #define CTLENDVAR ((unsigned char)'\203')
740 #define CTLBACKQ ((unsigned char)'\204')
741 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
742 #define CTLENDARI ((unsigned char)'\207')
743 #define CTLQUOTEMARK ((unsigned char)'\210')
744 #define CTL_LAST CTLQUOTEMARK
746 /* variable substitution byte (follows CTLVAR) */
747 #define VSTYPE 0x0f /* type of variable substitution */
748 #define VSNUL 0x10 /* colon--treat the empty string as unset */
750 /* values of VSTYPE field */
751 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
752 #define VSMINUS 0x2 /* ${var-text} */
753 #define VSPLUS 0x3 /* ${var+text} */
754 #define VSQUESTION 0x4 /* ${var?message} */
755 #define VSASSIGN 0x5 /* ${var=text} */
756 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
757 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
758 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
759 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
760 #define VSLENGTH 0xa /* ${#var} */
762 #define VSSUBSTR 0xc /* ${var:position:length} */
764 #if BASH_PATTERN_SUBST
765 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
766 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
769 static const char dolatstr[] ALIGN1 = {
770 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
772 #define DOLATSTRLEN 6
791 #if BASH_REDIR_OUTPUT
808 smallint type; /* Nxxxx */
812 union node *redirect;
817 smallint pipe_backgnd;
818 struct nodelist *cmdlist;
825 union node *redirect;
838 union node *elsepart;
874 struct nodelist *backquote;
877 /* nfile and ndup layout must match!
878 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
879 * that it is actually NTO2 (>&file), and change its type.
896 char *_unused_expfname;
915 struct nredir nredir;
916 struct nbinary nbinary;
920 struct nclist nclist;
921 struct ndefun ndefun;
930 * NODE_EOF is returned by parsecmd when it encounters an end of file.
931 * It must be distinct from NULL.
933 #define NODE_EOF ((union node *) -1L)
936 struct nodelist *next;
949 freefunc(struct funcnode *f)
951 if (f && --f->count < 0)
956 /* ============ Debugging output */
960 static FILE *tracefile;
963 trace_printf(const char *fmt, ...)
970 fprintf(tracefile, "%u ", (int) time(NULL));
972 fprintf(tracefile, "[%u] ", (int) getpid());
974 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
976 vfprintf(tracefile, fmt, va);
981 trace_vprintf(const char *fmt, va_list va)
985 vfprintf(tracefile, fmt, va);
986 fprintf(tracefile, "\n");
990 trace_puts(const char *s)
998 trace_puts_quoted(char *s)
1005 putc('"', tracefile);
1006 for (p = s; *p; p++) {
1007 switch ((unsigned char)*p) {
1008 case '\n': c = 'n'; goto backslash;
1009 case '\t': c = 't'; goto backslash;
1010 case '\r': c = 'r'; goto backslash;
1011 case '\"': c = '\"'; goto backslash;
1012 case '\\': c = '\\'; goto backslash;
1013 case CTLESC: c = 'e'; goto backslash;
1014 case CTLVAR: c = 'v'; goto backslash;
1015 case CTLBACKQ: c = 'q'; goto backslash;
1017 putc('\\', tracefile);
1021 if (*p >= ' ' && *p <= '~')
1022 putc(*p, tracefile);
1024 putc('\\', tracefile);
1025 putc((*p >> 6) & 03, tracefile);
1026 putc((*p >> 3) & 07, tracefile);
1027 putc(*p & 07, tracefile);
1032 putc('"', tracefile);
1036 trace_puts_args(char **ap)
1043 trace_puts_quoted(*ap);
1045 putc('\n', tracefile);
1048 putc(' ', tracefile);
1063 /* leave open because libedit might be using it */
1066 strcpy(s, "./trace");
1068 if (!freopen(s, "a", tracefile)) {
1069 fprintf(stderr, "Can't re-open %s\n", s);
1074 tracefile = fopen(s, "a");
1075 if (tracefile == NULL) {
1076 fprintf(stderr, "Can't open %s\n", s);
1082 flags = fcntl(fileno(tracefile), F_GETFL);
1084 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
1086 setlinebuf(tracefile);
1087 fputs("\nTracing started.\n", tracefile);
1091 indent(int amount, char *pfx, FILE *fp)
1095 for (i = 0; i < amount; i++) {
1096 if (pfx && i == amount - 1)
1102 /* little circular references here... */
1103 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
1106 sharg(union node *arg, FILE *fp)
1109 struct nodelist *bqlist;
1110 unsigned char subtype;
1112 if (arg->type != NARG) {
1113 out1fmt("<node type %d>\n", arg->type);
1116 bqlist = arg->narg.backquote;
1117 for (p = arg->narg.text; *p; p++) {
1118 switch ((unsigned char)*p) {
1127 if (subtype == VSLENGTH)
1135 if (subtype & VSNUL)
1138 switch (subtype & VSTYPE) {
1164 case VSTRIMRIGHTMAX:
1171 out1fmt("<subtype %d>", subtype);
1180 shtree(bqlist->n, -1, NULL, fp);
1191 shcmd(union node *cmd, FILE *fp)
1199 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1205 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1209 switch (np->nfile.type) {
1210 case NTO: s = ">>"+1; dftfd = 1; break;
1211 case NCLOBBER: s = ">|"; dftfd = 1; break;
1212 case NAPPEND: s = ">>"; dftfd = 1; break;
1213 #if BASH_REDIR_OUTPUT
1216 case NTOFD: s = ">&"; dftfd = 1; break;
1217 case NFROM: s = "<"; break;
1218 case NFROMFD: s = "<&"; break;
1219 case NFROMTO: s = "<>"; break;
1220 default: s = "*error*"; break;
1222 if (np->nfile.fd != dftfd)
1223 fprintf(fp, "%d", np->nfile.fd);
1225 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1226 fprintf(fp, "%d", np->ndup.dupfd);
1228 sharg(np->nfile.fname, fp);
1235 shtree(union node *n, int ind, char *pfx, FILE *fp)
1237 struct nodelist *lp;
1243 indent(ind, pfx, fp);
1245 if (n == NODE_EOF) {
1260 shtree(n->nbinary.ch1, ind, NULL, fp);
1263 shtree(n->nbinary.ch2, ind, NULL, fp);
1271 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1272 shtree(lp->n, 0, NULL, fp);
1276 if (n->npipe.pipe_backgnd)
1282 fprintf(fp, "<node type %d>", n->type);
1290 showtree(union node *n)
1292 trace_puts("showtree called\n");
1293 shtree(n, 1, NULL, stderr);
1299 /* ============ Parser data */
1302 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1305 struct strlist *next;
1312 struct strpush *prev; /* preceding string on stack */
1314 int prev_left_in_line;
1315 #if ENABLE_ASH_ALIAS
1316 struct alias *ap; /* if push was associated with an alias */
1318 char *string; /* remember the string since it may change */
1320 /* Remember last two characters for pungetc. */
1323 /* Number of outstanding calls to pungetc. */
1328 * The parsefile structure pointed to by the global variable parsefile
1329 * contains information about the current file being read.
1332 struct parsefile *prev; /* preceding file on stack */
1333 int linno; /* current line */
1334 int pf_fd; /* file descriptor (or -1 if string) */
1335 int left_in_line; /* number of chars left in this line */
1336 int left_in_buffer; /* number of chars left in this buffer past the line */
1337 char *next_to_pgetc; /* next char in buffer */
1338 char *buf; /* input buffer */
1339 struct strpush *strpush; /* for pushing strings at this level */
1340 struct strpush basestrpush; /* so pushing one is fast */
1342 /* Remember last two characters for pungetc. */
1345 /* Number of outstanding calls to pungetc. */
1349 static struct parsefile basepf; /* top level input file */
1350 static struct parsefile *g_parsefile = &basepf; /* current input file */
1351 static char *commandname; /* currently executing command */
1354 /* ============ Message printing */
1357 ash_vmsg(const char *msg, va_list ap)
1359 fprintf(stderr, "%s: ", arg0);
1361 if (strcmp(arg0, commandname))
1362 fprintf(stderr, "%s: ", commandname);
1363 if (!iflag || g_parsefile->pf_fd > 0)
1364 fprintf(stderr, "line %d: ", errlinno);
1366 vfprintf(stderr, msg, ap);
1367 newline_and_flush(stderr);
1371 * Exverror is called to raise the error exception. If the second argument
1372 * is not NULL then error prints an error message using printf style
1373 * formatting. It then raises the error exception.
1375 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1377 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1381 TRACE(("ash_vmsg_and_raise(%d):", cond));
1384 TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
1389 flush_stdout_stderr();
1390 raise_exception(cond);
1394 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1396 ash_msg_and_raise_error(const char *msg, ...)
1403 ash_vmsg_and_raise(EXERROR, msg, ap);
1409 * 'fmt' must be a string literal.
1411 #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": "STRERROR_FMT, ##__VA_ARGS__ STRERROR_ERRNO)
1413 static void raise_error_syntax(const char *) NORETURN;
1415 raise_error_syntax(const char *msg)
1417 errlinno = g_parsefile->linno;
1418 ash_msg_and_raise_error("syntax error: %s", msg);
1422 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1424 ash_msg_and_raise(int cond, const char *msg, ...)
1429 ash_vmsg_and_raise(cond, msg, ap);
1435 * error/warning routines for external builtins
1438 ash_msg(const char *fmt, ...)
1448 * Return a string describing an error. The returned string may be a
1449 * pointer to a static buffer that will be overwritten on the next call.
1450 * Action describes the operation that got the error.
1453 errmsg(int e, const char *em)
1455 if (e == ENOENT || e == ENOTDIR) {
1462 /* ============ Memory allocation */
1465 /* I consider these wrappers nearly useless:
1466 * ok, they return you to nearest exception handler, but
1467 * how much memory do you leak in the process, making
1468 * memory starvation worse?
1471 ckrealloc(void * p, size_t nbytes)
1473 p = realloc(p, nbytes);
1475 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1480 ckmalloc(size_t nbytes)
1482 return ckrealloc(NULL, nbytes);
1486 ckzalloc(size_t nbytes)
1488 return memset(ckmalloc(nbytes), 0, nbytes);
1492 ckstrdup(const char *s)
1494 char *p = strdup(s);
1496 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1500 /* Using bbox equivalents. They exit if out of memory */
1501 # define ckrealloc xrealloc
1502 # define ckmalloc xmalloc
1503 # define ckzalloc xzalloc
1504 # define ckstrdup xstrdup
1508 * It appears that grabstackstr() will barf with such alignments
1509 * because stalloc() will return a string allocated in a new stackblock.
1511 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1513 /* Most machines require the value returned from malloc to be aligned
1514 * in some way. The following macro will get this right
1515 * on many machines. */
1516 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1517 /* Minimum size of a block */
1518 MINSIZE = SHELL_ALIGN(504),
1521 struct stack_block {
1522 struct stack_block *prev;
1523 char space[MINSIZE];
1527 struct stack_block *stackp;
1533 struct globals_memstack {
1534 struct stack_block *g_stackp; // = &stackbase;
1535 char *g_stacknxt; // = stackbase.space;
1536 char *sstrend; // = stackbase.space + MINSIZE;
1537 size_t g_stacknleft; // = MINSIZE;
1538 struct stack_block stackbase;
1540 extern struct globals_memstack *BB_GLOBAL_CONST ash_ptr_to_globals_memstack;
1541 #define G_memstack (*ash_ptr_to_globals_memstack)
1542 #define g_stackp (G_memstack.g_stackp )
1543 #define g_stacknxt (G_memstack.g_stacknxt )
1544 #define sstrend (G_memstack.sstrend )
1545 #define g_stacknleft (G_memstack.g_stacknleft)
1546 #define stackbase (G_memstack.stackbase )
1547 #define INIT_G_memstack() do { \
1548 (*(struct globals_memstack**)not_const_pp(&ash_ptr_to_globals_memstack)) = xzalloc(sizeof(G_memstack)); \
1550 g_stackp = &stackbase; \
1551 g_stacknxt = stackbase.space; \
1552 g_stacknleft = MINSIZE; \
1553 sstrend = stackbase.space + MINSIZE; \
1557 #define stackblock() ((void *)g_stacknxt)
1558 #define stackblocksize() g_stacknleft
1561 * Parse trees for commands are allocated in lifo order, so we use a stack
1562 * to make this more efficient, and also to avoid all sorts of exception
1563 * handling code to handle interrupts in the middle of a parse.
1565 * The size 504 was chosen because the Ultrix malloc handles that size
1569 stalloc(size_t nbytes)
1574 aligned = SHELL_ALIGN(nbytes);
1575 if (aligned > g_stacknleft) {
1578 struct stack_block *sp;
1580 blocksize = aligned;
1581 if (blocksize < MINSIZE)
1582 blocksize = MINSIZE;
1583 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1584 if (len < blocksize)
1585 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1588 sp->prev = g_stackp;
1589 g_stacknxt = sp->space;
1590 g_stacknleft = blocksize;
1591 sstrend = g_stacknxt + blocksize;
1596 g_stacknxt += aligned;
1597 g_stacknleft -= aligned;
1602 stzalloc(size_t nbytes)
1604 return memset(stalloc(nbytes), 0, nbytes);
1611 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1612 write(STDERR_FILENO, "stunalloc\n", 10);
1616 g_stacknleft += g_stacknxt - (char *)p;
1621 * Like strdup but works with the ash stack.
1624 sstrdup(const char *p)
1626 size_t len = strlen(p) + 1;
1627 return memcpy(stalloc(len), p, len);
1630 static ALWAYS_INLINE void
1631 grabstackblock(size_t len)
1637 pushstackmark(struct stackmark *mark, size_t len)
1639 mark->stackp = g_stackp;
1640 mark->stacknxt = g_stacknxt;
1641 mark->stacknleft = g_stacknleft;
1642 grabstackblock(len);
1646 setstackmark(struct stackmark *mark)
1648 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1652 popstackmark(struct stackmark *mark)
1654 struct stack_block *sp;
1660 while (g_stackp != mark->stackp) {
1662 g_stackp = sp->prev;
1665 g_stacknxt = mark->stacknxt;
1666 g_stacknleft = mark->stacknleft;
1667 sstrend = mark->stacknxt + mark->stacknleft;
1672 * When the parser reads in a string, it wants to stick the string on the
1673 * stack and only adjust the stack pointer when it knows how big the
1674 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1675 * of space on top of the stack and stackblocklen returns the length of
1676 * this block. Growstackblock will grow this space by at least one byte,
1677 * possibly moving it (like realloc). Grabstackblock actually allocates the
1678 * part of the block that has been used.
1681 growstackblock(void)
1685 newlen = g_stacknleft * 2;
1686 if (newlen < g_stacknleft)
1687 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1691 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1692 struct stack_block *sp;
1693 struct stack_block *prevstackp;
1698 prevstackp = sp->prev;
1699 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1700 sp = ckrealloc(sp, grosslen);
1701 sp->prev = prevstackp;
1703 g_stacknxt = sp->space;
1704 g_stacknleft = newlen;
1705 sstrend = sp->space + newlen;
1708 char *oldspace = g_stacknxt;
1709 size_t oldlen = g_stacknleft;
1710 char *p = stalloc(newlen);
1712 /* free the space we just allocated */
1713 g_stacknxt = memcpy(p, oldspace, oldlen);
1714 g_stacknleft += newlen;
1719 * The following routines are somewhat easier to use than the above.
1720 * The user declares a variable of type STACKSTR, which may be declared
1721 * to be a register. The macro STARTSTACKSTR initializes things. Then
1722 * the user uses the macro STPUTC to add characters to the string. In
1723 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1724 * grown as necessary. When the user is done, she can just leave the
1725 * string there and refer to it using stackblock(). Or she can allocate
1726 * the space for it using grabstackstr(). If it is necessary to allow
1727 * someone else to use the stack temporarily and then continue to grow
1728 * the string, the user should use grabstack to allocate the space, and
1729 * then call ungrabstr(p) to return to the previous mode of operation.
1731 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1732 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1733 * is space for at least one character.
1738 size_t len = stackblocksize();
1740 return (char *)stackblock() + len;
1744 growstackto(size_t len)
1746 while (stackblocksize() < len)
1749 return stackblock();
1753 * Called from CHECKSTRSPACE.
1756 makestrspace(size_t newlen, char *p)
1758 size_t len = p - g_stacknxt;
1760 return growstackto(len + newlen) + len;
1764 stack_nputstr(const char *s, size_t n, char *p)
1766 p = makestrspace(n, p);
1767 p = (char *)mempcpy(p, s, n);
1772 stack_putstr(const char *s, char *p)
1774 return stack_nputstr(s, strlen(s), p);
1778 _STPUTC(int c, char *p)
1786 #define STARTSTACKSTR(p) ((p) = stackblock())
1787 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1788 #define CHECKSTRSPACE(n, p) do { \
1791 size_t m = sstrend - q; \
1793 (p) = makestrspace(l, q); \
1795 #define USTPUTC(c, p) (*(p)++ = (c))
1796 #define STACKSTRNUL(p) do { \
1797 if ((p) == sstrend) \
1798 (p) = growstackstr(); \
1801 #define STUNPUTC(p) (--(p))
1802 #define STTOPC(p) ((p)[-1])
1803 #define STADJUST(amount, p) ((p) += (amount))
1805 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1806 #define ungrabstackstr(s, p) stunalloc(s)
1807 #define stackstrend() ((void *)sstrend)
1810 /* ============ String helpers */
1813 * prefix -- see if pfx is a prefix of string.
1816 prefix(const char *string, const char *pfx)
1819 if (*pfx++ != *string++)
1822 return (char *) string;
1826 * Check for a valid number. This should be elsewhere.
1829 is_number(const char *p)
1834 } while (*++p != '\0');
1839 * Convert a string of digits to an integer, printing an error message on
1843 number(const char *s)
1846 ash_msg_and_raise_error(msg_illnum, s);
1851 * Produce a single quoted string suitable as input to the shell.
1852 * The return string is allocated on the stack.
1855 single_quote(const char *s)
1865 len = strchrnul(s, '\'') - s;
1867 q = p = makestrspace(len + 3, p);
1870 q = (char *)mempcpy(q, s, len);
1879 do len++; while (*++s == '\'');
1881 q = p = makestrspace(len + 3, p);
1884 q = (char *)mempcpy(q, s - len, len);
1892 return stackblock();
1896 * Produce a possibly single quoted string suitable as input to the shell.
1897 * If quoting was done, the return string is allocated on the stack,
1898 * otherwise a pointer to the original string is returned.
1901 maybe_single_quote(const char *s)
1906 /* Assuming ACSII */
1907 /* quote ctrl_chars space !"#$%&'()* */
1911 if (*p >= ';' && *p <= '?')
1920 /* quote {|}~ DEL and high bytes */
1923 /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
1924 /* TODO: maybe avoid quoting % */
1930 return single_quote(s);
1934 /* ============ nextopt */
1936 static char **argptr; /* argument list for builtin commands */
1937 static char *optionarg; /* set by nextopt (like getopt) */
1938 static char *optptr; /* used by nextopt */
1941 * XXX - should get rid of. Have all builtins use getopt(3).
1942 * The library getopt must have the BSD extension static variable
1943 * "optreset", otherwise it can't be used within the shell safely.
1945 * Standard option processing (a la getopt) for builtin routines.
1946 * The only argument that is passed to nextopt is the option string;
1947 * the other arguments are unnecessary. It returns the character,
1948 * or '\0' on end of input.
1951 nextopt(const char *optstring)
1958 if (p == NULL || *p == '\0') {
1959 /* We ate entire "-param", take next one */
1965 if (*++p == '\0') /* just "-" ? */
1968 if (LONE_DASH(p)) /* "--" ? */
1970 /* p => next "-param" */
1972 /* p => some option char in the middle of a "-param" */
1974 for (q = optstring; *q != c;) {
1976 ash_msg_and_raise_error("illegal option -%c", c);
1984 ash_msg_and_raise_error("no arg for -%c option", c);
1994 /* ============ Shell variables */
1997 int nparam; /* # of positional parameters (without $0) */
1998 #if ENABLE_ASH_GETOPTS
1999 int optind; /* next parameter to be processed by getopts */
2000 int optoff; /* used by getopts */
2002 unsigned char malloced; /* if parameter list dynamically allocated */
2003 char **p; /* parameter list */
2007 * Free the list of positional parameters.
2010 freeparam(volatile struct shparam *param)
2012 if (param->malloced) {
2014 ap = ap1 = param->p;
2021 #if ENABLE_ASH_GETOPTS
2022 static void FAST_FUNC getoptsreset(const char *value);
2026 struct var *next; /* next entry in hash list */
2027 int flags; /* flags are defined above */
2028 const char *var_text; /* name=value */
2029 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
2030 /* the variable gets set/unset */
2034 struct localvar *next; /* next local variable in list */
2035 struct var *vp; /* the variable that was made local */
2036 int flags; /* saved flags */
2037 const char *text; /* saved text */
2041 #define VEXPORT 0x01 /* variable is exported */
2042 #define VREADONLY 0x02 /* variable cannot be modified */
2043 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
2044 #define VTEXTFIXED 0x08 /* text is statically allocated */
2045 #define VSTACK 0x10 /* text is allocated on the stack */
2046 #define VUNSET 0x20 /* the variable is not set */
2047 #define VNOFUNC 0x40 /* don't call the callback function */
2048 #define VNOSET 0x80 /* do not set variable - just readonly test */
2049 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
2050 #if ENABLE_ASH_RANDOM_SUPPORT
2051 # define VDYNAMIC 0x200 /* dynamic variable */
2057 /* Need to be before varinit_data[] */
2058 #if ENABLE_LOCALE_SUPPORT
2059 static void FAST_FUNC
2060 change_lc_all(const char *value)
2062 if (value && *value != '\0')
2063 setlocale(LC_ALL, value);
2065 static void FAST_FUNC
2066 change_lc_ctype(const char *value)
2068 if (value && *value != '\0')
2069 setlocale(LC_CTYPE, value);
2073 static void chkmail(void);
2074 static void changemail(const char *var_value) FAST_FUNC;
2076 # define chkmail() ((void)0)
2078 static void changepath(const char *) FAST_FUNC;
2079 #if ENABLE_ASH_RANDOM_SUPPORT
2080 static void change_random(const char *) FAST_FUNC;
2083 static void change_seconds(const char *) FAST_FUNC;
2084 static void change_realtime(const char *) FAST_FUNC;
2087 static const struct {
2089 const char *var_text;
2090 void (*var_func)(const char *) FAST_FUNC;
2091 } varinit_data[] = {
2093 * Note: VEXPORT would not work correctly here for NOFORK applets:
2094 * some environment strings may be constant.
2096 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
2098 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
2099 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
2101 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
2102 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
2103 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
2104 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
2105 #if ENABLE_ASH_GETOPTS
2106 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
2108 { VSTRFIXED|VTEXTFIXED , NULL /* inited to linenovar */, NULL },
2109 #if ENABLE_ASH_RANDOM_SUPPORT
2110 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
2113 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "EPOCHSECONDS", change_seconds },
2114 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "EPOCHREALTIME", change_realtime },
2116 #if ENABLE_LOCALE_SUPPORT
2117 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
2118 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
2120 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
2121 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
2127 struct globals_var {
2128 struct shparam shellparam; /* $@ current positional parameters */
2129 struct redirtab *redirlist;
2130 int preverrout_fd; /* stderr fd: usually 2, unless redirect moved it */
2131 struct var *vartab[VTABSIZE];
2132 struct var varinit[ARRAY_SIZE(varinit_data)];
2134 char linenovar[sizeof("LINENO=") + sizeof(int)*3];
2136 extern struct globals_var *BB_GLOBAL_CONST ash_ptr_to_globals_var;
2137 #define G_var (*ash_ptr_to_globals_var)
2138 #define shellparam (G_var.shellparam )
2139 //#define redirlist (G_var.redirlist )
2140 #define preverrout_fd (G_var.preverrout_fd)
2141 #define vartab (G_var.vartab )
2142 #define varinit (G_var.varinit )
2143 #define lineno (G_var.lineno )
2144 #define linenovar (G_var.linenovar )
2145 #define vifs varinit[0]
2147 # define vmail varinit[1]
2148 # define vmpath varinit[2]
2150 #define VAR_OFFSET1 (ENABLE_ASH_MAIL*2)
2151 #define vpath varinit[VAR_OFFSET1 + 1]
2152 #define vps1 varinit[VAR_OFFSET1 + 2]
2153 #define vps2 varinit[VAR_OFFSET1 + 3]
2154 #define vps4 varinit[VAR_OFFSET1 + 4]
2155 #if ENABLE_ASH_GETOPTS
2156 # define voptind varinit[VAR_OFFSET1 + 5]
2158 #define VAR_OFFSET2 (VAR_OFFSET1 + ENABLE_ASH_GETOPTS)
2159 #define vlineno varinit[VAR_OFFSET2 + 5]
2160 #if ENABLE_ASH_RANDOM_SUPPORT
2161 # define vrandom varinit[VAR_OFFSET2 + 6]
2163 #define VAR_OFFSET3 (VAR_OFFSET2 + ENABLE_ASH_RANDOM_SUPPORT)
2165 # define vepochs varinit[VAR_OFFSET3 + 6]
2166 # define vepochr varinit[VAR_OFFSET3 + 7]
2168 #define INIT_G_var() do { \
2170 (*(struct globals_var**)not_const_pp(&ash_ptr_to_globals_var)) = xzalloc(sizeof(G_var)); \
2172 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
2173 varinit[i].flags = varinit_data[i].flags; \
2174 varinit[i].var_text = varinit_data[i].var_text; \
2175 varinit[i].var_func = varinit_data[i].var_func; \
2177 strcpy(linenovar, "LINENO="); \
2178 vlineno.var_text = linenovar; \
2182 * The following macros access the values of the above variables.
2183 * They have to skip over the name. They return the null string
2184 * for unset variables.
2186 #define ifsval() (vifs.var_text + 4)
2187 #define ifsset() ((vifs.flags & VUNSET) == 0)
2189 # define mailval() (vmail.var_text + 5)
2190 # define mpathval() (vmpath.var_text + 9)
2191 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2193 #define pathval() (vpath.var_text + 5)
2194 #define ps1val() (vps1.var_text + 4)
2195 #define ps2val() (vps2.var_text + 4)
2196 #define ps4val() (vps4.var_text + 4)
2197 #if ENABLE_ASH_GETOPTS
2198 # define optindval() (voptind.var_text + 7)
2201 #if ENABLE_ASH_GETOPTS
2202 static void FAST_FUNC
2203 getoptsreset(const char *value)
2205 shellparam.optind = 1;
2206 if (is_number(value))
2207 shellparam.optind = number(value) ?: 1;
2208 shellparam.optoff = -1;
2213 * Compares two strings up to the first = or '\0'. The first
2214 * string must be terminated by '='; the second may be terminated by
2215 * either '=' or '\0'.
2218 varcmp(const char *p, const char *q)
2222 while ((c = *p) == (d = *q)) {
2223 if (c == '\0' || c == '=')
2237 * Find the appropriate entry in the hash table from the name.
2239 static struct var **
2240 hashvar(const char *p)
2244 hashval = ((unsigned char) *p) << 4;
2245 while (*p && *p != '=')
2246 hashval += (unsigned char) *p++;
2247 return &vartab[hashval % VTABSIZE];
2251 vpcmp(const void *a, const void *b)
2253 return varcmp(*(const char **)a, *(const char **)b);
2257 * This routine initializes the builtin variables.
2267 * PS1 depends on uid
2269 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2270 vps1.var_text = "PS1=\\w \\$ ";
2273 vps1.var_text = "PS1=# ";
2276 end = vp + ARRAY_SIZE(varinit);
2278 vpp = hashvar(vp->var_text);
2281 } while (++vp < end);
2284 static struct var **
2285 findvar(struct var **vpp, const char *name)
2287 for (; *vpp; vpp = &(*vpp)->next) {
2288 if (varcmp((*vpp)->var_text, name) == 0) {
2296 * Find the value of a variable. Returns NULL if not set.
2298 static const char* FAST_FUNC
2299 lookupvar(const char *name)
2303 v = *findvar(hashvar(name), name);
2305 #if ENABLE_ASH_RANDOM_SUPPORT || BASH_EPOCH_VARS
2307 * Dynamic variables are implemented roughly the same way they are
2308 * in bash. Namely, they're "special" so long as they aren't unset.
2309 * As soon as they're unset, they're no longer dynamic, and dynamic
2310 * lookup will no longer happen at that point. -- PFM.
2312 if (v->flags & VDYNAMIC)
2315 if (!(v->flags & VUNSET)) {
2316 if (v == &vlineno && v->var_text == linenovar) {
2317 fmtstr(linenovar+7, sizeof(linenovar)-7, "%d", lineno);
2319 return var_end(v->var_text);
2325 #if ENABLE_UNICODE_SUPPORT
2327 reinit_unicode_for_ash(void)
2329 /* Unicode support should be activated even if LANG is set
2330 * _during_ shell execution, not only if it was set when
2331 * shell was started. Therefore, re-check LANG every time:
2333 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2334 || ENABLE_UNICODE_USING_LOCALE
2336 const char *s = lookupvar("LC_ALL");
2337 if (!s) s = lookupvar("LC_CTYPE");
2338 if (!s) s = lookupvar("LANG");
2343 # define reinit_unicode_for_ash() ((void)0)
2347 * Search the environment of a builtin command.
2349 static ALWAYS_INLINE const char *
2350 bltinlookup(const char *name)
2352 return lookupvar(name);
2356 * Same as setvar except that the variable and value are passed in
2357 * the first argument as name=value. Since the first argument will
2358 * be actually stored in the table, it should not be a string that
2360 * Called with interrupts off.
2363 setvareq(char *s, int flags)
2365 struct var *vp, **vpp;
2368 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2369 vpp = findvar(vpp, s);
2372 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2375 if (flags & VNOSAVE)
2379 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2385 if (vp->var_func && !(flags & VNOFUNC))
2386 vp->var_func(var_end(s));
2388 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2389 free((char*)vp->var_text);
2391 if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
2395 if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
2400 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2401 #if ENABLE_ASH_RANDOM_SUPPORT || BASH_EPOCH_VARS
2406 /* variable s is not found */
2409 if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
2411 vp = ckzalloc(sizeof(*vp));
2413 /*vp->func = NULL; - ckzalloc did it */
2416 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2426 * Set the value of a variable. The flags argument is ored with the
2427 * flags of the variable. If val is NULL, the variable is unset.
2430 setvar(const char *name, const char *val, int flags)
2439 q = endofname(name);
2440 p = strchrnul(q, '=');
2442 if (!namelen || p != q)
2443 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2448 vallen = strlen(val);
2452 nameeq = ckzalloc(namelen + vallen + 2);
2453 p = mempcpy(nameeq, name, namelen);
2456 memcpy(p, val, vallen);
2458 vp = setvareq(nameeq, flags | VNOSAVE);
2464 static void FAST_FUNC
2465 setvar0(const char *name, const char *val)
2467 setvar(name, val, 0);
2471 * Unset the specified variable.
2474 unsetvar(const char *s)
2480 * Process a linked list of variable assignments.
2483 listsetvar(struct strlist *list_set_var, int flags)
2485 struct strlist *lp = list_set_var;
2491 setvareq(lp->text, flags);
2498 * Generate a list of variables satisfying the given conditions.
2500 #if !ENABLE_FEATURE_SH_NOFORK
2501 # define listvars(on, off, lp, end) listvars(on, off, end)
2504 listvars(int on, int off, struct strlist *lp, char ***end)
2515 for (vp = *vpp; vp; vp = vp->next) {
2516 if ((vp->flags & mask) == on) {
2517 #if ENABLE_FEATURE_SH_NOFORK
2518 /* If variable with the same name is both
2519 * exported and temporarily set for a command:
2522 * then "ZVAR=6" will be both in vartab and
2523 * lp lists. Do not pass it twice to printenv.
2525 struct strlist *lp1 = lp;
2527 if (strcmp(lp1->text, vp->var_text) == 0)
2532 if (ep == stackstrend())
2533 ep = growstackstr();
2534 *ep++ = (char*)vp->var_text;
2535 #if ENABLE_FEATURE_SH_NOFORK
2540 } while (++vpp < vartab + VTABSIZE);
2542 #if ENABLE_FEATURE_SH_NOFORK
2544 if (ep == stackstrend())
2545 ep = growstackstr();
2551 if (ep == stackstrend())
2552 ep = growstackstr();
2556 return grabstackstr(ep);
2560 /* ============ Path search helper */
2562 legal_pathopt(const char *opt, const char *term, int magic)
2570 opt = prefix(opt, "builtin") ?: prefix(opt, "func");
2574 opt += strcspn(opt, term);
2578 if (opt && *opt == '%')
2585 * The variable path (passed by reference) should be set to the start
2586 * of the path before the first call; padvance will update
2587 * this value as it proceeds. Successive calls to padvance will return
2588 * the possible path expansions in sequence. If an option (indicated by
2589 * a percent sign) appears in the path entry then the global variable
2590 * pathopt will be set to point to it; otherwise pathopt will be set to
2593 * If magic is 0 then pathopt recognition will be disabled. If magic is
2594 * 1 we shall recognise %builtin/%func. Otherwise we shall accept any
2597 static const char *pathopt; /* set by padvance */
2600 padvance_magic(const char **path, const char *name, int magic)
2602 const char *term = "%:";
2603 const char *lpathopt;
2616 if (*start == '%' && (p = legal_pathopt(start + 1, term, magic))) {
2617 lpathopt = start + 1;
2622 len = strcspn(start, term);
2626 size_t extra = strchrnul(p, ':') - p;
2628 if (legal_pathopt(p + 1, term, magic))
2637 *path = *p == ':' ? p + 1 : NULL;
2639 /* "2" is for '/' and '\0' */
2640 qlen = len + strlen(name) + 2;
2641 q = growstackto(qlen);
2644 q = mempcpy(q, start, len);
2653 padvance(const char **path, const char *name)
2655 return padvance_magic(path, name, 1);
2659 /* ============ Prompt */
2661 static smallint doprompt; /* if set, prompt the user */
2662 static smallint needprompt; /* true if interactive and at start of line */
2664 #if ENABLE_FEATURE_EDITING
2665 static line_input_t *line_input_state;
2666 static const char *cmdedit_prompt;
2668 putprompt(const char *s)
2670 if (ENABLE_ASH_EXPAND_PRMT) {
2671 free((char*)cmdedit_prompt);
2672 cmdedit_prompt = ckstrdup(s);
2679 putprompt(const char *s)
2685 /* expandstr() needs parsing machinery, so it is far away ahead... */
2686 static const char *expandstr(const char *ps, int syntax_type);
2687 /* Values for syntax param */
2688 #define BASESYNTAX 0 /* not in quotes */
2689 #define DQSYNTAX 1 /* in double quotes */
2690 #define SQSYNTAX 2 /* in single quotes */
2691 #define ARISYNTAX 3 /* in arithmetic */
2692 #if ENABLE_ASH_EXPAND_PRMT
2693 # define PSSYNTAX 4 /* prompt. never passed to SIT() */
2695 /* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
2698 * called by editline -- any expansions to the prompt should be added here.
2701 setprompt_if(smallint do_set, int whichprompt)
2704 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2711 switch (whichprompt) {
2721 #if ENABLE_ASH_EXPAND_PRMT
2722 pushstackmark(&smark, stackblocksize());
2723 putprompt(expandstr(prompt, PSSYNTAX));
2724 popstackmark(&smark);
2731 /* ============ The cd and pwd commands */
2733 #define CD_PHYSICAL 1
2743 while ((i = nextopt("LP")) != '\0') {
2745 flags ^= CD_PHYSICAL;
2754 * Update curdir (the name of the current directory) in response to a
2758 updatepwd(const char *dir)
2765 cdcomppath = sstrdup(dir);
2768 if (curdir == nullstr)
2770 new = stack_putstr(curdir, new);
2772 new = makestrspace(strlen(dir) + 2, new);
2773 lim = (char *)stackblock() + 1;
2777 if (new > lim && *lim == '/')
2782 if (dir[1] == '/' && dir[2] != '/') {
2788 p = strtok(cdcomppath, "/");
2792 if (p[1] == '.' && p[2] == '\0') {
2804 new = stack_putstr(p, new);
2807 p = strtok(NULL, "/");
2812 return stackblock();
2816 * Find out what the current directory is. If we already know the current
2817 * directory, this routine returns immediately.
2822 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2823 return dir ? dir : nullstr;
2827 setpwd(const char *val, int setold)
2831 oldcur = dir = curdir;
2834 setvar("OLDPWD", oldcur, VEXPORT);
2837 if (physdir != nullstr) {
2838 if (physdir != oldcur)
2842 if (oldcur == val || !val) {
2848 dir = ckstrdup(val);
2849 if (oldcur != dir && oldcur != nullstr) {
2854 setvar("PWD", dir, VEXPORT);
2857 static void hashcd(void);
2860 * Actually do the chdir. We also call hashcd to let other routines
2861 * know that the current directory has changed.
2864 docd(const char *dest, int flags)
2866 const char *dir = NULL;
2869 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2872 if (!(flags & CD_PHYSICAL)) {
2873 dir = updatepwd(dest);
2887 static int FAST_FUNC
2888 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2901 dest = bltinlookup("HOME");
2902 else if (LONE_DASH(dest)) {
2903 dest = bltinlookup("OLDPWD");
2925 path = bltinlookup("CDPATH");
2926 while (p = path, (len = padvance(&path, dest)) >= 0) {
2930 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2934 if (!docd(p, flags))
2945 ash_msg_and_raise_perror("can't cd to %s", dest);
2948 if (flags & CD_PRINT)
2949 out1fmt("%s\n", curdir);
2953 static int FAST_FUNC
2954 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2957 const char *dir = curdir;
2961 if (physdir == nullstr)
2965 out1fmt("%s\n", dir);
2970 /* ============ ... */
2973 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2975 /* Syntax classes */
2976 #define CWORD 0 /* character is nothing special */
2977 #define CNL 1 /* newline character */
2978 #define CBACK 2 /* a backslash character */
2979 #define CSQUOTE 3 /* single quote */
2980 #define CDQUOTE 4 /* double quote */
2981 #define CENDQUOTE 5 /* a terminating quote */
2982 #define CBQUOTE 6 /* backwards single quote */
2983 #define CVAR 7 /* a dollar sign */
2984 #define CENDVAR 8 /* a '}' character */
2985 #define CLP 9 /* a left paren in arithmetic */
2986 #define CRP 10 /* a right paren in arithmetic */
2987 #define CENDFILE 11 /* end of file */
2988 #define CCTL 12 /* like CWORD, except it must be escaped */
2989 #define CSPCL 13 /* these terminate a word */
2990 #define CIGN 14 /* character should be ignored */
2993 #if ENABLE_ASH_ALIAS
2997 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2999 #if ENABLE_FEATURE_SH_MATH
3000 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
3002 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
3004 static const uint16_t S_I_T[] ALIGN2 = {
3005 #if ENABLE_ASH_ALIAS
3006 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
3008 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
3009 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
3010 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
3011 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
3012 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
3013 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
3014 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
3015 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
3016 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
3017 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
3018 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
3019 #if !USE_SIT_FUNCTION
3020 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
3021 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
3022 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
3026 /* Constants below must match table above */
3028 #if ENABLE_ASH_ALIAS
3029 CSPCL_CIGN_CIGN_CIGN , /* 0 */
3031 CSPCL_CWORD_CWORD_CWORD , /* 1 */
3032 CNL_CNL_CNL_CNL , /* 2 */
3033 CWORD_CCTL_CCTL_CWORD , /* 3 */
3034 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
3035 CVAR_CVAR_CWORD_CVAR , /* 5 */
3036 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
3037 CSPCL_CWORD_CWORD_CLP , /* 7 */
3038 CSPCL_CWORD_CWORD_CRP , /* 8 */
3039 CBACK_CBACK_CCTL_CBACK , /* 9 */
3040 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
3041 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
3042 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
3043 CWORD_CWORD_CWORD_CWORD , /* 13 */
3044 CCTL_CCTL_CCTL_CCTL , /* 14 */
3047 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
3048 * caller must ensure proper cast on it if c is *char_ptr!
3050 #if USE_SIT_FUNCTION
3053 SIT(int c, int syntax)
3055 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
3056 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
3058 * This causes '/' to be prepended with CTLESC in dquoted string,
3059 * making "./file"* treated incorrectly because we feed
3060 * ".\/file*" string to glob(), confusing it (see expandmeta func).
3061 * The "homegrown" glob implementation is okay with that,
3062 * but glibc one isn't. With '/' always treated as CWORD,
3065 # if ENABLE_ASH_ALIAS
3066 static const uint8_t syntax_index_table[] ALIGN1 = {
3067 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
3068 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
3069 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
3073 static const uint8_t syntax_index_table[] ALIGN1 = {
3074 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
3075 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
3076 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
3085 # if ENABLE_ASH_ALIAS
3091 /* Cast is purely for paranoia here,
3092 * just in case someone passed signed char to us */
3093 if ((unsigned char)c >= CTL_FIRST
3094 && (unsigned char)c <= CTL_LAST
3098 s = strchrnul(spec_symbls, c);
3101 indx = syntax_index_table[s - spec_symbls];
3103 return (S_I_T[indx] >> (syntax*4)) & 0xf;
3106 #else /* !USE_SIT_FUNCTION */
3108 static const uint8_t syntax_index_table[] ALIGN1 = {
3109 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
3110 /* 0 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 1 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 2 */ CWORD_CWORD_CWORD_CWORD,
3113 /* 3 */ CWORD_CWORD_CWORD_CWORD,
3114 /* 4 */ CWORD_CWORD_CWORD_CWORD,
3115 /* 5 */ CWORD_CWORD_CWORD_CWORD,
3116 /* 6 */ CWORD_CWORD_CWORD_CWORD,
3117 /* 7 */ CWORD_CWORD_CWORD_CWORD,
3118 /* 8 */ CWORD_CWORD_CWORD_CWORD,
3119 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
3120 /* 10 "\n" */ CNL_CNL_CNL_CNL,
3121 /* 11 */ CWORD_CWORD_CWORD_CWORD,
3122 /* 12 */ CWORD_CWORD_CWORD_CWORD,
3123 /* 13 */ CWORD_CWORD_CWORD_CWORD,
3124 /* 14 */ CWORD_CWORD_CWORD_CWORD,
3125 /* 15 */ CWORD_CWORD_CWORD_CWORD,
3126 /* 16 */ CWORD_CWORD_CWORD_CWORD,
3127 /* 17 */ CWORD_CWORD_CWORD_CWORD,
3128 /* 18 */ CWORD_CWORD_CWORD_CWORD,
3129 /* 19 */ CWORD_CWORD_CWORD_CWORD,
3130 /* 20 */ CWORD_CWORD_CWORD_CWORD,
3131 /* 21 */ CWORD_CWORD_CWORD_CWORD,
3132 /* 22 */ CWORD_CWORD_CWORD_CWORD,
3133 /* 23 */ CWORD_CWORD_CWORD_CWORD,
3134 /* 24 */ CWORD_CWORD_CWORD_CWORD,
3135 /* 25 */ CWORD_CWORD_CWORD_CWORD,
3136 /* 26 */ CWORD_CWORD_CWORD_CWORD,
3137 /* 27 */ CWORD_CWORD_CWORD_CWORD,
3138 /* 28 */ CWORD_CWORD_CWORD_CWORD,
3139 /* 29 */ CWORD_CWORD_CWORD_CWORD,
3140 /* 30 */ CWORD_CWORD_CWORD_CWORD,
3141 /* 31 */ CWORD_CWORD_CWORD_CWORD,
3142 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
3143 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
3144 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
3145 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
3146 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
3147 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
3148 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
3149 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
3150 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
3151 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
3152 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
3153 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
3154 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
3155 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
3156 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
3157 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
3158 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
3159 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
3160 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
3161 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
3162 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
3163 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
3164 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
3165 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
3166 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
3167 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
3168 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
3169 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
3170 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
3171 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
3172 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
3173 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
3174 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
3175 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
3176 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
3177 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
3178 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
3179 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
3180 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
3181 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
3182 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
3183 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
3184 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
3185 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
3186 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
3187 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
3188 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
3189 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
3190 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
3191 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
3192 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
3193 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
3194 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
3195 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
3196 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
3197 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
3198 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
3199 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
3200 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
3201 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
3202 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
3203 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
3204 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
3205 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
3206 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
3207 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
3208 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
3209 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
3210 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
3211 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
3212 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
3213 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
3214 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
3215 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
3216 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
3217 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
3218 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
3219 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
3220 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
3221 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
3222 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3223 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3224 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3225 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3226 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3227 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3228 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3229 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3230 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3231 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3232 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3233 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3234 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3235 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3236 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3237 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3238 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
3239 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
3240 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
3241 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
3242 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
3243 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
3244 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
3245 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3246 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3247 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3248 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3249 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3250 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3251 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3252 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3253 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3254 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3255 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3256 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3257 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3258 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3259 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3260 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3261 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3262 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3263 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3264 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3265 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3266 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3267 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3268 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3269 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3270 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3271 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3272 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3273 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3274 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3275 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3276 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3277 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3278 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3279 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3280 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3281 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3282 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3283 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3284 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3285 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3286 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3287 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3288 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3289 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3290 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3291 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3292 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3293 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3294 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3295 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3296 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3297 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3298 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3299 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3300 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3301 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3302 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3303 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3304 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3305 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3306 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3307 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3308 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3309 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3310 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3311 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3312 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3313 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3314 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3315 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3316 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3317 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3318 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3319 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3320 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3321 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3322 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3323 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3324 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3325 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3326 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3327 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3328 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3329 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3330 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3331 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3332 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3333 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3334 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3335 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3336 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3337 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3338 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3339 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3340 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3341 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3342 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3343 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3344 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3345 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3346 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3347 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3348 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3349 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3350 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3351 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3352 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3353 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3354 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3355 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3356 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3357 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3358 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3359 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3360 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3361 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3362 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3363 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3364 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3365 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3366 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3367 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3368 # if ENABLE_ASH_ALIAS
3369 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3374 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3375 #else /* debug version, caught one signed char bug */
3376 # define SIT(c, syntax) \
3378 if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
3379 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3380 if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
3381 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3382 ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
3386 #endif /* !USE_SIT_FUNCTION */
3389 /* ============ Alias handling */
3391 #if ENABLE_ASH_ALIAS
3393 #define ALIASINUSE 1
3404 static struct alias **atab; // [ATABSIZE];
3405 #define INIT_G_alias() do { \
3406 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3410 static struct alias **
3411 __lookupalias(const char *name)
3413 unsigned int hashval;
3420 ch = (unsigned char)*p;
3424 ch = (unsigned char)*++p;
3426 app = &atab[hashval % ATABSIZE];
3428 for (; *app; app = &(*app)->next) {
3429 if (strcmp(name, (*app)->name) == 0) {
3437 static struct alias *
3438 lookupalias(const char *name, int check)
3440 struct alias *ap = *__lookupalias(name);
3442 if (check && ap && (ap->flag & ALIASINUSE))
3447 static struct alias *
3448 freealias(struct alias *ap)
3452 if (ap->flag & ALIASINUSE) {
3453 ap->flag |= ALIASDEAD;
3465 setalias(const char *name, const char *val)
3467 struct alias *ap, **app;
3469 app = __lookupalias(name);
3473 if (!(ap->flag & ALIASINUSE)) {
3476 ap->val = ckstrdup(val);
3477 ap->flag &= ~ALIASDEAD;
3480 ap = ckzalloc(sizeof(struct alias));
3481 ap->name = ckstrdup(name);
3482 ap->val = ckstrdup(val);
3483 /*ap->flag = 0; - ckzalloc did it */
3484 /*ap->next = NULL;*/
3491 unalias(const char *name)
3495 app = __lookupalias(name);
3499 *app = freealias(*app);
3510 struct alias *ap, **app;
3514 for (i = 0; i < ATABSIZE; i++) {
3516 for (ap = *app; ap; ap = *app) {
3517 *app = freealias(*app);
3527 printalias(const struct alias *ap)
3529 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3533 * TODO - sort output
3535 static int FAST_FUNC
3536 aliascmd(int argc UNUSED_PARAM, char **argv)
3545 for (i = 0; i < ATABSIZE; i++) {
3546 for (ap = atab[i]; ap; ap = ap->next) {
3552 while ((n = *++argv) != NULL) {
3553 v = strchr(n+1, '=');
3554 if (v == NULL) { /* n+1: funny ksh stuff */
3555 ap = *__lookupalias(n);
3557 fprintf(stderr, "%s: %s not found\n", "alias", n);
3570 static int FAST_FUNC
3571 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3575 while (nextopt("a") != '\0') {
3579 for (i = 0; *argptr; argptr++) {
3580 if (unalias(*argptr)) {
3581 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3589 #endif /* ASH_ALIAS */
3592 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3595 #define FORK_NOJOB 2
3597 /* mode flags for showjob(s) */
3598 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3599 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3600 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3601 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3604 * A job structure contains information about a job. A job is either a
3605 * single process or a set of processes contained in a pipeline. In the
3606 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3610 pid_t ps_pid; /* process id */
3611 int ps_status; /* last process status from wait() */
3612 char *ps_cmd; /* text of command being run */
3616 struct procstat ps0; /* status of process */
3617 struct procstat *ps; /* status of processes when more than one */
3619 int stopstatus; /* status of a stopped job */
3621 unsigned nprocs; /* number of processes */
3623 #define JOBRUNNING 0 /* at least one proc running */
3624 #define JOBSTOPPED 1 /* all procs are stopped */
3625 #define JOBDONE 2 /* all procs are completed */
3629 sigint: 1, /* job was killed by SIGINT */
3630 jobctl: 1, /* job running under job control */
3632 waited: 1, /* true if this entry has been waited for */
3633 used: 1, /* true if this entry is in used */
3634 changed: 1; /* true if status has changed */
3635 struct job *prev_job; /* previous job */
3638 static struct job *makejob(/*union node *,*/ int);
3639 static int forkshell(struct job *, union node *, int);
3640 static int waitforjob(struct job *);
3643 enum { doing_jobctl = 0 };
3644 #define setjobctl(on) do {} while (0)
3646 static smallint doing_jobctl; //references:8
3647 static void setjobctl(int);
3654 ignoresig(int signo)
3656 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3657 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3658 /* No, need to do it */
3659 signal(signo, SIG_IGN);
3661 sigmode[signo - 1] = S_HARD_IGN;
3665 * Only one usage site - in setsignal()
3668 signal_handler(int signo)
3670 if (signo == SIGCHLD) {
3676 gotsig[signo - 1] = 1;
3677 pending_sig = signo;
3679 if (signo == SIGINT && !trap[SIGINT]) {
3680 if (!suppress_int) {
3682 raise_interrupt(); /* does not return */
3689 * Set the signal handler for the specified signal. The routine figures
3690 * out what it should be set to.
3693 setsignal(int signo)
3696 char cur_act, new_act;
3697 struct sigaction act;
3701 if (t != NULL) { /* trap for this sig is set */
3703 if (t[0] == '\0') /* trap is "": ignore this sig */
3707 if (rootshell && new_act == S_DFL) {
3710 if (iflag || minusc || sflag == 0)
3719 * "In all cases, bash ignores SIGQUIT. Non-builtin
3720 * commands run by bash have signal handlers
3721 * set to the values inherited by the shell
3722 * from its parent". */
3738 /* if !rootshell, we reset SIGQUIT to DFL,
3739 * whereas we have to restore it to what shell got on entry.
3740 * This is handled by the fact that if signal was IGNored on entry,
3741 * then cur_act is S_HARD_IGN and we never change its sigaction
3745 if (signo == SIGCHLD)
3748 t = &sigmode[signo - 1];
3751 /* current setting is not yet known */
3752 if (sigaction(signo, NULL, &act)) {
3753 /* pretend it worked; maybe we should give a warning,
3754 * but other shells don't. We don't alter sigmode,
3755 * so we retry every time.
3756 * btw, in Linux it never fails. --vda */
3759 if (act.sa_handler == SIG_IGN) {
3760 cur_act = S_HARD_IGN;
3762 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3764 cur_act = S_IGN; /* don't hard ignore these */
3767 if (act.sa_handler == SIG_DFL && new_act == S_DFL) {
3768 /* installing SIG_DFL over SIG_DFL is a no-op */
3769 /* saves one sigaction call in each "sh -c SCRIPT" invocation */
3774 if (cur_act == S_HARD_IGN || cur_act == new_act)
3779 act.sa_handler = SIG_DFL;
3782 act.sa_handler = signal_handler;
3785 act.sa_handler = SIG_IGN;
3788 /* flags and mask matter only if !DFL and !IGN, but we do it
3789 * for all cases for more deterministic behavior:
3791 act.sa_flags = 0; //TODO: why not SA_RESTART?
3792 sigfillset(&act.sa_mask);
3794 sigaction_set(signo, &act);
3797 /* mode flags for set_curjob */
3798 #define CUR_DELETE 2
3799 #define CUR_RUNNING 1
3800 #define CUR_STOPPED 0
3803 /* pgrp of shell on invocation */
3804 static int initialpgrp; //references:2
3805 static int ttyfd = -1; //5
3808 static struct job *jobtab; //5
3810 static unsigned njobs; //4
3812 static struct job *curjob; //lots
3815 /* Bash has a feature: it restores termios after a successful wait for
3816 * a foreground job which had at least one stopped or sigkilled member.
3817 * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
3818 * properly restoring tty state. Should we do this too?
3819 * A reproducer: ^Z an interactive python:
3822 * Python 2.7.12 (...)
3824 * { python leaves tty in -icanon -echo state. We do survive that... }
3825 * [1]+ Stopped python
3826 * { ...however, next program (python #2) does not survive it well: }
3828 * Python 2.7.12 (...)
3829 * >>> Traceback (most recent call last):
3830 * { above, I typed "qwerty<CR>", but -echo state is still in effect }
3831 * File "<stdin>", line 1, in <module>
3832 * NameError: name 'qwerty' is not defined
3834 * The implementation below is modeled on bash code and seems to work.
3835 * However, I'm not sure we should do this. For one: what if I'd fg
3836 * the stopped python instead? It'll be confused by "restored" tty state.
3838 static struct termios shell_tty_info;
3842 if (rootshell && ttyfd >= 0)
3843 tcgetattr(ttyfd, &shell_tty_info);
3848 /* if (rootshell) - caller ensures this */
3850 tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
3853 job_signal_status(struct job *jp)
3857 struct procstat *ps = jp->ps;
3858 for (i = 0; i < jp->nprocs; i++) {
3859 status = ps[i].ps_status;
3860 if (WIFSIGNALED(status) || WIFSTOPPED(status))
3866 restore_tty_if_stopped_or_signaled(struct job *jp)
3868 //TODO: check what happens if we come from waitforjob() in expbackq()
3870 int s = job_signal_status(jp);
3871 if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
3876 # define get_tty_state() ((void)0)
3877 # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
3881 set_curjob(struct job *jp, unsigned mode)
3884 struct job **jpp, **curp;
3886 /* first remove from list */
3887 jpp = curp = &curjob;
3892 jpp = &jp1->prev_job;
3894 *jpp = jp1->prev_job;
3896 /* Then re-insert in correct position */
3904 /* job being deleted */
3907 /* newly created job or backgrounded job,
3908 * put after all stopped jobs.
3913 if (!jp1 || jp1->state != JOBSTOPPED)
3916 jpp = &jp1->prev_job;
3922 /* newly stopped job - becomes curjob */
3923 jp->prev_job = *jpp;
3931 jobno(const struct job *jp)
3933 return jp - jobtab + 1;
3938 * Convert a job name to a job structure.
3941 #define getjob(name, getctl) getjob(name)
3944 getjob(const char *name, int getctl)
3948 const char *err_msg = "%s: no such job";
3952 char *(*match)(const char *, const char *);
3967 if (c == '+' || c == '%') {
3969 err_msg = "No current job";
3975 err_msg = "No previous job";
3985 if (num > 0 && num <= njobs) {
3986 jp = jobtab + num - 1;
4001 if (match(jp->ps[0].ps_cmd, p)) {
4005 err_msg = "%s: ambiguous";
4015 err_msg = "job %s not created under job control";
4016 if (getctl && jp->jobctl == 0)
4021 ash_msg_and_raise_error(err_msg, name);
4025 * Mark a job structure as unused.
4028 freejob(struct job *jp)
4030 struct procstat *ps;
4034 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
4035 if (ps->ps_cmd != nullstr)
4038 if (jp->ps != &jp->ps0)
4041 set_curjob(jp, CUR_DELETE);
4047 xtcsetpgrp(int fd, pid_t pgrp)
4049 if (tcsetpgrp(fd, pgrp))
4050 ash_msg_and_raise_perror("can't set tty process group");
4054 * Turn job control on and off.
4056 * Note: This code assumes that the third arg to ioctl is a character
4057 * pointer, which is true on Berkeley systems but not System V. Since
4058 * System V doesn't have job control yet, this isn't a problem now.
4060 * Called with interrupts off.
4068 if (on == doing_jobctl || rootshell == 0)
4072 ofd = fd = open(_PATH_TTY, O_RDWR);
4074 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
4075 * That sometimes helps to acquire controlling tty.
4076 * Obviously, a workaround for bugs when someone
4077 * failed to provide a controlling tty to bash! :) */
4083 /* fd is a tty at this point */
4084 fd = fcntl(fd, F_DUPFD_CLOEXEC, 10);
4085 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
4088 goto out; /* F_DUPFD failed */
4089 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
4090 close_on_exec_on(fd);
4091 while (1) { /* while we are in the background */
4092 pgrp = tcgetpgrp(fd);
4095 ash_msg("can't access tty; job control turned off");
4099 if (pgrp == getpgrp())
4110 xtcsetpgrp(fd, pgrp);
4112 /* turning job control off */
4115 /* was xtcsetpgrp, but this can make exiting ash
4116 * loop forever if pty is already deleted */
4117 tcsetpgrp(fd, pgrp);
4131 static int FAST_FUNC
4132 killcmd(int argc, char **argv)
4134 if (argv[1] && strcmp(argv[1], "-l") != 0) {
4137 if (argv[i][0] == '%') {
4139 * "kill %N" - job kill
4140 * Converting to pgrp / pid kill
4146 jp = getjob(argv[i], 0);
4148 * In jobs started under job control, we signal
4149 * entire process group by kill -PGRP_ID.
4150 * This happens, f.e., in interactive shell.
4152 * Otherwise, we signal each child via
4153 * kill PID1 PID2 PID3.
4155 * sh -c 'sleep 1|sleep 1 & kill %1'
4156 * sh -c 'true|sleep 2 & sleep 1; kill %1'
4157 * sh -c 'true|sleep 1 & sleep 2; kill %1'
4159 n = jp->nprocs; /* can't be 0 (I hope) */
4162 dst = alloca(n * sizeof(int)*4);
4164 for (j = 0; j < n; j++) {
4165 struct procstat *ps = &jp->ps[j];
4166 /* Skip non-running and not-stopped members
4167 * (i.e. dead members) of the job
4169 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
4172 * kill_main has matching code to expect
4173 * leading space. Needed to not confuse
4174 * negative pids with "kill -SIGNAL_NO" syntax
4176 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
4180 } while (argv[++i]);
4182 return kill_main(argc, argv);
4186 showpipe(struct job *jp /*, FILE *out*/)
4188 struct procstat *ps;
4189 struct procstat *psend;
4191 psend = jp->ps + jp->nprocs;
4192 for (ps = jp->ps + 1; ps < psend; ps++)
4193 printf(" | %s", ps->ps_cmd);
4194 newline_and_flush(stdout);
4195 flush_stdout_stderr();
4200 restartjob(struct job *jp, int mode)
4202 struct procstat *ps;
4208 if (jp->state == JOBDONE)
4210 jp->state = JOBRUNNING;
4211 pgid = jp->ps[0].ps_pid;
4212 if (mode == FORK_FG) {
4214 xtcsetpgrp(ttyfd, pgid);
4216 killpg(pgid, SIGCONT);
4220 if (WIFSTOPPED(ps->ps_status)) {
4226 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
4231 static int FAST_FUNC
4232 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
4238 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
4242 jp = getjob(*argv, 1);
4243 if (mode == FORK_BG) {
4244 set_curjob(jp, CUR_RUNNING);
4245 printf("[%d] ", jobno(jp));
4247 out1str(jp->ps[0].ps_cmd);
4248 showpipe(jp /*, stdout*/);
4249 retval = restartjob(jp, mode);
4250 } while (*argv && *++argv);
4256 sprint_status48(char *os, int status, int sigonly)
4261 if (!WIFEXITED(status)) {
4263 if (WIFSTOPPED(status))
4264 st = WSTOPSIG(status);
4267 st = WTERMSIG(status);
4269 if (st == SIGINT || st == SIGPIPE)
4272 if (WIFSTOPPED(status))
4277 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
4278 //s = stpncpy(s, strsignal(st), 32); //not all libc have stpncpy()
4279 s += fmtstr(s, 32, strsignal(st));
4280 if (WCOREDUMP(status)) {
4281 s = stpcpy(s, " (core dumped)");
4283 } else if (!sigonly) {
4284 st = WEXITSTATUS(status);
4285 s += fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
4292 wait_block_or_sig(int *status)
4299 /* Poll all children for changes in their state */
4301 /* if job control is active, accept stopped processes too */
4302 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
4304 break; /* Error (e.g. EINTR, ECHILD) or pid */
4306 /* Children exist, but none are ready. Sleep until interesting signal */
4309 sigprocmask2(SIG_SETMASK, &mask); /* mask is updated */
4310 while (!got_sigchld && !pending_sig) {
4312 /* ^^^ add "sigdelset(&mask, SIGCHLD);" before sigsuspend
4313 * to make sure SIGCHLD is not masked off?
4314 * It was reported that this:
4315 * fn() { : | return; }
4319 * under bash 4.4.23 runs SCRIPT with SIGCHLD masked,
4320 * making "wait" commands in SCRIPT block forever.
4323 sigprocmask(SIG_SETMASK, &mask, NULL);
4324 #else /* unsafe: a signal can set pending_sig after check, but before pause() */
4325 while (!got_sigchld && !pending_sig)
4329 /* If it was SIGCHLD, poll children again */
4330 } while (got_sigchld);
4335 #define DOWAIT_NONBLOCK 0
4336 #define DOWAIT_BLOCK 1
4337 #define DOWAIT_BLOCK_OR_SIG 2
4339 # define DOWAIT_JOBSTATUS 0x10 /* OR this to get job's exitstatus instead of pid */
4343 waitone(int block, struct job *job)
4348 struct job *thisjob;
4350 bool want_jobexitstatus = (block & DOWAIT_JOBSTATUS);
4351 block = (block & ~DOWAIT_JOBSTATUS);
4354 TRACE(("dowait(0x%x) called\n", block));
4356 /* It's wrong to call waitpid() outside of INT_OFF region:
4357 * signal can arrive just after syscall return and handler can
4358 * longjmp away, losing stop/exit notification processing.
4359 * Thus, for "jobs" builtin, and for waiting for a fg job,
4360 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
4362 * However, for "wait" builtin it is wrong to simply call waitpid()
4363 * in INT_OFF region: "wait" needs to wait for any running job
4364 * to change state, but should exit on any trap too.
4365 * In INT_OFF region, a signal just before syscall entry can set
4366 * pending_sig variables, but we can't check them, and we would
4367 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
4369 * Because of this, we run inside INT_OFF, but use a special routine
4370 * which combines waitpid() and sigsuspend().
4371 * This is the reason why we need to have a handler for SIGCHLD:
4372 * SIG_DFL handler does not wake sigsuspend().
4375 if (block == DOWAIT_BLOCK_OR_SIG) {
4376 pid = wait_block_or_sig(&status);
4379 if (block == DOWAIT_NONBLOCK)
4380 wait_flags = WNOHANG;
4381 /* if job control is active, accept stopped processes too */
4383 wait_flags |= WUNTRACED;
4384 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4385 pid = waitpid(-1, &status, wait_flags);
4387 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4388 pid, status, errno, strerror(errno)));
4393 for (jp = curjob; jp; jp = jp->prev_job) {
4395 struct procstat *ps;
4396 struct procstat *psend;
4397 if (jp->state == JOBDONE)
4401 psend = ps + jp->nprocs;
4403 if (ps->ps_pid == pid) {
4404 TRACE(("Job %d: changing status of proc %d "
4405 "from 0x%x to 0x%x\n",
4406 jobno(jp), pid, ps->ps_status, status));
4407 ps->ps_status = status;
4410 if (ps->ps_status == -1)
4411 jobstate = JOBRUNNING;
4413 if (jobstate == JOBRUNNING)
4415 if (WIFSTOPPED(ps->ps_status)) {
4416 jp->stopstatus = ps->ps_status;
4417 jobstate = JOBSTOPPED;
4420 } while (++ps < psend);
4424 /* Found the job where one of its processes changed its state.
4425 * Is there at least one live and running process in this job? */
4426 if (jobstate != JOBRUNNING) {
4427 /* No. All live processes in the job are stopped
4428 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4430 thisjob->changed = 1;
4431 if (thisjob->state != jobstate) {
4432 TRACE(("Job %d: changing state from %d to %d\n",
4433 jobno(thisjob), thisjob->state, jobstate));
4434 thisjob->state = jobstate;
4436 if (jobstate == JOBSTOPPED)
4437 set_curjob(thisjob, CUR_STOPPED);
4443 /* The process wasn't found in job list */
4448 if (want_jobexitstatus) {
4450 if (thisjob && thisjob->state == JOBDONE)
4451 pid = thisjob->ps[thisjob->nprocs - 1].ps_status;
4454 if (thisjob && thisjob == job) {
4458 len = sprint_status48(s, status, 1);
4469 dowait(int block, struct job *jp)
4471 int pid = block == DOWAIT_NONBLOCK ? got_sigchld : 1;
4473 while (jp ? jp->state == JOBRUNNING : pid > 0) {
4476 pid = waitone(block, jp);
4484 showjob(struct job *jp, int mode)
4486 struct procstat *ps;
4487 struct procstat *psend;
4490 char s[16 + 16 + 48];
4491 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4495 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4496 /* just output process (group) id of pipeline */
4497 fprintf(out, "%d\n", ps->ps_pid);
4501 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4506 else if (curjob && jp == curjob->prev_job)
4509 if (mode & SHOW_PIDS)
4510 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4512 psend = ps + jp->nprocs;
4514 if (jp->state == JOBRUNNING) {
4515 strcpy(s + col, "Running");
4516 col += sizeof("Running") - 1;
4518 int status = psend[-1].ps_status;
4519 if (jp->state == JOBSTOPPED)
4520 status = jp->stopstatus;
4521 col += sprint_status48(s + col, status, 0);
4523 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4525 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4526 * or prints several "PID | <cmdN>" lines,
4527 * depending on SHOW_PIDS bit.
4528 * We do not print status of individual processes
4529 * between PID and <cmdN>. bash does it, but not very well:
4530 * first line shows overall job status, not process status,
4531 * making it impossible to know 1st process status.
4535 /* for each process */
4538 if (mode & SHOW_PIDS)
4539 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4541 fprintf(out, "%s%*c%s%s",
4543 33 - col >= 0 ? 33 - col : 0, ' ',
4544 ps == jp->ps ? "" : "| ",
4547 } while (++ps != psend);
4548 newline_and_flush(out);
4552 if (jp->state == JOBDONE) {
4553 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4559 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4560 * statuses have changed since the last call to showjobs.
4567 TRACE(("showjobs(0x%x) called\n", mode));
4569 /* Handle all finished jobs */
4570 dowait(DOWAIT_NONBLOCK, NULL);
4572 for (jp = curjob; jp; jp = jp->prev_job) {
4573 if (!(mode & SHOW_CHANGED) || jp->changed) {
4579 static int FAST_FUNC
4580 jobscmd(int argc UNUSED_PARAM, char **argv)
4585 while ((m = nextopt("lp")) != '\0') {
4589 mode |= SHOW_ONLY_PGID;
4595 showjob(getjob(*argv, 0), mode);
4605 /* Called only on finished or stopped jobs (no members are running) */
4607 getstatus(struct job *job)
4611 struct procstat *ps;
4613 /* Fetch last member's status */
4614 ps = job->ps + job->nprocs - 1;
4615 status = ps->ps_status;
4617 /* "set -o pipefail" mode: use last _nonzero_ status */
4618 while (status == 0 && --ps >= job->ps)
4619 status = ps->ps_status;
4622 retval = WEXITSTATUS(status);
4623 if (!WIFEXITED(status)) {
4625 retval = WSTOPSIG(status);
4626 if (!WIFSTOPPED(status))
4629 /* XXX: limits number of signals */
4630 retval = WTERMSIG(status);
4632 if (retval == SIGINT)
4638 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4639 jobno(job), job->nprocs, status, retval));
4643 static int FAST_FUNC
4644 waitcmd(int argc UNUSED_PARAM, char **argv)
4651 char one = nextopt("n");
4659 /* wait for all jobs / one job if -n */
4664 /* exitcode of "wait -n" with nothing to wait for is 127, not 0 */
4668 if (!jp) /* no running procs */
4670 if (jp->state == JOBRUNNING)
4676 * "When bash is waiting for an asynchronous command via
4677 * the wait builtin, the reception of a signal for which a trap
4678 * has been set will cause the wait builtin to return immediately
4679 * with an exit status greater than 128, immediately after which
4680 * the trap is executed."
4683 status = dowait(DOWAIT_BLOCK_OR_SIG | DOWAIT_JOBSTATUS, NULL);
4685 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4687 /* if child sends us a signal *and immediately exits*,
4688 * dowait() returns pid > 0. Check this case,
4689 * not "if (dowait() < 0)"!
4695 /* wait -n waits for one _job_, not one _process_.
4696 * date; sleep 3 & sleep 2 | sleep 1 & wait -n; date
4697 * should wait for 2 seconds. Not 1 or 3.
4699 if (status != -1 && !WIFSTOPPED(status)) {
4700 retval = WEXITSTATUS(status);
4701 if (WIFSIGNALED(status))
4702 retval = WTERMSIG(status) + 128;
4712 if (**argv != '%') {
4713 pid_t pid = number(*argv);
4718 if (job->ps[job->nprocs - 1].ps_pid == pid)
4720 job = job->prev_job;
4723 job = getjob(*argv, 0);
4725 /* loop until process terminated or stopped */
4726 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4730 retval = getstatus(job);
4737 retval = 128 + pending_sig;
4746 struct job *jp, *jq;
4748 len = njobs * sizeof(*jp);
4750 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4752 offset = (char *)jp - (char *)jq;
4754 /* Relocate pointers */
4757 jq = (struct job *)((char *)jq + l);
4761 #define joff(p) ((struct job *)((char *)(p) + l))
4762 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4763 if (joff(jp)->ps == &jq->ps0)
4764 jmove(joff(jp)->ps);
4765 if (joff(jp)->prev_job)
4766 jmove(joff(jp)->prev_job);
4776 jp = (struct job *)((char *)jp + len);
4780 } while (--jq >= jp);
4785 * Return a new job structure.
4786 * Called with interrupts off.
4789 makejob(/*union node *node,*/ int nprocs)
4794 for (i = njobs, jp = jobtab; ; jp++) {
4801 if (jp->state != JOBDONE || !jp->waited)
4810 memset(jp, 0, sizeof(*jp));
4812 /* jp->jobctl is a bitfield.
4813 * "jp->jobctl |= doing_jobctl" likely to give awful code */
4817 jp->prev_job = curjob;
4822 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4824 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4831 * Return a string identifying a command (to be printed by the
4834 static char *cmdnextc;
4837 cmdputs(const char *s)
4839 static const char vstype[VSTYPE + 1][3] = {
4840 "", "}", "-", "+", "?", "=",
4841 "%", "%%", "#", "##"
4842 IF_BASH_SUBSTR(, ":")
4843 IF_BASH_PATTERN_SUBST(, "/", "//")
4846 const char *p, *str;
4850 unsigned char subtype = 0;
4854 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4856 while ((c = *p++) != '\0') {
4864 if ((subtype & VSTYPE) == VSLENGTH)
4871 str += !(quoted & 1);
4878 #if ENABLE_FEATURE_SH_MATH
4893 if ((subtype & VSTYPE) != VSNORMAL)
4895 str = vstype[subtype & VSTYPE];
4896 if (subtype & VSNUL)
4905 /* These can only happen inside quotes */
4911 // [1]+ Done true ${\$} <<=== BUG: ${\$} is not a valid way to write $$ (${$} would be ok)
4922 while ((c = *str++) != '\0') {
4925 } /* while *p++ not NUL */
4928 USTPUTC('"', nextc);
4934 /* cmdtxt() and cmdlist() call each other */
4935 static void cmdtxt(union node *n);
4938 cmdlist(union node *np, int sep)
4940 for (; np; np = np->narg.next) {
4944 if (sep && np->narg.next)
4950 cmdtxt(union node *n)
4953 struct nodelist *lp;
4964 lp = n->npipe.cmdlist;
4982 cmdtxt(n->nbinary.ch1);
4998 cmdtxt(n->nif.test);
5000 if (n->nif.elsepart) {
5001 cmdtxt(n->nif.ifpart);
5003 n = n->nif.elsepart;
5021 cmdtxt(n->nbinary.ch1);
5031 cmdputs(n->nfor.var);
5033 cmdlist(n->nfor.args, 1);
5038 cmdputs(n->ndefun.text);
5042 cmdlist(n->ncmd.args, 1);
5043 cmdlist(n->ncmd.redirect, 0);
5056 cmdputs(n->ncase.expr->narg.text);
5058 for (np = n->ncase.cases; np; np = np->nclist.next) {
5059 cmdtxt(np->nclist.pattern);
5061 cmdtxt(np->nclist.body);
5075 #if BASH_REDIR_OUTPUT
5090 cmdputs(utoa(n->nfile.fd));
5092 if (n->type == NTOFD || n->type == NFROMFD) {
5093 if (n->ndup.dupfd >= 0)
5094 cmdputs(utoa(n->ndup.dupfd));
5105 commandtext(union node *n)
5109 STARTSTACKSTR(cmdnextc);
5111 name = stackblock();
5112 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
5113 return ckstrdup(name);
5118 * Fork off a subshell. If we are doing job control, give the subshell its
5119 * own process group. Jp is a job structure that the job is to be added to.
5120 * N is the command that will be evaluated by the child. Both jp and n may
5121 * be NULL. The mode parameter can be one of the following:
5122 * FORK_FG - Fork off a foreground process.
5123 * FORK_BG - Fork off a background process.
5124 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
5125 * process group even if job control is on.
5127 * When job control is turned off, background processes have their standard
5128 * input redirected to /dev/null (except for the second and later processes
5131 * Called with interrupts off.
5134 * Clear traps on a fork.
5142 for (tp = trap; tp < &trap[NSIG]; tp++) {
5143 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
5144 if (trap_ptr == trap)
5146 /* else: it "belongs" to trap_ptr vector, don't free */
5148 if ((tp - trap) != 0)
5149 setsignal(tp - trap);
5156 /* Lives far away from here, needed for forkchild */
5157 static void closescript(void);
5159 /* Called after fork(), in child */
5160 /* jp and n are NULL when called by openhere() for heredoc support */
5161 static NOINLINE void
5162 forkchild(struct job *jp, union node *n, int mode)
5166 TRACE(("Child shell %d\n", getpid()));
5170 /* man bash: "Non-builtin commands run by bash have signal handlers
5171 * set to the values inherited by the shell from its parent".
5172 * Do we do it correctly? */
5176 if (mode == FORK_NOJOB /* is it `xxx` ? */
5177 && n && n->type == NCMD /* is it single cmd? */
5178 /* && n->ncmd.args->type == NARG - always true? */
5179 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
5180 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
5181 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
5183 TRACE(("Trap hack\n"));
5184 /* Awful hack for `trap` or $(trap).
5186 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5187 * contains an example where "trap" is executed in a subshell:
5189 * save_traps=$(trap)
5191 * eval "$save_traps"
5193 * Standard does not say that "trap" in subshell shall print
5194 * parent shell's traps. It only says that its output
5195 * must have suitable form, but then, in the above example
5196 * (which is not supposed to be normative), it implies that.
5198 * bash (and probably other shell) does implement it
5199 * (traps are reset to defaults, but "trap" still shows them),
5200 * but as a result, "trap" logic is hopelessly messed up:
5203 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5204 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5205 * # true | trap <--- trap is in subshell - no output (ditto)
5206 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5207 * trap -- 'echo Ho' SIGWINCH
5208 * # echo `(trap)` <--- in subshell in subshell - output
5209 * trap -- 'echo Ho' SIGWINCH
5210 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5211 * trap -- 'echo Ho' SIGWINCH
5213 * The rules when to forget and when to not forget traps
5214 * get really complex and nonsensical.
5216 * Our solution: ONLY bare $(trap) or `trap` is special.
5218 /* Save trap handler strings for trap builtin to print */
5219 trap_ptr = xmemdup(trap, sizeof(trap));
5220 /* Fall through into clearing traps */
5224 /* do job control only in root shell */
5226 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
5229 if (jp->nprocs == 0)
5232 pgrp = jp->ps[0].ps_pid;
5233 /* this can fail because we are doing it in the parent also */
5235 if (mode == FORK_FG)
5236 xtcsetpgrp(ttyfd, pgrp);
5241 if (mode == FORK_BG) {
5242 /* man bash: "When job control is not in effect,
5243 * asynchronous commands ignore SIGINT and SIGQUIT" */
5246 if (jp->nprocs == 0) {
5248 if (open(bb_dev_null, O_RDONLY) != 0)
5249 ash_msg_and_raise_perror("can't open '%s'", bb_dev_null);
5253 if (iflag) { /* why if iflag only? */
5258 * "In all cases, bash ignores SIGQUIT. Non-builtin
5259 * commands run by bash have signal handlers
5260 * set to the values inherited by the shell
5262 * Take care of the second rule: */
5266 if (n && n->type == NCMD
5267 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
5269 TRACE(("Job hack\n"));
5270 /* "jobs": we do not want to clear job list for it,
5271 * instead we remove only _its_ own_ job from job list.
5272 * This makes "jobs .... | cat" more useful.
5278 for (jp = curjob; jp; jp = jp->prev_job)
5282 /* Called after fork(), in parent */
5284 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
5287 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
5289 TRACE(("In parent shell: child = %d\n", pid));
5290 if (!jp) /* jp is NULL when called by openhere() for heredoc support */
5293 if (mode != FORK_NOJOB && jp->jobctl) {
5296 if (jp->nprocs == 0)
5299 pgrp = jp->ps[0].ps_pid;
5300 /* This can fail because we are doing it in the child also */
5304 if (mode == FORK_BG) {
5305 backgndpid = pid; /* set $! */
5306 set_curjob(jp, CUR_RUNNING);
5309 struct procstat *ps = &jp->ps[jp->nprocs++];
5312 ps->ps_cmd = nullstr;
5314 if (doing_jobctl && n)
5315 ps->ps_cmd = commandtext(n);
5320 /* jp and n are NULL when called by openhere() for heredoc support */
5322 forkshell(struct job *jp, union node *n, int mode)
5326 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
5329 TRACE(("Fork failed, errno=%d", errno));
5332 ash_msg_and_raise_perror("can't fork");
5335 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
5336 forkchild(jp, n, mode);
5338 forkparent(jp, n, mode, pid);
5344 * Wait for job to finish.
5346 * Under job control we have the problem that while a child process
5347 * is running interrupts generated by the user are sent to the child
5348 * but not to the shell. This means that an infinite loop started by
5349 * an interactive user may be hard to kill. With job control turned off,
5350 * an interactive user may place an interactive program inside a loop.
5351 * If the interactive program catches interrupts, the user doesn't want
5352 * these interrupts to also abort the loop. The approach we take here
5353 * is to have the shell ignore interrupt signals while waiting for a
5354 * foreground process to terminate, and then send itself an interrupt
5355 * signal if the child process was terminated by an interrupt signal.
5356 * Unfortunately, some programs want to do a bit of cleanup and then
5357 * exit on interrupt; unless these processes terminate themselves by
5358 * sending a signal to themselves (instead of calling exit) they will
5359 * confuse this approach.
5361 * Called with interrupts off.
5364 waitforjob(struct job *jp)
5368 TRACE(("waitforjob(%%%d) called\n", jp ? jobno(jp) : 0));
5370 /* In non-interactive shells, we _can_ get
5371 * a keyboard signal here and be EINTRed, but we just loop
5372 * inside dowait(), waiting for command to complete.
5375 * "If bash is waiting for a command to complete and receives
5376 * a signal for which a trap has been set, the trap
5377 * will not be executed until the command completes."
5379 * Reality is that even if trap is not set, bash
5380 * will not act on the signal until command completes.
5381 * Try this. sleep5intoff.c:
5382 * #include <signal.h>
5383 * #include <unistd.h>
5386 * sigemptyset(&set);
5387 * sigaddset(&set, SIGINT);
5388 * sigaddset(&set, SIGQUIT);
5389 * sigprocmask(SIG_BLOCK, &set, NULL);
5393 * $ bash -c './sleep5intoff; echo hi'
5394 * ^C^C^C^C <--- pressing ^C once a second
5396 * $ bash -c './sleep5intoff; echo hi'
5397 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
5400 dowait(jp ? DOWAIT_BLOCK : DOWAIT_NONBLOCK, jp);
5407 xtcsetpgrp(ttyfd, rootpid);
5408 restore_tty_if_stopped_or_signaled(jp);
5411 * This is truly gross.
5412 * If we're doing job control, then we did a TIOCSPGRP which
5413 * caused us (the shell) to no longer be in the controlling
5414 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
5415 * intuit from the subprocess exit status whether a SIGINT
5416 * occurred, and if so interrupt ourselves. Yuck. - mycroft
5418 if (jp->sigint) /* TODO: do the same with all signals */
5419 raise(SIGINT); /* ... by raise(jp->sig) instead? */
5421 if (jp->state == JOBDONE)
5428 * return 1 if there are stopped jobs, otherwise 0
5440 if (jp && jp->state == JOBSTOPPED) {
5441 out2str("You have stopped jobs.\n");
5451 * Code for dealing with input/output redirection.
5456 #define EMPTY -2 /* marks an unused slot in redirtab */
5457 #define CLOSED -1 /* marks a slot of previously-closed fd */
5460 * Handle here documents. Normally we fork off a process to write the
5461 * data to a pipe. If the document is short, we can stuff the data in
5462 * the pipe without forking.
5464 /* openhere needs this forward reference */
5465 static void expandhere(union node *arg, int fd);
5467 openhere(union node *redir)
5473 ash_msg_and_raise_perror("can't create pipe");
5474 if (redir->type == NHERE) {
5475 len = strlen(redir->nhere.doc->narg.text);
5476 if (len <= PIPE_BUF) {
5477 full_write(pip[1], redir->nhere.doc->narg.text, len);
5481 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5484 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5485 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5486 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5487 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5488 signal(SIGPIPE, SIG_DFL);
5489 if (redir->type == NHERE)
5490 full_write(pip[1], redir->nhere.doc->narg.text, len);
5492 expandhere(redir->nhere.doc, pip[1]);
5493 _exit(EXIT_SUCCESS);
5501 openredirect(union node *redir)
5507 switch (redir->nfile.type) {
5508 /* Can't happen, our single caller does this itself */
5514 return openhere(redir);
5517 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5518 * allocated space. Do it only when we know it is safe.
5520 fname = redir->nfile.expfname;
5522 switch (redir->nfile.type) {
5528 f = open(fname, O_RDONLY);
5533 f = open(fname, O_RDWR|O_CREAT, 0666);
5538 #if BASH_REDIR_OUTPUT
5541 /* Take care of noclobber mode. */
5543 if (stat(fname, &sb) < 0) {
5544 f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5547 } else if (!S_ISREG(sb.st_mode)) {
5548 f = open(fname, O_WRONLY, 0666);
5551 if (!fstat(f, &sb) && S_ISREG(sb.st_mode)) {
5564 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5569 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5577 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5579 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5583 * Copy a file descriptor to be >= 10. Throws exception on error.
5591 newfd = fcntl(from, F_DUPFD_CLOEXEC, 10);
5592 err = newfd < 0 ? errno : 0;
5595 ash_msg_and_raise_perror("%d", from);
5597 if (F_DUPFD_CLOEXEC == F_DUPFD)
5598 close_on_exec_on(newfd);
5604 dup2_or_raise(int from, int to)
5608 newfd = (from != to) ? dup2(from, to) : to;
5610 /* Happens when source fd is not open: try "echo >&99" */
5611 ash_msg_and_raise_perror("%d", from);
5616 dup_CLOEXEC(int fd, int avoid_fd)
5620 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
5622 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
5623 close_on_exec_on(newfd);
5624 } else { /* newfd < 0 */
5633 xdup_CLOEXEC_and_close(int fd, int avoid_fd)
5637 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
5643 /* fd was not open? */
5646 ash_msg_and_raise_perror("%d", newfd);
5648 if (F_DUPFD_CLOEXEC == F_DUPFD)
5649 close_on_exec_on(newfd);
5654 /* Struct def and variable are moved down to the first usage site */
5660 struct redirtab *next;
5662 struct squirrel two_fd[];
5664 #define redirlist (G_var.redirlist)
5667 add_squirrel_closed(struct redirtab *sq, int fd)
5674 for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
5675 /* If we collide with an already moved fd... */
5676 if (fd == sq->two_fd[i].orig_fd) {
5678 * "echo 3>FILE 3>&- 3>FILE"
5679 * "echo 3>&- 3>FILE"
5680 * No need for last redirect to insert
5681 * another "need to close 3" indicator.
5683 TRACE(("redirect_fd %d: already moved or closed\n", fd));
5687 TRACE(("redirect_fd %d: previous fd was closed\n", fd));
5688 sq->two_fd[i].orig_fd = fd;
5689 sq->two_fd[i].moved_to = CLOSED;
5693 save_fd_on_redirect(int fd, int avoid_fd, struct redirtab *sq)
5697 if (avoid_fd < 9) /* the important case here is that it can be -1 */
5702 /* Testcase: "ls -l /proc/$$/fd 10>&-" should work */
5703 ttyfd = xdup_CLOEXEC_and_close(ttyfd, avoid_fd);
5704 TRACE(("redirect_fd %d: matches ttyfd, moving it to %d\n", fd, ttyfd));
5705 return 1; /* "we closed fd" */
5708 /* Are we called from redirect(0)? E.g. redirect
5709 * in a forked child. No need to save fds,
5710 * we aren't going to use them anymore, ok to trash.
5715 /* If this one of script's fds? */
5717 struct parsefile *pf = g_parsefile;
5719 /* We skip fd == 0 case because of the following:
5720 * $ ash # running ash interactively
5722 * and in script.sh: "exec 9>&0".
5723 * Even though top-level pf_fd _is_ 0,
5724 * it's still ok to use it: "read" builtin uses it,
5725 * why should we cripple "exec" builtin?
5727 if (fd == pf->pf_fd) {
5728 pf->pf_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
5729 return 1; /* "we closed fd" */
5735 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
5737 /* First: do we collide with some already moved fds? */
5738 for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
5739 /* If we collide with an already moved fd... */
5740 if (fd == sq->two_fd[i].moved_to) {
5741 new_fd = dup_CLOEXEC(fd, avoid_fd);
5742 sq->two_fd[i].moved_to = new_fd;
5743 TRACE(("redirect_fd %d: already busy, moving to %d\n", fd, new_fd));
5744 if (new_fd < 0) /* what? */
5746 return 0; /* "we did not close fd" */
5748 if (fd == sq->two_fd[i].orig_fd) {
5749 /* Example: echo Hello >/dev/null 1>&2 */
5750 TRACE(("redirect_fd %d: already moved\n", fd));
5751 return 0; /* "we did not close fd" */
5755 /* If this fd is open, we move and remember it; if it's closed, new_fd = CLOSED (-1) */
5756 new_fd = dup_CLOEXEC(fd, avoid_fd);
5757 TRACE(("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, new_fd));
5761 /* new_fd = CLOSED; - already is -1 */
5763 sq->two_fd[i].moved_to = new_fd;
5764 sq->two_fd[i].orig_fd = fd;
5766 /* if we move stderr, let "set -x" code know */
5767 if (fd == preverrout_fd)
5768 preverrout_fd = new_fd;
5770 return 0; /* "we did not close fd" */
5774 internally_opened_fd(int fd, struct redirtab *sq)
5781 /* If this one of script's fds? */
5783 struct parsefile *pf = g_parsefile;
5785 if (fd == pf->pf_fd)
5791 if (sq) for (i = 0; i < sq->pair_count && sq->two_fd[i].orig_fd != EMPTY; i++) {
5792 if (fd == sq->two_fd[i].moved_to)
5799 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5800 * old file descriptors are stashed away so that the redirection can be
5801 * undone by calling popredir.
5803 /* flags passed to redirect */
5804 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5806 redirect(union node *redir, int flags)
5808 struct redirtab *sv;
5815 if (flags & REDIR_PUSH)
5823 fd = redir->nfile.fd;
5824 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5825 //bb_error_msg("doing %d > %d", fd, newfd);
5826 newfd = redir->ndup.dupfd;
5829 newfd = openredirect(redir); /* always >= 0 */
5831 /* open() gave us precisely the fd we wanted.
5832 * This means that this fd was not busy
5833 * (not opened to anywhere).
5834 * Remember to close it on restore:
5836 add_squirrel_closed(sv, fd);
5845 /* if "N>FILE": move newfd to fd */
5846 /* if "N>&M": dup newfd to fd */
5847 /* if "N>&-": close fd (newfd is -1) */
5849 IF_BASH_REDIR_OUTPUT(redirect_more:)
5851 closed = save_fd_on_redirect(fd, /*avoid:*/ newfd, sv);
5853 /* "N>&-" means "close me" */
5855 /* ^^^ optimization: saving may already
5856 * have closed it. If not... */
5860 /* if newfd is a script fd or saved fd, simulate EBADF */
5861 if (internally_opened_fd(newfd, sv)) {
5863 ash_msg_and_raise_perror("%d", newfd);
5865 dup2_or_raise(newfd, fd);
5866 if (close_fd >= 0) /* "N>FILE" or ">&FILE" or heredoc? */
5868 #if BASH_REDIR_OUTPUT
5869 if (redir->nfile.type == NTO2 && fd == 1) {
5870 /* ">&FILE". we already redirected to 1, now copy 1 to 2 */
5878 } while ((redir = redir->nfile.next) != NULL);
5881 //dash:#define REDIR_SAVEFD2 03 /* set preverrout */
5882 #define REDIR_SAVEFD2 0
5883 // dash has a bug: since REDIR_SAVEFD2=3 and REDIR_PUSH=1, this test
5884 // triggers for pure REDIR_PUSH too. Thus, this is done almost always,
5885 // not only for calls with flags containing REDIR_SAVEFD2.
5886 // We do this unconditionally (see save_fd_on_redirect()).
5887 //if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5888 // preverrout_fd = copied_fd2;
5892 redirectsafe(union node *redir, int flags)
5895 volatile int saveint;
5896 struct jmploc *volatile savehandler = exception_handler;
5897 struct jmploc jmploc;
5900 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5901 err = setjmp(jmploc.loc); /* was = setjmp(jmploc.loc) * 2; */
5903 exception_handler = &jmploc;
5904 redirect(redir, flags);
5906 exception_handler = savehandler;
5907 if (err && exception_type != EXERROR)
5908 longjmp(exception_handler->loc, 1);
5909 RESTORE_INT(saveint);
5913 static struct redirtab*
5914 pushredir(union node *redir)
5916 struct redirtab *sv;
5925 #if BASH_REDIR_OUTPUT
5926 if (redir->nfile.type == NTO2)
5929 redir = redir->nfile.next;
5932 sv = ckzalloc(sizeof(*sv) + i * sizeof(sv->two_fd[0]));
5935 sv->two_fd[i].orig_fd = sv->two_fd[i].moved_to = EMPTY;
5936 sv->next = redirlist;
5942 * Undo the effects of the last redirection.
5947 struct redirtab *rp;
5950 if (redirlist == NULL)
5954 for (i = 0; i < rp->pair_count; i++) {
5955 int fd = rp->two_fd[i].orig_fd;
5956 int copy = rp->two_fd[i].moved_to;
5957 if (copy == CLOSED) {
5962 if (copy != EMPTY) {
5965 dup2_or_raise(copy, fd);
5970 redirlist = rp->next;
5976 unwindredir(struct redirtab *stop)
5978 while (redirlist != stop)
5979 popredir(/*drop:*/ 0);
5983 /* ============ Routines to expand arguments to commands
5985 * We have to deal with backquotes, shell variables, and file metacharacters.
5988 #if ENABLE_FEATURE_SH_MATH
5990 ash_arith(const char *s)
5992 arith_state_t math_state;
5995 math_state.lookupvar = lookupvar;
5996 math_state.setvar = setvar0;
5997 //math_state.endofname = endofname;
6000 result = arith(&math_state, s);
6001 if (math_state.errmsg)
6002 ash_msg_and_raise_error(math_state.errmsg);
6009 # if ENABLE_FEATURE_SH_MATH
6010 static int substr_atoi(const char *s)
6012 arith_t t = ash_arith(s);
6013 if (sizeof(t) > sizeof(int)) {
6014 /* clamp very large or very large negative nums for ${v:N:M}:
6015 * else "${v:0:0x100000001}" would work as "${v:0:1}"
6025 # define substr_atoi(s) number(s)
6032 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
6033 #define EXP_TILDE 0x2 /* do normal tilde expansion */
6034 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
6035 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
6036 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
6037 * POSIX says for this case:
6038 * Pathname expansion shall not be performed on the word by a
6039 * non-interactive shell; an interactive shell may perform it, but shall
6040 * do so only when the expansion would result in one word.
6041 * Currently, our code complies to the above rule by never globbing
6042 * redirection filenames.
6043 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
6044 * (this means that on a typical Linux distro, bash almost always
6045 * performs globbing, and thus diverges from what we do).
6047 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
6048 #define EXP_VARTILDE2 0x20 /* expand tildes after colons only */
6049 #define EXP_WORD 0x40 /* expand word in parameter expansion */
6050 #define EXP_QUOTED 0x100 /* expand word in double quotes */
6054 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
6055 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
6056 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
6057 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
6059 /* Add CTLESC when necessary. */
6060 #define QUOTES_ESC (EXP_FULL | EXP_CASE)
6061 /* Do not skip NUL characters. */
6062 #define QUOTES_KEEPNUL EXP_TILDE
6065 * Structure specifying which parts of the string should be searched
6066 * for IFS characters.
6069 struct ifsregion *next; /* next region in list */
6070 int begoff; /* offset of start of region */
6071 int endoff; /* offset of end of region */
6072 int nulonly; /* search for nul bytes only */
6076 struct strlist *list;
6077 struct strlist **lastp;
6080 /* output of current string */
6081 static char *expdest;
6082 /* list of back quote expressions */
6083 static struct nodelist *argbackq;
6084 /* first struct in list of ifs regions */
6085 static struct ifsregion ifsfirst;
6086 /* last struct in list */
6087 static struct ifsregion *ifslastp;
6088 /* holds expanded arg list */
6089 static struct arglist exparg;
6093 * cvtnum() is used even if math support is off (to prepare $? values and such).
6100 /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
6101 len = sizeof(arith_t) * 3;
6102 /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
6103 if (sizeof(arith_t) < 4) len += 2;
6105 expdest = makestrspace(len, expdest);
6106 len = fmtstr(expdest, len, ARITH_FMT, num);
6107 STADJUST(len, expdest);
6112 * Break the argument string into pieces based upon IFS and add the
6113 * strings to the argument list. The regions of the string to be
6114 * searched for IFS characters have been stored by recordregion.
6117 ifsbreakup(char *string, struct arglist *arglist)
6119 struct ifsregion *ifsp;
6124 const char *ifs, *realifs;
6129 if (ifslastp != NULL) {
6132 realifs = ifsset() ? ifsval() : defifs;
6137 p = string + ifsp->begoff;
6139 nulonly = ifsp->nulonly;
6140 ifs = nulonly ? nullstr : realifs;
6142 while (p < string + ifsp->endoff) {
6144 if ((unsigned char)*p == CTLESC)
6146 if (!strchr(ifs, *p)) {
6150 if (!(afternul || nulonly))
6151 ifsspc = (strchr(defifs, *p) != NULL);
6152 /* Ignore IFS whitespace at start */
6153 if (q == start && ifsspc) {
6159 sp = stzalloc(sizeof(*sp));
6161 *arglist->lastp = sp;
6162 arglist->lastp = &sp->next;
6166 if (p >= string + ifsp->endoff) {
6170 if ((unsigned char)*p == CTLESC)
6172 if (strchr(ifs, *p) == NULL) {
6176 if (strchr(defifs, *p) == NULL) {
6191 } while (ifsp != NULL);
6200 sp = stzalloc(sizeof(*sp));
6202 *arglist->lastp = sp;
6203 arglist->lastp = &sp->next;
6209 struct ifsregion *p = ifsfirst.next;
6216 struct ifsregion *ifsp;
6221 ifsfirst.next = NULL;
6228 esclen(const char *start, const char *p)
6232 while (p > start && (unsigned char)*--p == CTLESC) {
6239 * Remove any CTLESC characters from a string.
6241 #if !BASH_PATTERN_SUBST
6242 #define rmescapes(str, flag, slash_position) \
6243 rmescapes(str, flag)
6246 rmescapes(char *str, int flag, int *slash_position)
6248 static const char qchars[] ALIGN1 = {
6249 IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
6252 unsigned protect_against_glob;
6255 p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash_position));
6261 if (flag & RMESCAPE_ALLOC) {
6262 size_t len = p - str;
6263 size_t fulllen = len + strlen(p) + 1;
6265 if (flag & RMESCAPE_GROW) {
6266 int strloc = str - (char *)stackblock();
6267 r = makestrspace(fulllen, expdest);
6268 /* p and str may be invalidated by makestrspace */
6269 str = (char *)stackblock() + strloc;
6271 } else if (flag & RMESCAPE_HEAP) {
6272 r = ckmalloc(fulllen);
6274 r = stalloc(fulllen);
6278 q = (char *)mempcpy(q, str, len);
6282 globbing = flag & RMESCAPE_GLOB;
6283 protect_against_glob = globbing;
6285 if ((unsigned char)*p == CTLQUOTEMARK) {
6286 // Note: protect_against_glob only affect whether
6287 // CTLESC,<ch> gets converted to <ch> or to \<ch>
6289 protect_against_glob = globbing;
6293 /* naked back slash */
6294 protect_against_glob = 0;
6297 if ((unsigned char)*p == CTLESC) {
6301 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
6303 if (protect_against_glob) {
6305 * We used to trust glob() and fnmatch() to eat
6306 * superfluous escapes (\z where z has no
6307 * special meaning anyway). But this causes
6308 * bugs such as string of one greek letter rho
6309 * (unicode-encoded as two bytes "cf,81")
6310 * getting encoded as "cf,CTLESC,81"
6311 * and here, converted to "cf,\,81" -
6312 * which does not go well with some flavors
6313 * of fnmatch() in unicode locales
6314 * (for example, glibc <= 2.22).
6316 * Lets add "\" only on the chars which need it.
6317 * Testcases for less obvious chars are shown.
6322 || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
6323 || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
6324 || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
6325 || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
6326 /* Some libc support [^negate], that's why "^" also needs love */
6327 || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
6333 #if BASH_PATTERN_SUBST
6334 else if (slash_position && p == str + *slash_position) {
6335 /* stop handling globbing */
6337 *slash_position = q - r;
6338 slash_position = NULL;
6341 protect_against_glob = globbing;
6346 if (flag & RMESCAPE_GROW) {
6348 STADJUST(q - r + 1, expdest);
6352 #define pmatch(a, b) !fnmatch((a), (b), 0)
6355 * Prepare a pattern for a expmeta (internal glob(3)) call.
6357 * Returns an stalloced string.
6360 preglob(const char *pattern, int flag)
6362 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB, NULL);
6366 * Put a string on the stack.
6369 memtodest(const char *p, size_t len, int syntax, int quotes)
6376 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
6379 unsigned char c = *p++;
6381 if (quotes & QUOTES_ESC) {
6382 int n = SIT(c, syntax);
6384 || (syntax != BASESYNTAX && n == CBACK)
6389 } else if (!(quotes & QUOTES_KEEPNUL))
6398 strtodest(const char *p, int syntax, int quotes)
6400 size_t len = strlen(p);
6401 memtodest(p, len, syntax, quotes);
6406 * Record the fact that we have to scan this region of the
6407 * string for IFS characters.
6410 recordregion(int start, int end, int nulonly)
6412 struct ifsregion *ifsp;
6414 if (ifslastp == NULL) {
6418 ifsp = ckzalloc(sizeof(*ifsp));
6419 /*ifsp->next = NULL; - ckzalloc did it */
6420 ifslastp->next = ifsp;
6424 ifslastp->begoff = start;
6425 ifslastp->endoff = end;
6426 ifslastp->nulonly = nulonly;
6430 removerecordregions(int endoff)
6432 if (ifslastp == NULL)
6435 if (ifsfirst.endoff > endoff) {
6436 while (ifsfirst.next) {
6437 struct ifsregion *ifsp;
6439 ifsp = ifsfirst.next->next;
6440 free(ifsfirst.next);
6441 ifsfirst.next = ifsp;
6444 if (ifsfirst.begoff > endoff) {
6447 ifslastp = &ifsfirst;
6448 ifsfirst.endoff = endoff;
6453 ifslastp = &ifsfirst;
6454 while (ifslastp->next && ifslastp->next->begoff < endoff)
6455 ifslastp = ifslastp->next;
6456 while (ifslastp->next) {
6457 struct ifsregion *ifsp;
6459 ifsp = ifslastp->next->next;
6460 free(ifslastp->next);
6461 ifslastp->next = ifsp;
6464 if (ifslastp->endoff > endoff)
6465 ifslastp->endoff = endoff;
6469 exptilde(char *startp, char *p, int flags)
6475 int quotes = flags & QUOTES_ESC;
6479 while ((c = *++p) != '\0') {
6486 if (flags & EXP_VARTILDE)
6496 if (*name == '\0') {
6497 home = lookupvar("HOME");
6499 pw = getpwnam(name);
6507 strtodest(home, SQSYNTAX, quotes);
6515 * Execute a command inside back quotes. If it's a builtin command, we
6516 * want to save its output in a block obtained from malloc. Otherwise
6517 * we fork off a subprocess and get the output of the command via a pipe.
6518 * Should be called with interrupts off.
6520 struct backcmd { /* result of evalbackcmd */
6521 int fd; /* file descriptor to read from */
6522 int nleft; /* number of chars in buffer */
6523 char *buf; /* buffer */
6524 struct job *jp; /* job structure for command */
6527 /* These forward decls are needed to use "eval" code for backticks handling: */
6528 /* flags in argument to evaltree */
6529 #define EV_EXIT 01 /* exit after evaluating tree */
6530 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
6531 static int evaltree(union node *, int);
6533 /* An evaltree() which is known to never return.
6534 * Used to use an alias:
6535 * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
6536 * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
6538 static ALWAYS_INLINE NORETURN void
6539 evaltreenr(union node *n, int flags)
6542 bb_unreachable(abort());
6546 static void FAST_FUNC
6547 evalbackcmd(union node *n, struct backcmd *result)
6561 ash_msg_and_raise_perror("can't create pipe");
6562 jp = makejob(/*n,*/ 1);
6563 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6569 dup2_or_raise(pip[1], 1);
6572 /* TODO: eflag clearing makes the following not abort:
6573 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6574 * which is what bash does (unless it is in POSIX mode).
6575 * dash deleted "eflag = 0" line in the commit
6576 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6577 * [EVAL] Don't clear eflag in evalbackcmd
6578 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6582 evaltreenr(n, EV_EXIT);
6587 result->fd = pip[0];
6591 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6592 result->fd, result->buf, result->nleft, result->jp));
6596 * Expand stuff in backwards quotes.
6599 expbackq(union node *cmd, int flag)
6607 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6608 struct stackmark smark;
6611 startloc = expdest - (char *)stackblock();
6612 pushstackmark(&smark, startloc);
6613 evalbackcmd(cmd, &in);
6614 popstackmark(&smark);
6621 memtodest(p, i, syntax, flag & QUOTES_ESC);
6625 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6626 TRACE(("expbackq: read returns %d\n", i));
6635 back_exitstatus = waitforjob(in.jp);
6639 /* Eat all trailing newlines */
6641 for (; dest > ((char *)stackblock() + startloc) && dest[-1] == '\n';)
6645 if (!(flag & EXP_QUOTED))
6646 recordregion(startloc, dest - (char *)stackblock(), 0);
6647 TRACE(("evalbackq: size:%d:'%.*s'\n",
6648 (int)((dest - (char *)stackblock()) - startloc),
6649 (int)((dest - (char *)stackblock()) - startloc),
6650 stackblock() + startloc));
6653 #if ENABLE_FEATURE_SH_MATH
6655 * Expand arithmetic expression. Backup to start of expression,
6656 * evaluate, place result in (backed up) result, adjust string position.
6668 * This routine is slightly over-complicated for
6669 * efficiency. Next we scan backwards looking for the
6670 * start of arithmetic.
6672 start = stackblock();
6679 while ((unsigned char)*p != CTLARI) {
6683 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6688 esc = esclen(start, p);
6698 removerecordregions(begoff);
6702 if (flag & QUOTES_ESC)
6703 rmescapes(p + 1, 0, NULL);
6705 len = cvtnum(ash_arith(p + 1));
6707 if (!(flag & EXP_QUOTED))
6708 recordregion(begoff, begoff + len, 0);
6712 /* argstr needs it */
6713 static char *evalvar(char *p, int flags);
6716 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6717 * characters to allow for further processing. Otherwise treat
6718 * $@ like $* since no splitting will be performed.
6721 argstr(char *p, int flags)
6723 static const char spclchars[] ALIGN1 = {
6731 #if ENABLE_FEATURE_SH_MATH
6736 const char *reject = spclchars;
6737 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6742 if (!(flags & EXP_VARTILDE)) {
6744 } else if (flags & EXP_VARTILDE2) {
6749 if (flags & EXP_TILDE) {
6752 flags &= ~EXP_TILDE;
6756 p = exptilde(p, q, flags);
6759 startloc = expdest - (char *)stackblock();
6763 length += strcspn(p + length, reject);
6767 IF_FEATURE_SH_MATH(|| c == CTLENDARI)
6769 /* c == '=' || c == ':' || c == CTLENDARI */
6775 expdest = stack_nputstr(p, length, expdest);
6776 newloc = expdest - (char *)stackblock();
6777 if (breakall && !inquotes && newloc > startloc) {
6778 recordregion(startloc, newloc, 0);
6789 if (flags & EXP_VARTILDE2) {
6793 flags |= EXP_VARTILDE2;
6798 * sort of a hack - expand tildes in variable
6799 * assignments (after the first '=' and after ':'s).
6808 case CTLENDVAR: /* ??? */
6811 /* "$@" syntax adherence hack */
6812 if (!inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6813 p = evalvar(p + 1, flags | EXP_QUOTED) + 1;
6816 inquotes ^= EXP_QUOTED;
6818 if (flags & QUOTES_ESC) {
6829 TRACE(("argstr: evalvar('%s')\n", p));
6830 p = evalvar(p, flags | inquotes);
6831 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6834 expbackq(argbackq->n, flags | inquotes);
6835 argbackq = argbackq->next;
6837 #if ENABLE_FEATURE_SH_MATH
6840 expari(flags | inquotes);
6849 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6850 char *pattern, int quotes, int zero)
6859 const char *s = loc2;
6866 match = pmatch(pattern, s);
6871 if (quotes && (unsigned char)*loc == CTLESC)
6880 scanright(char *startp, char *rmesc, char *rmescend,
6881 char *pattern, int quotes, int match_at_start)
6883 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6884 int try2optimize = match_at_start;
6890 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6891 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6892 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6894 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6895 * and on each iteration they go back two/one char until they reach the beginning.
6896 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6898 /* TODO: document in what other circumstances we are called. */
6900 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6903 const char *s = loc2;
6904 if (match_at_start) {
6908 match = pmatch(pattern, s);
6909 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6913 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6915 /* Maybe we can optimize this:
6916 * if pattern ends with unescaped *, we can avoid checking
6917 * shorter strings: if "foo*" doesn't match "raw_value_of_v",
6918 * it won't match truncated "raw_value_of_" strings too.
6920 unsigned plen = strlen(pattern);
6921 /* Does it end with "*"? */
6922 if (plen != 0 && pattern[--plen] == '*') {
6923 /* "xxxx*" is not escaped */
6924 /* "xxx\*" is escaped */
6925 /* "xx\\*" is not escaped */
6926 /* "x\\\*" is escaped */
6928 while (plen != 0 && pattern[--plen] == '\\')
6931 break; /* ends with unescaped "*" */
6939 esc = esclen(startp, loc);
6950 static void varunset(const char *, const char *, const char *, int) NORETURN;
6952 varunset(const char *end, const char *var, const char *umsg, int varflags)
6958 msg = "parameter not set";
6960 if ((unsigned char)*end == CTLENDVAR) {
6961 if (varflags & VSNUL)
6967 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6971 subevalvar(char *p, char *varname, int strloc, int subtype,
6972 int startloc, int varflags, int flag)
6974 struct nodelist *saveargbackq = argbackq;
6975 int quotes = flag & QUOTES_ESC;
6978 char *rmesc, *rmescend;
6980 int amount, resetloc;
6982 IF_BASH_PATTERN_SUBST(int workloc;)
6983 IF_BASH_PATTERN_SUBST(int slash_pos;)
6984 IF_BASH_PATTERN_SUBST(char *repl;)
6986 char *(*scan)(char*, char*, char*, char*, int, int);
6988 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6989 // p, varname, strloc, subtype, startloc, varflags, quotes);
6991 #if BASH_PATTERN_SUBST
6992 /* For "${v/pattern/repl}", we must find the delimiter _before_
6993 * argstr() call expands possible variable references in pattern:
6994 * think about "v=a; a=a/; echo ${v/$a/r}" case.
6997 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6998 /* Find '/' and replace with NUL */
7000 /* The pattern can't be empty.
7001 * IOW: if the first char after "${v//" is a slash,
7002 * it does not terminate the pattern - it's the first char of the pattern:
7003 * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
7004 * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
7009 if (*repl == '\0') {
7017 /* Handle escaped slashes, e.g. "${v/\//_}" (they are CTLESC'ed by this point) */
7018 if ((unsigned char)*repl == CTLESC && repl[1])
7024 argstr_flags = EXP_TILDE;
7025 if (subtype != VSASSIGN
7026 && subtype != VSQUESTION
7028 && subtype != VSSUBSTR
7031 /* EXP_CASE keeps CTLESC's */
7032 argstr_flags = EXP_TILDE | EXP_CASE;
7034 argstr(p, argstr_flags);
7035 //bb_error_msg("str0:'%s'", (char *)stackblock() + strloc);
7036 #if BASH_PATTERN_SUBST
7039 slash_pos = expdest - ((char *)stackblock() + strloc);
7040 STPUTC('/', expdest);
7041 //bb_error_msg("repl+1:'%s'", repl + 1);
7042 argstr(repl + 1, EXP_TILDE); /* EXP_TILDE: echo "${v/x/~}" expands ~ ! */
7046 STPUTC('\0', expdest);
7047 argbackq = saveargbackq;
7048 startp = (char *)stackblock() + startloc;
7049 //bb_error_msg("str1:'%s'", (char *)stackblock() + strloc);
7053 setvar0(varname, startp);
7054 amount = startp - expdest;
7055 STADJUST(amount, expdest);
7059 varunset(p, varname, startp, varflags);
7064 int pos, len, orig_len;
7067 loc = str = stackblock() + strloc;
7069 /* Read POS in ${var:POS:LEN} */
7070 colon = strchr(loc, ':');
7071 if (colon) *colon = '\0';
7072 pos = substr_atoi(loc);
7073 if (colon) *colon = ':';
7075 /* Read LEN in ${var:POS:LEN} */
7076 len = str - startp - 1;
7077 /* *loc != '\0', guaranteed by parser */
7080 /* Adjust the length by the number of escapes */
7081 for (ptr = startp; ptr < (str - 1); ptr++) {
7082 if ((unsigned char)*ptr == CTLESC) {
7089 if (*loc++ == ':') {
7091 len = substr_atoi(loc);
7093 /* Skip POS in ${var:POS:LEN} */
7095 while (*loc && *loc != ':')
7098 len = substr_atoi(loc);
7101 /* ${VAR:$((-n)):l} starts n chars from the end */
7102 pos = orig_len + pos;
7104 if ((unsigned)pos >= orig_len) {
7105 /* apart from obvious ${VAR:999999:l},
7106 * covers ${VAR:$((-9999999)):l} - result is ""
7113 /* ${VAR:N:-M} sets LEN to strlen()-M */
7114 len = (orig_len - pos) + len;
7116 if ((unsigned)len > (orig_len - pos))
7117 len = orig_len - pos;
7119 for (str = startp; pos; str++, pos--) {
7120 if (quotes && (unsigned char)*str == CTLESC)
7123 for (loc = startp; len; len--) {
7124 if (quotes && (unsigned char)*str == CTLESC)
7129 amount = loc - expdest;
7130 STADJUST(amount, expdest);
7133 #endif /* BASH_SUBSTR */
7136 resetloc = expdest - (char *)stackblock();
7138 #if BASH_PATTERN_SUBST
7141 /* We'll comeback here if we grow the stack while handling
7142 * a VSREPLACE or VSREPLACEALL, since our pointers into the
7143 * stack will need rebasing, and we'll need to remove our work
7149 amount = expdest - ((char *)stackblock() + resetloc);
7150 STADJUST(-amount, expdest);
7151 startp = (char *)stackblock() + startloc;
7154 rmescend = (char *)stackblock() + strloc;
7155 //bb_error_msg("str7:'%s'", rmescend);
7157 //TODO: how to handle slash_pos here if string changes (shortens?)
7158 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW, NULL);
7159 if (rmesc != startp) {
7161 startp = (char *)stackblock() + startloc;
7165 str = (char *)stackblock() + strloc;
7167 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
7168 * The result is a_\_z_c (not a\_\_z_c)!
7170 * The search pattern and replace string treat backslashes differently!
7171 * "&slash_pos" causes rmescapes() to work differently on the pattern
7172 * and string. It's only used on the first call.
7174 //bb_error_msg("str8:'%s' slash_pos:%d", str, slash_pos);
7175 rmescapes(str, RMESCAPE_GLOB,
7176 repl ? NULL : (slash_pos < 0 ? NULL : &slash_pos)
7179 #if BASH_PATTERN_SUBST
7180 workloc = expdest - (char *)stackblock();
7181 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
7186 //bb_error_msg("str9:'%s' slash_pos:%d", str, slash_pos);
7188 if (slash_pos >= 0) {
7189 repl = str + slash_pos;
7193 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
7195 /* If there's no pattern to match, return the expansion unmolested */
7204 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
7205 //bb_error_msg("scanright('%s'):'%s'", str, loc);
7207 /* No match, advance */
7208 char *restart_detect = stackblock();
7210 STPUTC(*idx, expdest);
7211 if (quotes && (unsigned char)*idx == CTLESC) {
7214 STPUTC(*idx, expdest);
7216 if (stackblock() != restart_detect)
7221 /* continue; - prone to quadratic behavior, smarter code: */
7224 if (str[0] == '*') {
7225 /* Pattern is "*foo". If "*foo" does not match "long_string",
7226 * it would never match "ong_string" etc, no point in trying.
7233 if (subtype == VSREPLACEALL) {
7235 if (quotes && (unsigned char)*idx == CTLESC)
7244 //bb_error_msg("repl:'%s'", repl);
7245 for (loc = (char*)repl; *loc; loc++) {
7246 char *restart_detect = stackblock();
7247 if (quotes && *loc == '\\') {
7248 STPUTC(CTLESC, expdest);
7251 STPUTC(*loc, expdest);
7252 if (stackblock() != restart_detect)
7257 if (subtype == VSREPLACE) {
7258 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
7260 char *restart_detect = stackblock();
7261 STPUTC(*idx, expdest);
7262 if (stackblock() != restart_detect)
7271 /* We've put the replaced text into a buffer at workloc, now
7272 * move it to the right place and adjust the stack.
7274 STPUTC('\0', expdest);
7275 startp = (char *)stackblock() + startloc;
7276 memmove(startp, (char *)stackblock() + workloc, len + 1);
7277 //bb_error_msg("startp:'%s'", startp);
7278 amount = expdest - (startp + len);
7279 STADJUST(-amount, expdest);
7282 #endif /* BASH_PATTERN_SUBST */
7284 subtype -= VSTRIMRIGHT;
7286 if (subtype < 0 || subtype > 7)
7289 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
7290 zero = subtype >> 1;
7291 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
7292 scan = (subtype & 1) ^ zero ? scanleft : scanright;
7294 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
7297 memmove(startp, loc, str - loc);
7298 loc = startp + (str - loc) - 1;
7301 amount = loc - expdest;
7302 STADJUST(amount, expdest);
7308 * Add the value of a specialized variable to the stack string.
7309 * name parameter (examples):
7310 * ash -c 'echo $1' name:'1='
7311 * ash -c 'echo $qwe' name:'qwe='
7312 * ash -c 'echo $$' name:'$='
7313 * ash -c 'echo ${$}' name:'$='
7314 * ash -c 'echo ${$##q}' name:'$=q'
7315 * ash -c 'echo ${#$}' name:'$='
7316 * note: examples with bad shell syntax:
7317 * ash -c 'echo ${#$1}' name:'$=1'
7318 * ash -c 'echo ${#1#}' name:'1=#'
7320 static NOINLINE ssize_t
7321 varvalue(char *name, int varflags, int flags, int quoted)
7328 int subtype = varflags & VSTYPE;
7329 int discard = subtype == VSPLUS || subtype == VSLENGTH;
7330 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
7333 sep = (flags & EXP_FULL) << CHAR_BIT;
7334 syntax = quoted ? DQSYNTAX : BASESYNTAX;
7344 num = shellparam.nparam;
7352 goto check_1char_name;
7354 expdest = makestrspace(NOPTS, expdest);
7355 for (i = NOPTS - 1; i >= 0; i--) {
7356 if (optlist[i] && optletters(i)) {
7357 USTPUTC(optletters(i), expdest);
7363 /* handles cases similar to ${#$1} */
7364 if (name[2] != '\0')
7365 raise_error_syntax("bad substitution");
7377 /* We will set c to 0 or ~0 depending on whether
7378 * we're doing field splitting. We won't do field
7379 * splitting if either we're quoted or sep is zero.
7381 * Instead of testing (quoted || !sep) the following
7382 * trick optimises away any branches by using the
7383 * fact that EXP_QUOTED (which is the only bit that
7384 * can be set in quoted) is the same as EXP_FULL <<
7385 * CHAR_BIT (which is the only bit that can be set
7388 #if EXP_QUOTED >> CHAR_BIT != EXP_FULL
7389 #error The following two lines expect EXP_QUOTED == EXP_FULL << CHAR_BIT
7391 c = !((quoted | ~sep) & EXP_QUOTED) - 1;
7393 sep |= ifsset() ? (unsigned char)(c & ifsval()[0]) : ' ';
7399 while ((p = *ap++) != NULL) {
7400 len += strtodest(p, syntax, quotes);
7404 memtodest(&sepc, 1, syntax, quotes);
7419 num = atoi(name); /* number(name) fails on ${N#str} etc */
7420 if (num < 0 || num > shellparam.nparam)
7422 p = num ? shellparam.p[num - 1] : arg0;
7425 /* NB: name has form "VAR=..." */
7426 p = lookupvar(name);
7431 len = strtodest(p, syntax, quotes);
7432 #if ENABLE_UNICODE_SUPPORT
7433 if (subtype == VSLENGTH && len > 0) {
7434 reinit_unicode_for_ash();
7435 if (unicode_status == UNICODE_ON) {
7436 STADJUST(-len, expdest);
7438 len = unicode_strlen(p);
7446 STADJUST(-len, expdest);
7451 * Expand a variable, and return a pointer to the next character in the
7455 evalvar(char *p, int flag)
7465 varflags = (unsigned char) *p++;
7466 subtype = varflags & VSTYPE;
7469 raise_error_syntax("bad substitution");
7471 quoted = flag & EXP_QUOTED;
7473 startloc = expdest - (char *)stackblock();
7474 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
7477 varlen = varvalue(var, varflags, flag, quoted);
7478 if (varflags & VSNUL)
7481 if (subtype == VSPLUS) {
7482 varlen = -1 - varlen;
7486 if (subtype == VSMINUS) {
7491 flag | EXP_TILDE | EXP_WORD
7498 if (subtype == VSASSIGN || subtype == VSQUESTION) {
7502 subevalvar(p, var, 0, subtype, startloc, varflags,
7503 flag & ~QUOTES_ESC);
7506 * Remove any recorded regions beyond
7509 removerecordregions(startloc);
7513 if (varlen < 0 && uflag)
7514 varunset(p, var, 0, 0);
7516 if (subtype == VSLENGTH) {
7517 cvtnum(varlen > 0 ? varlen : 0);
7521 if (subtype == VSNORMAL) {
7524 quoted = *var == '@' && shellparam.nparam;
7528 recordregion(startloc, expdest - (char *)stackblock(), quoted);
7537 case VSTRIMRIGHTMAX:
7541 #if BASH_PATTERN_SUBST
7553 * Terminate the string and start recording the pattern
7556 STPUTC('\0', expdest);
7557 patloc = expdest - (char *)stackblock();
7558 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
7559 startloc, varflags, flag)) {
7560 int amount = expdest - (
7561 (char *)stackblock() + patloc - 1
7563 STADJUST(-amount, expdest);
7565 /* Remove any recorded regions beyond start of variable */
7566 removerecordregions(startloc);
7573 if (subtype != VSNORMAL) { /* skip to end of alternative */
7576 unsigned char c = *p++;
7579 else if (c == CTLBACKQ) {
7581 argbackq = argbackq->next;
7582 } else if (c == CTLVAR) {
7583 if ((*p++ & VSTYPE) != VSNORMAL)
7585 } else if (c == CTLENDVAR) {
7595 * Add a file name to the list.
7598 addfname(const char *name)
7602 sp = stzalloc(sizeof(*sp));
7603 sp->text = sstrdup(name);
7605 exparg.lastp = &sp->next;
7608 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7610 hasmeta(const char *p)
7612 static const char chars[] ALIGN1 = {
7613 '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
7617 p = strpbrk(p, chars);
7620 switch ((unsigned char)*p) {
7624 if ((unsigned char)*p == CTLQUOTEMARK)
7626 if ((unsigned char)*p == CTLESC)
7628 if (*p == '\0') /* huh? */
7639 if (!strchr(p + 1, ']')) {
7640 /* It's not a properly closed [] pattern,
7641 * but other metas may follow. Continue checking.
7642 * my[file* _is_ globbed by bash
7643 * and matches filenames like "my[file1".
7659 /* If we want to use glob() from libc... */
7660 #if !ENABLE_ASH_INTERNAL_GLOB
7662 /* Add the result of glob() to the list */
7664 addglob(const glob_t *pglob)
7666 char **p = pglob->gl_pathv;
7673 expandmeta(struct strlist *str /*, int flag*/)
7675 /* TODO - EXP_REDIR */
7685 if (!hasmeta(str->text))
7689 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7690 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7691 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7693 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7694 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7695 // Which means you need to unescape the string, right? Not so fast:
7696 // if there _is_ a file named "file\?" (with backslash), it is returned
7697 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7698 // You DON'T KNOW by looking at the result whether you need to unescape it.
7700 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7701 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7702 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7703 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7704 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7705 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7706 i = glob(p, 0, NULL, &pglob);
7707 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7712 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7713 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7714 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7726 *exparg.lastp = str;
7727 rmescapes(str->text, 0, NULL);
7728 exparg.lastp = &str->next;
7730 default: /* GLOB_NOSPACE */
7733 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7740 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7743 * Do metacharacter (i.e. *, ?, [...]) expansion.
7745 typedef struct exp_t {
7750 expmeta(exp_t *exp, char *name, unsigned name_len, unsigned expdir_len)
7752 #define expdir exp->dir
7753 #define expdir_max exp->dir_max
7754 char *enddir = expdir + expdir_len;
7769 for (p = name; esc = 0, *p; p += esc + 1) {
7770 if (*p == '*' || *p == '?')
7772 else if (*p == '[') {
7779 if (*q == '/' || *q == '\0')
7787 if (*p == '\\' && p[1])
7789 if (p[esc] == '/') {
7792 start = p + esc + 1;
7796 if (metaflag == 0) { /* we've reached the end of the file name */
7801 if (*p == '\\' && p[1])
7805 if (lstat(expdir, &statb) == 0)
7813 if (*p == '\\' && p[1])
7816 } while (p < start);
7820 expdir_len = enddir - cp;
7826 if (*endname == 0) {
7833 name_len -= endname - name;
7840 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7841 if (dp->d_name[0] == '.' && !matchdot)
7843 if (pmatch(start, dp->d_name)) {
7845 strcpy(enddir, dp->d_name);
7851 p = stpcpy(enddir, dp->d_name);
7854 offset = p - expdir + 1;
7855 len = offset + name_len + NAME_MAX;
7856 if (len > expdir_max) {
7858 expdir = ckrealloc(expdir, len);
7862 expmeta(exp, endname, name_len, offset);
7863 enddir = expdir + expdir_len;
7869 endname[-esc - 1] = esc ? '\\' : '/';
7874 static struct strlist *
7875 msort(struct strlist *list, int len)
7877 struct strlist *p, *q = NULL;
7878 struct strlist **lpp;
7886 for (n = half; --n >= 0;) {
7890 q->next = NULL; /* terminate first half of list */
7891 q = msort(list, half); /* sort first half of list */
7892 p = msort(p, len - half); /* sort second half */
7895 #if ENABLE_LOCALE_SUPPORT
7896 if (strcoll(p->text, q->text) < 0)
7898 if (strcmp(p->text, q->text) < 0)
7922 * Sort the results of file name expansion. It calculates the number of
7923 * strings to sort and then calls msort (short for merge sort) to do the
7926 static struct strlist *
7927 expsort(struct strlist *str)
7933 for (sp = str; sp; sp = sp->next)
7935 return msort(str, len);
7939 expandmeta(struct strlist *str /*, int flag*/)
7941 /* TODO - EXP_REDIR */
7945 struct strlist **savelastp;
7952 if (!hasmeta(str->text))
7954 savelastp = exparg.lastp;
7957 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7959 exp.dir_max = len + PATH_MAX;
7960 exp.dir = ckmalloc(exp.dir_max);
7962 expmeta(&exp, p, len, 0);
7967 if (exparg.lastp == savelastp) {
7972 *exparg.lastp = str;
7973 rmescapes(str->text, 0, NULL);
7974 exparg.lastp = &str->next;
7976 *exparg.lastp = NULL;
7977 *savelastp = sp = expsort(*savelastp);
7978 while (sp->next != NULL)
7980 exparg.lastp = &sp->next;
7985 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7988 * Perform variable substitution and command substitution on an argument,
7989 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7990 * perform splitting and file name expansion. When arglist is NULL, perform
7991 * here document expansion.
7994 expandarg(union node *arg, struct arglist *arglist, int flag)
7999 argbackq = arg->narg.backquote;
8000 STARTSTACKSTR(expdest);
8001 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
8002 argstr(arg->narg.text, flag);
8003 p = _STPUTC('\0', expdest);
8005 if (arglist == NULL) {
8006 /* here document expanded */
8009 p = grabstackstr(p);
8010 TRACE(("expandarg: p:'%s'\n", p));
8011 exparg.lastp = &exparg.list;
8015 if (flag & EXP_FULL) {
8016 ifsbreakup(p, &exparg);
8017 *exparg.lastp = NULL;
8018 exparg.lastp = &exparg.list;
8019 expandmeta(exparg.list /*, flag*/);
8021 sp = stzalloc(sizeof(*sp));
8024 exparg.lastp = &sp->next;
8026 *exparg.lastp = NULL;
8028 *arglist->lastp = exparg.list;
8029 arglist->lastp = exparg.lastp;
8037 * Expand shell variables and backquotes inside a here document.
8040 expandhere(union node *arg, int fd)
8042 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
8043 full_write(fd, stackblock(), expdest - (char *)stackblock());
8047 * Returns true if the pattern matches the string.
8050 patmatch(char *pattern, const char *string)
8052 char *p = preglob(pattern, 0);
8053 int r = pmatch(p, string);
8054 //bb_error_msg("!fnmatch(pattern:'%s',str:'%s',0):%d", p, string, r);
8059 * See if a pattern matches in a case statement.
8062 casematch(union node *pattern, char *val)
8064 struct stackmark smark;
8067 setstackmark(&smark);
8068 argbackq = pattern->narg.backquote;
8069 STARTSTACKSTR(expdest);
8070 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
8071 STACKSTRNUL(expdest);
8073 result = patmatch(stackblock(), val);
8074 popstackmark(&smark);
8079 /* ============ find_command */
8083 int (*builtin)(int, char **) FAST_FUNC;
8084 /* unsigned flags; */
8086 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
8087 /* "regular" builtins always take precedence over commands,
8088 * regardless of PATH=....%builtin... position */
8089 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
8090 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
8093 smallint cmdtype; /* CMDxxx */
8096 /* index >= 0 for commands without path (slashes) */
8097 /* (TODO: what exactly does the value mean? PATH position?) */
8098 /* index == -1 for commands with slashes */
8099 /* index == (-2 - applet_no) for NOFORK applets */
8100 const struct builtincmd *cmd;
8101 struct funcnode *func;
8104 /* values of cmdtype */
8105 #define CMDUNKNOWN -1 /* no entry in table for command */
8106 #define CMDNORMAL 0 /* command is an executable program */
8107 #define CMDFUNCTION 1 /* command is a shell function */
8108 #define CMDBUILTIN 2 /* command is a shell builtin */
8110 /* action to find_command() */
8111 #define DO_ERR 0x01 /* prints errors */
8112 #define DO_ABS 0x02 /* checks absolute paths */
8113 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
8114 #define DO_ALTPATH 0x08 /* using alternate path */
8115 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
8117 static void find_command(char *, struct cmdentry *, int, const char *);
8120 /* ============ Hashing commands */
8123 * When commands are first encountered, they are entered in a hash table.
8124 * This ensures that a full path search will not have to be done for them
8125 * on each invocation.
8127 * We should investigate converting to a linear search, even though that
8128 * would make the command name "hash" a misnomer.
8132 struct tblentry *next; /* next entry in hash chain */
8133 union param param; /* definition of builtin function */
8134 smallint cmdtype; /* CMDxxx */
8135 char rehash; /* if set, cd done since entry created */
8136 char cmdname[1]; /* name of command */
8139 static struct tblentry **cmdtable;
8140 #define INIT_G_cmdtable() do { \
8141 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
8144 static int builtinloc = -1; /* index in path of %builtin, or -1 */
8148 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
8150 #if ENABLE_FEATURE_SH_STANDALONE
8151 if (applet_no >= 0) {
8152 if (APPLET_IS_NOEXEC(applet_no)) {
8156 popredir(/*drop:*/ 1);
8157 run_noexec_applet_and_exit(applet_no, cmd, argv);
8159 /* re-exec ourselves with the new arguments */
8160 execve(bb_busybox_exec_path, argv, envp);
8161 /* If they called chroot or otherwise made the binary no longer
8162 * executable, fall through */
8169 execve(cmd, argv, envp);
8170 } while (errno == EINTR);
8172 execve(cmd, argv, envp);
8175 if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
8176 /* Run "cmd" as a shell script:
8177 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
8178 * "If the execve() function fails with ENOEXEC, the shell
8179 * shall execute a command equivalent to having a shell invoked
8180 * with the command name as its first operand,
8181 * with any remaining arguments passed to the new shell"
8183 * That is, do not use $SHELL, user's shell, or /bin/sh;
8184 * just call ourselves.
8186 * Note that bash reads ~80 chars of the file, and if it sees
8187 * a zero byte before it sees newline, it doesn't try to
8188 * interpret it, but fails with "cannot execute binary file"
8189 * message and exit code 126. For one, this prevents attempts
8190 * to interpret foreign ELF binaries as shell scripts.
8192 argv[0] = (char*) cmd;
8193 cmd = bb_busybox_exec_path;
8194 /* NB: this is only possible because all callers of shellexec()
8195 * ensure that the argv[-1] slot exists!
8198 argv[0] = (char*) "ash";
8204 * Exec a program. Never returns. If you change this routine, you may
8205 * have to change the find_command routine as well.
8206 * argv[-1] must exist and be writable! See tryexec() for why.
8208 static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
8209 static void shellexec(char *prog, char **argv, const char *path, int idx)
8215 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
8217 envp = listvars(VEXPORT, VUNSET, /*strlist:*/ NULL, /*end:*/ NULL);
8218 if (strchr(prog, '/') != NULL
8219 #if ENABLE_FEATURE_SH_STANDALONE
8220 || (applet_no = find_applet_by_name(prog)) >= 0
8223 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
8224 if (applet_no >= 0) {
8225 /* We tried execing ourself, but it didn't work.
8226 * Maybe /proc/self/exe doesn't exist?
8235 while (padvance(&path, argv[0]) >= 0) {
8236 cmdname = stackblock();
8237 if (--idx < 0 && pathopt == NULL) {
8238 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
8239 if (errno != ENOENT && errno != ENOTDIR)
8245 /* Map to POSIX errors */
8257 exitstatus = exerrno;
8258 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
8259 prog, e, suppress_int));
8260 ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
8265 printentry(struct tblentry *cmdp)
8271 idx = cmdp->param.index;
8274 padvance(&path, cmdp->cmdname);
8275 } while (--idx >= 0);
8276 name = stackblock();
8277 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
8281 * Clear out command entries.
8286 struct tblentry **tblp;
8287 struct tblentry **pp;
8288 struct tblentry *cmdp;
8291 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
8293 while ((cmdp = *pp) != NULL) {
8294 if (cmdp->cmdtype == CMDNORMAL
8295 || (cmdp->cmdtype == CMDBUILTIN
8296 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
8311 * Locate a command in the command hash table. If "add" is nonzero,
8312 * add the command to the table if it is not already present. The
8313 * variable "lastcmdentry" is set to point to the address of the link
8314 * pointing to the entry, so that delete_cmd_entry can delete the
8317 * Interrupts must be off if called with add != 0.
8319 static struct tblentry **lastcmdentry;
8321 static struct tblentry *
8322 cmdlookup(const char *name, int add)
8324 unsigned int hashval;
8326 struct tblentry *cmdp;
8327 struct tblentry **pp;
8330 hashval = (unsigned char)*p << 4;
8332 hashval += (unsigned char)*p++;
8334 pp = &cmdtable[hashval % CMDTABLESIZE];
8335 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8336 if (strcmp(cmdp->cmdname, name) == 0)
8340 if (add && cmdp == NULL) {
8341 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
8343 /* + 1 - already done because
8344 * tblentry::cmdname is char[1] */);
8345 /*cmdp->next = NULL; - ckzalloc did it */
8346 cmdp->cmdtype = CMDUNKNOWN;
8347 strcpy(cmdp->cmdname, name);
8354 * Delete the command entry returned on the last lookup.
8357 delete_cmd_entry(void)
8359 struct tblentry *cmdp;
8362 cmdp = *lastcmdentry;
8363 *lastcmdentry = cmdp->next;
8364 if (cmdp->cmdtype == CMDFUNCTION)
8365 freefunc(cmdp->param.func);
8371 * Add a new command entry, replacing any existing command entry for
8372 * the same name - except special builtins.
8375 addcmdentry(char *name, struct cmdentry *entry)
8377 struct tblentry *cmdp;
8379 cmdp = cmdlookup(name, 1);
8380 if (cmdp->cmdtype == CMDFUNCTION) {
8381 freefunc(cmdp->param.func);
8383 cmdp->cmdtype = entry->cmdtype;
8384 cmdp->param = entry->u;
8388 static int FAST_FUNC
8389 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8391 struct tblentry **pp;
8392 struct tblentry *cmdp;
8394 struct cmdentry entry;
8397 if (nextopt("r") != '\0') {
8402 if (*argptr == NULL) {
8403 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8404 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8405 if (cmdp->cmdtype == CMDNORMAL)
8413 while ((name = *argptr) != NULL) {
8414 cmdp = cmdlookup(name, 0);
8416 && (cmdp->cmdtype == CMDNORMAL
8417 || (cmdp->cmdtype == CMDBUILTIN
8418 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
8425 find_command(name, &entry, DO_ERR, pathval());
8426 if (entry.cmdtype == CMDUNKNOWN)
8434 * Called when a cd is done. Marks all commands so the next time they
8435 * are executed they will be rehashed.
8440 struct tblentry **pp;
8441 struct tblentry *cmdp;
8443 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8444 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8445 if (cmdp->cmdtype == CMDNORMAL
8446 || (cmdp->cmdtype == CMDBUILTIN
8447 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
8457 * Fix command hash table when PATH changed.
8458 * Called before PATH is changed. The argument is the new value of PATH;
8459 * pathval() still returns the old value at this point.
8460 * Called with interrupts off.
8462 static void FAST_FUNC
8463 changepath(const char *newval)
8473 if (*new == '%' && prefix(new + 1, "builtin")) {
8477 new = strchr(new, ':');
8520 typedef smallint token_id_t;
8522 /* Nth bit indicates if token marks the end of a list */
8525 /* 0 */ | (1u << TEOF)
8526 /* 1 */ | (0u << TNL)
8527 /* 2 */ | (0u << TREDIR)
8528 /* 3 */ | (0u << TWORD)
8529 /* 4 */ | (0u << TSEMI)
8530 /* 5 */ | (0u << TBACKGND)
8531 /* 6 */ | (0u << TAND)
8532 /* 7 */ | (0u << TOR)
8533 /* 8 */ | (0u << TPIPE)
8534 /* 9 */ | (0u << TLP)
8535 /* 10 */ | (1u << TRP)
8536 /* 11 */ | (1u << TENDCASE)
8537 /* 12 */ | (1u << TENDBQUOTE)
8538 /* 13 */ | (0u << TNOT)
8539 /* 14 */ | (0u << TCASE)
8540 /* 15 */ | (1u << TDO)
8541 /* 16 */ | (1u << TDONE)
8542 /* 17 */ | (1u << TELIF)
8543 /* 18 */ | (1u << TELSE)
8544 /* 19 */ | (1u << TESAC)
8545 /* 20 */ | (1u << TFI)
8546 /* 21 */ | (0u << TFOR)
8548 /* 22 */ | (0u << TFUNCTION)
8550 /* 23 */ | (0u << TIF)
8551 /* 24 */ | (0u << TIN)
8552 /* 25 */ | (1u << TTHEN)
8553 /* 26 */ | (0u << TUNTIL)
8554 /* 27 */ | (0u << TWHILE)
8555 /* 28 */ | (0u << TBEGIN)
8556 /* 29 */ | (1u << TEND)
8557 , /* thus far 29 bits used */
8560 static const char *const tokname_array[] = {
8574 #define KWDOFFSET 13
8575 /* the following are keywords */
8597 /* Wrapper around strcmp for qsort/bsearch/... */
8599 pstrcmp(const void *a, const void *b)
8601 return strcmp((char*)a, *(char**)b);
8604 static const char *const *
8605 findkwd(const char *s)
8607 return bsearch(s, tokname_array + KWDOFFSET,
8608 ARRAY_SIZE(tokname_array) - KWDOFFSET,
8609 sizeof(tokname_array[0]), pstrcmp);
8613 * Locate and print what a word is...
8616 describe_command(char *command, const char *path, int describe_command_verbose)
8618 struct cmdentry entry;
8619 #if ENABLE_ASH_ALIAS
8620 const struct alias *ap;
8623 path = path ? path : pathval();
8625 if (describe_command_verbose) {
8629 /* First look at the keywords */
8630 if (findkwd(command)) {
8631 out1str(describe_command_verbose ? " is a shell keyword" : command);
8635 #if ENABLE_ASH_ALIAS
8636 /* Then look at the aliases */
8637 ap = lookupalias(command, 0);
8639 if (!describe_command_verbose) {
8644 out1fmt(" is an alias for %s", ap->val);
8649 find_command(command, &entry, DO_ABS, path);
8651 switch (entry.cmdtype) {
8653 int j = entry.u.index;
8659 padvance(&path, command);
8663 if (describe_command_verbose) {
8664 out1fmt(" is %s", p);
8672 if (describe_command_verbose) {
8673 /*out1str(" is a shell function");*/
8674 out1str(" is a function"); /* bash says this */
8681 if (describe_command_verbose) {
8682 out1fmt(" is a %sshell builtin",
8683 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8684 "special " : nullstr
8692 if (describe_command_verbose) {
8693 out1str(": not found\n");
8702 static int FAST_FUNC
8703 typecmd(int argc UNUSED_PARAM, char **argv)
8709 /* type -p ... ? (we don't bother checking for 'p') */
8710 if (argv[1] && argv[1][0] == '-') {
8715 err |= describe_command(argv[i++], NULL, verbose);
8720 #if ENABLE_ASH_CMDCMD
8721 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8723 parse_command_args(char **argv, const char **path)
8736 if (c == '-' && !*cp) {
8744 *path = bb_default_path;
8747 /* run 'typecmd' for other options */
8756 static int FAST_FUNC
8757 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8765 const char *path = NULL;
8767 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8768 * never reaches this function.
8771 while ((c = nextopt("pvV")) != '\0')
8773 verify |= VERIFY_VERBOSE;
8775 /*verify |= VERIFY_BRIEF*/;
8781 path = bb_default_path;
8783 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8785 if (/*verify && */ cmd)
8786 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8793 /*static int funcblocksize; // size of structures in function */
8794 /*static int funcstringsize; // size of strings in node */
8795 static void *funcblock; /* block to allocate function from */
8796 static char *funcstring_end; /* end of block to allocate strings from */
8798 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8799 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8800 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8801 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8802 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8803 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8804 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8805 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8806 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8807 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8808 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8809 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8810 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8811 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8812 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8813 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8814 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8815 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8816 #if BASH_REDIR_OUTPUT
8817 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8819 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8820 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8821 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8822 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8823 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8824 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8825 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8826 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8827 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8830 static int calcsize(int funcblocksize, union node *n);
8833 sizenodelist(int funcblocksize, struct nodelist *lp)
8836 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8837 funcblocksize = calcsize(funcblocksize, lp->n);
8840 return funcblocksize;
8844 calcsize(int funcblocksize, union node *n)
8847 return funcblocksize;
8848 funcblocksize += nodesize[n->type];
8851 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8852 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8853 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8856 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8861 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8862 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8869 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8870 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8873 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8874 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8875 funcblocksize = calcsize(funcblocksize, n->nif.test);
8878 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8879 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8880 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8883 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8884 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8887 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8888 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8889 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8892 funcblocksize = calcsize(funcblocksize, n->ndefun.body);
8893 funcblocksize += SHELL_ALIGN(strlen(n->ndefun.text) + 1);
8896 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8897 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8898 funcblocksize = calcsize(funcblocksize, n->narg.next);
8901 #if BASH_REDIR_OUTPUT
8908 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8909 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8913 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8914 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8918 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8919 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8922 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8925 return funcblocksize;
8929 nodeckstrdup(char *s)
8931 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8932 return strcpy(funcstring_end, s);
8935 static union node *copynode(union node *);
8937 static struct nodelist *
8938 copynodelist(struct nodelist *lp)
8940 struct nodelist *start;
8941 struct nodelist **lpp;
8946 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8947 (*lpp)->n = copynode(lp->n);
8949 lpp = &(*lpp)->next;
8956 copynode(union node *n)
8963 funcblock = (char *) funcblock + nodesize[n->type];
8967 new->ncmd.redirect = copynode(n->ncmd.redirect);
8968 new->ncmd.args = copynode(n->ncmd.args);
8969 new->ncmd.assign = copynode(n->ncmd.assign);
8970 new->ncmd.linno = n->ncmd.linno;
8973 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8974 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8979 new->nredir.redirect = copynode(n->nredir.redirect);
8980 new->nredir.n = copynode(n->nredir.n);
8981 new->nredir.linno = n->nredir.linno;
8988 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8989 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8992 new->nif.elsepart = copynode(n->nif.elsepart);
8993 new->nif.ifpart = copynode(n->nif.ifpart);
8994 new->nif.test = copynode(n->nif.test);
8997 new->nfor.var = nodeckstrdup(n->nfor.var);
8998 new->nfor.body = copynode(n->nfor.body);
8999 new->nfor.args = copynode(n->nfor.args);
9000 new->nfor.linno = n->nfor.linno;
9003 new->ncase.cases = copynode(n->ncase.cases);
9004 new->ncase.expr = copynode(n->ncase.expr);
9005 new->ncase.linno = n->ncase.linno;
9008 new->nclist.body = copynode(n->nclist.body);
9009 new->nclist.pattern = copynode(n->nclist.pattern);
9010 new->nclist.next = copynode(n->nclist.next);
9013 new->ndefun.body = copynode(n->ndefun.body);
9014 new->ndefun.text = nodeckstrdup(n->ndefun.text);
9015 new->ndefun.linno = n->ndefun.linno;
9018 new->narg.backquote = copynodelist(n->narg.backquote);
9019 new->narg.text = nodeckstrdup(n->narg.text);
9020 new->narg.next = copynode(n->narg.next);
9023 #if BASH_REDIR_OUTPUT
9030 new->nfile.fname = copynode(n->nfile.fname);
9031 new->nfile.fd = n->nfile.fd;
9032 new->nfile.next = copynode(n->nfile.next);
9036 new->ndup.vname = copynode(n->ndup.vname);
9037 new->ndup.dupfd = n->ndup.dupfd;
9038 new->ndup.fd = n->ndup.fd;
9039 new->ndup.next = copynode(n->ndup.next);
9043 new->nhere.doc = copynode(n->nhere.doc);
9044 new->nhere.fd = n->nhere.fd;
9045 new->nhere.next = copynode(n->nhere.next);
9048 new->nnot.com = copynode(n->nnot.com);
9051 new->type = n->type;
9056 * Make a copy of a parse tree.
9058 static struct funcnode *
9059 copyfunc(union node *n)
9064 /*funcstringsize = 0;*/
9065 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
9066 f = ckzalloc(blocksize /* + funcstringsize */);
9067 funcblock = (char *) f + offsetof(struct funcnode, n);
9068 funcstring_end = (char *) f + blocksize;
9070 /* f->count = 0; - ckzalloc did it */
9075 * Define a shell function.
9078 defun(union node *func)
9080 struct cmdentry entry;
9083 entry.cmdtype = CMDFUNCTION;
9084 entry.u.func = copyfunc(func);
9085 addcmdentry(func->ndefun.text, &entry);
9089 /* Reasons for skipping commands (see comment on breakcmd routine) */
9090 #define SKIPBREAK (1 << 0)
9091 #define SKIPCONT (1 << 1)
9092 #define SKIPFUNC (1 << 2)
9093 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
9094 static int skipcount; /* number of levels to skip */
9095 static int loopnest; /* current loop nesting level */
9096 static int funcline; /* starting line number of current function, or 0 if not in a function */
9098 /* Forward decl way out to parsing code - dotrap needs it */
9099 static int evalstring(char *s, int flags);
9101 /* Called to execute a trap.
9102 * Single callsite - at the end of evaltree().
9103 * If we return non-zero, evaltree raises EXEXIT exception.
9105 * Perhaps we should avoid entering new trap handlers
9106 * while we are executing a trap handler. [is it a TODO?]
9113 int status, last_status;
9118 status = savestatus;
9119 last_status = status;
9121 status = exitstatus;
9122 savestatus = status;
9127 TRACE(("dotrap entered\n"));
9128 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
9140 /* non-trapped SIGINT is handled separately by raise_interrupt,
9141 * don't upset it by resetting gotsig[SIGINT-1] */
9142 if (sig == SIGINT && !p)
9145 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
9150 exitstatus = status;
9153 savestatus = last_status;
9154 TRACE(("dotrap returns\n"));
9157 /* forward declarations - evaluation is fairly recursive business... */
9158 static int evalloop(union node *, int);
9159 static int evalfor(union node *, int);
9160 static int evalcase(union node *, int);
9161 static int evalsubshell(union node *, int);
9162 static void expredir(union node *);
9163 static int evalpipe(union node *, int);
9164 static int evalcommand(union node *, int);
9165 static int evalbltin(const struct builtincmd *, int, char **, int);
9166 static void prehash(union node *);
9169 * Evaluate a parse tree. The value is left in the global variable
9173 evaltree(union node *n, int flags)
9176 int (*evalfn)(union node *, int);
9177 struct stackmark smark;
9180 setstackmark(&smark);
9183 TRACE(("evaltree(NULL) called\n"));
9186 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
9193 out1fmt("Node type = %d\n", n->type);
9198 status = !evaltree(n->nnot.com, EV_TESTED);
9201 errlinno = lineno = n->nredir.linno;
9203 lineno -= funcline - 1;
9204 expredir(n->nredir.redirect);
9205 pushredir(n->nredir.redirect);
9206 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
9208 status = evaltree(n->nredir.n, flags & EV_TESTED);
9210 if (n->nredir.redirect)
9211 popredir(/*drop:*/ 0);
9214 evalfn = evalcommand;
9216 if (eflag && !(flags & EV_TESTED))
9228 evalfn = evalsubshell;
9241 #error NAND + 1 != NOR
9243 #if NOR + 1 != NSEMI
9244 #error NOR + 1 != NSEMI
9246 unsigned is_or = n->type - NAND;
9249 (flags | ((is_or >> 1) - 1)) & EV_TESTED
9251 if ((!status) == is_or || evalskip)
9257 status = evalfn(n, flags);
9261 status = evaltree(n->nif.test, EV_TESTED);
9268 if (n->nif.elsepart) {
9269 n = n->nif.elsepart;
9276 /* Not necessary. To test it:
9277 * "false; f() { qwerty; }; echo $?" should print 0.
9281 exitstatus = status;
9285 /* Order of checks below is important:
9286 * signal handlers trigger before exit caused by "set -e".
9290 if (checkexit & status)
9291 raise_exception(EXEXIT);
9292 if (flags & EV_EXIT)
9293 raise_exception(EXEXIT);
9295 popstackmark(&smark);
9296 TRACE(("leaving evaltree (no interrupts)\n"));
9303 int skip = evalskip;
9310 if (--skipcount <= 0) {
9321 evalloop(union node *n, int flags)
9332 i = evaltree(n->nbinary.ch1, EV_TESTED);
9334 if (skip == SKIPFUNC)
9338 if (n->type != NWHILE)
9342 status = evaltree(n->nbinary.ch2, flags);
9344 } while (!(skip & ~SKIPCONT));
9351 evalfor(union node *n, int flags)
9353 struct arglist arglist;
9358 errlinno = lineno = n->ncase.linno;
9360 lineno -= funcline - 1;
9362 arglist.list = NULL;
9363 arglist.lastp = &arglist.list;
9364 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
9365 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9367 *arglist.lastp = NULL;
9371 for (sp = arglist.list; sp; sp = sp->next) {
9372 setvar0(n->nfor.var, sp->text);
9373 status = evaltree(n->nfor.body, flags);
9374 if (skiploop() & ~SKIPCONT)
9383 evalcase(union node *n, int flags)
9387 struct arglist arglist;
9390 errlinno = lineno = n->ncase.linno;
9392 lineno -= funcline - 1;
9394 arglist.list = NULL;
9395 arglist.lastp = &arglist.list;
9396 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
9397 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
9398 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
9399 if (casematch(patp, arglist.list->text)) {
9400 /* Ensure body is non-empty as otherwise
9401 * EV_EXIT may prevent us from setting the
9404 if (evalskip == 0 && cp->nclist.body) {
9405 status = evaltree(cp->nclist.body, flags);
9416 * Kick off a subshell to evaluate a tree.
9419 evalsubshell(union node *n, int flags)
9422 int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
9425 errlinno = lineno = n->nredir.linno;
9427 lineno -= funcline - 1;
9429 expredir(n->nredir.redirect);
9430 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
9433 if (backgnd == FORK_FG)
9435 jp = makejob(/*n,*/ 1);
9436 if (forkshell(jp, n, backgnd) == 0) {
9441 flags &= ~EV_TESTED;
9443 redirect(n->nredir.redirect, 0);
9444 evaltreenr(n->nredir.n, flags);
9449 if (backgnd == FORK_FG)
9450 status = waitforjob(jp);
9456 * Compute the names of the files in a redirection list.
9458 static void fixredir(union node *, const char *, int);
9460 expredir(union node *n)
9464 for (redir = n; redir; redir = redir->nfile.next) {
9468 fn.lastp = &fn.list;
9469 switch (redir->type) {
9473 #if BASH_REDIR_OUTPUT
9478 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
9479 TRACE(("expredir expanded to '%s'\n", fn.list->text));
9480 #if BASH_REDIR_OUTPUT
9484 // By the design of stack allocator, the loop of this kind:
9485 // while true; do while true; do break; done </dev/null; done
9486 // will look like a memory leak: ash plans to free expfname's
9487 // of "/dev/null" as soon as it finishes running the loop
9488 // (in this case, never).
9489 // This "fix" is wrong:
9490 if (redir->nfile.expfname)
9491 stunalloc(redir->nfile.expfname);
9492 // It results in corrupted state of stacked allocations.
9494 redir->nfile.expfname = fn.list->text;
9497 case NTOFD: /* >& */
9498 if (redir->ndup.vname) {
9499 expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR);
9500 if (fn.list == NULL)
9501 ash_msg_and_raise_error("redir error");
9502 #if BASH_REDIR_OUTPUT
9503 if (!isdigit_str9(fn.list->text)) {
9504 /* >&file, not >&fd */
9505 if (redir->nfile.fd != 1) /* 123>&file - BAD */
9506 ash_msg_and_raise_error("redir error");
9508 goto store_expfname;
9511 fixredir(redir, fn.list->text, 1);
9519 * Evaluate a pipeline. All the processes in the pipeline are children
9520 * of the process creating the pipeline. (This differs from some versions
9521 * of the shell, which make the last process in a pipeline the parent
9525 evalpipe(union node *n, int flags)
9528 struct nodelist *lp;
9534 TRACE(("evalpipe(0x%lx) called\n", (long)n));
9536 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
9540 if (n->npipe.pipe_backgnd == 0)
9542 jp = makejob(/*n,*/ pipelen);
9544 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
9548 if (pipe(pip) < 0) {
9550 ash_msg_and_raise_perror("can't create pipe");
9553 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
9567 evaltreenr(lp->n, flags);
9574 /* Don't want to trigger debugging */
9578 if (n->npipe.pipe_backgnd == 0) {
9579 status = waitforjob(jp);
9580 TRACE(("evalpipe: job done exit status %d\n", status));
9587 /* setinteractive needs this forward reference */
9588 #if EDITING_HAS_get_exe_name
9589 static const char *get_builtin_name(int i) FAST_FUNC;
9593 * Controls whether the shell is interactive or not.
9596 setinteractive(int on)
9598 static smallint is_interactive;
9600 if (++on == is_interactive)
9602 is_interactive = on;
9606 if (is_interactive > 1) {
9607 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9608 /* Looks like they want an interactive shell */
9609 static smallint did_banner;
9612 /* note: ash and hush share this string */
9613 out1fmt("\n\n%s %s\n"
9614 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
9617 "built-in shell (ash)"
9622 #if ENABLE_FEATURE_EDITING
9623 if (!line_input_state) {
9624 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
9625 # if EDITING_HAS_get_exe_name
9626 line_input_state->get_exe_name = get_builtin_name;
9639 setinteractive(iflag);
9641 #if ENABLE_FEATURE_EDITING_VI
9642 if (line_input_state) {
9644 line_input_state->flags |= VI_MODE;
9646 line_input_state->flags &= ~VI_MODE;
9649 viflag = 0; /* forcibly keep the option off */
9653 struct localvar_list {
9654 struct localvar_list *next;
9655 struct localvar *lv;
9658 static struct localvar_list *localvar_stack;
9661 * Called after a function returns.
9662 * Interrupts must be off.
9665 poplocalvars(int keep)
9667 struct localvar_list *ll;
9668 struct localvar *lvp, *next;
9672 ll = localvar_stack;
9673 localvar_stack = ll->next;
9678 while ((lvp = next) != NULL) {
9681 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9683 int bits = VSTRFIXED;
9685 if (lvp->flags != VUNSET) {
9686 if (vp->var_text == lvp->text)
9688 else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
9689 free((char*)lvp->text);
9693 vp->flags |= (lvp->flags & bits);
9696 (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
9697 unsetvar(vp->var_text);
9698 } else if (vp == NULL) { /* $- saved */
9699 memcpy(optlist, lvp->text, sizeof(optlist));
9700 free((char*)lvp->text);
9702 } else if (lvp->flags == VUNSET) {
9703 vp->flags &= ~(VSTRFIXED|VREADONLY);
9704 unsetvar(vp->var_text);
9707 vp->var_func(var_end(lvp->text));
9708 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9709 free((char*)vp->var_text);
9710 vp->flags = lvp->flags;
9711 vp->var_text = lvp->text;
9719 * Create a new localvar environment.
9721 static struct localvar_list *
9724 struct localvar_list *ll;
9727 ll = ckzalloc(sizeof(*ll));
9728 /*ll->lv = NULL; - zalloc did it */
9729 ll->next = localvar_stack;
9730 localvar_stack = ll;
9737 unwindlocalvars(struct localvar_list *stop)
9739 while (localvar_stack != stop)
9744 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9746 volatile struct shparam saveparam;
9747 struct jmploc *volatile savehandler;
9748 struct jmploc jmploc;
9752 saveparam = shellparam;
9753 savefuncline = funcline;
9754 savehandler = exception_handler;
9755 e = setjmp(jmploc.loc);
9760 exception_handler = &jmploc;
9761 shellparam.malloced = 0;
9763 funcline = func->n.ndefun.linno;
9765 shellparam.nparam = argc - 1;
9766 shellparam.p = argv + 1;
9767 #if ENABLE_ASH_GETOPTS
9768 shellparam.optind = 1;
9769 shellparam.optoff = -1;
9771 evaltree(func->n.ndefun.body, flags & EV_TESTED);
9774 funcline = savefuncline;
9776 freeparam(&shellparam);
9777 shellparam = saveparam;
9778 exception_handler = savehandler;
9780 evalskip &= ~SKIPFUNC;
9785 * Make a variable a local variable. When a variable is made local, it's
9786 * value and flags are saved in a localvar structure. The saved values
9787 * will be restored when the shell function returns. We handle the name
9788 * "-" as a special case: it makes changes to "set +-options" local
9789 * (options will be restored on return from the function).
9794 struct localvar *lvp;
9797 char *eq = strchr(name, '=');
9800 /* Cater for duplicate "local". Examples:
9801 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9802 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9804 lvp = localvar_stack->lv;
9806 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9810 * it's a duplicate "local VAR" declaration, do nothing
9817 lvp = ckzalloc(sizeof(*lvp));
9818 if (LONE_DASH(name)) {
9820 p = ckmalloc(sizeof(optlist));
9821 lvp->text = memcpy(p, optlist, sizeof(optlist));
9824 vpp = hashvar(name);
9825 vp = *findvar(vpp, name);
9827 /* variable did not exist yet */
9829 vp = setvareq(name, VSTRFIXED);
9831 vp = setvar(name, NULL, VSTRFIXED);
9832 lvp->flags = VUNSET;
9834 lvp->text = vp->var_text;
9835 lvp->flags = vp->flags;
9836 /* make sure neither "struct var" nor string gets freed
9837 * during (un)setting:
9839 vp->flags |= VSTRFIXED|VTEXTFIXED;
9843 /* "local VAR" unsets VAR: */
9844 setvar0(name, NULL);
9848 lvp->next = localvar_stack->lv;
9849 localvar_stack->lv = lvp;
9855 * The "local" command.
9857 static int FAST_FUNC
9858 localcmd(int argc UNUSED_PARAM, char **argv)
9862 if (!localvar_stack)
9863 ash_msg_and_raise_error("not in a function");
9866 while ((name = *argv++) != NULL) {
9872 static int FAST_FUNC
9873 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9878 static int FAST_FUNC
9879 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9884 static int FAST_FUNC
9885 execcmd(int argc UNUSED_PARAM, char **argv)
9888 while (nextopt("a:") != '\0')
9889 /* nextopt() sets optionarg to "-a ARGV0" */;
9895 iflag = 0; /* exit on error */
9898 /* We should set up signals for "exec CMD"
9899 * the same way as for "CMD" without "exec".
9900 * But optschanged->setinteractive->setsignal
9901 * still thought we are a root shell. Therefore, for example,
9902 * SIGQUIT is still set to IGN. Fix it:
9906 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9907 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9908 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9912 argv[0] = optionarg;
9913 shellexec(prog, argv, pathval(), 0);
9920 * The return command.
9922 static int FAST_FUNC
9923 returncmd(int argc UNUSED_PARAM, char **argv)
9926 * If called outside a function, do what ksh does;
9927 * skip the rest of the file.
9929 evalskip = SKIPFUNC;
9930 return argv[1] ? number(argv[1]) : exitstatus;
9933 /* Forward declarations for builtintab[] */
9934 static int breakcmd(int, char **) FAST_FUNC;
9935 static int dotcmd(int, char **) FAST_FUNC;
9936 static int evalcmd(int, char **, int) FAST_FUNC;
9937 static int exitcmd(int, char **) FAST_FUNC;
9938 static int exportcmd(int, char **) FAST_FUNC;
9939 #if ENABLE_ASH_GETOPTS
9940 static int getoptscmd(int, char **) FAST_FUNC;
9943 static int helpcmd(int, char **) FAST_FUNC;
9946 static int historycmd(int, char **) FAST_FUNC;
9948 #if ENABLE_FEATURE_SH_MATH
9949 static int letcmd(int, char **) FAST_FUNC;
9951 static int readcmd(int, char **) FAST_FUNC;
9952 static int setcmd(int, char **) FAST_FUNC;
9953 static int shiftcmd(int, char **) FAST_FUNC;
9954 static int timescmd(int, char **) FAST_FUNC;
9955 static int trapcmd(int, char **) FAST_FUNC;
9956 static int umaskcmd(int, char **) FAST_FUNC;
9957 static int unsetcmd(int, char **) FAST_FUNC;
9958 static int ulimitcmd(int, char **) FAST_FUNC;
9960 #define BUILTIN_NOSPEC "0"
9961 #define BUILTIN_SPECIAL "1"
9962 #define BUILTIN_REGULAR "2"
9963 #define BUILTIN_SPEC_REG "3"
9964 #define BUILTIN_ASSIGN "4"
9965 #define BUILTIN_SPEC_ASSG "5"
9966 #define BUILTIN_REG_ASSG "6"
9967 #define BUILTIN_SPEC_REG_ASSG "7"
9969 /* Stubs for calling non-FAST_FUNC's */
9971 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9973 #if ENABLE_ASH_PRINTF
9974 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9976 #if ENABLE_ASH_TEST || BASH_TEST2
9977 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9980 /* Keep these in proper order since it is searched via bsearch() */
9981 static const struct builtincmd builtintab[] = {
9982 { BUILTIN_SPEC_REG "." , dotcmd },
9983 { BUILTIN_SPEC_REG ":" , truecmd },
9985 { BUILTIN_REGULAR "[" , testcmd },
9988 { BUILTIN_REGULAR "[[" , testcmd },
9990 #if ENABLE_ASH_ALIAS
9991 { BUILTIN_REG_ASSG "alias" , aliascmd },
9994 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9996 { BUILTIN_SPEC_REG "break" , breakcmd },
9997 { BUILTIN_REGULAR "cd" , cdcmd },
9998 { BUILTIN_NOSPEC "chdir" , cdcmd },
9999 #if ENABLE_ASH_CMDCMD
10000 { BUILTIN_REGULAR "command" , commandcmd },
10002 { BUILTIN_SPEC_REG "continue", breakcmd },
10003 #if ENABLE_ASH_ECHO
10004 { BUILTIN_REGULAR "echo" , echocmd },
10006 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
10007 { BUILTIN_SPEC_REG "exec" , execcmd },
10008 { BUILTIN_SPEC_REG "exit" , exitcmd },
10009 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
10010 { BUILTIN_REGULAR "false" , falsecmd },
10012 { BUILTIN_REGULAR "fg" , fg_bgcmd },
10014 #if ENABLE_ASH_GETOPTS
10015 { BUILTIN_REGULAR "getopts" , getoptscmd },
10017 { BUILTIN_REGULAR "hash" , hashcmd },
10018 #if ENABLE_ASH_HELP
10019 { BUILTIN_NOSPEC "help" , helpcmd },
10022 { BUILTIN_NOSPEC "history" , historycmd },
10025 { BUILTIN_REGULAR "jobs" , jobscmd },
10026 { BUILTIN_REGULAR "kill" , killcmd },
10028 #if ENABLE_FEATURE_SH_MATH
10029 { BUILTIN_NOSPEC "let" , letcmd },
10031 { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
10032 #if ENABLE_ASH_PRINTF
10033 { BUILTIN_REGULAR "printf" , printfcmd },
10035 { BUILTIN_REGULAR "pwd" , pwdcmd },
10036 { BUILTIN_REGULAR "read" , readcmd },
10037 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
10038 { BUILTIN_SPEC_REG "return" , returncmd },
10039 { BUILTIN_SPEC_REG "set" , setcmd },
10040 { BUILTIN_SPEC_REG "shift" , shiftcmd },
10042 { BUILTIN_SPEC_REG "source" , dotcmd },
10044 #if ENABLE_ASH_TEST
10045 { BUILTIN_REGULAR "test" , testcmd },
10047 { BUILTIN_SPEC_REG "times" , timescmd },
10048 { BUILTIN_SPEC_REG "trap" , trapcmd },
10049 { BUILTIN_REGULAR "true" , truecmd },
10050 { BUILTIN_REGULAR "type" , typecmd },
10051 { BUILTIN_REGULAR "ulimit" , ulimitcmd },
10052 { BUILTIN_REGULAR "umask" , umaskcmd },
10053 #if ENABLE_ASH_ALIAS
10054 { BUILTIN_REGULAR "unalias" , unaliascmd },
10056 { BUILTIN_SPEC_REG "unset" , unsetcmd },
10057 { BUILTIN_REGULAR "wait" , waitcmd },
10060 /* Should match the above table! */
10061 #define COMMANDCMD (builtintab + \
10063 /* [ */ 1 * ENABLE_ASH_TEST + \
10064 /* [[ */ 1 * BASH_TEST2 + \
10065 /* alias */ 1 * ENABLE_ASH_ALIAS + \
10066 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
10067 /* break cd cddir */ 3)
10068 #define EVALCMD (COMMANDCMD + \
10069 /* command */ 1 * ENABLE_ASH_CMDCMD + \
10070 /* continue */ 1 + \
10071 /* echo */ 1 * ENABLE_ASH_ECHO + \
10073 #define EXECCMD (EVALCMD + \
10077 * Search the table of builtin commands.
10080 pstrcmp1(const void *a, const void *b)
10082 return strcmp((char*)a, *(char**)b + 1);
10084 static struct builtincmd *
10085 find_builtin(const char *name)
10087 struct builtincmd *bp;
10090 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
10096 #if EDITING_HAS_get_exe_name
10097 static const char * FAST_FUNC
10098 get_builtin_name(int i)
10100 return /*i >= 0 &&*/ i < ARRAY_SIZE(builtintab) ? builtintab[i].name + 1 : NULL;
10105 * Execute a simple command.
10107 static void unwindfiles(struct parsefile *stop);
10109 isassignment(const char *p)
10111 const char *q = endofname(p);
10116 static int FAST_FUNC
10117 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10119 /* Preserve exitstatus of a previous possible redirection
10120 * as POSIX mandates */
10121 return back_exitstatus;
10124 evalcommand(union node *cmd, int flags)
10126 static const struct builtincmd null_bltin = {
10127 "\0\0", bltincmd /* why three NULs? */
10129 struct localvar_list *localvar_stop;
10130 struct parsefile *file_stop;
10131 struct redirtab *redir_stop;
10133 struct arglist arglist;
10134 struct arglist varlist;
10137 const struct strlist *sp;
10138 struct cmdentry cmdentry;
10145 smallint cmd_is_exec;
10147 errlinno = lineno = cmd->ncmd.linno;
10149 lineno -= funcline - 1;
10151 /* First expand the arguments. */
10152 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
10153 localvar_stop = pushlocalvars();
10154 file_stop = g_parsefile;
10155 back_exitstatus = 0;
10157 cmdentry.cmdtype = CMDBUILTIN;
10158 cmdentry.u.cmd = &null_bltin;
10159 varlist.lastp = &varlist.list;
10160 *varlist.lastp = NULL;
10161 arglist.lastp = &arglist.list;
10162 *arglist.lastp = NULL;
10165 if (cmd->ncmd.args) {
10166 struct builtincmd *bcmd;
10167 smallint pseudovarflag;
10169 bcmd = find_builtin(cmd->ncmd.args->narg.text);
10170 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
10172 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
10173 struct strlist **spp;
10175 spp = arglist.lastp;
10176 if (pseudovarflag && isassignment(argp->narg.text))
10177 expandarg(argp, &arglist, EXP_VARTILDE);
10179 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
10181 for (sp = *spp; sp; sp = sp->next)
10186 /* Reserve one extra spot at the front for shellexec. */
10187 nargv = stalloc(sizeof(char *) * (argc + 2));
10189 for (sp = arglist.list; sp; sp = sp->next) {
10190 TRACE(("evalcommand arg: %s\n", sp->text));
10191 *nargv++ = sp->text;
10196 if (iflag && funcline == 0 && argc > 0)
10197 lastarg = nargv[-1];
10199 expredir(cmd->ncmd.redirect);
10200 redir_stop = pushredir(cmd->ncmd.redirect);
10202 if (BASH_XTRACEFD && xflag) {
10203 /* NB: bash closes fd == $BASH_XTRACEFD when it is changed.
10204 * we do not emulate this. We only use its value.
10206 const char *xtracefd = lookupvar("BASH_XTRACEFD");
10207 if (xtracefd && is_number(xtracefd))
10208 preverrout_fd = atoi(xtracefd);
10211 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
10213 path = vpath.var_text;
10214 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
10215 struct strlist **spp;
10218 spp = varlist.lastp;
10219 expandarg(argp, &varlist, EXP_VARTILDE);
10221 mklocal((*spp)->text);
10224 * Modify the command lookup path, if a PATH= assignment
10228 if (varcmp(p, path) == 0)
10232 /* Print the command if xflag is set. */
10234 const char *pfx = "";
10236 fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
10240 char *varval = sp->text;
10241 char *eq = strchrnul(varval, '=');
10244 fdprintf(preverrout_fd, "%s%.*s%s",
10246 (int)(eq - varval), varval,
10247 maybe_single_quote(eq)
10255 fdprintf(preverrout_fd, "%s%s",
10257 /* always quote if matches reserved word: */
10259 ? single_quote(sp->text)
10260 : maybe_single_quote(sp->text)
10265 safe_write(preverrout_fd, "\n", 1);
10271 /* Now locate the command. */
10273 int cmd_flag = DO_ERR;
10274 #if ENABLE_ASH_CMDCMD
10275 const char *oldpath = path + 5;
10279 find_command(argv[0], &cmdentry, cmd_flag, path);
10280 if (cmdentry.cmdtype == CMDUNKNOWN) {
10281 flush_stdout_stderr();
10286 /* implement bltin and command here */
10287 if (cmdentry.cmdtype != CMDBUILTIN)
10290 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
10291 if (cmdentry.u.cmd == EXECCMD)
10293 #if ENABLE_ASH_CMDCMD
10294 if (cmdentry.u.cmd == COMMANDCMD) {
10296 nargv = parse_command_args(argv, &path);
10299 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
10300 * nargv => "PROG". path is updated if -p.
10302 argc -= nargv - argv;
10304 cmd_flag |= DO_NOFUNC;
10313 exitstatus = status;
10315 /* We have a redirection error. */
10317 raise_exception(EXERROR);
10324 /* Execute the command. */
10325 switch (cmdentry.cmdtype) {
10328 #if ENABLE_FEATURE_SH_STANDALONE \
10329 && ENABLE_FEATURE_SH_NOFORK \
10331 /* (1) BUG: if variables are set, we need to fork, or save/restore them
10332 * around run_nofork_applet() call.
10333 * (2) Should this check also be done in forkshell()?
10334 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
10336 /* find_command() encodes applet_no as (-2 - applet_no) */
10337 int applet_no = (- cmdentry.u.index - 2);
10338 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
10342 sv_environ = environ;
10343 environ = listvars(VEXPORT, VUNSET, varlist.list, /*end:*/ NULL);
10345 * Run <applet>_main().
10346 * Signals (^C) can't interrupt here.
10347 * Otherwise we can mangle stdio or malloc internal state.
10348 * This makes applets which can run for a long time
10349 * and/or wait for user input ineligible for NOFORK:
10350 * for example, "yes" or "rm" (rm -i waits for input).
10352 status = run_nofork_applet(applet_no, argv);
10353 environ = sv_environ;
10355 * Try enabling NOFORK for "yes" applet.
10356 * ^C _will_ stop it (write returns EINTR),
10357 * but this causes stdout FILE to be stuck
10358 * and needing clearerr(). What if other applets
10359 * also can get EINTRs? Do we need to switch
10360 * our signals to SA_RESTART?
10362 /*clearerr(stdout);*/
10367 /* Can we avoid forking? For example, very last command
10368 * in a script or a subshell does not need forking,
10369 * we can just exec it.
10371 if (!(flags & EV_EXIT) || may_have_traps) {
10372 /* No, forking off a child is necessary */
10375 jp = makejob(/*cmd,*/ 1);
10376 if (forkshell(jp, cmd, FORK_FG) != 0) {
10378 TRACE(("forked child exited with %d\n", status));
10383 /* fall through to exec'ing external program */
10385 listsetvar(varlist.list, VEXPORT|VSTACK);
10386 shellexec(argv[0], argv, path, cmdentry.u.index);
10390 if (spclbltin > 0 || argc == 0) {
10392 if (cmd_is_exec && argc > 1)
10393 listsetvar(varlist.list, VEXPORT);
10395 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)
10396 && !(exception_type == EXERROR && spclbltin <= 0)
10399 longjmp(exception_handler->loc, 1);
10404 if (evalfun(cmdentry.u.func, argc, argv, flags))
10409 status = waitforjob(jp);
10413 if (cmd->ncmd.redirect)
10414 popredir(/*drop:*/ cmd_is_exec);
10415 unwindredir(redir_stop);
10416 unwindfiles(file_stop);
10417 unwindlocalvars(localvar_stop);
10419 /* dsl: I think this is intended to be used to support
10420 * '_' in 'vi' command mode during line editing...
10421 * However I implemented that within libedit itself.
10423 setvar0("_", lastarg);
10430 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
10432 char *volatile savecmdname;
10433 struct jmploc *volatile savehandler;
10434 struct jmploc jmploc;
10438 savecmdname = commandname;
10439 savehandler = exception_handler;
10440 i = setjmp(jmploc.loc);
10443 exception_handler = &jmploc;
10444 commandname = argv[0];
10446 optptr = NULL; /* initialize nextopt */
10447 if (cmd == EVALCMD)
10448 status = evalcmd(argc, argv, flags);
10450 status = (*cmd->builtin)(argc, argv);
10451 flush_stdout_stderr();
10452 status |= ferror(stdout);
10453 exitstatus = status;
10456 commandname = savecmdname;
10457 exception_handler = savehandler;
10463 goodname(const char *p)
10465 return endofname(p)[0] == '\0';
10470 * Search for a command. This is called before we fork so that the
10471 * location of the command will be available in the parent as well as
10472 * the child. The check for "goodname" is an overly conservative
10473 * check that the name will not be subject to expansion.
10476 prehash(union node *n)
10478 struct cmdentry entry;
10480 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
10481 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
10485 /* ============ Builtin commands
10487 * Builtin commands whose functions are closely tied to evaluation
10488 * are implemented here.
10492 * Handle break and continue commands. Break, continue, and return are
10493 * all handled by setting the evalskip flag. The evaluation routines
10494 * above all check this flag, and if it is set they start skipping
10495 * commands rather than executing them. The variable skipcount is
10496 * the number of loops to break/continue, or the number of function
10497 * levels to return. (The latter is always 1.) It should probably
10498 * be an error to break out of more loops than exist, but it isn't
10499 * in the standard shell so we don't make it one here.
10501 static int FAST_FUNC
10502 breakcmd(int argc UNUSED_PARAM, char **argv)
10504 int n = argv[1] ? number(argv[1]) : 1;
10507 ash_msg_and_raise_error(msg_illnum, argv[1]);
10511 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
10519 * This implements the input routines used by the parser.
10523 INPUT_PUSH_FILE = 1,
10524 INPUT_NOFILE_OK = 2,
10527 static smallint checkkwd;
10528 /* values of checkkwd variable */
10529 #define CHKALIAS 0x1
10532 #define CHKEOFMARK 0x8
10535 * Push a string back onto the input at this current parsefile level.
10536 * We handle aliases this way.
10538 #if !ENABLE_ASH_ALIAS
10539 #define pushstring(s, ap) pushstring(s)
10542 pushstring(char *s, struct alias *ap)
10544 struct strpush *sp;
10549 if (g_parsefile->strpush) {
10550 sp = ckzalloc(sizeof(*sp));
10551 sp->prev = g_parsefile->strpush;
10553 sp = &(g_parsefile->basestrpush);
10555 g_parsefile->strpush = sp;
10556 sp->prev_string = g_parsefile->next_to_pgetc;
10557 sp->prev_left_in_line = g_parsefile->left_in_line;
10558 sp->unget = g_parsefile->unget;
10559 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
10560 #if ENABLE_ASH_ALIAS
10563 ap->flag |= ALIASINUSE;
10567 g_parsefile->next_to_pgetc = s;
10568 g_parsefile->left_in_line = len;
10569 g_parsefile->unget = 0;
10576 struct strpush *sp = g_parsefile->strpush;
10579 #if ENABLE_ASH_ALIAS
10581 if (g_parsefile->next_to_pgetc[-1] == ' '
10582 || g_parsefile->next_to_pgetc[-1] == '\t'
10584 checkkwd |= CHKALIAS;
10586 if (sp->string != sp->ap->val) {
10589 sp->ap->flag &= ~ALIASINUSE;
10590 if (sp->ap->flag & ALIASDEAD) {
10591 unalias(sp->ap->name);
10595 g_parsefile->next_to_pgetc = sp->prev_string;
10596 g_parsefile->left_in_line = sp->prev_left_in_line;
10597 g_parsefile->unget = sp->unget;
10598 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
10599 g_parsefile->strpush = sp->prev;
10600 if (sp != &(g_parsefile->basestrpush))
10609 char *buf = g_parsefile->buf;
10611 g_parsefile->next_to_pgetc = buf;
10612 #if ENABLE_FEATURE_EDITING
10614 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
10615 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10617 # if ENABLE_ASH_IDLE_TIMEOUT
10619 const char *tmout_var = lookupvar("TMOUT");
10621 timeout = atoi(tmout_var) * 1000;
10625 line_input_state->timeout = timeout;
10627 # if ENABLE_FEATURE_TAB_COMPLETION
10628 line_input_state->path_lookup = pathval();
10630 reinit_unicode_for_ash();
10631 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ);
10633 /* ^C pressed, "convert" to SIGINT */
10634 write(STDOUT_FILENO, "^C", 2);
10635 if (trap[SIGINT]) {
10641 exitstatus = 128 + SIGINT;
10647 /* Ctrl+D pressed */
10650 # if ENABLE_ASH_IDLE_TIMEOUT
10651 else if (errno == EAGAIN && timeout > 0) {
10652 puts("\007timed out waiting for input: auto-logout");
10659 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10662 #if 0 /* disabled: nonblock_immune_read() handles this problem */
10664 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
10665 int flags = fcntl(0, F_GETFL);
10666 if (flags >= 0 && (flags & O_NONBLOCK)) {
10667 flags &= ~O_NONBLOCK;
10668 if (fcntl(0, F_SETFL, flags) >= 0) {
10669 out2str("sh: turning off NDELAY mode\n");
10680 * Refill the input buffer and return the next input character:
10682 * 1) If a string was pushed back on the input, pop it;
10683 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
10684 * or we are reading from a string so we can't refill the buffer,
10686 * 3) If there is more stuff in this buffer, use it else call read to fill it.
10687 * 4) Process input up to the next newline, deleting nul characters.
10689 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
10690 #define pgetc_debug(...) ((void)0)
10691 static int pgetc(void);
10698 if (g_parsefile->strpush) {
10699 #if ENABLE_ASH_ALIAS
10700 if (g_parsefile->left_in_line == -1
10701 && g_parsefile->strpush->ap
10702 && g_parsefile->next_to_pgetc[-1] != ' '
10703 && g_parsefile->next_to_pgetc[-1] != '\t'
10705 pgetc_debug("preadbuffer PEOA");
10712 /* on both branches above g_parsefile->left_in_line < 0.
10713 * "pgetc" needs refilling.
10716 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
10717 * pungetc() may increment it a few times.
10718 * Assuming it won't increment it to less than -90.
10720 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
10721 pgetc_debug("preadbuffer PEOF1");
10722 /* even in failure keep left_in_line and next_to_pgetc
10723 * in lock step, for correct multi-layer pungetc.
10724 * left_in_line was decremented before preadbuffer(),
10725 * must inc next_to_pgetc: */
10726 g_parsefile->next_to_pgetc++;
10730 more = g_parsefile->left_in_buffer;
10732 flush_stdout_stderr();
10736 /* don't try reading again */
10737 g_parsefile->left_in_line = -99;
10738 pgetc_debug("preadbuffer PEOF2");
10739 g_parsefile->next_to_pgetc++;
10744 /* Find out where's the end of line.
10745 * Set g_parsefile->left_in_line
10746 * and g_parsefile->left_in_buffer acordingly.
10747 * NUL chars are deleted.
10749 q = g_parsefile->next_to_pgetc;
10757 memmove(q, q + 1, more);
10761 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10767 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10768 if (g_parsefile->left_in_line < 0)
10773 g_parsefile->left_in_buffer = more;
10778 out2str(g_parsefile->next_to_pgetc);
10782 pgetc_debug("preadbuffer at %d:%p'%s'",
10783 g_parsefile->left_in_line,
10784 g_parsefile->next_to_pgetc,
10785 g_parsefile->next_to_pgetc);
10786 return (unsigned char)*g_parsefile->next_to_pgetc++;
10792 g_parsefile->linno++;
10793 setprompt_if(doprompt, 2);
10798 g_parsefile->linno++;
10799 needprompt = doprompt;
10807 pgetc_debug("pgetc at %d:%p'%s'",
10808 g_parsefile->left_in_line,
10809 g_parsefile->next_to_pgetc,
10810 g_parsefile->next_to_pgetc);
10811 if (g_parsefile->unget)
10812 return g_parsefile->lastc[--g_parsefile->unget];
10814 if (--g_parsefile->left_in_line >= 0)
10815 c = (unsigned char)*g_parsefile->next_to_pgetc++;
10819 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10820 g_parsefile->lastc[0] = c;
10825 #if ENABLE_ASH_ALIAS
10827 pgetc_without_PEOA(void)
10831 pgetc_debug("pgetc at %d:%p'%s'",
10832 g_parsefile->left_in_line,
10833 g_parsefile->next_to_pgetc,
10834 g_parsefile->next_to_pgetc);
10836 } while (c == PEOA);
10840 # define pgetc_without_PEOA() pgetc()
10844 * Undo a call to pgetc. Only two characters may be pushed back.
10845 * PEOF may be pushed back.
10850 g_parsefile->unget++;
10853 /* This one eats backslash+newline */
10859 while ((c = pgetc()) == '\\') {
10860 if (pgetc() != '\n') {
10873 uint8_t innerdq :1;
10874 uint8_t varpushed :1;
10875 uint8_t dblquote :1;
10876 int varnest; /* levels of variables expansion */
10877 int dqvarnest; /* levels of variables expansion within double quotes */
10878 int parenlevel; /* levels of parens in arithmetic */
10879 struct synstack *prev;
10880 struct synstack *next;
10884 pgetc_top(struct synstack *stack)
10886 return stack->syntax == SQSYNTAX ? pgetc() : pgetc_eatbnl();
10890 synstack_push(struct synstack **stack, struct synstack *next, int syntax)
10892 memset(next, 0, sizeof(*next));
10893 next->syntax = syntax;
10894 next->next = *stack;
10895 (*stack)->prev = next;
10899 static ALWAYS_INLINE void
10900 synstack_pop(struct synstack **stack)
10902 *stack = (*stack)->next;
10906 * To handle the "." command, a stack of input files is used. Pushfile
10907 * adds a new entry to the stack and popfile restores the previous level.
10912 struct parsefile *pf;
10914 pf = ckzalloc(sizeof(*pf));
10915 pf->prev = g_parsefile;
10917 /*pf->strpush = NULL; - ckzalloc did it */
10918 /*pf->basestrpush.prev = NULL;*/
10926 struct parsefile *pf = g_parsefile;
10932 if (pf->pf_fd >= 0)
10935 while (pf->strpush)
10937 g_parsefile = pf->prev;
10943 unwindfiles(struct parsefile *stop)
10945 while (g_parsefile != stop)
10950 * Return to top level.
10955 unwindfiles(&basepf);
10959 * Close the file(s) that the shell is reading commands from. Called
10960 * after a fork is done.
10966 if (g_parsefile->pf_fd > 0) {
10967 close(g_parsefile->pf_fd);
10968 g_parsefile->pf_fd = 0;
10973 * Like setinputfile, but takes an open file descriptor. Call this with
10977 setinputfd(int fd, int push)
10981 g_parsefile->buf = NULL;
10983 g_parsefile->pf_fd = fd;
10984 if (g_parsefile->buf == NULL)
10985 g_parsefile->buf = ckmalloc(IBUFSIZ);
10986 g_parsefile->left_in_buffer = 0;
10987 g_parsefile->left_in_line = 0;
10988 g_parsefile->linno = 1;
10992 * Set the input to take input from a file. If push is set, push the
10993 * old input onto the stack first.
10996 setinputfile(const char *fname, int flags)
11001 fd = open(fname, O_RDONLY | O_CLOEXEC);
11003 if (flags & INPUT_NOFILE_OK)
11006 ash_msg_and_raise_perror("can't open '%s'", fname);
11010 else if (O_CLOEXEC == 0) /* old libc */
11011 close_on_exec_on(fd);
11013 setinputfd(fd, flags & INPUT_PUSH_FILE);
11020 * Like setinputfile, but takes input from a string.
11023 setinputstring(char *string)
11027 g_parsefile->next_to_pgetc = string;
11028 g_parsefile->left_in_line = strlen(string);
11029 g_parsefile->buf = NULL;
11030 g_parsefile->linno = 1;
11036 * Routines to check for mail.
11039 #if ENABLE_ASH_MAIL
11041 /* Hash of mtimes of mailboxes */
11042 static unsigned mailtime_hash;
11043 /* Set if MAIL or MAILPATH is changed. */
11044 static smallint mail_var_path_changed;
11047 * Print appropriate message(s) if mail has arrived.
11048 * If mail_var_path_changed is set,
11049 * then the value of MAIL has mail_var_path_changed,
11050 * so we just update the values.
11059 struct stackmark smark;
11062 setstackmark(&smark);
11063 mpath = mpathset() ? mpathval() : mailval();
11068 len = padvance_magic(&mpath, nullstr, 2);
11075 for (q = p; *q; q++)
11081 q[-1] = '\0'; /* delete trailing '/' */
11082 if (stat(p, &statb) < 0) {
11085 /* Very simplistic "hash": just a sum of all mtimes */
11086 new_hash += (unsigned)statb.st_mtime;
11088 if (!mail_var_path_changed && mailtime_hash != new_hash) {
11089 if (mailtime_hash != 0)
11090 out2str("you have mail\n");
11091 mailtime_hash = new_hash;
11093 mail_var_path_changed = 0;
11094 popstackmark(&smark);
11097 static void FAST_FUNC
11098 changemail(const char *val UNUSED_PARAM)
11100 mail_var_path_changed = 1;
11103 #endif /* ASH_MAIL */
11106 /* ============ ??? */
11109 * Set the shell parameters.
11112 setparam(char **argv)
11118 for (nparam = 0; argv[nparam]; nparam++)
11120 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
11122 *ap++ = ckstrdup(*argv++);
11125 freeparam(&shellparam);
11126 shellparam.malloced = 1;
11127 shellparam.nparam = nparam;
11128 shellparam.p = newparam;
11129 #if ENABLE_ASH_GETOPTS
11130 shellparam.optind = 1;
11131 shellparam.optoff = -1;
11136 * Process shell options. The global variable argptr contains a pointer
11137 * to the argument list; we advance it past the options.
11139 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
11140 * For a non-interactive shell, an error condition encountered
11141 * by a special built-in ... shall cause the shell to write a diagnostic message
11142 * to standard error and exit as shown in the following table:
11143 * Error Special Built-In
11145 * Utility syntax error (option or operand error) Shall exit
11147 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
11148 * we see that bash does not do that (set "finishes" with error code 1 instead,
11149 * and shell continues), and people rely on this behavior!
11151 * set -o barfoo 2>/dev/null
11154 * Oh well. Let's mimic that.
11157 plus_minus_o(char *name, int val)
11162 for (i = 0; i < NOPTS; i++) {
11163 if (strcmp(name, optnames(i)) == 0) {
11168 ash_msg("illegal option %co %s", val ? '-' : '+', name);
11171 for (i = 0; i < NOPTS; i++) {
11172 if (optnames(i)[0] == '\0')
11175 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
11177 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
11183 setoption(int flag, int val)
11187 for (i = 0; i < NOPTS; i++) {
11188 if (optletters(i) == flag && optnames(i)[0] != '\0') {
11193 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
11196 /* If login_sh is not NULL, we are called to parse command line opts,
11200 options(int *login_sh)
11208 while ((p = *argptr) != NULL) {
11210 if (c != '-' && c != '+')
11213 val = 0; /* val = 0 if c == '+' */
11216 if (p[0] == '\0' || LONE_DASH(p)) {
11218 /* "-" means turn off -x and -v */
11221 /* "--" means reset params */
11222 else if (*argptr == NULL)
11225 break; /* "-" or "--" terminates options */
11228 /* first char was + or - */
11229 while ((c = *p++) != '\0') {
11231 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
11233 minusc = p; /* command is after shell args */
11237 if (c == 's') { /* -s, +s */
11241 if (c == 'i') { /* -i, +i */
11246 *login_sh = 1; /* -l or +l == --login */
11249 /* bash does not accept +-login, we also won't */
11250 if (val && (c == '-')) { /* long options */
11251 if (strcmp(p, "login") == 0) {
11258 if (plus_minus_o(*argptr, val)) {
11259 /* it already printed err message */
11260 return 1; /* error */
11273 * The shift builtin command.
11275 static int FAST_FUNC
11276 shiftcmd(int argc UNUSED_PARAM, char **argv)
11283 n = number(argv[1]);
11284 if (n > shellparam.nparam)
11287 shellparam.nparam -= n;
11288 for (ap1 = shellparam.p; --n >= 0; ap1++) {
11289 if (shellparam.malloced)
11292 ap2 = shellparam.p;
11293 while ((*ap2++ = *ap1++) != NULL)
11295 #if ENABLE_ASH_GETOPTS
11296 shellparam.optind = 1;
11297 shellparam.optoff = -1;
11304 * POSIX requires that 'set' (but not export or readonly) output the
11305 * variables in lexicographic order - by the locale's collating order (sigh).
11306 * Maybe we could keep them in an ordered balanced binary tree
11307 * instead of hashed lists.
11308 * For now just roll 'em through qsort for printing...
11311 showvars(const char *sep_prefix, int on, int off)
11314 char **ep, **epend;
11316 ep = listvars(on, off, /*strlist:*/ NULL, &epend);
11317 qsort(ep, epend - ep, sizeof(char *), vpcmp);
11319 sep = *sep_prefix ? " " : sep_prefix;
11321 for (; ep < epend; ep++) {
11325 p = endofname(*ep);
11326 /* Used to have simple "p = strchrnul(*ep, '=')" here instead, but this
11327 * makes "export -p" to have output not suitable for "eval":
11329 * os.environ["test-test"]="test"
11330 * if os.fork() == 0:
11331 * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
11332 * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ])
11336 q = single_quote(++p);
11337 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
11343 * The set command builtin.
11345 static int FAST_FUNC
11346 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
11351 return showvars(nullstr, 0, VUNSET);
11354 retval = options(/*login_sh:*/ NULL);
11355 if (retval == 0) { /* if no parse error... */
11357 if (*argptr != NULL) {
11365 #if ENABLE_ASH_RANDOM_SUPPORT
11366 static void FAST_FUNC
11367 change_random(const char *value)
11371 if (value == NULL) {
11372 /* "get", generate */
11373 t = next_random(&random_gen);
11374 /* set without recursion */
11375 setvar(vrandom.var_text, utoa(t), VNOFUNC);
11376 vrandom.flags &= ~VNOFUNC;
11379 t = strtoul(value, NULL, 10);
11380 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
11385 #if BASH_EPOCH_VARS
11386 static void FAST_FUNC
11387 change_epoch(struct var *vepoch, const char *fmt)
11390 char buffer[sizeof("%lu.nnnnnn") + sizeof(long)*3];
11392 gettimeofday(&tv, NULL);
11393 sprintf(buffer, fmt, (unsigned long)tv.tv_sec, (unsigned)tv.tv_usec);
11394 setvar(vepoch->var_text, buffer, VNOFUNC);
11395 vepoch->flags &= ~VNOFUNC;
11398 static void FAST_FUNC
11399 change_seconds(const char *value UNUSED_PARAM)
11401 change_epoch(&vepochs, "%lu");
11404 static void FAST_FUNC
11405 change_realtime(const char *value UNUSED_PARAM)
11407 change_epoch(&vepochr, "%lu.%06u");
11411 #if ENABLE_ASH_GETOPTS
11413 getopts(char *optstr, char *optvar, char **optfirst)
11420 int ind = shellparam.optind;
11421 int off = shellparam.optoff;
11425 shellparam.optind = -1;
11426 optnext = optfirst + ind - 1;
11428 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
11431 p = optnext[-1] + off;
11432 if (p == NULL || *p == '\0') {
11433 /* Current word is done, advance */
11435 if (p == NULL || *p != '-' || *++p == '\0') {
11437 unsetvar("OPTARG");
11443 if (LONE_DASH(p)) /* check for "--" */
11448 for (q = optstr; *q != c;) {
11450 /* OPTERR is a bashism */
11451 const char *cp = lookupvar("OPTERR");
11452 if ((cp && LONE_CHAR(cp, '0'))
11453 || (optstr[0] == ':')
11456 /*sbuf[1] = '\0'; - already is */
11457 setvar0("OPTARG", sbuf);
11459 fprintf(stderr, "Illegal option -%c\n", c);
11460 unsetvar("OPTARG");
11470 if (*p == '\0' && (p = *optnext) == NULL) {
11471 /* OPTERR is a bashism */
11472 const char *cp = lookupvar("OPTERR");
11473 if ((cp && LONE_CHAR(cp, '0'))
11474 || (optstr[0] == ':')
11477 /*sbuf[1] = '\0'; - already is */
11478 setvar0("OPTARG", sbuf);
11481 fprintf(stderr, "No arg for -%c option\n", c);
11482 unsetvar("OPTARG");
11490 setvar0("OPTARG", p);
11493 setvar0("OPTARG", nullstr);
11495 ind = optnext - optfirst + 1;
11496 setvar("OPTIND", itoa(ind), VNOFUNC);
11498 /*sbuf[1] = '\0'; - already is */
11499 setvar0(optvar, sbuf);
11501 shellparam.optoff = p ? p - *(optnext - 1) : -1;
11502 shellparam.optind = ind;
11508 * The getopts builtin. Shellparam.optnext points to the next argument
11509 * to be processed. Shellparam.optptr points to the next character to
11510 * be processed in the current argument. If shellparam.optnext is NULL,
11511 * then it's the first time getopts has been called.
11513 static int FAST_FUNC
11514 getoptscmd(int argc, char **argv)
11519 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
11521 optbase = shellparam.p;
11522 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
11523 shellparam.optind = 1;
11524 shellparam.optoff = -1;
11527 optbase = &argv[3];
11528 if ((unsigned)shellparam.optind > argc - 2) {
11529 shellparam.optind = 1;
11530 shellparam.optoff = -1;
11534 return getopts(argv[1], argv[2], optbase);
11536 #endif /* ASH_GETOPTS */
11539 /* ============ Shell parser */
11542 struct heredoc *next; /* next here document in list */
11543 union node *here; /* redirection node */
11544 char *eofmark; /* string indicating end of input */
11545 smallint striptabs; /* if set, strip leading tabs */
11548 static smallint tokpushback; /* last token pushed back */
11549 static smallint quoteflag; /* set if (part of) last token was quoted */
11550 static token_id_t lasttoken; /* last token read (integer id Txxx) */
11551 static struct heredoc *heredoclist; /* list of here documents to read */
11552 static char *wordtext; /* text of last word returned by readtoken */
11553 static struct nodelist *backquotelist;
11554 static union node *redirnode;
11555 static struct heredoc *heredoc;
11557 static const char *
11558 tokname(char *buf, int tok)
11561 return tokname_array[tok];
11562 sprintf(buf, "\"%s\"", tokname_array[tok]);
11566 /* raise_error_unexpected_syntax:
11567 * Called when an unexpected token is read during the parse. The argument
11568 * is the token that is expected, or -1 if more than one type of token can
11569 * occur at this point.
11571 static void raise_error_unexpected_syntax(int) NORETURN;
11573 raise_error_unexpected_syntax(int token)
11579 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
11581 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
11582 raise_error_syntax(msg);
11586 /* parsing is heavily cross-recursive, need these forward decls */
11587 static union node *andor(void);
11588 static union node *pipeline(void);
11589 static union node *parse_command(void);
11590 static void parseheredoc(void);
11591 static int peektoken(void);
11592 static int readtoken(void);
11594 static union node *
11597 union node *n1, *n2, *n3;
11602 switch (peektoken()) {
11610 if (!n1 && (nlflag & 1))
11616 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11617 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
11623 if (tok == TBACKGND) {
11624 if (n2->type == NPIPE) {
11625 n2->npipe.pipe_backgnd = 1;
11627 if (n2->type != NREDIR) {
11628 n3 = stzalloc(sizeof(struct nredir));
11630 /*n3->nredir.redirect = NULL; - stzalloc did it */
11633 n2->type = NBACKGND;
11639 n3 = stzalloc(sizeof(struct nbinary));
11641 n3->nbinary.ch1 = n1;
11642 n3->nbinary.ch2 = n2;
11655 raise_error_unexpected_syntax(-1);
11662 static union node *
11665 union node *n1, *n2, *n3;
11673 } else if (t == TOR) {
11679 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11681 n3 = stzalloc(sizeof(struct nbinary));
11683 n3->nbinary.ch1 = n1;
11684 n3->nbinary.ch2 = n2;
11689 static union node *
11692 union node *n1, *n2, *pipenode;
11693 struct nodelist *lp, *prev;
11697 TRACE(("pipeline: entered\n"));
11698 if (readtoken() == TNOT) {
11700 checkkwd = CHKKWD | CHKALIAS;
11703 n1 = parse_command();
11704 if (readtoken() == TPIPE) {
11705 pipenode = stzalloc(sizeof(struct npipe));
11706 pipenode->type = NPIPE;
11707 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
11708 lp = stzalloc(sizeof(struct nodelist));
11709 pipenode->npipe.cmdlist = lp;
11713 lp = stzalloc(sizeof(struct nodelist));
11714 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11715 lp->n = parse_command();
11717 } while (readtoken() == TPIPE);
11723 n2 = stzalloc(sizeof(struct nnot));
11731 static union node *
11736 n = stzalloc(sizeof(struct narg));
11738 /*n->narg.next = NULL; - stzalloc did it */
11739 n->narg.text = wordtext;
11740 n->narg.backquote = backquotelist;
11745 fixredir(union node *n, const char *text, int err)
11749 TRACE(("Fix redir %s %d\n", text, err));
11751 n->ndup.vname = NULL;
11753 fd = bb_strtou(text, NULL, 10);
11754 if (!errno && fd >= 0)
11755 n->ndup.dupfd = fd;
11756 else if (LONE_DASH(text))
11757 n->ndup.dupfd = -1;
11760 raise_error_syntax("bad fd number");
11761 n->ndup.vname = makename();
11768 union node *n = redirnode;
11770 if (n->type == NHERE)
11771 checkkwd = CHKEOFMARK;
11772 if (readtoken() != TWORD)
11773 raise_error_unexpected_syntax(-1);
11774 if (n->type == NHERE) {
11775 struct heredoc *here = heredoc;
11778 if (quoteflag == 0)
11780 TRACE(("Here document %d\n", n->type));
11781 rmescapes(wordtext, 0, NULL);
11782 here->eofmark = wordtext;
11784 if (heredoclist == NULL)
11785 heredoclist = here;
11787 for (p = heredoclist; p->next; p = p->next)
11791 } else if (n->type == NTOFD || n->type == NFROMFD) {
11792 fixredir(n, wordtext, 0);
11794 n->nfile.fname = makename();
11798 static union node *
11801 union node *args, **app;
11802 union node *n = NULL;
11803 union node *vars, **vpp;
11804 union node **rpp, *redir;
11808 smallint double_brackets_flag = 0;
11810 IF_BASH_FUNCTION(smallint function_flag = 0;)
11819 savecheckkwd = CHKALIAS;
11820 savelinno = g_parsefile->linno;
11823 checkkwd = savecheckkwd;
11828 if (peektoken() != TWORD)
11829 raise_error_unexpected_syntax(TWORD);
11834 case TAND: /* "&&" */
11835 case TOR: /* "||" */
11836 if (!double_brackets_flag) {
11840 wordtext = (char *) (t == TAND ? "-a" : "-o");
11843 n = stzalloc(sizeof(struct narg));
11845 /*n->narg.next = NULL; - stzalloc did it */
11846 n->narg.text = wordtext;
11848 if (strcmp("[[", wordtext) == 0)
11849 double_brackets_flag = 1;
11850 else if (strcmp("]]", wordtext) == 0)
11851 double_brackets_flag = 0;
11853 n->narg.backquote = backquotelist;
11854 if (savecheckkwd && isassignment(wordtext)) {
11856 vpp = &n->narg.next;
11859 app = &n->narg.next;
11863 if (function_flag) {
11864 checkkwd = CHKNL | CHKKWD;
11865 switch (peektoken()) {
11878 if (strcmp("[[", wordtext) == 0)
11883 raise_error_unexpected_syntax(-1);
11889 *rpp = n = redirnode;
11890 rpp = &n->nfile.next;
11891 parsefname(); /* read name of redirection file */
11894 IF_BASH_FUNCTION(do_func:)
11895 if (args && app == &args->narg.next
11898 struct builtincmd *bcmd;
11901 /* We have a function */
11902 if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
11903 raise_error_unexpected_syntax(TRP);
11904 name = n->narg.text;
11905 if (!goodname(name)
11906 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11908 raise_error_syntax("bad function name");
11911 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11912 n->ndefun.text = n->narg.text;
11913 n->ndefun.linno = g_parsefile->linno;
11914 n->ndefun.body = parse_command();
11917 IF_BASH_FUNCTION(function_flag = 0;)
11928 n = stzalloc(sizeof(struct ncmd));
11931 n->ncmd.linno = savelinno;
11932 n->ncmd.args = args;
11933 n->ncmd.assign = vars;
11934 n->ncmd.redirect = redir;
11938 static union node *
11939 parse_command(void)
11941 union node *n1, *n2;
11942 union node *ap, **app;
11943 union node *cp, **cpp;
11944 union node *redir, **rpp;
11952 savelinno = g_parsefile->linno;
11954 switch (readtoken()) {
11956 raise_error_unexpected_syntax(-1);
11959 n1 = stzalloc(sizeof(struct nif));
11961 n1->nif.test = list(0);
11962 if (readtoken() != TTHEN)
11963 raise_error_unexpected_syntax(TTHEN);
11964 n1->nif.ifpart = list(0);
11966 while (readtoken() == TELIF) {
11967 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11968 n2 = n2->nif.elsepart;
11970 n2->nif.test = list(0);
11971 if (readtoken() != TTHEN)
11972 raise_error_unexpected_syntax(TTHEN);
11973 n2->nif.ifpart = list(0);
11975 if (lasttoken == TELSE)
11976 n2->nif.elsepart = list(0);
11978 n2->nif.elsepart = NULL;
11986 n1 = stzalloc(sizeof(struct nbinary));
11987 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11988 n1->nbinary.ch1 = list(0);
11991 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11992 got == TWORD ? wordtext : ""));
11993 raise_error_unexpected_syntax(TDO);
11995 n1->nbinary.ch2 = list(0);
12000 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
12001 raise_error_syntax("bad for loop variable");
12002 n1 = stzalloc(sizeof(struct nfor));
12004 n1->nfor.linno = savelinno;
12005 n1->nfor.var = wordtext;
12006 checkkwd = CHKNL | CHKKWD | CHKALIAS;
12007 if (readtoken() == TIN) {
12009 while (readtoken() == TWORD) {
12010 n2 = stzalloc(sizeof(struct narg));
12012 /*n2->narg.next = NULL; - stzalloc did it */
12013 n2->narg.text = wordtext;
12014 n2->narg.backquote = backquotelist;
12016 app = &n2->narg.next;
12019 n1->nfor.args = ap;
12020 if (lasttoken != TNL && lasttoken != TSEMI)
12021 raise_error_unexpected_syntax(-1);
12023 n2 = stzalloc(sizeof(struct narg));
12025 /*n2->narg.next = NULL; - stzalloc did it */
12026 n2->narg.text = (char *)dolatstr;
12027 /*n2->narg.backquote = NULL;*/
12028 n1->nfor.args = n2;
12030 * Newline or semicolon here is optional (but note
12031 * that the original Bourne shell only allowed NL).
12033 if (lasttoken != TSEMI)
12036 checkkwd = CHKNL | CHKKWD | CHKALIAS;
12037 if (readtoken() != TDO)
12038 raise_error_unexpected_syntax(TDO);
12039 n1->nfor.body = list(0);
12043 n1 = stzalloc(sizeof(struct ncase));
12045 n1->ncase.linno = savelinno;
12046 if (readtoken() != TWORD)
12047 raise_error_unexpected_syntax(TWORD);
12048 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
12050 /*n2->narg.next = NULL; - stzalloc did it */
12051 n2->narg.text = wordtext;
12052 n2->narg.backquote = backquotelist;
12053 checkkwd = CHKNL | CHKKWD | CHKALIAS;
12054 if (readtoken() != TIN)
12055 raise_error_unexpected_syntax(TIN);
12056 cpp = &n1->ncase.cases;
12058 checkkwd = CHKNL | CHKKWD;
12060 while (t != TESAC) {
12061 if (lasttoken == TLP)
12063 *cpp = cp = stzalloc(sizeof(struct nclist));
12065 app = &cp->nclist.pattern;
12067 *app = ap = stzalloc(sizeof(struct narg));
12069 /*ap->narg.next = NULL; - stzalloc did it */
12070 ap->narg.text = wordtext;
12071 ap->narg.backquote = backquotelist;
12072 if (readtoken() != TPIPE)
12074 app = &ap->narg.next;
12077 //ap->narg.next = NULL;
12078 if (lasttoken != TRP)
12079 raise_error_unexpected_syntax(TRP);
12080 cp->nclist.body = list(2);
12082 cpp = &cp->nclist.next;
12084 checkkwd = CHKNL | CHKKWD;
12088 raise_error_unexpected_syntax(TENDCASE);
12095 n1 = stzalloc(sizeof(struct nredir));
12096 n1->type = NSUBSHELL;
12097 n1->nredir.linno = savelinno;
12098 n1->nredir.n = list(0);
12099 /*n1->nredir.redirect = NULL; - stzalloc did it */
12106 IF_BASH_FUNCTION(case TFUNCTION:)
12110 return simplecmd();
12113 if (readtoken() != t)
12114 raise_error_unexpected_syntax(t);
12117 /* Now check for redirection which may follow command */
12118 checkkwd = CHKKWD | CHKALIAS;
12120 while (readtoken() == TREDIR) {
12121 *rpp = n2 = redirnode;
12122 rpp = &n2->nfile.next;
12128 if (n1->type != NSUBSHELL) {
12129 n2 = stzalloc(sizeof(struct nredir));
12131 n2->nredir.linno = savelinno;
12135 n1->nredir.redirect = redir;
12140 #if BASH_DOLLAR_SQUOTE
12142 decode_dollar_squote(void)
12144 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
12150 p = strchr(C_escapes, c);
12155 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
12159 } while ((unsigned char)(c - '0') <= 7 && --cnt);
12161 } else if (c == 'x') { /* \xHH */
12165 } while (isxdigit(c) && --cnt);
12167 if (cnt == 3) { /* \x but next char is "bad" */
12171 } else { /* simple seq like \\ or \t */
12176 c = bb_process_escape_sequence((void*)&p);
12177 } else { /* unrecognized "\z": print both chars unless ' or " */
12178 if (c != '\'' && c != '"') {
12180 c |= 0x100; /* "please encode \, then me" */
12187 /* Used by expandstr to get here-doc like behaviour. */
12188 #define FAKEEOFMARK ((char*)(uintptr_t)1)
12190 static ALWAYS_INLINE int
12191 realeofmark(const char *eofmark)
12193 return eofmark && eofmark != FAKEEOFMARK;
12197 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
12198 * is not NULL, read a here document. In the latter case, eofmark is the
12199 * word which marks the end of the document and striptabs is true if
12200 * leading tabs should be stripped from the document. The argument c
12201 * is the first character of the input token or document.
12203 * Because C does not have internal subroutines, I have simulated them
12204 * using goto's to implement the subroutine linkage. The following macros
12205 * will run code that appears at the end of readtoken1.
12207 #define CHECKEND() {goto checkend; checkend_return:;}
12208 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
12209 #define PARSESUB() {goto parsesub; parsesub_return:;}
12210 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
12211 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
12212 #define PARSEARITH() {goto parsearith; parsearith_return:;}
12214 readtoken1(int c, int syntax, char *eofmark, int striptabs)
12216 /* NB: syntax parameter fits into smallint */
12217 /* c parameter is an unsigned char or PEOF or PEOA */
12220 struct nodelist *bqlist;
12223 smallint pssyntax; /* we are expanding a prompt string */
12224 IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
12226 struct synstack synbase = { };
12227 struct synstack *synstack = &synbase;
12229 #if ENABLE_ASH_EXPAND_PRMT
12230 pssyntax = (syntax == PSSYNTAX);
12234 pssyntax = 0; /* constant */
12236 synstack->syntax = syntax;
12238 if (syntax == DQSYNTAX)
12239 synstack->dblquote = 1;
12243 STARTSTACKSTR(out);
12245 /* For each line, until end of word */
12246 CHECKEND(); /* set c to PEOF if at end of here document */
12247 for (;;) { /* until end of line or end of word */
12248 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
12249 switch (SIT(c, synstack->syntax)) {
12250 case CNL: /* '\n' */
12251 if (synstack->syntax == BASESYNTAX
12252 && !synstack->varnest
12254 goto endword; /* exit outer loop */
12258 c = pgetc_top(synstack);
12259 goto loop; /* continue outer loop */
12264 #if BASH_DOLLAR_SQUOTE
12265 if (c == '\\' && bash_dollar_squote) {
12266 c = decode_dollar_squote();
12268 /* skip $'\000', $'\x00' (like bash) */
12272 /* Unknown escape. Encode as '\z' */
12273 c = (unsigned char)c;
12274 if (eofmark == NULL || synstack->dblquote)
12275 USTPUTC(CTLESC, out);
12276 USTPUTC('\\', out);
12280 if (!eofmark || synstack->dblquote || synstack->varnest)
12281 USTPUTC(CTLESC, out);
12284 case CBACK: /* backslash */
12285 c = pgetc_without_PEOA();
12287 USTPUTC(CTLESC, out);
12288 USTPUTC('\\', out);
12291 if (pssyntax && c == '$') {
12292 USTPUTC(CTLESC, out);
12293 USTPUTC('\\', out);
12295 /* Backslash is retained if we are in "str"
12296 * and next char isn't dquote-special.
12298 if (synstack->dblquote
12302 && (c != '"' || (eofmark != NULL && !synstack->varnest))
12303 && (c != '}' || !synstack->varnest)
12305 USTPUTC(CTLESC, out); /* protect '\' from glob */
12306 USTPUTC('\\', out);
12308 USTPUTC(CTLESC, out);
12314 synstack->syntax = SQSYNTAX;
12316 if (eofmark == NULL) {
12317 USTPUTC(CTLQUOTEMARK, out);
12321 synstack->syntax = DQSYNTAX;
12322 synstack->dblquote = 1;
12324 if (synstack->varnest)
12325 synstack->innerdq ^= 1;
12328 IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
12329 if (eofmark != NULL && synstack->varnest == 0) {
12334 if (synstack->dqvarnest == 0) {
12335 synstack->syntax = BASESYNTAX;
12336 synstack->dblquote = 0;
12345 case CVAR: /* '$' */
12346 PARSESUB(); /* parse substitution */
12348 case CENDVAR: /* '}' */
12349 if (!synstack->innerdq && synstack->varnest > 0) {
12350 if (!--synstack->varnest && synstack->varpushed)
12351 synstack_pop(&synstack);
12352 else if (synstack->dqvarnest > 0)
12353 synstack->dqvarnest--;
12358 #if ENABLE_FEATURE_SH_MATH
12359 case CLP: /* '(' in arithmetic */
12360 synstack->parenlevel++;
12363 case CRP: /* ')' in arithmetic */
12364 if (synstack->parenlevel > 0) {
12365 synstack->parenlevel--;
12367 if (pgetc_eatbnl() == ')') {
12369 synstack_pop(&synstack);
12372 * unbalanced parens
12373 * (don't 2nd guess - no error)
12381 case CBQUOTE: /* '`' */
12382 if (checkkwd & CHKEOFMARK) {
12391 goto endword; /* exit outer loop */
12395 if (synstack->varnest == 0) {
12396 #if BASH_REDIR_OUTPUT
12398 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
12399 if (pgetc() == '>')
12400 c = 0x100 + '>'; /* flag &> */
12404 goto endword; /* exit outer loop */
12406 IF_ASH_ALIAS(if (c != PEOA))
12409 c = pgetc_top(synstack);
12413 #if ENABLE_FEATURE_SH_MATH
12414 if (synstack->syntax == ARISYNTAX)
12415 raise_error_syntax("missing '))'");
12417 if (synstack->syntax != BASESYNTAX && eofmark == NULL)
12418 raise_error_syntax("unterminated quoted string");
12419 if (synstack->varnest != 0) {
12421 raise_error_syntax("missing '}'");
12423 USTPUTC('\0', out);
12424 len = out - (char *)stackblock();
12425 out = stackblock();
12426 if (eofmark == NULL) {
12427 if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
12430 if (isdigit_str9(out)) {
12431 PARSEREDIR(); /* passed as params: out, c */
12432 lasttoken = TREDIR;
12435 /* else: non-number X seen, interpret it
12436 * as "NNNX>file" = "NNNX >file" */
12440 quoteflag = quotef;
12441 backquotelist = bqlist;
12442 grabstackblock(len);
12446 /* end of readtoken routine */
12449 * Check to see whether we are at the end of the here document. When this
12450 * is called, c is set to the first character of the next input line. If
12451 * we are at the end of the here document, this routine sets the c to PEOF.
12454 if (realeofmark(eofmark)) {
12458 #if ENABLE_ASH_ALIAS
12460 c = pgetc_without_PEOA();
12463 while (c == '\t') {
12464 c = pgetc_without_PEOA();
12468 markloc = out - (char *)stackblock();
12469 for (p = eofmark; STPUTC(c, out), *p; p++) {
12472 /* FIXME: fails for backslash-newlined terminator:
12477 * (see heredoc_bkslash_newline2.tests)
12479 c = pgetc_without_PEOA();
12482 if (c == '\n' || c == PEOF) {
12484 g_parsefile->linno++;
12485 needprompt = doprompt;
12490 p = (char *)stackblock() + markloc + 1;
12491 len_here = out - p;
12494 len_here -= (c >= PEOF);
12500 str = alloca(len_here + 1);
12501 *(char *)mempcpy(str, p, len_here) = '\0';
12503 pushstring(str, NULL);
12508 STADJUST((char *)stackblock() + markloc - out, out);
12510 goto checkend_return;
12514 * Parse a redirection operator. The variable "out" points to a string
12515 * specifying the fd to be redirected. The variable "c" contains the
12516 * first character of the redirection operator.
12519 /* out is already checked to be a valid number or "" */
12520 int fd = (*out == '\0' ? -1 : atoi(out));
12523 np = stzalloc(sizeof(struct nfile));
12526 c = pgetc_eatbnl();
12528 np->type = NAPPEND;
12530 np->type = NCLOBBER;
12533 /* it also can be NTO2 (>&file), but we can't figure it out yet */
12539 #if BASH_REDIR_OUTPUT
12540 else if (c == 0x100 + '>') { /* this flags &> redirection */
12542 pgetc(); /* this is '>', no need to check */
12546 else { /* c == '<' */
12547 /*np->nfile.fd = 0; - stzalloc did it */
12548 c = pgetc_eatbnl();
12551 if (sizeof(struct nfile) != sizeof(struct nhere)) {
12552 np = stzalloc(sizeof(struct nhere));
12553 /*np->nfile.fd = 0; - stzalloc did it */
12556 heredoc = stzalloc(sizeof(struct heredoc));
12557 heredoc->here = np;
12558 c = pgetc_eatbnl();
12560 heredoc->striptabs = 1;
12562 /*heredoc->striptabs = 0; - stzalloc did it */
12568 np->type = NFROMFD;
12572 np->type = NFROMTO;
12584 goto parseredir_return;
12588 * Parse a substitution. At this point, we have read the dollar sign
12589 * and nothing else.
12592 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
12593 * (assuming ascii char codes, as the original implementation did) */
12594 #define is_special(c) \
12595 (((unsigned)(c) - 33 < 32) \
12596 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
12598 unsigned char subtype;
12601 c = pgetc_eatbnl();
12602 if ((checkkwd & CHKEOFMARK)
12603 || c > 255 /* PEOA or PEOF */
12604 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
12606 #if BASH_DOLLAR_SQUOTE
12607 if (synstack->syntax != DQSYNTAX && c == '\'')
12608 bash_dollar_squote = 1;
12613 } else if (c == '(') {
12614 /* $(command) or $((arith)) */
12615 if (pgetc_eatbnl() == '(') {
12616 #if ENABLE_FEATURE_SH_MATH
12619 raise_error_syntax("support for $((arith)) is disabled");
12626 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
12627 smalluint newsyn = synstack->syntax;
12629 USTPUTC(CTLVAR, out);
12630 typeloc = out - (char *)stackblock();
12632 subtype = VSNORMAL;
12634 c = pgetc_eatbnl();
12639 /* $[{[#]]NAME[}] */
12642 c = pgetc_eatbnl();
12643 } while (is_in_name(c));
12644 } else if (isdigit(c)) {
12645 /* $[{[#]]NUM[}] */
12648 c = pgetc_eatbnl();
12649 } while (!subtype && isdigit(c));
12650 } else if (c != '}') {
12651 /* $[{[#]]<specialchar>[}] */
12654 c = pgetc_eatbnl();
12655 if (!subtype && cc == '#') {
12656 subtype = VSLENGTH;
12657 if (c == '_' || isalnum(c))
12660 c = pgetc_eatbnl();
12661 if (cc == '}' || c != '}') {
12669 if (!is_special(cc)) {
12670 if (subtype == VSLENGTH)
12679 if (c != '}' && subtype == VSLENGTH) {
12680 /* ${#VAR didn't end with } */
12684 if (subtype == 0) {
12685 static const char types[] ALIGN1 = "}-+?=";
12686 /* ${VAR...} but not $VAR or ${#VAR} */
12687 /* c == first char after VAR */
12692 c = pgetc_eatbnl();
12694 /* This check is only needed to not misinterpret
12695 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
12698 if (!strchr(types, c)) {
12699 subtype = VSSUBSTR;
12701 break; /* "goto badsub" is bigger (!) */
12707 const char *p = strchr(types, c);
12710 subtype |= p - types + VSNORMAL;
12715 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
12716 c = pgetc_eatbnl();
12722 newsyn = BASESYNTAX;
12724 #if BASH_PATTERN_SUBST
12726 /* ${v/[/]pattern/repl} */
12727 //TODO: encode pattern and repl separately.
12728 // Currently cases like: v=1;echo ${v/$((1/1))/ONE}
12729 // are broken (should print "ONE")
12730 subtype = VSREPLACE;
12731 newsyn = BASESYNTAX;
12732 c = pgetc_eatbnl();
12735 subtype++; /* VSREPLACEALL */
12744 if (newsyn == ARISYNTAX)
12747 if ((newsyn != synstack->syntax || synstack->innerdq)
12748 && subtype != VSNORMAL
12750 synstack_push(&synstack,
12751 synstack->prev ?: alloca(sizeof(*synstack)),
12754 synstack->varpushed = 1;
12755 synstack->dblquote = newsyn != BASESYNTAX;
12758 ((unsigned char *)stackblock())[typeloc] = subtype;
12759 if (subtype != VSNORMAL) {
12760 synstack->varnest++;
12761 if (synstack->dblquote)
12762 synstack->dqvarnest++;
12766 goto parsesub_return;
12770 * Called to parse command substitutions. Newstyle is set if the command
12771 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
12772 * list of commands (passed by reference), and savelen is the number of
12773 * characters on the top of the stack which must be preserved.
12776 struct nodelist **nlpp;
12780 struct heredoc *saveheredoclist;
12781 smallint saveprompt = 0;
12784 savelen = out - (char *)stackblock();
12787 * FIXME: this can allocate very large block on stack and SEGV.
12789 * echo "..<100kbytes>..`true` $(true) `true` ..."
12790 * allocates 100kb for every command subst. With about
12791 * a hundred command substitutions stack overflows.
12792 * With larger prepended string, SEGV happens sooner.
12794 str = alloca(savelen);
12795 memcpy(str, stackblock(), savelen);
12799 /* We must read until the closing backquote, giving special
12800 * treatment to some slashes, and then push the string and
12801 * reread it as input, interpreting it normally.
12807 STARTSTACKSTR(pout);
12811 setprompt_if(needprompt, 2);
12812 pc = pgetc_eatbnl();
12818 pc = pgetc(); /* or pgetc_eatbnl()? why (example)? */
12819 if (pc != '\\' && pc != '`' && pc != '$'
12820 && (!synstack->dblquote || pc != '"')
12822 STPUTC('\\', pout);
12824 if (pc <= 255 /* not PEOA or PEOF */) {
12830 IF_ASH_ALIAS(case PEOA:)
12831 raise_error_syntax("EOF in backquote substitution");
12843 STPUTC('\0', pout);
12844 psavelen = pout - (char *)stackblock();
12845 if (psavelen > 0) {
12846 pstr = grabstackstr(pout);
12847 setinputstring(pstr);
12852 nlpp = &(*nlpp)->next;
12853 *nlpp = stzalloc(sizeof(**nlpp));
12854 /* (*nlpp)->next = NULL; - stzalloc did it */
12856 saveheredoclist = heredoclist;
12857 heredoclist = NULL;
12860 saveprompt = doprompt;
12867 doprompt = saveprompt;
12869 if (readtoken() != TRP)
12870 raise_error_unexpected_syntax(TRP);
12871 setinputstring(nullstr);
12875 heredoclist = saveheredoclist;
12878 /* Start reading from old file again. */
12880 /* Ignore any pushed back tokens left from the backquote parsing. */
12883 out = growstackto(savelen + 1);
12885 memcpy(out, str, savelen);
12886 STADJUST(savelen, out);
12888 USTPUTC(CTLBACKQ, out);
12890 goto parsebackq_oldreturn;
12891 goto parsebackq_newreturn;
12894 #if ENABLE_FEATURE_SH_MATH
12896 * Parse an arithmetic expansion (indicate start of one and set state)
12900 synstack_push(&synstack,
12901 synstack->prev ?: alloca(sizeof(*synstack)),
12903 synstack->dblquote = 1;
12904 USTPUTC(CTLARI, out);
12905 goto parsearith_return;
12908 } /* end of readtoken */
12911 * Read the next input token.
12912 * If the token is a word, we set backquotelist to the list of cmds in
12913 * backquotes. We set quoteflag to true if any part of the word was
12915 * If the token is TREDIR, then we set redirnode to a structure containing
12918 * [Change comment: here documents and internal procedures]
12919 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12920 * word parsing code into a separate routine. In this case, readtoken
12921 * doesn't need to have any internal procedures, but parseword does.
12922 * We could also make parseoperator in essence the main routine, and
12923 * have parseword (readtoken1?) handle both words and redirection.]
12925 #define NEW_xxreadtoken
12926 #ifdef NEW_xxreadtoken
12927 /* singles must be first! */
12928 static const char xxreadtoken_chars[7] ALIGN1 = {
12929 '\n', '(', ')', /* singles */
12930 '&', '|', ';', /* doubles */
12934 #define xxreadtoken_singles 3
12935 #define xxreadtoken_doubles 3
12937 static const char xxreadtoken_tokens[] ALIGN1 = {
12938 TNL, TLP, TRP, /* only single occurrence allowed */
12939 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12940 TEOF, /* corresponds to trailing nul */
12941 TAND, TOR, TENDCASE /* if double occurrence */
12953 setprompt_if(needprompt, 2);
12954 for (;;) { /* until token or start of word found */
12955 c = pgetc_eatbnl();
12956 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12960 while ((c = pgetc()) != '\n' && c != PEOF)
12963 } else if (c == '\\') {
12964 break; /* return readtoken1(...) */
12968 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12974 p = strchr(xxreadtoken_chars, c);
12976 break; /* return readtoken1(...) */
12978 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12979 int cc = pgetc_eatbnl();
12980 if (cc == c) { /* double occurrence? */
12981 p += xxreadtoken_doubles + 1;
12984 #if BASH_REDIR_OUTPUT
12985 if (c == '&' && cc == '>') /* &> */
12986 break; /* return readtoken1(...) */
12991 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12996 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12998 #else /* old xxreadtoken */
12999 #define RETURN(token) return lasttoken = token
13009 setprompt_if(needprompt, 2);
13010 for (;;) { /* until token or start of word found */
13011 c = pgetc_eatbnl();
13013 case ' ': case '\t':
13014 IF_ASH_ALIAS(case PEOA:)
13017 while ((c = pgetc()) != '\n' && c != PEOF)
13027 if (pgetc_eatbnl() == '&')
13032 if (pgetc_eatbnl() == '|')
13037 if (pgetc_eatbnl() == ';')
13048 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
13051 #endif /* old xxreadtoken */
13057 int kwd = checkkwd;
13059 smallint alreadyseen = tokpushback;
13062 #if ENABLE_ASH_ALIAS
13078 if (t != TWORD || quoteflag) {
13083 * check for keywords
13085 if (kwd & CHKKWD) {
13086 const char *const *pp;
13088 pp = findkwd(wordtext);
13090 lasttoken = t = pp - tokname_array;
13091 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
13096 if (checkkwd & CHKALIAS) {
13097 #if ENABLE_ASH_ALIAS
13099 ap = lookupalias(wordtext, 1);
13102 pushstring(ap->val, ap);
13112 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
13114 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
13130 * Read and parse a command. Returns NODE_EOF on end of file.
13131 * (NULL is a valid parse tree indicating a blank line.)
13133 static union node *
13134 parsecmd(int interact)
13139 doprompt = interact;
13140 setprompt_if(doprompt, doprompt);
13146 * Input any here documents.
13151 struct heredoc *here;
13154 here = heredoclist;
13155 heredoclist = NULL;
13159 setprompt_if(needprompt, 2);
13160 if (here->here->type == NHERE)
13161 readtoken1(pgetc(), SQSYNTAX, here->eofmark, here->striptabs);
13163 readtoken1(pgetc_eatbnl(), DQSYNTAX, here->eofmark, here->striptabs);
13164 n = stzalloc(sizeof(struct narg));
13165 n->narg.type = NARG;
13166 /*n->narg.next = NULL; - stzalloc did it */
13167 n->narg.text = wordtext;
13168 n->narg.backquote = backquotelist;
13169 here->here->nhere.doc = n;
13175 static const char *
13176 expandstr(const char *ps, int syntax_type)
13180 struct parsefile *file_stop = g_parsefile;
13181 volatile int saveint;
13182 struct jmploc *volatile savehandler = exception_handler;
13183 struct jmploc jmploc;
13184 const char *volatile result;
13187 /* XXX Fix (char *) cast. */
13188 setinputstring((char *)ps);
13190 saveprompt = doprompt;
13195 err = setjmp(jmploc.loc);
13199 /* readtoken1() might die horribly.
13200 * Try a prompt with syntactically wrong command:
13201 * PS1='$(date "+%H:%M:%S) > '
13203 exception_handler = &jmploc;
13204 readtoken1(pgetc(), syntax_type, FAKEEOFMARK, 0);
13206 n.narg.type = NARG;
13207 n.narg.next = NULL;
13208 n.narg.text = wordtext;
13209 n.narg.backquote = backquotelist;
13211 /* expandarg() might fail too:
13214 expandarg(&n, NULL, EXP_QUOTED);
13215 result = stackblock();
13218 exception_handler = savehandler;
13219 if (err && exception_type != EXERROR)
13220 longjmp(exception_handler->loc, 1);
13221 RESTORE_INT(saveint);
13223 doprompt = saveprompt;
13224 /* Try: PS1='`xxx(`' */
13225 unwindfiles(file_stop);
13233 return tokpushback && lasttoken == TEOF;
13237 * Execute a command or commands contained in a string.
13240 evalstring(char *s, int flags)
13242 struct jmploc *volatile savehandler;
13243 struct jmploc jmploc;
13247 struct stackmark smark;
13252 setstackmark(&smark);
13255 /* On exception inside execution loop, we must popfile().
13256 * Try interactively:
13258 * command eval "a=b" # throws "is read only" error
13259 * "command BLTIN" is not supposed to abort (even in non-interactive use).
13260 * But if we skip popfile(), we hit EOF in eval's string, and exit.
13262 savehandler = exception_handler;
13263 ex = setjmp(jmploc.loc);
13266 exception_handler = &jmploc;
13268 while ((n = parsecmd(0)) != NODE_EOF) {
13271 i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
13274 popstackmark(&smark);
13279 popstackmark(&smark);
13283 exception_handler = savehandler;
13285 longjmp(exception_handler->loc, ex);
13291 * The eval command.
13293 static int FAST_FUNC
13294 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
13303 STARTSTACKSTR(concat);
13305 concat = stack_putstr(p, concat);
13309 STPUTC(' ', concat);
13311 STPUTC('\0', concat);
13312 p = grabstackstr(concat);
13314 return evalstring(p, flags & EV_TESTED);
13320 * Read and execute commands.
13321 * "Top" is nonzero for the top level command loop;
13322 * it turns on prompting if the shell is interactive.
13328 struct stackmark smark;
13333 TRACE(("cmdloop(%d) called\n", top));
13337 setstackmark(&smark);
13340 showjobs(SHOW_CHANGED|SHOW_STDERR);
13343 if (iflag && top) {
13347 n = parsecmd(inter);
13349 if (DEBUG > 2 && debug && (n != NODE_EOF))
13352 if (n == NODE_EOF) {
13353 if (!top || numeof >= 50)
13355 if (!stoppedjobs()) {
13358 newline_and_flush(stderr);
13362 out2str("\nUse \"exit\" to leave shell.\n");
13365 } else if (nflag == 0) {
13368 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
13371 i = evaltree(n, 0);
13375 popstackmark(&smark);
13379 evalskip &= ~SKIPFUNC;
13387 * Take commands from a file. To be compatible we should do a path
13388 * search for the file, which is necessary to find sub-commands.
13391 find_dot_file(char *basename)
13394 const char *path = pathval();
13398 /* don't try this for absolute or relative paths */
13399 if (strchr(basename, '/'))
13402 while ((len = padvance(&path, basename)) >= 0) {
13403 fullname = stackblock();
13404 if ((!pathopt || *pathopt == 'f')
13405 && !stat(fullname, &statb) && S_ISREG(statb.st_mode)
13407 /* This will be freed by the caller. */
13408 return stalloc(len);
13411 /* not found in PATH */
13413 #if ENABLE_ASH_BASH_SOURCE_CURDIR
13416 ash_msg_and_raise_error("%s: not found", basename);
13421 static int FAST_FUNC
13422 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
13424 /* "false; . empty_file; echo $?" should print 0, not 1: */
13428 char *args_need_save;
13429 volatile struct shparam saveparam;
13432 // struct strlist *sp;
13433 // for (sp = cmdenviron; sp; sp = sp->next)
13434 // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
13436 nextopt(nullstr); /* handle possible "--" */
13440 /* bash says: "bash: .: filename argument required" */
13441 return 2; /* bash compat */
13444 /* This aborts if file isn't found, which is POSIXly correct.
13445 * bash returns exitcode 1 instead.
13447 fullname = find_dot_file(argv[0]);
13449 args_need_save = argv[0];
13450 if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
13452 saveparam = shellparam;
13453 shellparam.malloced = 0;
13457 shellparam.nparam = argc;
13458 shellparam.p = argv;
13461 /* This aborts if file can't be opened, which is POSIXly correct.
13462 * bash returns exitcode 1 instead.
13464 setinputfile(fullname, INPUT_PUSH_FILE);
13465 commandname = fullname;
13466 status = cmdloop(0);
13469 if (args_need_save) {
13470 freeparam(&shellparam);
13471 shellparam = saveparam;
13477 static int FAST_FUNC
13478 exitcmd(int argc UNUSED_PARAM, char **argv)
13484 savestatus = number(argv[1]);
13486 raise_exception(EXEXIT);
13491 * Read a file containing shell functions.
13494 readcmdfile(char *name)
13496 setinputfile(name, INPUT_PUSH_FILE);
13502 /* ============ find_command inplementation */
13505 * Resolve a command name. If you change this routine, you may have to
13506 * change the shellexec routine as well.
13509 find_command(char *name, struct cmdentry *entry, int act, const char *path)
13511 struct tblentry *cmdp;
13518 struct builtincmd *bcmd;
13521 /* If name contains a slash, don't use PATH or hash table */
13522 if (strchr(name, '/') != NULL) {
13523 entry->u.index = -1;
13524 if (act & DO_ABS) {
13525 while (stat(name, &statb) < 0) {
13527 if (errno == EINTR)
13530 entry->cmdtype = CMDUNKNOWN;
13534 entry->cmdtype = CMDNORMAL;
13538 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
13540 updatetbl = (path == pathval());
13543 if (strstr(path, "%builtin") != NULL)
13544 act |= DO_ALTBLTIN;
13547 /* If name is in the table, check answer will be ok */
13548 cmdp = cmdlookup(name, 0);
13549 if (cmdp != NULL) {
13552 switch (cmdp->cmdtype) {
13564 bit = IS_BUILTIN_REGULAR(cmdp->param.cmd) ? 0 : DO_ALTBLTIN;
13570 } else if (cmdp->rehash == 0)
13571 /* if not invalidated by cd, we're done */
13575 /* If %builtin not in path, check for builtin next */
13576 bcmd = find_builtin(name);
13578 if (IS_BUILTIN_REGULAR(bcmd))
13579 goto builtin_success;
13580 if (act & DO_ALTPATH) {
13581 if (!(act & DO_ALTBLTIN))
13582 goto builtin_success;
13583 } else if (builtinloc <= 0) {
13584 goto builtin_success;
13588 #if ENABLE_FEATURE_SH_STANDALONE
13590 int applet_no = find_applet_by_name(name);
13591 if (applet_no >= 0) {
13592 entry->cmdtype = CMDNORMAL;
13593 entry->u.index = -2 - applet_no;
13599 /* We have to search path. */
13600 prev = -1; /* where to start */
13601 if (cmdp && cmdp->rehash) { /* doing a rehash */
13602 if (cmdp->cmdtype == CMDBUILTIN)
13605 prev = cmdp->param.index;
13611 while ((len = padvance(&path, name)) >= 0) {
13612 const char *lpathopt = pathopt;
13614 fullname = stackblock();
13617 if (*lpathopt == 'b') {
13619 goto builtin_success;
13621 } else if (!(act & DO_NOFUNC)) {
13622 /* handled below */
13624 /* ignore unimplemented options */
13628 /* if rehash, don't redo absolute path names */
13629 if (fullname[0] == '/' && idx <= prev) {
13632 TRACE(("searchexec \"%s\": no change\n", name));
13635 while (stat(fullname, &statb) < 0) {
13637 if (errno == EINTR)
13640 if (errno != ENOENT && errno != ENOTDIR)
13644 e = EACCES; /* if we fail, this will be the error */
13645 if (!S_ISREG(statb.st_mode))
13647 if (lpathopt) { /* this is a %func directory */
13649 /* NB: stalloc will return space pointed by fullname
13650 * (because we don't have any intervening allocations
13651 * between stunalloc above and this stalloc) */
13652 readcmdfile(fullname);
13653 cmdp = cmdlookup(name, 0);
13654 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
13655 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
13656 stunalloc(fullname);
13659 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
13661 entry->cmdtype = CMDNORMAL;
13662 entry->u.index = idx;
13666 cmdp = cmdlookup(name, 1);
13667 cmdp->cmdtype = CMDNORMAL;
13668 cmdp->param.index = idx;
13673 /* We failed. If there was an entry for this command, delete it */
13674 if (cmdp && updatetbl)
13675 delete_cmd_entry();
13676 if (act & DO_ERR) {
13677 #if ENABLE_ASH_BASH_NOT_FOUND_HOOK
13678 struct tblentry *hookp = cmdlookup("command_not_found_handle", 0);
13679 if (hookp && hookp->cmdtype == CMDFUNCTION) {
13681 argv[0] = (char*) "command_not_found_handle";
13684 evalfun(hookp->param.func, 2, argv, 0);
13685 entry->cmdtype = CMDUNKNOWN;
13689 ash_msg("%s: %s", name, errmsg(e, "not found"));
13691 entry->cmdtype = CMDUNKNOWN;
13696 entry->cmdtype = CMDBUILTIN;
13697 entry->u.cmd = bcmd;
13701 cmdp = cmdlookup(name, 1);
13702 cmdp->cmdtype = CMDBUILTIN;
13703 cmdp->param.cmd = bcmd;
13707 entry->cmdtype = cmdp->cmdtype;
13708 entry->u = cmdp->param;
13713 * The trap builtin.
13715 static int FAST_FUNC
13716 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13720 int signo, exitcode;
13725 for (signo = 0; signo < NSIG; signo++) {
13726 char *tr = trap_ptr[signo];
13728 /* note: bash adds "SIG", but only if invoked
13729 * as "bash". If called as "sh", or if set -o posix,
13730 * then it prints short signal names.
13731 * We are printing short names: */
13732 out1fmt("trap -- %s %s\n",
13734 get_signame(signo));
13735 /* trap_ptr != trap only if we are in special-cased `trap` code.
13736 * In this case, we will exit very soon, no need to free(). */
13737 /* if (trap_ptr != trap && tp[0]) */
13742 if (trap_ptr != trap) {
13750 /* Why the second check?
13751 * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
13752 * In this case, NUM is signal no, not an action.
13755 if (ap[1] && !is_number(ap[0]))
13760 signo = get_signum(*ap);
13762 /* Mimic bash message exactly */
13763 ash_msg("%s: invalid signal specification", *ap);
13769 if (LONE_DASH(action))
13772 if (action[0]) /* not NULL and not "" and not "-" */
13773 may_have_traps = 1;
13774 action = ckstrdup(action);
13778 trap[signo] = action;
13789 /* ============ Builtins */
13791 #if ENABLE_ASH_HELP
13792 static int FAST_FUNC
13793 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13799 "Built-in commands:\n"
13800 "------------------\n");
13801 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
13802 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
13803 builtintab[i].name + 1);
13809 # if ENABLE_FEATURE_SH_STANDALONE
13811 const char *a = applet_names;
13813 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
13818 while (*a++ != '\0')
13823 newline_and_flush(stdout);
13824 return EXIT_SUCCESS;
13829 static int FAST_FUNC
13830 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13832 if (line_input_state)
13833 show_history(line_input_state);
13834 return EXIT_SUCCESS;
13839 * The export and readonly commands.
13841 static int FAST_FUNC
13842 exportcmd(int argc UNUSED_PARAM, char **argv)
13852 /* "readonly" in bash accepts, but ignores -n.
13853 * We do the same: it saves a conditional in nextopt's param.
13856 while ((opt = nextopt("np")) != '\0') {
13858 flag_off = VEXPORT;
13861 if (argv[0][0] == 'r') {
13863 flag_off = 0; /* readonly ignores -n */
13865 flag_off = ~flag_off;
13867 /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
13873 p = strchr(name, '=');
13877 vp = *findvar(hashvar(name), name);
13879 vp->flags = ((vp->flags | flag) & flag_off);
13883 setvar(name, p, (flag & flag_off));
13884 } while ((name = *++aptr) != NULL);
13889 /* No arguments. Show the list of exported or readonly vars.
13892 showvars(argv[0], flag, 0);
13897 * Delete a function if it exists.
13900 unsetfunc(const char *name)
13902 struct tblentry *cmdp;
13904 cmdp = cmdlookup(name, 0);
13905 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
13906 delete_cmd_entry();
13910 * The unset builtin command. We unset the function before we unset the
13911 * variable to allow a function to be unset when there is a readonly variable
13912 * with the same name.
13914 static int FAST_FUNC
13915 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13921 while ((i = nextopt("vf")) != 0) {
13925 for (ap = argptr; *ap; ap++) {
13936 static const unsigned char timescmd_str[] ALIGN1 = {
13937 ' ', offsetof(struct tms, tms_utime),
13938 '\n', offsetof(struct tms, tms_stime),
13939 ' ', offsetof(struct tms, tms_cutime),
13940 '\n', offsetof(struct tms, tms_cstime),
13943 static int FAST_FUNC
13944 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13947 const unsigned char *p;
13950 clk_tck = bb_clk_tck();
13955 unsigned sec, frac;
13957 t = *(clock_t *)(((char *) &buf) + p[1]);
13959 frac = t % clk_tck;
13960 out1fmt("%um%u.%03us%c",
13961 sec / 60, sec % 60,
13962 (frac * 1000) / clk_tck,
13970 #if ENABLE_FEATURE_SH_MATH
13972 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13973 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13975 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13977 static int FAST_FUNC
13978 letcmd(int argc UNUSED_PARAM, char **argv)
13984 ash_msg_and_raise_error("expression expected");
13986 i = ash_arith(*argv);
13994 * The read builtin. Options:
13995 * -r Do not interpret '\' specially
13996 * -s Turn off echo (tty only)
13997 * -n NCHARS Read NCHARS max
13998 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13999 * -t SECONDS Timeout after SECONDS (tty or pipe only)
14000 * -u FD Read from given FD instead of fd 0
14001 * -d DELIM End on DELIM char, not newline
14002 * This uses unbuffered input, which may be avoidable in some cases.
14003 * TODO: bash also has:
14004 * -a ARRAY Read into array[0],[1],etc
14005 * -e Use line editing (tty only)
14007 static int FAST_FUNC
14008 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
14010 struct builtin_read_params params;
14014 memset(¶ms, 0, sizeof(params));
14016 while ((i = nextopt("p:u:rt:n:sd:")) != '\0') {
14019 params.opt_p = optionarg;
14022 params.opt_n = optionarg;
14025 params.read_flags |= BUILTIN_READ_SILENT;
14028 params.opt_t = optionarg;
14031 params.read_flags |= BUILTIN_READ_RAW;
14034 params.opt_u = optionarg;
14038 params.opt_d = optionarg;
14046 params.argv = argptr;
14047 params.setvar = setvar0;
14048 params.ifs = bltinlookup("IFS"); /* can be NULL */
14050 /* "read -s" needs to save/restore termios, can't allow ^C
14051 * to jump out of it.
14055 r = shell_builtin_read(¶ms);
14058 if ((uintptr_t)r == 1 && errno == EINTR) {
14059 /* To get SIGCHLD: sleep 1 & read x; echo $x
14060 * Correct behavior is to not exit "read"
14062 if (pending_sig == 0)
14066 if ((uintptr_t)r > 1)
14067 ash_msg_and_raise_error(r);
14069 return (uintptr_t)r;
14072 static int FAST_FUNC
14073 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
14075 static const char permuser[3] ALIGN1 = "ogu";
14078 int symbolic_mode = 0;
14080 while (nextopt("S") != '\0') {
14089 if (*argptr == NULL) {
14090 if (symbolic_mode) {
14091 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
14098 *p++ = permuser[i];
14100 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
14101 if (!(mask & 0400)) *p++ = 'r';
14102 if (!(mask & 0200)) *p++ = 'w';
14103 if (!(mask & 0100)) *p++ = 'x';
14111 out1fmt("%04o\n", mask);
14114 char *modestr = *argptr;
14115 /* numeric umasks are taken as-is */
14116 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
14117 if (!isdigit(modestr[0]))
14119 mask = bb_parse_mode(modestr, mask);
14120 if ((unsigned)mask > 0777) {
14121 ash_msg_and_raise_error("illegal mode: %s", modestr);
14123 if (!isdigit(modestr[0]))
14130 static int FAST_FUNC
14131 ulimitcmd(int argc UNUSED_PARAM, char **argv)
14133 return shell_builtin_ulimit(argv);
14136 /* ============ main() and helpers */
14139 * Called to exit the shell.
14147 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
14148 if (line_input_state)
14149 save_history(line_input_state);
14151 savestatus = exitstatus;
14152 TRACE(("pid %d, exitshell(%d)\n", getpid(), savestatus));
14153 if (setjmp(loc.loc))
14155 exception_handler = &loc;
14161 /*free(p); - we'll exit soon */
14164 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
14165 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
14168 flush_stdout_stderr();
14173 /* Don't inline: conserve stack of caller from having our locals too */
14174 static NOINLINE void
14177 /* we will never free this */
14178 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
14181 sigmode[SIGCHLD - 1] = S_DFL; /* ensure we install handler even if it is SIG_IGNed */
14182 setsignal(SIGCHLD);
14189 for (envp = environ; envp && *envp; envp++) {
14191 * p = endofname(*envp);
14192 * if (p != *envp && *p == '=') {
14193 * here to weed out badly-named variables, but this breaks
14194 * scenarios where people do want them passed to children:
14196 * os.environ["test-test"]="test"
14197 * if os.fork() == 0:
14198 * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
14199 * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ]) # breaks this
14201 if (strchr(*envp, '=')) {
14202 setvareq(*envp, VEXPORT|VTEXTFIXED);
14206 setvareq((char*)defifsvar, VTEXTFIXED);
14207 setvareq((char*)defoptindvar, VTEXTFIXED);
14209 setvar0("PPID", utoa(getppid()));
14211 p = lookupvar("SHLVL");
14212 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
14214 #if BASH_HOSTNAME_VAR
14215 if (!lookupvar("HOSTNAME")) {
14216 struct utsname uts;
14218 setvar0("HOSTNAME", uts.nodename);
14221 p = lookupvar("PWD");
14223 struct stat st1, st2;
14224 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
14225 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
14235 //usage:#define ash_trivial_usage
14236 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
14237 //usage:#define ash_full_usage "\n\n"
14238 //usage: "Unix shell interpreter"
14241 * Process the shell command line arguments.
14244 procargs(char **argv)
14247 const char *xminusc;
14252 login_sh = xargv[0] && xargv[0][0] == '-';
14253 #if NUM_SCRIPTS > 0
14258 /* if (xargv[0]) - mmm, this is always true! */
14261 for (i = 0; i < NOPTS; i++)
14263 if (options(&login_sh)) {
14264 /* it already printed err message */
14265 raise_exception(EXERROR);
14269 if (*xargv == NULL) {
14271 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
14274 if (iflag == 2 /* no explicit -i given */
14275 && sflag == 1 /* -s given (or implied) */
14276 && !minusc /* bash compat: ash -sc 'echo $-' is not interactive (dash is) */
14277 && isatty(0) && isatty(1) /* we are on tty */
14283 for (i = 0; i < NOPTS; i++)
14284 if (optlist[i] == 2)
14289 /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
14294 } else if (!sflag) {
14295 setinputfile(*xargv, 0);
14298 commandname = arg0;
14301 shellparam.p = xargv;
14302 #if ENABLE_ASH_GETOPTS
14303 shellparam.optind = 1;
14304 shellparam.optoff = -1;
14306 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
14308 shellparam.nparam++;
14317 * Read /etc/profile, ~/.profile, $ENV.
14320 read_profile(const char *name)
14322 name = expandstr(name, DQSYNTAX);
14323 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
14330 * This routine is called when an error or an interrupt occurs in an
14331 * interactive shell and control is returned to the main command loop
14332 * but prior to exitshell.
14340 if (savestatus >= 0) {
14341 exitstatus = savestatus;
14345 /* from expand.c: */
14348 /* from redir.c: */
14353 * This routine is called when an error or an interrupt occurs in an
14354 * interactive shell and control is returned to the main command loop.
14355 * (In dash, this function is auto-generated by build machinery).
14360 /* from input.c: */
14361 g_parsefile->left_in_buffer = 0;
14362 g_parsefile->left_in_line = 0; /* clear input buffer */
14366 unwindlocalvars(NULL);
14370 static short profile_buf[16384];
14371 extern int etext();
14375 * Main routine. We initialize things, parse the arguments, execute
14376 * profiles if we're a login shell, and then call cmdloop to execute
14377 * commands. The setjmp call sets up the location to jump to when an
14378 * exception occurs. When an exception occurs the variable "state"
14379 * is used to figure out how far we had gotten.
14381 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
14382 #if NUM_SCRIPTS > 0
14383 int ash_main(int argc, char **argv)
14385 int ash_main(int argc UNUSED_PARAM, char **argv)
14387 /* note: 'argc' is used only if embedded scripts are enabled */
14389 volatile smallint state;
14390 struct jmploc jmploc;
14391 struct stackmark smark;
14394 /* Initialize global data */
14398 #if ENABLE_ASH_ALIAS
14404 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
14408 if (setjmp(jmploc.loc)) {
14414 e = exception_type;
14416 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
14423 newline_and_flush(stderr);
14426 popstackmark(&smark);
14427 FORCE_INT_ON; /* enable interrupts */
14436 exception_handler = &jmploc;
14437 rootpid = getpid();
14440 setstackmark(&smark);
14442 #if NUM_SCRIPTS > 0
14444 /* Non-NULL minusc tells procargs that an embedded script is being run */
14445 minusc = get_script_content(-argc - 1);
14447 login_sh = procargs(argv);
14449 TRACE(("Shell args: "));
14450 trace_puts_args(argv);
14457 read_profile("/etc/profile");
14460 hp = lookupvar("HOME");
14462 read_profile("$HOME/.profile");
14468 getuid() == geteuid() && getgid() == getegid() &&
14472 const char *shinit = lookupvar("ENV");
14473 if (shinit != NULL && *shinit != '\0')
14474 read_profile(shinit);
14476 popstackmark(&smark);
14480 /* evalstring pushes parsefile stack.
14481 * Ensure we don't falsely claim that 0 (stdin)
14482 * is one of stacked source fds.
14483 * Testcase: ash -c 'exec 1>&0' must not complain. */
14485 // if (!sflag) g_parsefile->pf_fd = -1;
14486 // ^^ not necessary since now we special-case fd 0
14487 // in save_fd_on_redirect()
14489 // dash: evalstring(minusc, sflag ? 0 : EV_EXIT);
14491 // ash -sc 'echo $-'
14492 // continue reading input from stdin after running 'echo'.
14493 // bash does not do this: it prints "hBcs" and exits.
14494 evalstring(minusc, EV_EXIT);
14497 if (sflag || minusc == NULL) {
14498 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
14500 const char *hp = lookupvar("HISTFILE");
14502 hp = lookupvar("HOME");
14505 hp = concat_path_file(hp, ".ash_history");
14506 setvar0("HISTFILE", hp);
14509 hp = lookupvar("HISTFILE");
14513 line_input_state->hist_file = hp;
14514 # if ENABLE_FEATURE_SH_HISTFILESIZE
14515 hp = lookupvar("HISTFILESIZE");
14516 line_input_state->max_history = size_from_HISTFILESIZE(hp);
14520 state4: /* XXX ??? - why isn't this before the "if" statement */
14522 /* Interactive bash re-enables SIGHUP which is SIG_IGNed on entry.
14524 * trap '' hup; bash; echo RET # type "kill -hup $$", see SIGHUP having effect
14525 * trap '' hup; bash -c 'kill -hup $$; echo ALIVE' # here SIGHUP is SIG_IGNed
14527 signal(SIGHUP, SIG_DFL);
14536 extern void _mcleanup(void);
14540 TRACE(("End of main reached\n"));
14547 * Copyright (c) 1989, 1991, 1993, 1994
14548 * The Regents of the University of California. All rights reserved.
14550 * This code is derived from software contributed to Berkeley by
14551 * Kenneth Almquist.
14553 * Redistribution and use in source and binary forms, with or without
14554 * modification, are permitted provided that the following conditions
14556 * 1. Redistributions of source code must retain the above copyright
14557 * notice, this list of conditions and the following disclaimer.
14558 * 2. Redistributions in binary form must reproduce the above copyright
14559 * notice, this list of conditions and the following disclaimer in the
14560 * documentation and/or other materials provided with the distribution.
14561 * 3. Neither the name of the University nor the names of its contributors
14562 * may be used to endorse or promote products derived from this software
14563 * without specific prior written permission.
14565 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
14566 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
14567 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
14568 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
14569 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
14570 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
14571 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
14572 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
14573 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
14574 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF