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 * Generate a list of variables satisfying the given conditions.
2482 #if !ENABLE_FEATURE_SH_NOFORK
2483 # define listvars(on, off, lp, end) listvars(on, off, end)
2486 listvars(int on, int off, struct strlist *lp, char ***end)
2497 for (vp = *vpp; vp; vp = vp->next) {
2498 if ((vp->flags & mask) == on) {
2499 #if ENABLE_FEATURE_SH_NOFORK
2500 /* If variable with the same name is both
2501 * exported and temporarily set for a command:
2504 * then "ZVAR=6" will be both in vartab and
2505 * lp lists. Do not pass it twice to printenv.
2507 struct strlist *lp1 = lp;
2509 if (strcmp(lp1->text, vp->var_text) == 0)
2514 if (ep == stackstrend())
2515 ep = growstackstr();
2516 *ep++ = (char*)vp->var_text;
2517 #if ENABLE_FEATURE_SH_NOFORK
2522 } while (++vpp < vartab + VTABSIZE);
2524 #if ENABLE_FEATURE_SH_NOFORK
2526 if (ep == stackstrend())
2527 ep = growstackstr();
2533 if (ep == stackstrend())
2534 ep = growstackstr();
2538 return grabstackstr(ep);
2542 /* ============ Path search helper */
2544 legal_pathopt(const char *opt, const char *term, int magic)
2552 opt = prefix(opt, "builtin") ?: prefix(opt, "func");
2556 opt += strcspn(opt, term);
2560 if (opt && *opt == '%')
2567 * The variable path (passed by reference) should be set to the start
2568 * of the path before the first call; padvance will update
2569 * this value as it proceeds. Successive calls to padvance will return
2570 * the possible path expansions in sequence. If an option (indicated by
2571 * a percent sign) appears in the path entry then the global variable
2572 * pathopt will be set to point to it; otherwise pathopt will be set to
2575 * If magic is 0 then pathopt recognition will be disabled. If magic is
2576 * 1 we shall recognise %builtin/%func. Otherwise we shall accept any
2579 static const char *pathopt; /* set by padvance */
2582 padvance_magic(const char **path, const char *name, int magic)
2584 const char *term = "%:";
2585 const char *lpathopt;
2598 if (*start == '%' && (p = legal_pathopt(start + 1, term, magic))) {
2599 lpathopt = start + 1;
2604 len = strcspn(start, term);
2608 size_t extra = strchrnul(p, ':') - p;
2610 if (legal_pathopt(p + 1, term, magic))
2619 *path = *p == ':' ? p + 1 : NULL;
2621 /* "2" is for '/' and '\0' */
2622 qlen = len + strlen(name) + 2;
2623 q = growstackto(qlen);
2626 q = mempcpy(q, start, len);
2635 padvance(const char **path, const char *name)
2637 return padvance_magic(path, name, 1);
2641 /* ============ Prompt */
2643 static smallint doprompt; /* if set, prompt the user */
2644 static smallint needprompt; /* true if interactive and at start of line */
2646 #if ENABLE_FEATURE_EDITING
2647 static line_input_t *line_input_state;
2648 static const char *cmdedit_prompt;
2650 putprompt(const char *s)
2652 if (ENABLE_ASH_EXPAND_PRMT) {
2653 free((char*)cmdedit_prompt);
2654 cmdedit_prompt = ckstrdup(s);
2661 putprompt(const char *s)
2667 /* expandstr() needs parsing machinery, so it is far away ahead... */
2668 static const char *expandstr(const char *ps, int syntax_type);
2669 /* Values for syntax param */
2670 #define BASESYNTAX 0 /* not in quotes */
2671 #define DQSYNTAX 1 /* in double quotes */
2672 #define SQSYNTAX 2 /* in single quotes */
2673 #define ARISYNTAX 3 /* in arithmetic */
2674 #if ENABLE_ASH_EXPAND_PRMT
2675 # define PSSYNTAX 4 /* prompt. never passed to SIT() */
2677 /* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
2680 * called by editline -- any expansions to the prompt should be added here.
2683 setprompt_if(smallint do_set, int whichprompt)
2686 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2693 switch (whichprompt) {
2703 #if ENABLE_ASH_EXPAND_PRMT
2704 pushstackmark(&smark, stackblocksize());
2705 putprompt(expandstr(prompt, PSSYNTAX));
2706 popstackmark(&smark);
2713 /* ============ The cd and pwd commands */
2715 #define CD_PHYSICAL 1
2725 while ((i = nextopt("LP")) != '\0') {
2727 flags ^= CD_PHYSICAL;
2736 * Update curdir (the name of the current directory) in response to a
2740 updatepwd(const char *dir)
2747 cdcomppath = sstrdup(dir);
2750 if (curdir == nullstr)
2752 new = stack_putstr(curdir, new);
2754 new = makestrspace(strlen(dir) + 2, new);
2755 lim = (char *)stackblock() + 1;
2759 if (new > lim && *lim == '/')
2764 if (dir[1] == '/' && dir[2] != '/') {
2770 p = strtok(cdcomppath, "/");
2774 if (p[1] == '.' && p[2] == '\0') {
2786 new = stack_putstr(p, new);
2789 p = strtok(NULL, "/");
2794 return stackblock();
2798 * Find out what the current directory is. If we already know the current
2799 * directory, this routine returns immediately.
2804 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2805 return dir ? dir : nullstr;
2809 setpwd(const char *val, int setold)
2813 oldcur = dir = curdir;
2816 setvar("OLDPWD", oldcur, VEXPORT);
2819 if (physdir != nullstr) {
2820 if (physdir != oldcur)
2824 if (oldcur == val || !val) {
2830 dir = ckstrdup(val);
2831 if (oldcur != dir && oldcur != nullstr) {
2836 setvar("PWD", dir, VEXPORT);
2839 static void hashcd(void);
2842 * Actually do the chdir. We also call hashcd to let other routines
2843 * know that the current directory has changed.
2846 docd(const char *dest, int flags)
2848 const char *dir = NULL;
2851 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2854 if (!(flags & CD_PHYSICAL)) {
2855 dir = updatepwd(dest);
2869 static int FAST_FUNC
2870 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2883 dest = bltinlookup("HOME");
2884 else if (LONE_DASH(dest)) {
2885 dest = bltinlookup("OLDPWD");
2907 path = bltinlookup("CDPATH");
2908 while (p = path, (len = padvance(&path, dest)) >= 0) {
2912 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2916 if (!docd(p, flags))
2927 ash_msg_and_raise_perror("can't cd to %s", dest);
2930 if (flags & CD_PRINT)
2931 out1fmt("%s\n", curdir);
2935 static int FAST_FUNC
2936 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2939 const char *dir = curdir;
2943 if (physdir == nullstr)
2947 out1fmt("%s\n", dir);
2952 /* ============ ... */
2955 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2957 /* Syntax classes */
2958 #define CWORD 0 /* character is nothing special */
2959 #define CNL 1 /* newline character */
2960 #define CBACK 2 /* a backslash character */
2961 #define CSQUOTE 3 /* single quote */
2962 #define CDQUOTE 4 /* double quote */
2963 #define CENDQUOTE 5 /* a terminating quote */
2964 #define CBQUOTE 6 /* backwards single quote */
2965 #define CVAR 7 /* a dollar sign */
2966 #define CENDVAR 8 /* a '}' character */
2967 #define CLP 9 /* a left paren in arithmetic */
2968 #define CRP 10 /* a right paren in arithmetic */
2969 #define CENDFILE 11 /* end of file */
2970 #define CCTL 12 /* like CWORD, except it must be escaped */
2971 #define CSPCL 13 /* these terminate a word */
2972 #define CIGN 14 /* character should be ignored */
2975 #if ENABLE_ASH_ALIAS
2979 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2981 #if ENABLE_FEATURE_SH_MATH
2982 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2984 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2986 static const uint16_t S_I_T[] ALIGN2 = {
2987 #if ENABLE_ASH_ALIAS
2988 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2990 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2991 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2992 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2993 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2994 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2995 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2996 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2997 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2998 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2999 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
3000 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
3001 #if !USE_SIT_FUNCTION
3002 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
3003 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
3004 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
3008 /* Constants below must match table above */
3010 #if ENABLE_ASH_ALIAS
3011 CSPCL_CIGN_CIGN_CIGN , /* 0 */
3013 CSPCL_CWORD_CWORD_CWORD , /* 1 */
3014 CNL_CNL_CNL_CNL , /* 2 */
3015 CWORD_CCTL_CCTL_CWORD , /* 3 */
3016 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
3017 CVAR_CVAR_CWORD_CVAR , /* 5 */
3018 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
3019 CSPCL_CWORD_CWORD_CLP , /* 7 */
3020 CSPCL_CWORD_CWORD_CRP , /* 8 */
3021 CBACK_CBACK_CCTL_CBACK , /* 9 */
3022 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
3023 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
3024 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
3025 CWORD_CWORD_CWORD_CWORD , /* 13 */
3026 CCTL_CCTL_CCTL_CCTL , /* 14 */
3029 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
3030 * caller must ensure proper cast on it if c is *char_ptr!
3032 #if USE_SIT_FUNCTION
3035 SIT(int c, int syntax)
3037 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
3038 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
3040 * This causes '/' to be prepended with CTLESC in dquoted string,
3041 * making "./file"* treated incorrectly because we feed
3042 * ".\/file*" string to glob(), confusing it (see expandmeta func).
3043 * The "homegrown" glob implementation is okay with that,
3044 * but glibc one isn't. With '/' always treated as CWORD,
3047 # if ENABLE_ASH_ALIAS
3048 static const uint8_t syntax_index_table[] ALIGN1 = {
3049 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
3050 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
3051 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
3055 static const uint8_t syntax_index_table[] ALIGN1 = {
3056 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
3057 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
3058 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
3067 # if ENABLE_ASH_ALIAS
3073 /* Cast is purely for paranoia here,
3074 * just in case someone passed signed char to us */
3075 if ((unsigned char)c >= CTL_FIRST
3076 && (unsigned char)c <= CTL_LAST
3080 s = strchrnul(spec_symbls, c);
3083 indx = syntax_index_table[s - spec_symbls];
3085 return (S_I_T[indx] >> (syntax*4)) & 0xf;
3088 #else /* !USE_SIT_FUNCTION */
3090 static const uint8_t syntax_index_table[] ALIGN1 = {
3091 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
3092 /* 0 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 1 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 2 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 3 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 4 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 5 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 6 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 7 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 8 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
3102 /* 10 "\n" */ CNL_CNL_CNL_CNL,
3103 /* 11 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 12 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 13 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 14 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 15 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 16 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 17 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 18 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 19 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 20 */ CWORD_CWORD_CWORD_CWORD,
3113 /* 21 */ CWORD_CWORD_CWORD_CWORD,
3114 /* 22 */ CWORD_CWORD_CWORD_CWORD,
3115 /* 23 */ CWORD_CWORD_CWORD_CWORD,
3116 /* 24 */ CWORD_CWORD_CWORD_CWORD,
3117 /* 25 */ CWORD_CWORD_CWORD_CWORD,
3118 /* 26 */ CWORD_CWORD_CWORD_CWORD,
3119 /* 27 */ CWORD_CWORD_CWORD_CWORD,
3120 /* 28 */ CWORD_CWORD_CWORD_CWORD,
3121 /* 29 */ CWORD_CWORD_CWORD_CWORD,
3122 /* 30 */ CWORD_CWORD_CWORD_CWORD,
3123 /* 31 */ CWORD_CWORD_CWORD_CWORD,
3124 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
3125 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
3126 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
3127 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
3128 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
3129 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
3130 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
3131 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
3132 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
3133 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
3134 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
3135 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
3136 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
3137 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
3138 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
3139 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
3140 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
3141 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
3142 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
3143 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
3144 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
3145 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
3146 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
3147 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
3148 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
3149 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
3150 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
3151 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
3152 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
3153 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
3154 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
3155 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
3156 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
3157 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
3158 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
3159 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
3160 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
3161 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
3162 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
3163 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
3164 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
3165 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
3166 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
3167 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
3168 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
3169 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
3170 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
3171 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
3172 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
3173 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
3174 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
3175 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
3176 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
3177 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
3178 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
3179 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
3180 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
3181 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
3182 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
3183 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
3184 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
3185 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
3186 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
3187 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
3188 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
3189 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
3190 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
3191 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
3192 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
3193 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
3194 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
3195 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
3196 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
3197 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
3198 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
3199 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
3200 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
3201 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
3202 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
3203 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
3204 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3205 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3206 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3207 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3208 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3209 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3210 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3211 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3212 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3213 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3214 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3215 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3216 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3217 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3218 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3219 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3220 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
3221 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
3222 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
3223 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
3224 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
3225 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
3226 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
3227 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3228 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3229 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3230 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3231 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3232 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3233 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3234 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3235 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3236 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3237 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3238 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3239 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3240 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3241 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3242 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3243 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3244 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3245 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3246 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3247 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3248 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3249 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3250 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3251 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3252 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3253 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3254 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3255 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3256 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3257 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3258 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3259 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3260 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3261 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3262 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3263 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3264 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3265 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3266 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3267 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3268 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3269 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3270 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3271 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3272 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3273 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3274 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3275 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3276 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3277 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3278 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3279 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3280 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3281 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3282 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3283 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3284 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3285 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3286 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3287 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3288 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3289 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3290 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3291 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3292 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3293 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3294 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3295 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3296 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3297 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3298 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3299 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3300 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3301 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3302 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3303 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3304 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3305 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3306 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3307 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3308 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3309 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3310 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3311 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3312 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3313 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3314 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3315 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3316 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3317 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3318 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3319 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3320 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3321 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3322 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3323 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3324 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3325 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3326 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3327 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3328 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3329 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3330 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3331 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3332 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3333 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3334 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3335 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3336 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3337 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3338 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3339 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3340 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3341 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3342 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3343 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3344 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3345 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3346 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3347 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3348 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3349 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3350 # if ENABLE_ASH_ALIAS
3351 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3356 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3357 #else /* debug version, caught one signed char bug */
3358 # define SIT(c, syntax) \
3360 if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
3361 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3362 if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
3363 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3364 ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
3368 #endif /* !USE_SIT_FUNCTION */
3371 /* ============ Alias handling */
3373 #if ENABLE_ASH_ALIAS
3375 #define ALIASINUSE 1
3386 static struct alias **atab; // [ATABSIZE];
3387 #define INIT_G_alias() do { \
3388 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3392 static struct alias **
3393 __lookupalias(const char *name)
3395 unsigned int hashval;
3402 ch = (unsigned char)*p;
3406 ch = (unsigned char)*++p;
3408 app = &atab[hashval % ATABSIZE];
3410 for (; *app; app = &(*app)->next) {
3411 if (strcmp(name, (*app)->name) == 0) {
3419 static struct alias *
3420 lookupalias(const char *name, int check)
3422 struct alias *ap = *__lookupalias(name);
3424 if (check && ap && (ap->flag & ALIASINUSE))
3429 static struct alias *
3430 freealias(struct alias *ap)
3434 if (ap->flag & ALIASINUSE) {
3435 ap->flag |= ALIASDEAD;
3447 setalias(const char *name, const char *val)
3449 struct alias *ap, **app;
3451 app = __lookupalias(name);
3455 if (!(ap->flag & ALIASINUSE)) {
3458 ap->val = ckstrdup(val);
3459 ap->flag &= ~ALIASDEAD;
3462 ap = ckzalloc(sizeof(struct alias));
3463 ap->name = ckstrdup(name);
3464 ap->val = ckstrdup(val);
3465 /*ap->flag = 0; - ckzalloc did it */
3466 /*ap->next = NULL;*/
3473 unalias(const char *name)
3477 app = __lookupalias(name);
3481 *app = freealias(*app);
3492 struct alias *ap, **app;
3496 for (i = 0; i < ATABSIZE; i++) {
3498 for (ap = *app; ap; ap = *app) {
3499 *app = freealias(*app);
3509 printalias(const struct alias *ap)
3511 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3515 * TODO - sort output
3517 static int FAST_FUNC
3518 aliascmd(int argc UNUSED_PARAM, char **argv)
3527 for (i = 0; i < ATABSIZE; i++) {
3528 for (ap = atab[i]; ap; ap = ap->next) {
3534 while ((n = *++argv) != NULL) {
3535 v = strchr(n+1, '=');
3536 if (v == NULL) { /* n+1: funny ksh stuff */
3537 ap = *__lookupalias(n);
3539 fprintf(stderr, "%s: %s not found\n", "alias", n);
3552 static int FAST_FUNC
3553 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3557 while (nextopt("a") != '\0') {
3561 for (i = 0; *argptr; argptr++) {
3562 if (unalias(*argptr)) {
3563 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3571 #endif /* ASH_ALIAS */
3574 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3577 #define FORK_NOJOB 2
3579 /* mode flags for showjob(s) */
3580 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3581 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3582 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3583 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3586 * A job structure contains information about a job. A job is either a
3587 * single process or a set of processes contained in a pipeline. In the
3588 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3592 pid_t ps_pid; /* process id */
3593 int ps_status; /* last process status from wait() */
3594 char *ps_cmd; /* text of command being run */
3598 struct procstat ps0; /* status of process */
3599 struct procstat *ps; /* status of processes when more than one */
3601 int stopstatus; /* status of a stopped job */
3603 unsigned nprocs; /* number of processes */
3605 #define JOBRUNNING 0 /* at least one proc running */
3606 #define JOBSTOPPED 1 /* all procs are stopped */
3607 #define JOBDONE 2 /* all procs are completed */
3611 sigint: 1, /* job was killed by SIGINT */
3612 jobctl: 1, /* job running under job control */
3614 waited: 1, /* true if this entry has been waited for */
3615 used: 1, /* true if this entry is in used */
3616 changed: 1; /* true if status has changed */
3617 struct job *prev_job; /* previous job */
3620 static struct job *makejob(/*union node *,*/ int);
3621 static int forkshell(struct job *, union node *, int);
3622 static int waitforjob(struct job *);
3625 enum { doing_jobctl = 0 };
3626 #define setjobctl(on) do {} while (0)
3628 static smallint doing_jobctl; //references:8
3629 static void setjobctl(int);
3636 ignoresig(int signo)
3638 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3639 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3640 /* No, need to do it */
3641 signal(signo, SIG_IGN);
3643 sigmode[signo - 1] = S_HARD_IGN;
3647 * Only one usage site - in setsignal()
3650 signal_handler(int signo)
3652 if (signo == SIGCHLD) {
3658 gotsig[signo - 1] = 1;
3659 pending_sig = signo;
3661 if (signo == SIGINT && !trap[SIGINT]) {
3662 if (!suppress_int) {
3664 raise_interrupt(); /* does not return */
3671 * Set the signal handler for the specified signal. The routine figures
3672 * out what it should be set to.
3675 setsignal(int signo)
3678 char cur_act, new_act;
3679 struct sigaction act;
3683 if (t != NULL) { /* trap for this sig is set */
3685 if (t[0] == '\0') /* trap is "": ignore this sig */
3689 if (rootshell && new_act == S_DFL) {
3692 if (iflag || minusc || sflag == 0)
3701 * "In all cases, bash ignores SIGQUIT. Non-builtin
3702 * commands run by bash have signal handlers
3703 * set to the values inherited by the shell
3704 * from its parent". */
3720 /* if !rootshell, we reset SIGQUIT to DFL,
3721 * whereas we have to restore it to what shell got on entry.
3722 * This is handled by the fact that if signal was IGNored on entry,
3723 * then cur_act is S_HARD_IGN and we never change its sigaction
3727 if (signo == SIGCHLD)
3730 t = &sigmode[signo - 1];
3733 /* current setting is not yet known */
3734 if (sigaction(signo, NULL, &act)) {
3735 /* pretend it worked; maybe we should give a warning,
3736 * but other shells don't. We don't alter sigmode,
3737 * so we retry every time.
3738 * btw, in Linux it never fails. --vda */
3741 if (act.sa_handler == SIG_IGN) {
3742 cur_act = S_HARD_IGN;
3744 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3746 cur_act = S_IGN; /* don't hard ignore these */
3749 if (act.sa_handler == SIG_DFL && new_act == S_DFL) {
3750 /* installing SIG_DFL over SIG_DFL is a no-op */
3751 /* saves one sigaction call in each "sh -c SCRIPT" invocation */
3756 if (cur_act == S_HARD_IGN || cur_act == new_act)
3761 act.sa_handler = SIG_DFL;
3764 act.sa_handler = signal_handler;
3767 act.sa_handler = SIG_IGN;
3770 /* flags and mask matter only if !DFL and !IGN, but we do it
3771 * for all cases for more deterministic behavior:
3773 act.sa_flags = 0; //TODO: why not SA_RESTART?
3774 sigfillset(&act.sa_mask);
3776 sigaction_set(signo, &act);
3779 /* mode flags for set_curjob */
3780 #define CUR_DELETE 2
3781 #define CUR_RUNNING 1
3782 #define CUR_STOPPED 0
3785 /* pgrp of shell on invocation */
3786 static int initialpgrp; //references:2
3787 static int ttyfd = -1; //5
3790 static struct job *jobtab; //5
3792 static unsigned njobs; //4
3794 static struct job *curjob; //lots
3797 /* Bash has a feature: it restores termios after a successful wait for
3798 * a foreground job which had at least one stopped or sigkilled member.
3799 * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
3800 * properly restoring tty state. Should we do this too?
3801 * A reproducer: ^Z an interactive python:
3804 * Python 2.7.12 (...)
3806 * { python leaves tty in -icanon -echo state. We do survive that... }
3807 * [1]+ Stopped python
3808 * { ...however, next program (python #2) does not survive it well: }
3810 * Python 2.7.12 (...)
3811 * >>> Traceback (most recent call last):
3812 * { above, I typed "qwerty<CR>", but -echo state is still in effect }
3813 * File "<stdin>", line 1, in <module>
3814 * NameError: name 'qwerty' is not defined
3816 * The implementation below is modeled on bash code and seems to work.
3817 * However, I'm not sure we should do this. For one: what if I'd fg
3818 * the stopped python instead? It'll be confused by "restored" tty state.
3820 static struct termios shell_tty_info;
3824 if (rootshell && ttyfd >= 0)
3825 tcgetattr(ttyfd, &shell_tty_info);
3830 /* if (rootshell) - caller ensures this */
3832 tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
3835 job_signal_status(struct job *jp)
3839 struct procstat *ps = jp->ps;
3840 for (i = 0; i < jp->nprocs; i++) {
3841 status = ps[i].ps_status;
3842 if (WIFSIGNALED(status) || WIFSTOPPED(status))
3848 restore_tty_if_stopped_or_signaled(struct job *jp)
3850 //TODO: check what happens if we come from waitforjob() in expbackq()
3852 int s = job_signal_status(jp);
3853 if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
3858 # define get_tty_state() ((void)0)
3859 # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
3863 set_curjob(struct job *jp, unsigned mode)
3866 struct job **jpp, **curp;
3868 /* first remove from list */
3869 jpp = curp = &curjob;
3874 jpp = &jp1->prev_job;
3876 *jpp = jp1->prev_job;
3878 /* Then re-insert in correct position */
3886 /* job being deleted */
3889 /* newly created job or backgrounded job,
3890 * put after all stopped jobs.
3895 if (!jp1 || jp1->state != JOBSTOPPED)
3898 jpp = &jp1->prev_job;
3904 /* newly stopped job - becomes curjob */
3905 jp->prev_job = *jpp;
3913 jobno(const struct job *jp)
3915 return jp - jobtab + 1;
3920 * Convert a job name to a job structure.
3923 #define getjob(name, getctl) getjob(name)
3926 getjob(const char *name, int getctl)
3930 const char *err_msg = "%s: no such job";
3934 char *(*match)(const char *, const char *);
3949 if (c == '+' || c == '%') {
3951 err_msg = "No current job";
3957 err_msg = "No previous job";
3967 if (num > 0 && num <= njobs) {
3968 jp = jobtab + num - 1;
3983 if (match(jp->ps[0].ps_cmd, p)) {
3987 err_msg = "%s: ambiguous";
3997 err_msg = "job %s not created under job control";
3998 if (getctl && jp->jobctl == 0)
4003 ash_msg_and_raise_error(err_msg, name);
4007 * Mark a job structure as unused.
4010 freejob(struct job *jp)
4012 struct procstat *ps;
4016 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
4017 if (ps->ps_cmd != nullstr)
4020 if (jp->ps != &jp->ps0)
4023 set_curjob(jp, CUR_DELETE);
4029 xtcsetpgrp(int fd, pid_t pgrp)
4031 if (tcsetpgrp(fd, pgrp))
4032 ash_msg_and_raise_perror("can't set tty process group");
4036 * Turn job control on and off.
4038 * Note: This code assumes that the third arg to ioctl is a character
4039 * pointer, which is true on Berkeley systems but not System V. Since
4040 * System V doesn't have job control yet, this isn't a problem now.
4042 * Called with interrupts off.
4050 if (on == doing_jobctl || rootshell == 0)
4054 ofd = fd = open(_PATH_TTY, O_RDWR);
4056 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
4057 * That sometimes helps to acquire controlling tty.
4058 * Obviously, a workaround for bugs when someone
4059 * failed to provide a controlling tty to bash! :) */
4065 /* fd is a tty at this point */
4066 fd = fcntl(fd, F_DUPFD_CLOEXEC, 10);
4067 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
4070 goto out; /* F_DUPFD failed */
4071 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
4072 close_on_exec_on(fd);
4073 while (1) { /* while we are in the background */
4074 pgrp = tcgetpgrp(fd);
4077 ash_msg("can't access tty; job control turned off");
4081 if (pgrp == getpgrp())
4092 xtcsetpgrp(fd, pgrp);
4094 /* turning job control off */
4097 /* was xtcsetpgrp, but this can make exiting ash
4098 * loop forever if pty is already deleted */
4099 tcsetpgrp(fd, pgrp);
4113 static int FAST_FUNC
4114 killcmd(int argc, char **argv)
4116 if (argv[1] && strcmp(argv[1], "-l") != 0) {
4119 if (argv[i][0] == '%') {
4121 * "kill %N" - job kill
4122 * Converting to pgrp / pid kill
4128 jp = getjob(argv[i], 0);
4130 * In jobs started under job control, we signal
4131 * entire process group by kill -PGRP_ID.
4132 * This happens, f.e., in interactive shell.
4134 * Otherwise, we signal each child via
4135 * kill PID1 PID2 PID3.
4137 * sh -c 'sleep 1|sleep 1 & kill %1'
4138 * sh -c 'true|sleep 2 & sleep 1; kill %1'
4139 * sh -c 'true|sleep 1 & sleep 2; kill %1'
4141 n = jp->nprocs; /* can't be 0 (I hope) */
4144 dst = alloca(n * sizeof(int)*4);
4146 for (j = 0; j < n; j++) {
4147 struct procstat *ps = &jp->ps[j];
4148 /* Skip non-running and not-stopped members
4149 * (i.e. dead members) of the job
4151 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
4154 * kill_main has matching code to expect
4155 * leading space. Needed to not confuse
4156 * negative pids with "kill -SIGNAL_NO" syntax
4158 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
4162 } while (argv[++i]);
4164 return kill_main(argc, argv);
4168 showpipe(struct job *jp /*, FILE *out*/)
4170 struct procstat *ps;
4171 struct procstat *psend;
4173 psend = jp->ps + jp->nprocs;
4174 for (ps = jp->ps + 1; ps < psend; ps++)
4175 printf(" | %s", ps->ps_cmd);
4176 newline_and_flush(stdout);
4177 flush_stdout_stderr();
4182 restartjob(struct job *jp, int mode)
4184 struct procstat *ps;
4190 if (jp->state == JOBDONE)
4192 jp->state = JOBRUNNING;
4193 pgid = jp->ps[0].ps_pid;
4194 if (mode == FORK_FG) {
4196 xtcsetpgrp(ttyfd, pgid);
4198 killpg(pgid, SIGCONT);
4202 if (WIFSTOPPED(ps->ps_status)) {
4208 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
4213 static int FAST_FUNC
4214 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
4220 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
4224 jp = getjob(*argv, 1);
4225 if (mode == FORK_BG) {
4226 set_curjob(jp, CUR_RUNNING);
4227 printf("[%d] ", jobno(jp));
4229 out1str(jp->ps[0].ps_cmd);
4230 showpipe(jp /*, stdout*/);
4231 retval = restartjob(jp, mode);
4232 } while (*argv && *++argv);
4238 sprint_status48(char *os, int status, int sigonly)
4243 if (!WIFEXITED(status)) {
4245 if (WIFSTOPPED(status))
4246 st = WSTOPSIG(status);
4249 st = WTERMSIG(status);
4251 if (st == SIGINT || st == SIGPIPE)
4254 if (WIFSTOPPED(status))
4259 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
4260 //s = stpncpy(s, strsignal(st), 32); //not all libc have stpncpy()
4261 s += fmtstr(s, 32, strsignal(st));
4262 if (WCOREDUMP(status)) {
4263 s = stpcpy(s, " (core dumped)");
4265 } else if (!sigonly) {
4266 st = WEXITSTATUS(status);
4267 s += fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
4274 wait_block_or_sig(int *status)
4281 /* Poll all children for changes in their state */
4283 /* if job control is active, accept stopped processes too */
4284 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
4286 break; /* Error (e.g. EINTR, ECHILD) or pid */
4288 /* Children exist, but none are ready. Sleep until interesting signal */
4291 sigprocmask2(SIG_SETMASK, &mask); /* mask is updated */
4292 while (!got_sigchld && !pending_sig) {
4294 /* ^^^ add "sigdelset(&mask, SIGCHLD);" before sigsuspend
4295 * to make sure SIGCHLD is not masked off?
4296 * It was reported that this:
4297 * fn() { : | return; }
4301 * under bash 4.4.23 runs SCRIPT with SIGCHLD masked,
4302 * making "wait" commands in SCRIPT block forever.
4305 sigprocmask(SIG_SETMASK, &mask, NULL);
4306 #else /* unsafe: a signal can set pending_sig after check, but before pause() */
4307 while (!got_sigchld && !pending_sig)
4311 /* If it was SIGCHLD, poll children again */
4312 } while (got_sigchld);
4317 #define DOWAIT_NONBLOCK 0
4318 #define DOWAIT_BLOCK 1
4319 #define DOWAIT_BLOCK_OR_SIG 2
4321 # define DOWAIT_JOBSTATUS 0x10 /* OR this to get job's exitstatus instead of pid */
4325 waitone(int block, struct job *job)
4330 struct job *thisjob;
4332 bool want_jobexitstatus = (block & DOWAIT_JOBSTATUS);
4333 block = (block & ~DOWAIT_JOBSTATUS);
4336 TRACE(("dowait(0x%x) called\n", block));
4338 /* It's wrong to call waitpid() outside of INT_OFF region:
4339 * signal can arrive just after syscall return and handler can
4340 * longjmp away, losing stop/exit notification processing.
4341 * Thus, for "jobs" builtin, and for waiting for a fg job,
4342 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
4344 * However, for "wait" builtin it is wrong to simply call waitpid()
4345 * in INT_OFF region: "wait" needs to wait for any running job
4346 * to change state, but should exit on any trap too.
4347 * In INT_OFF region, a signal just before syscall entry can set
4348 * pending_sig variables, but we can't check them, and we would
4349 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
4351 * Because of this, we run inside INT_OFF, but use a special routine
4352 * which combines waitpid() and sigsuspend().
4353 * This is the reason why we need to have a handler for SIGCHLD:
4354 * SIG_DFL handler does not wake sigsuspend().
4357 if (block == DOWAIT_BLOCK_OR_SIG) {
4358 pid = wait_block_or_sig(&status);
4361 if (block == DOWAIT_NONBLOCK)
4362 wait_flags = WNOHANG;
4363 /* if job control is active, accept stopped processes too */
4365 wait_flags |= WUNTRACED;
4366 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4367 pid = waitpid(-1, &status, wait_flags);
4369 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4370 pid, status, errno, strerror(errno)));
4375 for (jp = curjob; jp; jp = jp->prev_job) {
4377 struct procstat *ps;
4378 struct procstat *psend;
4379 if (jp->state == JOBDONE)
4383 psend = ps + jp->nprocs;
4385 if (ps->ps_pid == pid) {
4386 TRACE(("Job %d: changing status of proc %d "
4387 "from 0x%x to 0x%x\n",
4388 jobno(jp), pid, ps->ps_status, status));
4389 ps->ps_status = status;
4392 if (ps->ps_status == -1)
4393 jobstate = JOBRUNNING;
4395 if (jobstate == JOBRUNNING)
4397 if (WIFSTOPPED(ps->ps_status)) {
4398 jp->stopstatus = ps->ps_status;
4399 jobstate = JOBSTOPPED;
4402 } while (++ps < psend);
4406 /* Found the job where one of its processes changed its state.
4407 * Is there at least one live and running process in this job? */
4408 if (jobstate != JOBRUNNING) {
4409 /* No. All live processes in the job are stopped
4410 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4412 thisjob->changed = 1;
4413 if (thisjob->state != jobstate) {
4414 TRACE(("Job %d: changing state from %d to %d\n",
4415 jobno(thisjob), thisjob->state, jobstate));
4416 thisjob->state = jobstate;
4418 if (jobstate == JOBSTOPPED)
4419 set_curjob(thisjob, CUR_STOPPED);
4425 /* The process wasn't found in job list */
4430 if (want_jobexitstatus) {
4432 if (thisjob && thisjob->state == JOBDONE)
4433 pid = thisjob->ps[thisjob->nprocs - 1].ps_status;
4436 if (thisjob && thisjob == job) {
4440 len = sprint_status48(s, status, 1);
4451 dowait(int block, struct job *jp)
4453 int pid = block == DOWAIT_NONBLOCK ? got_sigchld : 1;
4455 while (jp ? jp->state == JOBRUNNING : pid > 0) {
4458 pid = waitone(block, jp);
4466 showjob(struct job *jp, int mode)
4468 struct procstat *ps;
4469 struct procstat *psend;
4472 char s[16 + 16 + 48];
4473 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4477 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4478 /* just output process (group) id of pipeline */
4479 fprintf(out, "%d\n", ps->ps_pid);
4483 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4488 else if (curjob && jp == curjob->prev_job)
4491 if (mode & SHOW_PIDS)
4492 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4494 psend = ps + jp->nprocs;
4496 if (jp->state == JOBRUNNING) {
4497 strcpy(s + col, "Running");
4498 col += sizeof("Running") - 1;
4500 int status = psend[-1].ps_status;
4501 if (jp->state == JOBSTOPPED)
4502 status = jp->stopstatus;
4503 col += sprint_status48(s + col, status, 0);
4505 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4507 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4508 * or prints several "PID | <cmdN>" lines,
4509 * depending on SHOW_PIDS bit.
4510 * We do not print status of individual processes
4511 * between PID and <cmdN>. bash does it, but not very well:
4512 * first line shows overall job status, not process status,
4513 * making it impossible to know 1st process status.
4517 /* for each process */
4520 if (mode & SHOW_PIDS)
4521 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4523 fprintf(out, "%s%*c%s%s",
4525 33 - col >= 0 ? 33 - col : 0, ' ',
4526 ps == jp->ps ? "" : "| ",
4529 } while (++ps != psend);
4530 newline_and_flush(out);
4534 if (jp->state == JOBDONE) {
4535 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4541 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4542 * statuses have changed since the last call to showjobs.
4549 TRACE(("showjobs(0x%x) called\n", mode));
4551 /* Handle all finished jobs */
4552 dowait(DOWAIT_NONBLOCK, NULL);
4554 for (jp = curjob; jp; jp = jp->prev_job) {
4555 if (!(mode & SHOW_CHANGED) || jp->changed) {
4561 static int FAST_FUNC
4562 jobscmd(int argc UNUSED_PARAM, char **argv)
4567 while ((m = nextopt("lp")) != '\0') {
4571 mode |= SHOW_ONLY_PGID;
4577 showjob(getjob(*argv, 0), mode);
4587 /* Called only on finished or stopped jobs (no members are running) */
4589 getstatus(struct job *job)
4593 struct procstat *ps;
4595 /* Fetch last member's status */
4596 ps = job->ps + job->nprocs - 1;
4597 status = ps->ps_status;
4599 /* "set -o pipefail" mode: use last _nonzero_ status */
4600 while (status == 0 && --ps >= job->ps)
4601 status = ps->ps_status;
4604 retval = WEXITSTATUS(status);
4605 if (!WIFEXITED(status)) {
4607 retval = WSTOPSIG(status);
4608 if (!WIFSTOPPED(status))
4611 /* XXX: limits number of signals */
4612 retval = WTERMSIG(status);
4614 if (retval == SIGINT)
4620 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4621 jobno(job), job->nprocs, status, retval));
4625 static int FAST_FUNC
4626 waitcmd(int argc UNUSED_PARAM, char **argv)
4633 char one = nextopt("n");
4641 /* wait for all jobs / one job if -n */
4646 /* exitcode of "wait -n" with nothing to wait for is 127, not 0 */
4650 if (!jp) /* no running procs */
4652 if (jp->state == JOBRUNNING)
4658 * "When bash is waiting for an asynchronous command via
4659 * the wait builtin, the reception of a signal for which a trap
4660 * has been set will cause the wait builtin to return immediately
4661 * with an exit status greater than 128, immediately after which
4662 * the trap is executed."
4665 status = dowait(DOWAIT_BLOCK_OR_SIG | DOWAIT_JOBSTATUS, NULL);
4667 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4669 /* if child sends us a signal *and immediately exits*,
4670 * dowait() returns pid > 0. Check this case,
4671 * not "if (dowait() < 0)"!
4677 /* wait -n waits for one _job_, not one _process_.
4678 * date; sleep 3 & sleep 2 | sleep 1 & wait -n; date
4679 * should wait for 2 seconds. Not 1 or 3.
4681 if (status != -1 && !WIFSTOPPED(status)) {
4682 retval = WEXITSTATUS(status);
4683 if (WIFSIGNALED(status))
4684 retval = WTERMSIG(status) + 128;
4694 if (**argv != '%') {
4695 pid_t pid = number(*argv);
4700 if (job->ps[job->nprocs - 1].ps_pid == pid)
4702 job = job->prev_job;
4705 job = getjob(*argv, 0);
4707 /* loop until process terminated or stopped */
4708 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4712 retval = getstatus(job);
4719 retval = 128 + pending_sig;
4728 struct job *jp, *jq;
4730 len = njobs * sizeof(*jp);
4732 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4734 offset = (char *)jp - (char *)jq;
4736 /* Relocate pointers */
4739 jq = (struct job *)((char *)jq + l);
4743 #define joff(p) ((struct job *)((char *)(p) + l))
4744 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4745 if (joff(jp)->ps == &jq->ps0)
4746 jmove(joff(jp)->ps);
4747 if (joff(jp)->prev_job)
4748 jmove(joff(jp)->prev_job);
4758 jp = (struct job *)((char *)jp + len);
4762 } while (--jq >= jp);
4767 * Return a new job structure.
4768 * Called with interrupts off.
4771 makejob(/*union node *node,*/ int nprocs)
4776 for (i = njobs, jp = jobtab; ; jp++) {
4783 if (jp->state != JOBDONE || !jp->waited)
4792 memset(jp, 0, sizeof(*jp));
4794 /* jp->jobctl is a bitfield.
4795 * "jp->jobctl |= doing_jobctl" likely to give awful code */
4799 jp->prev_job = curjob;
4804 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4806 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4813 * Return a string identifying a command (to be printed by the
4816 static char *cmdnextc;
4819 cmdputs(const char *s)
4821 static const char vstype[VSTYPE + 1][3] = {
4822 "", "}", "-", "+", "?", "=",
4823 "%", "%%", "#", "##"
4824 IF_BASH_SUBSTR(, ":")
4825 IF_BASH_PATTERN_SUBST(, "/", "//")
4828 const char *p, *str;
4832 unsigned char subtype = 0;
4836 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4838 while ((c = *p++) != '\0') {
4846 if ((subtype & VSTYPE) == VSLENGTH)
4853 str += !(quoted & 1);
4860 #if ENABLE_FEATURE_SH_MATH
4875 if ((subtype & VSTYPE) != VSNORMAL)
4877 str = vstype[subtype & VSTYPE];
4878 if (subtype & VSNUL)
4887 /* These can only happen inside quotes */
4893 // [1]+ Done true ${\$} <<=== BUG: ${\$} is not a valid way to write $$ (${$} would be ok)
4904 while ((c = *str++) != '\0') {
4907 } /* while *p++ not NUL */
4910 USTPUTC('"', nextc);
4916 /* cmdtxt() and cmdlist() call each other */
4917 static void cmdtxt(union node *n);
4920 cmdlist(union node *np, int sep)
4922 for (; np; np = np->narg.next) {
4926 if (sep && np->narg.next)
4932 cmdtxt(union node *n)
4935 struct nodelist *lp;
4946 lp = n->npipe.cmdlist;
4964 cmdtxt(n->nbinary.ch1);
4980 cmdtxt(n->nif.test);
4982 if (n->nif.elsepart) {
4983 cmdtxt(n->nif.ifpart);
4985 n = n->nif.elsepart;
5003 cmdtxt(n->nbinary.ch1);
5013 cmdputs(n->nfor.var);
5015 cmdlist(n->nfor.args, 1);
5020 cmdputs(n->ndefun.text);
5024 cmdlist(n->ncmd.args, 1);
5025 cmdlist(n->ncmd.redirect, 0);
5038 cmdputs(n->ncase.expr->narg.text);
5040 for (np = n->ncase.cases; np; np = np->nclist.next) {
5041 cmdtxt(np->nclist.pattern);
5043 cmdtxt(np->nclist.body);
5057 #if BASH_REDIR_OUTPUT
5072 cmdputs(utoa(n->nfile.fd));
5074 if (n->type == NTOFD || n->type == NFROMFD) {
5075 if (n->ndup.dupfd >= 0)
5076 cmdputs(utoa(n->ndup.dupfd));
5087 commandtext(union node *n)
5091 STARTSTACKSTR(cmdnextc);
5093 name = stackblock();
5094 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
5095 return ckstrdup(name);
5100 * Fork off a subshell. If we are doing job control, give the subshell its
5101 * own process group. Jp is a job structure that the job is to be added to.
5102 * N is the command that will be evaluated by the child. Both jp and n may
5103 * be NULL. The mode parameter can be one of the following:
5104 * FORK_FG - Fork off a foreground process.
5105 * FORK_BG - Fork off a background process.
5106 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
5107 * process group even if job control is on.
5109 * When job control is turned off, background processes have their standard
5110 * input redirected to /dev/null (except for the second and later processes
5113 * Called with interrupts off.
5116 * Clear traps on a fork.
5124 for (tp = trap; tp < &trap[NSIG]; tp++) {
5125 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
5126 if (trap_ptr == trap)
5128 /* else: it "belongs" to trap_ptr vector, don't free */
5130 if ((tp - trap) != 0)
5131 setsignal(tp - trap);
5138 /* Lives far away from here, needed for forkchild */
5139 static void closescript(void);
5141 /* Called after fork(), in child */
5142 /* jp and n are NULL when called by openhere() for heredoc support */
5143 static NOINLINE void
5144 forkchild(struct job *jp, union node *n, int mode)
5148 TRACE(("Child shell %d\n", getpid()));
5152 /* man bash: "Non-builtin commands run by bash have signal handlers
5153 * set to the values inherited by the shell from its parent".
5154 * Do we do it correctly? */
5158 if (mode == FORK_NOJOB /* is it `xxx` ? */
5159 && n && n->type == NCMD /* is it single cmd? */
5160 /* && n->ncmd.args->type == NARG - always true? */
5161 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
5162 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
5163 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
5165 TRACE(("Trap hack\n"));
5166 /* Awful hack for `trap` or $(trap).
5168 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5169 * contains an example where "trap" is executed in a subshell:
5171 * save_traps=$(trap)
5173 * eval "$save_traps"
5175 * Standard does not say that "trap" in subshell shall print
5176 * parent shell's traps. It only says that its output
5177 * must have suitable form, but then, in the above example
5178 * (which is not supposed to be normative), it implies that.
5180 * bash (and probably other shell) does implement it
5181 * (traps are reset to defaults, but "trap" still shows them),
5182 * but as a result, "trap" logic is hopelessly messed up:
5185 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5186 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5187 * # true | trap <--- trap is in subshell - no output (ditto)
5188 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5189 * trap -- 'echo Ho' SIGWINCH
5190 * # echo `(trap)` <--- in subshell in subshell - output
5191 * trap -- 'echo Ho' SIGWINCH
5192 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5193 * trap -- 'echo Ho' SIGWINCH
5195 * The rules when to forget and when to not forget traps
5196 * get really complex and nonsensical.
5198 * Our solution: ONLY bare $(trap) or `trap` is special.
5200 /* Save trap handler strings for trap builtin to print */
5201 trap_ptr = xmemdup(trap, sizeof(trap));
5202 /* Fall through into clearing traps */
5206 /* do job control only in root shell */
5208 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
5211 if (jp->nprocs == 0)
5214 pgrp = jp->ps[0].ps_pid;
5215 /* this can fail because we are doing it in the parent also */
5217 if (mode == FORK_FG)
5218 xtcsetpgrp(ttyfd, pgrp);
5223 if (mode == FORK_BG) {
5224 /* man bash: "When job control is not in effect,
5225 * asynchronous commands ignore SIGINT and SIGQUIT" */
5228 if (jp->nprocs == 0) {
5230 if (open(bb_dev_null, O_RDONLY) != 0)
5231 ash_msg_and_raise_perror("can't open '%s'", bb_dev_null);
5235 if (iflag) { /* why if iflag only? */
5240 * "In all cases, bash ignores SIGQUIT. Non-builtin
5241 * commands run by bash have signal handlers
5242 * set to the values inherited by the shell
5244 * Take care of the second rule: */
5248 if (n && n->type == NCMD
5249 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
5251 TRACE(("Job hack\n"));
5252 /* "jobs": we do not want to clear job list for it,
5253 * instead we remove only _its_ own_ job from job list.
5254 * This makes "jobs .... | cat" more useful.
5260 for (jp = curjob; jp; jp = jp->prev_job)
5264 /* Called after fork(), in parent */
5266 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
5269 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
5271 TRACE(("In parent shell: child = %d\n", pid));
5272 if (!jp) /* jp is NULL when called by openhere() for heredoc support */
5275 if (mode != FORK_NOJOB && jp->jobctl) {
5278 if (jp->nprocs == 0)
5281 pgrp = jp->ps[0].ps_pid;
5282 /* This can fail because we are doing it in the child also */
5286 if (mode == FORK_BG) {
5287 backgndpid = pid; /* set $! */
5288 set_curjob(jp, CUR_RUNNING);
5291 struct procstat *ps = &jp->ps[jp->nprocs++];
5294 ps->ps_cmd = nullstr;
5296 if (doing_jobctl && n)
5297 ps->ps_cmd = commandtext(n);
5302 /* jp and n are NULL when called by openhere() for heredoc support */
5304 forkshell(struct job *jp, union node *n, int mode)
5308 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
5311 TRACE(("Fork failed, errno=%d", errno));
5314 ash_msg_and_raise_perror("can't fork");
5317 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
5318 forkchild(jp, n, mode);
5320 forkparent(jp, n, mode, pid);
5326 * Wait for job to finish.
5328 * Under job control we have the problem that while a child process
5329 * is running interrupts generated by the user are sent to the child
5330 * but not to the shell. This means that an infinite loop started by
5331 * an interactive user may be hard to kill. With job control turned off,
5332 * an interactive user may place an interactive program inside a loop.
5333 * If the interactive program catches interrupts, the user doesn't want
5334 * these interrupts to also abort the loop. The approach we take here
5335 * is to have the shell ignore interrupt signals while waiting for a
5336 * foreground process to terminate, and then send itself an interrupt
5337 * signal if the child process was terminated by an interrupt signal.
5338 * Unfortunately, some programs want to do a bit of cleanup and then
5339 * exit on interrupt; unless these processes terminate themselves by
5340 * sending a signal to themselves (instead of calling exit) they will
5341 * confuse this approach.
5343 * Called with interrupts off.
5346 waitforjob(struct job *jp)
5350 TRACE(("waitforjob(%%%d) called\n", jp ? jobno(jp) : 0));
5352 /* In non-interactive shells, we _can_ get
5353 * a keyboard signal here and be EINTRed, but we just loop
5354 * inside dowait(), waiting for command to complete.
5357 * "If bash is waiting for a command to complete and receives
5358 * a signal for which a trap has been set, the trap
5359 * will not be executed until the command completes."
5361 * Reality is that even if trap is not set, bash
5362 * will not act on the signal until command completes.
5363 * Try this. sleep5intoff.c:
5364 * #include <signal.h>
5365 * #include <unistd.h>
5368 * sigemptyset(&set);
5369 * sigaddset(&set, SIGINT);
5370 * sigaddset(&set, SIGQUIT);
5371 * sigprocmask(SIG_BLOCK, &set, NULL);
5375 * $ bash -c './sleep5intoff; echo hi'
5376 * ^C^C^C^C <--- pressing ^C once a second
5378 * $ bash -c './sleep5intoff; echo hi'
5379 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
5382 dowait(jp ? DOWAIT_BLOCK : DOWAIT_NONBLOCK, jp);
5389 xtcsetpgrp(ttyfd, rootpid);
5390 restore_tty_if_stopped_or_signaled(jp);
5393 * This is truly gross.
5394 * If we're doing job control, then we did a TIOCSPGRP which
5395 * caused us (the shell) to no longer be in the controlling
5396 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
5397 * intuit from the subprocess exit status whether a SIGINT
5398 * occurred, and if so interrupt ourselves. Yuck. - mycroft
5400 if (jp->sigint) /* TODO: do the same with all signals */
5401 raise(SIGINT); /* ... by raise(jp->sig) instead? */
5403 if (jp->state == JOBDONE)
5410 * return 1 if there are stopped jobs, otherwise 0
5422 if (jp && jp->state == JOBSTOPPED) {
5423 out2str("You have stopped jobs.\n");
5433 * Code for dealing with input/output redirection.
5438 #define EMPTY -2 /* marks an unused slot in redirtab */
5439 #define CLOSED -1 /* marks a slot of previously-closed fd */
5442 * Handle here documents. Normally we fork off a process to write the
5443 * data to a pipe. If the document is short, we can stuff the data in
5444 * the pipe without forking.
5446 /* openhere needs this forward reference */
5447 static void expandhere(union node *arg, int fd);
5449 openhere(union node *redir)
5455 ash_msg_and_raise_perror("can't create pipe");
5456 if (redir->type == NHERE) {
5457 len = strlen(redir->nhere.doc->narg.text);
5458 if (len <= PIPE_BUF) {
5459 full_write(pip[1], redir->nhere.doc->narg.text, len);
5463 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5466 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5467 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5468 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5469 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5470 signal(SIGPIPE, SIG_DFL);
5471 if (redir->type == NHERE)
5472 full_write(pip[1], redir->nhere.doc->narg.text, len);
5474 expandhere(redir->nhere.doc, pip[1]);
5475 _exit(EXIT_SUCCESS);
5483 openredirect(union node *redir)
5489 switch (redir->nfile.type) {
5490 /* Can't happen, our single caller does this itself */
5496 return openhere(redir);
5499 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5500 * allocated space. Do it only when we know it is safe.
5502 fname = redir->nfile.expfname;
5504 switch (redir->nfile.type) {
5510 f = open(fname, O_RDONLY);
5515 f = open(fname, O_RDWR|O_CREAT, 0666);
5520 #if BASH_REDIR_OUTPUT
5523 /* Take care of noclobber mode. */
5525 if (stat(fname, &sb) < 0) {
5526 f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5529 } else if (!S_ISREG(sb.st_mode)) {
5530 f = open(fname, O_WRONLY, 0666);
5533 if (!fstat(f, &sb) && S_ISREG(sb.st_mode)) {
5546 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5551 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5559 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5561 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5565 * Copy a file descriptor to be >= 10. Throws exception on error.
5573 newfd = fcntl(from, F_DUPFD_CLOEXEC, 10);
5574 err = newfd < 0 ? errno : 0;
5577 ash_msg_and_raise_perror("%d", from);
5579 if (F_DUPFD_CLOEXEC == F_DUPFD)
5580 close_on_exec_on(newfd);
5586 dup2_or_raise(int from, int to)
5590 newfd = (from != to) ? dup2(from, to) : to;
5592 /* Happens when source fd is not open: try "echo >&99" */
5593 ash_msg_and_raise_perror("%d", from);
5598 dup_CLOEXEC(int fd, int avoid_fd)
5602 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
5604 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
5605 close_on_exec_on(newfd);
5606 } else { /* newfd < 0 */
5615 xdup_CLOEXEC_and_close(int fd, int avoid_fd)
5619 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
5625 /* fd was not open? */
5628 ash_msg_and_raise_perror("%d", newfd);
5630 if (F_DUPFD_CLOEXEC == F_DUPFD)
5631 close_on_exec_on(newfd);
5636 /* Struct def and variable are moved down to the first usage site */
5642 struct redirtab *next;
5644 struct squirrel two_fd[];
5646 #define redirlist (G_var.redirlist)
5649 add_squirrel_closed(struct redirtab *sq, int fd)
5656 for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
5657 /* If we collide with an already moved fd... */
5658 if (fd == sq->two_fd[i].orig_fd) {
5660 * "echo 3>FILE 3>&- 3>FILE"
5661 * "echo 3>&- 3>FILE"
5662 * No need for last redirect to insert
5663 * another "need to close 3" indicator.
5665 TRACE(("redirect_fd %d: already moved or closed\n", fd));
5669 TRACE(("redirect_fd %d: previous fd was closed\n", fd));
5670 sq->two_fd[i].orig_fd = fd;
5671 sq->two_fd[i].moved_to = CLOSED;
5675 save_fd_on_redirect(int fd, int avoid_fd, struct redirtab *sq)
5679 if (avoid_fd < 9) /* the important case here is that it can be -1 */
5684 /* Testcase: "ls -l /proc/$$/fd 10>&-" should work */
5685 ttyfd = xdup_CLOEXEC_and_close(ttyfd, avoid_fd);
5686 TRACE(("redirect_fd %d: matches ttyfd, moving it to %d\n", fd, ttyfd));
5687 return 1; /* "we closed fd" */
5690 /* Are we called from redirect(0)? E.g. redirect
5691 * in a forked child. No need to save fds,
5692 * we aren't going to use them anymore, ok to trash.
5697 /* If this one of script's fds? */
5699 struct parsefile *pf = g_parsefile;
5701 /* We skip fd == 0 case because of the following:
5702 * $ ash # running ash interactively
5704 * and in script.sh: "exec 9>&0".
5705 * Even though top-level pf_fd _is_ 0,
5706 * it's still ok to use it: "read" builtin uses it,
5707 * why should we cripple "exec" builtin?
5709 if (fd == pf->pf_fd) {
5710 pf->pf_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
5711 return 1; /* "we closed fd" */
5717 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
5719 /* First: do we collide with some already moved fds? */
5720 for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
5721 /* If we collide with an already moved fd... */
5722 if (fd == sq->two_fd[i].moved_to) {
5723 new_fd = dup_CLOEXEC(fd, avoid_fd);
5724 sq->two_fd[i].moved_to = new_fd;
5725 TRACE(("redirect_fd %d: already busy, moving to %d\n", fd, new_fd));
5726 if (new_fd < 0) /* what? */
5728 return 0; /* "we did not close fd" */
5730 if (fd == sq->two_fd[i].orig_fd) {
5731 /* Example: echo Hello >/dev/null 1>&2 */
5732 TRACE(("redirect_fd %d: already moved\n", fd));
5733 return 0; /* "we did not close fd" */
5737 /* If this fd is open, we move and remember it; if it's closed, new_fd = CLOSED (-1) */
5738 new_fd = dup_CLOEXEC(fd, avoid_fd);
5739 TRACE(("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, new_fd));
5743 /* new_fd = CLOSED; - already is -1 */
5745 sq->two_fd[i].moved_to = new_fd;
5746 sq->two_fd[i].orig_fd = fd;
5748 /* if we move stderr, let "set -x" code know */
5749 if (fd == preverrout_fd)
5750 preverrout_fd = new_fd;
5752 return 0; /* "we did not close fd" */
5756 internally_opened_fd(int fd, struct redirtab *sq)
5763 /* If this one of script's fds? */
5765 struct parsefile *pf = g_parsefile;
5767 if (fd == pf->pf_fd)
5773 if (sq) for (i = 0; i < sq->pair_count && sq->two_fd[i].orig_fd != EMPTY; i++) {
5774 if (fd == sq->two_fd[i].moved_to)
5781 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5782 * old file descriptors are stashed away so that the redirection can be
5783 * undone by calling popredir.
5785 /* flags passed to redirect */
5786 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5788 redirect(union node *redir, int flags)
5790 struct redirtab *sv;
5797 if (flags & REDIR_PUSH)
5805 fd = redir->nfile.fd;
5806 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5807 //bb_error_msg("doing %d > %d", fd, newfd);
5808 newfd = redir->ndup.dupfd;
5811 newfd = openredirect(redir); /* always >= 0 */
5813 /* open() gave us precisely the fd we wanted.
5814 * This means that this fd was not busy
5815 * (not opened to anywhere).
5816 * Remember to close it on restore:
5818 add_squirrel_closed(sv, fd);
5827 /* if "N>FILE": move newfd to fd */
5828 /* if "N>&M": dup newfd to fd */
5829 /* if "N>&-": close fd (newfd is -1) */
5831 IF_BASH_REDIR_OUTPUT(redirect_more:)
5833 closed = save_fd_on_redirect(fd, /*avoid:*/ newfd, sv);
5835 /* "N>&-" means "close me" */
5837 /* ^^^ optimization: saving may already
5838 * have closed it. If not... */
5842 /* if newfd is a script fd or saved fd, simulate EBADF */
5843 if (internally_opened_fd(newfd, sv)) {
5845 ash_msg_and_raise_perror("%d", newfd);
5847 dup2_or_raise(newfd, fd);
5848 if (close_fd >= 0) /* "N>FILE" or ">&FILE" or heredoc? */
5850 #if BASH_REDIR_OUTPUT
5851 if (redir->nfile.type == NTO2 && fd == 1) {
5852 /* ">&FILE". we already redirected to 1, now copy 1 to 2 */
5860 } while ((redir = redir->nfile.next) != NULL);
5863 //dash:#define REDIR_SAVEFD2 03 /* set preverrout */
5864 #define REDIR_SAVEFD2 0
5865 // dash has a bug: since REDIR_SAVEFD2=3 and REDIR_PUSH=1, this test
5866 // triggers for pure REDIR_PUSH too. Thus, this is done almost always,
5867 // not only for calls with flags containing REDIR_SAVEFD2.
5868 // We do this unconditionally (see save_fd_on_redirect()).
5869 //if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5870 // preverrout_fd = copied_fd2;
5874 redirectsafe(union node *redir, int flags)
5877 volatile int saveint;
5878 struct jmploc *volatile savehandler = exception_handler;
5879 struct jmploc jmploc;
5882 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5883 err = setjmp(jmploc.loc); /* was = setjmp(jmploc.loc) * 2; */
5885 exception_handler = &jmploc;
5886 redirect(redir, flags);
5888 exception_handler = savehandler;
5889 if (err && exception_type != EXERROR)
5890 longjmp(exception_handler->loc, 1);
5891 RESTORE_INT(saveint);
5895 static struct redirtab*
5896 pushredir(union node *redir)
5898 struct redirtab *sv;
5907 #if BASH_REDIR_OUTPUT
5908 if (redir->nfile.type == NTO2)
5911 redir = redir->nfile.next;
5914 sv = ckzalloc(sizeof(*sv) + i * sizeof(sv->two_fd[0]));
5917 sv->two_fd[i].orig_fd = sv->two_fd[i].moved_to = EMPTY;
5918 sv->next = redirlist;
5924 * Undo the effects of the last redirection.
5929 struct redirtab *rp;
5932 if (redirlist == NULL)
5936 for (i = 0; i < rp->pair_count; i++) {
5937 int fd = rp->two_fd[i].orig_fd;
5938 int copy = rp->two_fd[i].moved_to;
5939 if (copy == CLOSED) {
5944 if (copy != EMPTY) {
5947 dup2_or_raise(copy, fd);
5952 redirlist = rp->next;
5958 unwindredir(struct redirtab *stop)
5960 while (redirlist != stop)
5961 popredir(/*drop:*/ 0);
5965 /* ============ Routines to expand arguments to commands
5967 * We have to deal with backquotes, shell variables, and file metacharacters.
5970 #if ENABLE_FEATURE_SH_MATH
5972 ash_arith(const char *s)
5974 arith_state_t math_state;
5977 math_state.lookupvar = lookupvar;
5978 math_state.setvar = setvar0;
5979 //math_state.endofname = endofname;
5982 result = arith(&math_state, s);
5983 if (math_state.errmsg)
5984 ash_msg_and_raise_error(math_state.errmsg);
5991 # if ENABLE_FEATURE_SH_MATH
5992 static int substr_atoi(const char *s)
5994 arith_t t = ash_arith(s);
5995 if (sizeof(t) > sizeof(int)) {
5996 /* clamp very large or very large negative nums for ${v:N:M}:
5997 * else "${v:0:0x100000001}" would work as "${v:0:1}"
6007 # define substr_atoi(s) number(s)
6014 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
6015 #define EXP_TILDE 0x2 /* do normal tilde expansion */
6016 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
6017 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
6018 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
6019 * POSIX says for this case:
6020 * Pathname expansion shall not be performed on the word by a
6021 * non-interactive shell; an interactive shell may perform it, but shall
6022 * do so only when the expansion would result in one word.
6023 * Currently, our code complies to the above rule by never globbing
6024 * redirection filenames.
6025 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
6026 * (this means that on a typical Linux distro, bash almost always
6027 * performs globbing, and thus diverges from what we do).
6029 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
6030 #define EXP_VARTILDE2 0x20 /* expand tildes after colons only */
6031 #define EXP_WORD 0x40 /* expand word in parameter expansion */
6032 #define EXP_QUOTED 0x100 /* expand word in double quotes */
6033 #define EXP_KEEPNUL 0x200 /* do not skip NUL characters */
6038 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
6039 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
6040 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
6041 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
6043 /* Add CTLESC when necessary. */
6044 #define QUOTES_ESC (EXP_FULL | EXP_CASE)
6047 * Structure specifying which parts of the string should be searched
6048 * for IFS characters.
6051 struct ifsregion *next; /* next region in list */
6052 int begoff; /* offset of start of region */
6053 int endoff; /* offset of end of region */
6054 int nulonly; /* search for nul bytes only */
6058 struct strlist *list;
6059 struct strlist **lastp;
6062 /* output of current string */
6063 static char *expdest;
6064 /* list of back quote expressions */
6065 static struct nodelist *argbackq;
6066 /* first struct in list of ifs regions */
6067 static struct ifsregion ifsfirst;
6068 /* last struct in list */
6069 static struct ifsregion *ifslastp;
6070 /* holds expanded arg list */
6071 static struct arglist exparg;
6075 * cvtnum() is used even if math support is off (to prepare $? values and such).
6082 /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
6083 len = sizeof(arith_t) * 3;
6084 /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
6085 if (sizeof(arith_t) < 4) len += 2;
6087 expdest = makestrspace(len, expdest);
6088 len = fmtstr(expdest, len, ARITH_FMT, num);
6089 STADJUST(len, expdest);
6094 * Break the argument string into pieces based upon IFS and add the
6095 * strings to the argument list. The regions of the string to be
6096 * searched for IFS characters have been stored by recordregion.
6099 ifsbreakup(char *string, struct arglist *arglist)
6101 struct ifsregion *ifsp;
6106 const char *ifs, *realifs;
6111 if (ifslastp != NULL) {
6114 realifs = ifsset() ? ifsval() : defifs;
6119 p = string + ifsp->begoff;
6121 nulonly = ifsp->nulonly;
6122 ifs = nulonly ? nullstr : realifs;
6124 while (p < string + ifsp->endoff) {
6126 if ((unsigned char)*p == CTLESC)
6128 if (!strchr(ifs, *p)) {
6132 if (!(afternul || nulonly))
6133 ifsspc = (strchr(defifs, *p) != NULL);
6134 /* Ignore IFS whitespace at start */
6135 if (q == start && ifsspc) {
6141 sp = stzalloc(sizeof(*sp));
6143 *arglist->lastp = sp;
6144 arglist->lastp = &sp->next;
6148 if (p >= string + ifsp->endoff) {
6152 if ((unsigned char)*p == CTLESC)
6154 if (strchr(ifs, *p) == NULL) {
6158 if (strchr(defifs, *p) == NULL) {
6173 } while (ifsp != NULL);
6182 sp = stzalloc(sizeof(*sp));
6184 *arglist->lastp = sp;
6185 arglist->lastp = &sp->next;
6191 struct ifsregion *p = ifsfirst.next;
6198 struct ifsregion *ifsp;
6203 ifsfirst.next = NULL;
6210 esclen(const char *start, const char *p)
6214 while (p > start && (unsigned char)*--p == CTLESC) {
6221 * Remove any CTLESC characters from a string.
6223 #if !BASH_PATTERN_SUBST
6224 #define rmescapes(str, flag, slash_position) \
6225 rmescapes(str, flag)
6228 rmescapes(char *str, int flag, int *slash_position)
6230 static const char qchars[] ALIGN1 = {
6231 IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
6234 unsigned protect_against_glob;
6237 p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash_position));
6243 if (flag & RMESCAPE_ALLOC) {
6244 size_t len = p - str;
6245 size_t fulllen = len + strlen(p) + 1;
6247 if (flag & RMESCAPE_GROW) {
6248 int strloc = str - (char *)stackblock();
6249 r = makestrspace(fulllen, expdest);
6250 /* p and str may be invalidated by makestrspace */
6251 str = (char *)stackblock() + strloc;
6253 } else if (flag & RMESCAPE_HEAP) {
6254 r = ckmalloc(fulllen);
6256 r = stalloc(fulllen);
6260 q = (char *)mempcpy(q, str, len);
6264 globbing = flag & RMESCAPE_GLOB;
6265 protect_against_glob = globbing;
6267 if ((unsigned char)*p == CTLQUOTEMARK) {
6268 // Note: protect_against_glob only affect whether
6269 // CTLESC,<ch> gets converted to <ch> or to \<ch>
6271 protect_against_glob = globbing;
6275 /* naked back slash */
6276 protect_against_glob = 0;
6279 if ((unsigned char)*p == CTLESC) {
6283 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
6285 if (protect_against_glob) {
6287 * We used to trust glob() and fnmatch() to eat
6288 * superfluous escapes (\z where z has no
6289 * special meaning anyway). But this causes
6290 * bugs such as string of one greek letter rho
6291 * (unicode-encoded as two bytes "cf,81")
6292 * getting encoded as "cf,CTLESC,81"
6293 * and here, converted to "cf,\,81" -
6294 * which does not go well with some flavors
6295 * of fnmatch() in unicode locales
6296 * (for example, glibc <= 2.22).
6298 * Lets add "\" only on the chars which need it.
6299 * Testcases for less obvious chars are shown.
6304 || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
6305 || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
6306 || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
6307 || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
6308 /* Some libc support [^negate], that's why "^" also needs love */
6309 || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
6315 #if BASH_PATTERN_SUBST
6316 else if (slash_position && p == str + *slash_position) {
6317 /* stop handling globbing */
6319 *slash_position = q - r;
6320 slash_position = NULL;
6323 protect_against_glob = globbing;
6328 if (flag & RMESCAPE_GROW) {
6330 STADJUST(q - r + 1, expdest);
6334 #define pmatch(a, b) !fnmatch((a), (b), 0)
6337 * Prepare a pattern for a expmeta (internal glob(3)) call.
6339 * Returns an stalloced string.
6342 preglob(const char *pattern, int flag)
6344 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB, NULL);
6348 * Put a string on the stack.
6351 memtodest(const char *p, size_t len, int flags)
6353 int syntax = flags & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6359 q = makestrspace(len * 2, expdest);
6362 unsigned char c = *p++;
6364 if (flags & QUOTES_ESC) {
6365 int n = SIT(c, syntax);
6367 || ((flags & EXP_QUOTED) && n == CBACK)
6372 } else if (!(flags & EXP_KEEPNUL))
6381 strtodest(const char *p, int flags)
6383 size_t len = strlen(p);
6384 memtodest(p, len, flags);
6389 * Record the fact that we have to scan this region of the
6390 * string for IFS characters.
6393 recordregion(int start, int end, int nulonly)
6395 struct ifsregion *ifsp;
6397 if (ifslastp == NULL) {
6401 ifsp = ckzalloc(sizeof(*ifsp));
6402 /*ifsp->next = NULL; - ckzalloc did it */
6403 ifslastp->next = ifsp;
6407 ifslastp->begoff = start;
6408 ifslastp->endoff = end;
6409 ifslastp->nulonly = nulonly;
6413 removerecordregions(int endoff)
6415 if (ifslastp == NULL)
6418 if (ifsfirst.endoff > endoff) {
6419 while (ifsfirst.next) {
6420 struct ifsregion *ifsp;
6422 ifsp = ifsfirst.next->next;
6423 free(ifsfirst.next);
6424 ifsfirst.next = ifsp;
6427 if (ifsfirst.begoff > endoff) {
6430 ifslastp = &ifsfirst;
6431 ifsfirst.endoff = endoff;
6436 ifslastp = &ifsfirst;
6437 while (ifslastp->next && ifslastp->next->begoff < endoff)
6438 ifslastp = ifslastp->next;
6439 while (ifslastp->next) {
6440 struct ifsregion *ifsp;
6442 ifsp = ifslastp->next->next;
6443 free(ifslastp->next);
6444 ifslastp->next = ifsp;
6447 if (ifslastp->endoff > endoff)
6448 ifslastp->endoff = endoff;
6452 exptilde(char *startp, char *p, int flag)
6461 while ((c = *++p) != '\0') {
6468 if (flag & EXP_VARTILDE)
6478 if (*name == '\0') {
6479 home = lookupvar("HOME");
6481 pw = getpwnam(name);
6489 strtodest(home, flag | EXP_QUOTED);
6497 * Execute a command inside back quotes. If it's a builtin command, we
6498 * want to save its output in a block obtained from malloc. Otherwise
6499 * we fork off a subprocess and get the output of the command via a pipe.
6500 * Should be called with interrupts off.
6502 struct backcmd { /* result of evalbackcmd */
6503 int fd; /* file descriptor to read from */
6504 int nleft; /* number of chars in buffer */
6505 char *buf; /* buffer */
6506 struct job *jp; /* job structure for command */
6509 /* These forward decls are needed to use "eval" code for backticks handling: */
6510 /* flags in argument to evaltree */
6511 #define EV_EXIT 01 /* exit after evaluating tree */
6512 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
6513 static int evaltree(union node *, int);
6515 /* An evaltree() which is known to never return.
6516 * Used to use an alias:
6517 * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
6518 * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
6520 static ALWAYS_INLINE NORETURN void
6521 evaltreenr(union node *n, int flags)
6524 bb_unreachable(abort());
6528 static void FAST_FUNC
6529 evalbackcmd(union node *n, struct backcmd *result)
6543 ash_msg_and_raise_perror("can't create pipe");
6544 jp = makejob(/*n,*/ 1);
6545 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6551 dup2_or_raise(pip[1], 1);
6554 /* TODO: eflag clearing makes the following not abort:
6555 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6556 * which is what bash does (unless it is in POSIX mode).
6557 * dash deleted "eflag = 0" line in the commit
6558 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6559 * [EVAL] Don't clear eflag in evalbackcmd
6560 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6564 evaltreenr(n, EV_EXIT);
6569 result->fd = pip[0];
6573 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6574 result->fd, result->buf, result->nleft, result->jp));
6578 * Expand stuff in backwards quotes.
6581 expbackq(union node *cmd, int flag)
6589 struct stackmark smark;
6592 startloc = expdest - (char *)stackblock();
6593 pushstackmark(&smark, startloc);
6594 evalbackcmd(cmd, &in);
6595 popstackmark(&smark);
6602 memtodest(p, i, flag);
6606 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6607 TRACE(("expbackq: read returns %d\n", i));
6616 back_exitstatus = waitforjob(in.jp);
6620 /* Eat all trailing newlines */
6622 for (; dest > ((char *)stackblock() + startloc) && dest[-1] == '\n';)
6626 if (!(flag & EXP_QUOTED))
6627 recordregion(startloc, dest - (char *)stackblock(), 0);
6628 TRACE(("evalbackq: size:%d:'%.*s'\n",
6629 (int)((dest - (char *)stackblock()) - startloc),
6630 (int)((dest - (char *)stackblock()) - startloc),
6631 stackblock() + startloc));
6634 #if ENABLE_FEATURE_SH_MATH
6636 * Expand arithmetic expression. Backup to start of expression,
6637 * evaluate, place result in (backed up) result, adjust string position.
6649 * This routine is slightly over-complicated for
6650 * efficiency. Next we scan backwards looking for the
6651 * start of arithmetic.
6653 start = stackblock();
6660 while ((unsigned char)*p != CTLARI) {
6664 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6669 esc = esclen(start, p);
6679 removerecordregions(begoff);
6683 if (flag & QUOTES_ESC)
6684 rmescapes(p + 1, 0, NULL);
6686 len = cvtnum(ash_arith(p + 1));
6688 if (!(flag & EXP_QUOTED))
6689 recordregion(begoff, begoff + len, 0);
6693 /* argstr needs it */
6694 static char *evalvar(char *p, int flags);
6697 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6698 * characters to allow for further processing. Otherwise treat
6699 * $@ like $* since no splitting will be performed.
6702 argstr(char *p, int flags)
6704 static const char spclchars[] ALIGN1 = {
6712 #if ENABLE_FEATURE_SH_MATH
6717 const char *reject = spclchars;
6718 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6723 if (!(flags & EXP_VARTILDE)) {
6725 } else if (flags & EXP_VARTILDE2) {
6730 if (flags & EXP_TILDE) {
6733 flags &= ~EXP_TILDE;
6737 p = exptilde(p, q, flags);
6740 startloc = expdest - (char *)stackblock();
6744 length += strcspn(p + length, reject);
6748 IF_FEATURE_SH_MATH(|| c == CTLENDARI)
6750 /* c == '=' || c == ':' || c == CTLENDARI */
6756 expdest = stack_nputstr(p, length, expdest);
6757 newloc = expdest - (char *)stackblock();
6758 if (breakall && !inquotes && newloc > startloc) {
6759 recordregion(startloc, newloc, 0);
6770 if (flags & EXP_VARTILDE2) {
6774 flags |= EXP_VARTILDE2;
6779 * sort of a hack - expand tildes in variable
6780 * assignments (after the first '=' and after ':'s).
6789 case CTLENDVAR: /* ??? */
6792 /* "$@" syntax adherence hack */
6793 if (!inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6794 p = evalvar(p + 1, flags | EXP_QUOTED) + 1;
6797 inquotes ^= EXP_QUOTED;
6799 if (flags & QUOTES_ESC) {
6810 TRACE(("argstr: evalvar('%s')\n", p));
6811 p = evalvar(p, flags | inquotes);
6812 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6815 expbackq(argbackq->n, flags | inquotes);
6816 argbackq = argbackq->next;
6818 #if ENABLE_FEATURE_SH_MATH
6821 expari(flags | inquotes);
6830 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6831 char *pattern, int quotes, int zero)
6840 const char *s = loc2;
6847 match = pmatch(pattern, s);
6852 if (quotes && (unsigned char)*loc == CTLESC)
6861 scanright(char *startp, char *rmesc, char *rmescend,
6862 char *pattern, int quotes, int match_at_start)
6864 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6865 int try2optimize = match_at_start;
6871 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6872 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6873 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6875 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6876 * and on each iteration they go back two/one char until they reach the beginning.
6877 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6879 /* TODO: document in what other circumstances we are called. */
6881 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6884 const char *s = loc2;
6885 if (match_at_start) {
6889 match = pmatch(pattern, s);
6890 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6894 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6896 /* Maybe we can optimize this:
6897 * if pattern ends with unescaped *, we can avoid checking
6898 * shorter strings: if "foo*" doesn't match "raw_value_of_v",
6899 * it won't match truncated "raw_value_of_" strings too.
6901 unsigned plen = strlen(pattern);
6902 /* Does it end with "*"? */
6903 if (plen != 0 && pattern[--plen] == '*') {
6904 /* "xxxx*" is not escaped */
6905 /* "xxx\*" is escaped */
6906 /* "xx\\*" is not escaped */
6907 /* "x\\\*" is escaped */
6909 while (plen != 0 && pattern[--plen] == '\\')
6912 break; /* ends with unescaped "*" */
6920 esc = esclen(startp, loc);
6931 static void varunset(const char *, const char *, const char *, int) NORETURN;
6933 varunset(const char *end, const char *var, const char *umsg, int varflags)
6939 msg = "parameter not set";
6941 if ((unsigned char)*end == CTLENDVAR) {
6942 if (varflags & VSNUL)
6948 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6952 subevalvar(char *p, char *varname, int strloc, int subtype,
6953 int startloc, int varflags, int flag)
6955 struct nodelist *saveargbackq = argbackq;
6956 int quotes = flag & QUOTES_ESC;
6959 char *rmesc, *rmescend;
6961 int amount, resetloc;
6963 IF_BASH_PATTERN_SUBST(int workloc;)
6964 IF_BASH_PATTERN_SUBST(int slash_pos;)
6965 IF_BASH_PATTERN_SUBST(char *repl;)
6967 char *(*scan)(char*, char*, char*, char*, int, int);
6969 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6970 // p, varname, strloc, subtype, startloc, varflags, quotes);
6972 #if BASH_PATTERN_SUBST
6973 /* For "${v/pattern/repl}", we must find the delimiter _before_
6974 * argstr() call expands possible variable references in pattern:
6975 * think about "v=a; a=a/; echo ${v/$a/r}" case.
6978 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6979 /* Find '/' and replace with NUL */
6981 /* The pattern can't be empty.
6982 * IOW: if the first char after "${v//" is a slash,
6983 * it does not terminate the pattern - it's the first char of the pattern:
6984 * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
6985 * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
6990 if (*repl == '\0') {
6998 /* Handle escaped slashes, e.g. "${v/\//_}" (they are CTLESC'ed by this point) */
6999 if ((unsigned char)*repl == CTLESC && repl[1])
7005 argstr_flags = EXP_TILDE;
7006 if (subtype != VSASSIGN
7007 && subtype != VSQUESTION
7009 && subtype != VSSUBSTR
7012 /* EXP_CASE keeps CTLESC's */
7013 argstr_flags = EXP_TILDE | EXP_CASE;
7015 argstr(p, argstr_flags);
7016 //bb_error_msg("str0:'%s'", (char *)stackblock() + strloc);
7017 #if BASH_PATTERN_SUBST
7020 slash_pos = expdest - ((char *)stackblock() + strloc);
7021 STPUTC('/', expdest);
7022 //bb_error_msg("repl+1:'%s'", repl + 1);
7023 argstr(repl + 1, EXP_TILDE); /* EXP_TILDE: echo "${v/x/~}" expands ~ ! */
7027 STPUTC('\0', expdest);
7028 argbackq = saveargbackq;
7029 startp = (char *)stackblock() + startloc;
7030 //bb_error_msg("str1:'%s'", (char *)stackblock() + strloc);
7034 setvar0(varname, startp);
7035 amount = startp - expdest;
7036 STADJUST(amount, expdest);
7040 varunset(p, varname, startp, varflags);
7045 int pos, len, orig_len;
7048 loc = str = stackblock() + strloc;
7050 /* Read POS in ${var:POS:LEN} */
7051 colon = strchr(loc, ':');
7052 if (colon) *colon = '\0';
7053 pos = substr_atoi(loc);
7054 if (colon) *colon = ':';
7056 /* Read LEN in ${var:POS:LEN} */
7057 len = str - startp - 1;
7058 /* *loc != '\0', guaranteed by parser */
7061 /* Adjust the length by the number of escapes */
7062 for (ptr = startp; ptr < (str - 1); ptr++) {
7063 if ((unsigned char)*ptr == CTLESC) {
7070 if (*loc++ == ':') {
7072 len = substr_atoi(loc);
7074 /* Skip POS in ${var:POS:LEN} */
7076 while (*loc && *loc != ':')
7079 len = substr_atoi(loc);
7082 /* ${VAR:$((-n)):l} starts n chars from the end */
7083 pos = orig_len + pos;
7085 if ((unsigned)pos >= orig_len) {
7086 /* apart from obvious ${VAR:999999:l},
7087 * covers ${VAR:$((-9999999)):l} - result is ""
7094 /* ${VAR:N:-M} sets LEN to strlen()-M */
7095 len = (orig_len - pos) + len;
7097 if ((unsigned)len > (orig_len - pos))
7098 len = orig_len - pos;
7100 for (str = startp; pos; str++, pos--) {
7101 if (quotes && (unsigned char)*str == CTLESC)
7104 for (loc = startp; len; len--) {
7105 if (quotes && (unsigned char)*str == CTLESC)
7110 amount = loc - expdest;
7111 STADJUST(amount, expdest);
7114 #endif /* BASH_SUBSTR */
7117 resetloc = expdest - (char *)stackblock();
7119 #if BASH_PATTERN_SUBST
7122 /* We'll comeback here if we grow the stack while handling
7123 * a VSREPLACE or VSREPLACEALL, since our pointers into the
7124 * stack will need rebasing, and we'll need to remove our work
7130 amount = expdest - ((char *)stackblock() + resetloc);
7131 STADJUST(-amount, expdest);
7132 startp = (char *)stackblock() + startloc;
7135 rmescend = (char *)stackblock() + strloc;
7136 //bb_error_msg("str7:'%s'", rmescend);
7138 //TODO: how to handle slash_pos here if string changes (shortens?)
7139 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW, NULL);
7140 if (rmesc != startp) {
7142 startp = (char *)stackblock() + startloc;
7146 str = (char *)stackblock() + strloc;
7148 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
7149 * The result is a_\_z_c (not a\_\_z_c)!
7151 * The search pattern and replace string treat backslashes differently!
7152 * "&slash_pos" causes rmescapes() to work differently on the pattern
7153 * and string. It's only used on the first call.
7155 //bb_error_msg("str8:'%s' slash_pos:%d", str, slash_pos);
7156 rmescapes(str, RMESCAPE_GLOB,
7157 repl ? NULL : (slash_pos < 0 ? NULL : &slash_pos)
7160 #if BASH_PATTERN_SUBST
7161 workloc = expdest - (char *)stackblock();
7162 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
7167 //bb_error_msg("str9:'%s' slash_pos:%d", str, slash_pos);
7169 if (slash_pos >= 0) {
7170 repl = str + slash_pos;
7174 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
7176 /* If there's no pattern to match, return the expansion unmolested */
7185 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
7186 //bb_error_msg("scanright('%s'):'%s'", str, loc);
7188 /* No match, advance */
7189 char *restart_detect = stackblock();
7191 STPUTC(*idx, expdest);
7192 if (quotes && (unsigned char)*idx == CTLESC) {
7195 STPUTC(*idx, expdest);
7197 if (stackblock() != restart_detect)
7202 /* continue; - prone to quadratic behavior, smarter code: */
7205 if (str[0] == '*') {
7206 /* Pattern is "*foo". If "*foo" does not match "long_string",
7207 * it would never match "ong_string" etc, no point in trying.
7214 if (subtype == VSREPLACEALL) {
7216 if (quotes && (unsigned char)*idx == CTLESC)
7225 //bb_error_msg("repl:'%s'", repl);
7226 for (loc = (char*)repl; *loc; loc++) {
7227 char *restart_detect = stackblock();
7228 if (quotes && *loc == '\\') {
7229 STPUTC(CTLESC, expdest);
7232 STPUTC(*loc, expdest);
7233 if (stackblock() != restart_detect)
7238 if (subtype == VSREPLACE) {
7239 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
7241 char *restart_detect = stackblock();
7242 STPUTC(*idx, expdest);
7243 if (stackblock() != restart_detect)
7252 /* We've put the replaced text into a buffer at workloc, now
7253 * move it to the right place and adjust the stack.
7255 STPUTC('\0', expdest);
7256 startp = (char *)stackblock() + startloc;
7257 memmove(startp, (char *)stackblock() + workloc, len + 1);
7258 //bb_error_msg("startp:'%s'", startp);
7259 amount = expdest - (startp + len);
7260 STADJUST(-amount, expdest);
7263 #endif /* BASH_PATTERN_SUBST */
7265 subtype -= VSTRIMRIGHT;
7267 if (subtype < 0 || subtype > 7)
7270 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
7271 zero = subtype >> 1;
7272 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
7273 scan = (subtype & 1) ^ zero ? scanleft : scanright;
7275 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
7278 memmove(startp, loc, str - loc);
7279 loc = startp + (str - loc) - 1;
7282 amount = loc - expdest;
7283 STADJUST(amount, expdest);
7289 * Add the value of a specialized variable to the stack string.
7290 * name parameter (examples):
7291 * ash -c 'echo $1' name:'1='
7292 * ash -c 'echo $qwe' name:'qwe='
7293 * ash -c 'echo $$' name:'$='
7294 * ash -c 'echo ${$}' name:'$='
7295 * ash -c 'echo ${$##q}' name:'$=q'
7296 * ash -c 'echo ${#$}' name:'$='
7297 * note: examples with bad shell syntax:
7298 * ash -c 'echo ${#$1}' name:'$=1'
7299 * ash -c 'echo ${#1#}' name:'1=#'
7301 static NOINLINE ssize_t
7302 varvalue(char *name, int varflags, int flags, int quoted)
7309 int subtype = varflags & VSTYPE;
7310 int discard = subtype == VSPLUS || subtype == VSLENGTH;
7312 flags |= EXP_KEEPNUL;
7313 flags &= discard ? ~QUOTES_ESC : ~0;
7314 sep = (flags & EXP_FULL) << CHAR_BIT;
7324 num = shellparam.nparam;
7332 goto check_1char_name;
7334 expdest = makestrspace(NOPTS, expdest);
7335 for (i = NOPTS - 1; i >= 0; i--) {
7336 if (optlist[i] && optletters(i)) {
7337 USTPUTC(optletters(i), expdest);
7343 /* handles cases similar to ${#$1} */
7344 if (name[2] != '\0')
7345 raise_error_syntax("bad substitution");
7357 /* We will set c to 0 or ~0 depending on whether
7358 * we're doing field splitting. We won't do field
7359 * splitting if either we're quoted or sep is zero.
7361 * Instead of testing (quoted || !sep) the following
7362 * trick optimises away any branches by using the
7363 * fact that EXP_QUOTED (which is the only bit that
7364 * can be set in quoted) is the same as EXP_FULL <<
7365 * CHAR_BIT (which is the only bit that can be set
7368 #if EXP_QUOTED >> CHAR_BIT != EXP_FULL
7369 #error The following two lines expect EXP_QUOTED == EXP_FULL << CHAR_BIT
7371 c = !((quoted | ~sep) & EXP_QUOTED) - 1;
7373 sep |= ifsset() ? (unsigned char)(c & ifsval()[0]) : ' ';
7379 while ((p = *ap++) != NULL) {
7380 len += strtodest(p, flags);
7384 memtodest(&sepc, 1, flags);
7399 num = atoi(name); /* number(name) fails on ${N#str} etc */
7400 if (num < 0 || num > shellparam.nparam)
7402 p = num ? shellparam.p[num - 1] : arg0;
7405 /* NB: name has form "VAR=..." */
7406 p = lookupvar(name);
7411 len = strtodest(p, flags);
7412 #if ENABLE_UNICODE_SUPPORT
7413 if (subtype == VSLENGTH && len > 0) {
7414 reinit_unicode_for_ash();
7415 if (unicode_status == UNICODE_ON) {
7416 STADJUST(-len, expdest);
7418 len = unicode_strlen(p);
7426 STADJUST(-len, expdest);
7431 * Expand a variable, and return a pointer to the next character in the
7435 evalvar(char *p, int flag)
7445 varflags = (unsigned char) *p++;
7446 subtype = varflags & VSTYPE;
7449 raise_error_syntax("bad substitution");
7451 quoted = flag & EXP_QUOTED;
7453 startloc = expdest - (char *)stackblock();
7454 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
7457 varlen = varvalue(var, varflags, flag, quoted);
7458 if (varflags & VSNUL)
7461 if (subtype == VSPLUS) {
7462 varlen = -1 - varlen;
7466 if (subtype == VSMINUS) {
7471 flag | EXP_TILDE | EXP_WORD
7478 if (subtype == VSASSIGN || subtype == VSQUESTION) {
7482 subevalvar(p, var, 0, subtype, startloc, varflags,
7483 flag & ~QUOTES_ESC);
7486 * Remove any recorded regions beyond
7489 removerecordregions(startloc);
7493 if (varlen < 0 && uflag)
7494 varunset(p, var, 0, 0);
7496 if (subtype == VSLENGTH) {
7497 cvtnum(varlen > 0 ? varlen : 0);
7501 if (subtype == VSNORMAL) {
7504 quoted = *var == '@' && shellparam.nparam;
7508 recordregion(startloc, expdest - (char *)stackblock(), quoted);
7517 case VSTRIMRIGHTMAX:
7521 #if BASH_PATTERN_SUBST
7533 * Terminate the string and start recording the pattern
7536 STPUTC('\0', expdest);
7537 patloc = expdest - (char *)stackblock();
7538 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
7539 startloc, varflags, flag)) {
7540 int amount = expdest - (
7541 (char *)stackblock() + patloc - 1
7543 STADJUST(-amount, expdest);
7545 /* Remove any recorded regions beyond start of variable */
7546 removerecordregions(startloc);
7553 if (subtype != VSNORMAL) { /* skip to end of alternative */
7556 unsigned char c = *p++;
7559 else if (c == CTLBACKQ) {
7561 argbackq = argbackq->next;
7562 } else if (c == CTLVAR) {
7563 if ((*p++ & VSTYPE) != VSNORMAL)
7565 } else if (c == CTLENDVAR) {
7575 * Add a file name to the list.
7578 addfname(const char *name)
7582 sp = stzalloc(sizeof(*sp));
7583 sp->text = sstrdup(name);
7585 exparg.lastp = &sp->next;
7588 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7590 hasmeta(const char *p)
7592 static const char chars[] ALIGN1 = {
7593 '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
7597 p = strpbrk(p, chars);
7600 switch ((unsigned char)*p) {
7604 if ((unsigned char)*p == CTLQUOTEMARK)
7606 if ((unsigned char)*p == CTLESC)
7608 if (*p == '\0') /* huh? */
7619 if (!strchr(p + 1, ']')) {
7620 /* It's not a properly closed [] pattern,
7621 * but other metas may follow. Continue checking.
7622 * my[file* _is_ globbed by bash
7623 * and matches filenames like "my[file1".
7639 /* If we want to use glob() from libc... */
7640 #if !ENABLE_ASH_INTERNAL_GLOB
7642 /* Add the result of glob() to the list */
7644 addglob(const glob_t *pglob)
7646 char **p = pglob->gl_pathv;
7653 expandmeta(struct strlist *str /*, int flag*/)
7655 /* TODO - EXP_REDIR */
7665 if (!hasmeta(str->text))
7669 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7670 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7671 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7673 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7674 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7675 // Which means you need to unescape the string, right? Not so fast:
7676 // if there _is_ a file named "file\?" (with backslash), it is returned
7677 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7678 // You DON'T KNOW by looking at the result whether you need to unescape it.
7680 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7681 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7682 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7683 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7684 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7685 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7686 i = glob(p, 0, NULL, &pglob);
7687 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7692 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7693 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7694 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7706 *exparg.lastp = str;
7707 rmescapes(str->text, 0, NULL);
7708 exparg.lastp = &str->next;
7710 default: /* GLOB_NOSPACE */
7713 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7720 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7723 * Do metacharacter (i.e. *, ?, [...]) expansion.
7725 typedef struct exp_t {
7730 expmeta(exp_t *exp, char *name, unsigned name_len, unsigned expdir_len)
7732 #define expdir exp->dir
7733 #define expdir_max exp->dir_max
7734 char *enddir = expdir + expdir_len;
7749 for (p = name; esc = 0, *p; p += esc + 1) {
7750 if (*p == '*' || *p == '?')
7752 else if (*p == '[') {
7759 if (*q == '/' || *q == '\0')
7767 if (*p == '\\' && p[1])
7769 if (p[esc] == '/') {
7772 start = p + esc + 1;
7776 if (metaflag == 0) { /* we've reached the end of the file name */
7781 if (*p == '\\' && p[1])
7785 if (lstat(expdir, &statb) == 0)
7793 if (*p == '\\' && p[1])
7796 } while (p < start);
7800 expdir_len = enddir - cp;
7806 if (*endname == 0) {
7813 name_len -= endname - name;
7820 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7821 if (dp->d_name[0] == '.' && !matchdot)
7823 if (pmatch(start, dp->d_name)) {
7825 strcpy(enddir, dp->d_name);
7831 p = stpcpy(enddir, dp->d_name);
7834 offset = p - expdir + 1;
7835 len = offset + name_len + NAME_MAX;
7836 if (len > expdir_max) {
7838 expdir = ckrealloc(expdir, len);
7842 expmeta(exp, endname, name_len, offset);
7843 enddir = expdir + expdir_len;
7849 endname[-esc - 1] = esc ? '\\' : '/';
7854 static struct strlist *
7855 msort(struct strlist *list, int len)
7857 struct strlist *p, *q = NULL;
7858 struct strlist **lpp;
7866 for (n = half; --n >= 0;) {
7870 q->next = NULL; /* terminate first half of list */
7871 q = msort(list, half); /* sort first half of list */
7872 p = msort(p, len - half); /* sort second half */
7875 #if ENABLE_LOCALE_SUPPORT
7876 if (strcoll(p->text, q->text) < 0)
7878 if (strcmp(p->text, q->text) < 0)
7902 * Sort the results of file name expansion. It calculates the number of
7903 * strings to sort and then calls msort (short for merge sort) to do the
7906 static struct strlist *
7907 expsort(struct strlist *str)
7913 for (sp = str; sp; sp = sp->next)
7915 return msort(str, len);
7919 expandmeta(struct strlist *str /*, int flag*/)
7921 /* TODO - EXP_REDIR */
7925 struct strlist **savelastp;
7932 if (!hasmeta(str->text))
7934 savelastp = exparg.lastp;
7937 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7939 exp.dir_max = len + PATH_MAX;
7940 exp.dir = ckmalloc(exp.dir_max);
7942 expmeta(&exp, p, len, 0);
7947 if (exparg.lastp == savelastp) {
7952 *exparg.lastp = str;
7953 rmescapes(str->text, 0, NULL);
7954 exparg.lastp = &str->next;
7956 *exparg.lastp = NULL;
7957 *savelastp = sp = expsort(*savelastp);
7958 while (sp->next != NULL)
7960 exparg.lastp = &sp->next;
7965 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7968 * Perform variable substitution and command substitution on an argument,
7969 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7970 * perform splitting and file name expansion. When arglist is NULL, perform
7971 * here document expansion.
7974 expandarg(union node *arg, struct arglist *arglist, int flag)
7979 argbackq = arg->narg.backquote;
7980 STARTSTACKSTR(expdest);
7981 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7982 argstr(arg->narg.text, flag);
7983 p = _STPUTC('\0', expdest);
7985 if (arglist == NULL) {
7986 /* here document expanded */
7989 p = grabstackstr(p);
7990 TRACE(("expandarg: p:'%s'\n", p));
7991 exparg.lastp = &exparg.list;
7995 if (flag & EXP_FULL) {
7996 ifsbreakup(p, &exparg);
7997 *exparg.lastp = NULL;
7998 exparg.lastp = &exparg.list;
7999 expandmeta(exparg.list /*, flag*/);
8001 sp = stzalloc(sizeof(*sp));
8004 exparg.lastp = &sp->next;
8006 *exparg.lastp = NULL;
8008 *arglist->lastp = exparg.list;
8009 arglist->lastp = exparg.lastp;
8017 * Expand shell variables and backquotes inside a here document.
8020 expandhere(union node *arg, int fd)
8022 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
8023 full_write(fd, stackblock(), expdest - (char *)stackblock());
8027 * Returns true if the pattern matches the string.
8030 patmatch(char *pattern, const char *string)
8032 char *p = preglob(pattern, 0);
8033 int r = pmatch(p, string);
8034 //bb_error_msg("!fnmatch(pattern:'%s',str:'%s',0):%d", p, string, r);
8039 * See if a pattern matches in a case statement.
8042 casematch(union node *pattern, char *val)
8044 struct stackmark smark;
8047 setstackmark(&smark);
8048 argbackq = pattern->narg.backquote;
8049 STARTSTACKSTR(expdest);
8050 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
8051 STACKSTRNUL(expdest);
8053 result = patmatch(stackblock(), val);
8054 popstackmark(&smark);
8059 /* ============ find_command */
8063 int (*builtin)(int, char **) FAST_FUNC;
8064 /* unsigned flags; */
8066 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
8067 /* "regular" builtins always take precedence over commands,
8068 * regardless of PATH=....%builtin... position */
8069 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
8070 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
8073 smallint cmdtype; /* CMDxxx */
8076 /* index >= 0 for commands without path (slashes) */
8077 /* (TODO: what exactly does the value mean? PATH position?) */
8078 /* index == -1 for commands with slashes */
8079 /* index == (-2 - applet_no) for NOFORK applets */
8080 const struct builtincmd *cmd;
8081 struct funcnode *func;
8084 /* values of cmdtype */
8085 #define CMDUNKNOWN -1 /* no entry in table for command */
8086 #define CMDNORMAL 0 /* command is an executable program */
8087 #define CMDFUNCTION 1 /* command is a shell function */
8088 #define CMDBUILTIN 2 /* command is a shell builtin */
8090 /* action to find_command() */
8091 #define DO_ERR 0x01 /* prints errors */
8092 #define DO_ABS 0x02 /* checks absolute paths */
8093 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
8094 #define DO_ALTPATH 0x08 /* using alternate path */
8095 #define DO_REGBLTIN 0x10 /* regular built-ins and functions only */
8097 static void find_command(char *, struct cmdentry *, int, const char *);
8100 /* ============ Hashing commands */
8103 * When commands are first encountered, they are entered in a hash table.
8104 * This ensures that a full path search will not have to be done for them
8105 * on each invocation.
8107 * We should investigate converting to a linear search, even though that
8108 * would make the command name "hash" a misnomer.
8112 struct tblentry *next; /* next entry in hash chain */
8113 union param param; /* definition of builtin function */
8114 smallint cmdtype; /* CMDxxx */
8115 char rehash; /* if set, cd done since entry created */
8116 char cmdname[1]; /* name of command */
8119 static struct tblentry **cmdtable;
8120 #define INIT_G_cmdtable() do { \
8121 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
8124 static int builtinloc = -1; /* index in path of %builtin, or -1 */
8128 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
8130 #if ENABLE_FEATURE_SH_STANDALONE
8131 if (applet_no >= 0) {
8132 if (APPLET_IS_NOEXEC(applet_no)) {
8136 popredir(/*drop:*/ 1);
8137 run_noexec_applet_and_exit(applet_no, cmd, argv);
8139 /* re-exec ourselves with the new arguments */
8140 execve(bb_busybox_exec_path, argv, envp);
8141 /* If they called chroot or otherwise made the binary no longer
8142 * executable, fall through */
8149 execve(cmd, argv, envp);
8150 } while (errno == EINTR);
8152 execve(cmd, argv, envp);
8155 if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
8156 /* Run "cmd" as a shell script:
8157 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
8158 * "If the execve() function fails with ENOEXEC, the shell
8159 * shall execute a command equivalent to having a shell invoked
8160 * with the command name as its first operand,
8161 * with any remaining arguments passed to the new shell"
8163 * That is, do not use $SHELL, user's shell, or /bin/sh;
8164 * just call ourselves.
8166 * Note that bash reads ~80 chars of the file, and if it sees
8167 * a zero byte before it sees newline, it doesn't try to
8168 * interpret it, but fails with "cannot execute binary file"
8169 * message and exit code 126. For one, this prevents attempts
8170 * to interpret foreign ELF binaries as shell scripts.
8172 argv[0] = (char*) cmd;
8173 cmd = bb_busybox_exec_path;
8174 /* NB: this is only possible because all callers of shellexec()
8175 * ensure that the argv[-1] slot exists!
8178 argv[0] = (char*) "ash";
8184 * Exec a program. Never returns. If you change this routine, you may
8185 * have to change the find_command routine as well.
8186 * argv[-1] must exist and be writable! See tryexec() for why.
8188 static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
8189 static void shellexec(char *prog, char **argv, const char *path, int idx)
8195 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
8197 envp = listvars(VEXPORT, VUNSET, /*strlist:*/ NULL, /*end:*/ NULL);
8198 if (strchr(prog, '/') != NULL
8199 #if ENABLE_FEATURE_SH_STANDALONE
8200 || (applet_no = find_applet_by_name(prog)) >= 0
8203 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
8204 if (applet_no >= 0) {
8205 /* We tried execing ourself, but it didn't work.
8206 * Maybe /proc/self/exe doesn't exist?
8215 while (padvance(&path, argv[0]) >= 0) {
8216 cmdname = stackblock();
8217 if (--idx < 0 && pathopt == NULL) {
8218 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
8219 if (errno != ENOENT && errno != ENOTDIR)
8225 /* Map to POSIX errors */
8237 exitstatus = exerrno;
8238 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
8239 prog, e, suppress_int));
8240 ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
8245 printentry(struct tblentry *cmdp)
8251 idx = cmdp->param.index;
8254 padvance(&path, cmdp->cmdname);
8255 } while (--idx >= 0);
8256 name = stackblock();
8257 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
8261 * Clear out command entries.
8266 struct tblentry **tblp;
8267 struct tblentry **pp;
8268 struct tblentry *cmdp;
8271 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
8273 while ((cmdp = *pp) != NULL) {
8274 if (cmdp->cmdtype == CMDNORMAL
8275 || (cmdp->cmdtype == CMDBUILTIN
8276 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
8291 * Locate a command in the command hash table. If "add" is nonzero,
8292 * add the command to the table if it is not already present. The
8293 * variable "lastcmdentry" is set to point to the address of the link
8294 * pointing to the entry, so that delete_cmd_entry can delete the
8297 * Interrupts must be off if called with add != 0.
8299 static struct tblentry **lastcmdentry;
8301 static struct tblentry *
8302 cmdlookup(const char *name, int add)
8304 unsigned int hashval;
8306 struct tblentry *cmdp;
8307 struct tblentry **pp;
8310 hashval = (unsigned char)*p << 4;
8312 hashval += (unsigned char)*p++;
8314 pp = &cmdtable[hashval % CMDTABLESIZE];
8315 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8316 if (strcmp(cmdp->cmdname, name) == 0)
8320 if (add && cmdp == NULL) {
8321 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
8323 /* + 1 - already done because
8324 * tblentry::cmdname is char[1] */);
8325 /*cmdp->next = NULL; - ckzalloc did it */
8326 cmdp->cmdtype = CMDUNKNOWN;
8327 strcpy(cmdp->cmdname, name);
8334 * Delete the command entry returned on the last lookup.
8337 delete_cmd_entry(void)
8339 struct tblentry *cmdp;
8342 cmdp = *lastcmdentry;
8343 *lastcmdentry = cmdp->next;
8344 if (cmdp->cmdtype == CMDFUNCTION)
8345 freefunc(cmdp->param.func);
8351 * Add a new command entry, replacing any existing command entry for
8352 * the same name - except special builtins.
8355 addcmdentry(char *name, struct cmdentry *entry)
8357 struct tblentry *cmdp;
8359 cmdp = cmdlookup(name, 1);
8360 if (cmdp->cmdtype == CMDFUNCTION) {
8361 freefunc(cmdp->param.func);
8363 cmdp->cmdtype = entry->cmdtype;
8364 cmdp->param = entry->u;
8368 static int FAST_FUNC
8369 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8371 struct tblentry **pp;
8372 struct tblentry *cmdp;
8374 struct cmdentry entry;
8377 if (nextopt("r") != '\0') {
8382 if (*argptr == NULL) {
8383 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8384 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8385 if (cmdp->cmdtype == CMDNORMAL)
8393 while ((name = *argptr) != NULL) {
8394 cmdp = cmdlookup(name, 0);
8396 && (cmdp->cmdtype == CMDNORMAL
8397 || (cmdp->cmdtype == CMDBUILTIN
8398 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
8405 find_command(name, &entry, DO_ERR, pathval());
8406 if (entry.cmdtype == CMDUNKNOWN)
8414 * Called when a cd is done. Marks all commands so the next time they
8415 * are executed they will be rehashed.
8420 struct tblentry **pp;
8421 struct tblentry *cmdp;
8423 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8424 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8425 if (cmdp->cmdtype == CMDNORMAL
8426 || (cmdp->cmdtype == CMDBUILTIN
8427 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
8437 * Fix command hash table when PATH changed.
8438 * Called before PATH is changed. The argument is the new value of PATH;
8439 * pathval() still returns the old value at this point.
8440 * Called with interrupts off.
8442 static void FAST_FUNC
8443 changepath(const char *newval)
8453 if (*new == '%' && prefix(new + 1, "builtin")) {
8457 new = strchr(new, ':');
8500 typedef smallint token_id_t;
8502 /* Nth bit indicates if token marks the end of a list */
8505 /* 0 */ | (1u << TEOF)
8506 /* 1 */ | (0u << TNL)
8507 /* 2 */ | (0u << TREDIR)
8508 /* 3 */ | (0u << TWORD)
8509 /* 4 */ | (0u << TSEMI)
8510 /* 5 */ | (0u << TBACKGND)
8511 /* 6 */ | (0u << TAND)
8512 /* 7 */ | (0u << TOR)
8513 /* 8 */ | (0u << TPIPE)
8514 /* 9 */ | (0u << TLP)
8515 /* 10 */ | (1u << TRP)
8516 /* 11 */ | (1u << TENDCASE)
8517 /* 12 */ | (1u << TENDBQUOTE)
8518 /* 13 */ | (0u << TNOT)
8519 /* 14 */ | (0u << TCASE)
8520 /* 15 */ | (1u << TDO)
8521 /* 16 */ | (1u << TDONE)
8522 /* 17 */ | (1u << TELIF)
8523 /* 18 */ | (1u << TELSE)
8524 /* 19 */ | (1u << TESAC)
8525 /* 20 */ | (1u << TFI)
8526 /* 21 */ | (0u << TFOR)
8528 /* 22 */ | (0u << TFUNCTION)
8530 /* 23 */ | (0u << TIF)
8531 /* 24 */ | (0u << TIN)
8532 /* 25 */ | (1u << TTHEN)
8533 /* 26 */ | (0u << TUNTIL)
8534 /* 27 */ | (0u << TWHILE)
8535 /* 28 */ | (0u << TBEGIN)
8536 /* 29 */ | (1u << TEND)
8537 , /* thus far 29 bits used */
8540 static const char *const tokname_array[] = {
8554 #define KWDOFFSET 13
8555 /* the following are keywords */
8577 /* Wrapper around strcmp for qsort/bsearch/... */
8579 pstrcmp(const void *a, const void *b)
8581 return strcmp((char*)a, *(char**)b);
8584 static const char *const *
8585 findkwd(const char *s)
8587 return bsearch(s, tokname_array + KWDOFFSET,
8588 ARRAY_SIZE(tokname_array) - KWDOFFSET,
8589 sizeof(tokname_array[0]), pstrcmp);
8593 * Locate and print what a word is...
8596 describe_command(char *command, const char *path, int describe_command_verbose)
8598 struct cmdentry entry;
8599 #if ENABLE_ASH_ALIAS
8600 const struct alias *ap;
8603 path = path ? path : pathval();
8605 if (describe_command_verbose) {
8609 /* First look at the keywords */
8610 if (findkwd(command)) {
8611 out1str(describe_command_verbose ? " is a shell keyword" : command);
8615 #if ENABLE_ASH_ALIAS
8616 /* Then look at the aliases */
8617 ap = lookupalias(command, 0);
8619 if (!describe_command_verbose) {
8624 out1fmt(" is an alias for %s", ap->val);
8629 find_command(command, &entry, DO_ABS, path);
8631 switch (entry.cmdtype) {
8633 int j = entry.u.index;
8639 padvance(&path, command);
8643 if (describe_command_verbose) {
8644 out1fmt(" is %s", p);
8652 if (describe_command_verbose) {
8653 /*out1str(" is a shell function");*/
8654 out1str(" is a function"); /* bash says this */
8661 if (describe_command_verbose) {
8662 out1fmt(" is a %sshell builtin",
8663 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8664 "special " : nullstr
8672 if (describe_command_verbose) {
8673 out1str(": not found\n");
8682 static int FAST_FUNC
8683 typecmd(int argc UNUSED_PARAM, char **argv)
8689 /* type -p ... ? (we don't bother checking for 'p') */
8690 if (argv[1] && argv[1][0] == '-') {
8695 err |= describe_command(argv[i++], NULL, verbose);
8700 #if ENABLE_ASH_CMDCMD
8701 static struct strlist *
8702 fill_arglist(struct arglist *arglist, union node **argpp)
8704 struct strlist **lastp = arglist->lastp;
8707 while ((argp = *argpp) != NULL) {
8708 expandarg(argp, arglist, EXP_FULL | EXP_TILDE);
8709 *argpp = argp->narg.next;
8717 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8719 parse_command_args(struct arglist *arglist, union node **argpp, const char **path)
8721 struct strlist *sp = arglist->list;
8725 sp = sp->next ? sp->next : fill_arglist(arglist, argpp);
8734 if (c == '-' && !*cp) {
8735 if (!sp->next && !fill_arglist(arglist, argpp))
8743 *path = bb_default_path;
8746 /* run 'typecmd' for other options */
8757 static int FAST_FUNC
8758 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8766 const char *path = NULL;
8768 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8769 * never reaches this function.
8772 while ((c = nextopt("pvV")) != '\0')
8774 verify |= VERIFY_VERBOSE;
8776 /*verify |= VERIFY_BRIEF*/;
8782 path = bb_default_path;
8784 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8786 if (/*verify && */ cmd)
8787 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8794 /*static int funcblocksize; // size of structures in function */
8795 /*static int funcstringsize; // size of strings in node */
8796 static void *funcblock; /* block to allocate function from */
8797 static char *funcstring_end; /* end of block to allocate strings from */
8799 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8800 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8801 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8802 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8803 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8804 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8805 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8806 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8807 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8808 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8809 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8810 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8811 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8812 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8813 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8814 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8815 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8816 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8817 #if BASH_REDIR_OUTPUT
8818 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8820 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8821 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8822 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8823 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8824 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8825 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8826 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8827 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8828 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8831 static int calcsize(int funcblocksize, union node *n);
8834 sizenodelist(int funcblocksize, struct nodelist *lp)
8837 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8838 funcblocksize = calcsize(funcblocksize, lp->n);
8841 return funcblocksize;
8845 calcsize(int funcblocksize, union node *n)
8848 return funcblocksize;
8849 funcblocksize += nodesize[n->type];
8852 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8853 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8854 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8857 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8862 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8863 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8870 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8871 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8874 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8875 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8876 funcblocksize = calcsize(funcblocksize, n->nif.test);
8879 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8880 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8881 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8884 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8885 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8888 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8889 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8890 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8893 funcblocksize = calcsize(funcblocksize, n->ndefun.body);
8894 funcblocksize += SHELL_ALIGN(strlen(n->ndefun.text) + 1);
8897 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8898 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8899 funcblocksize = calcsize(funcblocksize, n->narg.next);
8902 #if BASH_REDIR_OUTPUT
8909 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8910 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8914 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8915 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8919 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8920 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8923 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8926 return funcblocksize;
8930 nodeckstrdup(char *s)
8932 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8933 return strcpy(funcstring_end, s);
8936 static union node *copynode(union node *);
8938 static struct nodelist *
8939 copynodelist(struct nodelist *lp)
8941 struct nodelist *start;
8942 struct nodelist **lpp;
8947 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8948 (*lpp)->n = copynode(lp->n);
8950 lpp = &(*lpp)->next;
8957 copynode(union node *n)
8964 funcblock = (char *) funcblock + nodesize[n->type];
8968 new->ncmd.redirect = copynode(n->ncmd.redirect);
8969 new->ncmd.args = copynode(n->ncmd.args);
8970 new->ncmd.assign = copynode(n->ncmd.assign);
8971 new->ncmd.linno = n->ncmd.linno;
8974 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8975 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8980 new->nredir.redirect = copynode(n->nredir.redirect);
8981 new->nredir.n = copynode(n->nredir.n);
8982 new->nredir.linno = n->nredir.linno;
8989 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8990 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8993 new->nif.elsepart = copynode(n->nif.elsepart);
8994 new->nif.ifpart = copynode(n->nif.ifpart);
8995 new->nif.test = copynode(n->nif.test);
8998 new->nfor.var = nodeckstrdup(n->nfor.var);
8999 new->nfor.body = copynode(n->nfor.body);
9000 new->nfor.args = copynode(n->nfor.args);
9001 new->nfor.linno = n->nfor.linno;
9004 new->ncase.cases = copynode(n->ncase.cases);
9005 new->ncase.expr = copynode(n->ncase.expr);
9006 new->ncase.linno = n->ncase.linno;
9009 new->nclist.body = copynode(n->nclist.body);
9010 new->nclist.pattern = copynode(n->nclist.pattern);
9011 new->nclist.next = copynode(n->nclist.next);
9014 new->ndefun.body = copynode(n->ndefun.body);
9015 new->ndefun.text = nodeckstrdup(n->ndefun.text);
9016 new->ndefun.linno = n->ndefun.linno;
9019 new->narg.backquote = copynodelist(n->narg.backquote);
9020 new->narg.text = nodeckstrdup(n->narg.text);
9021 new->narg.next = copynode(n->narg.next);
9024 #if BASH_REDIR_OUTPUT
9031 new->nfile.fname = copynode(n->nfile.fname);
9032 new->nfile.fd = n->nfile.fd;
9033 new->nfile.next = copynode(n->nfile.next);
9037 new->ndup.vname = copynode(n->ndup.vname);
9038 new->ndup.dupfd = n->ndup.dupfd;
9039 new->ndup.fd = n->ndup.fd;
9040 new->ndup.next = copynode(n->ndup.next);
9044 new->nhere.doc = copynode(n->nhere.doc);
9045 new->nhere.fd = n->nhere.fd;
9046 new->nhere.next = copynode(n->nhere.next);
9049 new->nnot.com = copynode(n->nnot.com);
9052 new->type = n->type;
9057 * Make a copy of a parse tree.
9059 static struct funcnode *
9060 copyfunc(union node *n)
9065 /*funcstringsize = 0;*/
9066 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
9067 f = ckzalloc(blocksize /* + funcstringsize */);
9068 funcblock = (char *) f + offsetof(struct funcnode, n);
9069 funcstring_end = (char *) f + blocksize;
9071 /* f->count = 0; - ckzalloc did it */
9076 * Define a shell function.
9079 defun(union node *func)
9081 struct cmdentry entry;
9084 entry.cmdtype = CMDFUNCTION;
9085 entry.u.func = copyfunc(func);
9086 addcmdentry(func->ndefun.text, &entry);
9090 /* Reasons for skipping commands (see comment on breakcmd routine) */
9091 #define SKIPBREAK (1 << 0)
9092 #define SKIPCONT (1 << 1)
9093 #define SKIPFUNC (1 << 2)
9094 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
9095 static int skipcount; /* number of levels to skip */
9096 static int loopnest; /* current loop nesting level */
9097 static int funcline; /* starting line number of current function, or 0 if not in a function */
9099 /* Forward decl way out to parsing code - dotrap needs it */
9100 static int evalstring(char *s, int flags);
9102 /* Called to execute a trap.
9103 * Single callsite - at the end of evaltree().
9104 * If we return non-zero, evaltree raises EXEXIT exception.
9106 * Perhaps we should avoid entering new trap handlers
9107 * while we are executing a trap handler. [is it a TODO?]
9114 int status, last_status;
9119 status = savestatus;
9120 last_status = status;
9122 status = exitstatus;
9123 savestatus = status;
9128 TRACE(("dotrap entered\n"));
9129 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
9141 /* non-trapped SIGINT is handled separately by raise_interrupt,
9142 * don't upset it by resetting gotsig[SIGINT-1] */
9143 if (sig == SIGINT && !p)
9146 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
9151 exitstatus = status;
9154 savestatus = last_status;
9155 TRACE(("dotrap returns\n"));
9158 /* forward declarations - evaluation is fairly recursive business... */
9159 static int evalloop(union node *, int);
9160 static int evalfor(union node *, int);
9161 static int evalcase(union node *, int);
9162 static int evalsubshell(union node *, int);
9163 static void expredir(union node *);
9164 static int evalpipe(union node *, int);
9165 static int evalcommand(union node *, int);
9166 static int evalbltin(const struct builtincmd *, int, char **, int);
9167 static void prehash(union node *);
9170 * Evaluate a parse tree. The value is left in the global variable
9174 evaltree(union node *n, int flags)
9177 int (*evalfn)(union node *, int);
9178 struct stackmark smark;
9181 setstackmark(&smark);
9184 TRACE(("evaltree(NULL) called\n"));
9187 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
9194 out1fmt("Node type = %d\n", n->type);
9199 status = !evaltree(n->nnot.com, EV_TESTED);
9202 errlinno = lineno = n->nredir.linno;
9204 lineno -= funcline - 1;
9205 expredir(n->nredir.redirect);
9206 pushredir(n->nredir.redirect);
9207 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
9209 status = evaltree(n->nredir.n, flags & EV_TESTED);
9211 if (n->nredir.redirect)
9212 popredir(/*drop:*/ 0);
9215 evalfn = evalcommand;
9217 if (eflag && !(flags & EV_TESTED))
9229 evalfn = evalsubshell;
9242 #error NAND + 1 != NOR
9244 #if NOR + 1 != NSEMI
9245 #error NOR + 1 != NSEMI
9247 unsigned is_or = n->type - NAND;
9250 (flags | ((is_or >> 1) - 1)) & EV_TESTED
9252 if ((!status) == is_or || evalskip)
9258 status = evalfn(n, flags);
9262 status = evaltree(n->nif.test, EV_TESTED);
9269 if (n->nif.elsepart) {
9270 n = n->nif.elsepart;
9277 /* Not necessary. To test it:
9278 * "false; f() { qwerty; }; echo $?" should print 0.
9282 exitstatus = status;
9286 /* Order of checks below is important:
9287 * signal handlers trigger before exit caused by "set -e".
9291 if (checkexit & status)
9292 raise_exception(EXEXIT);
9293 if (flags & EV_EXIT)
9294 raise_exception(EXEXIT);
9296 popstackmark(&smark);
9297 TRACE(("leaving evaltree (no interrupts)\n"));
9304 int skip = evalskip;
9311 if (--skipcount <= 0) {
9322 evalloop(union node *n, int flags)
9333 i = evaltree(n->nbinary.ch1, EV_TESTED);
9335 if (skip == SKIPFUNC)
9339 if (n->type != NWHILE)
9343 status = evaltree(n->nbinary.ch2, flags);
9345 } while (!(skip & ~SKIPCONT));
9352 evalfor(union node *n, int flags)
9354 struct arglist arglist;
9359 errlinno = lineno = n->ncase.linno;
9361 lineno -= funcline - 1;
9363 arglist.list = NULL;
9364 arglist.lastp = &arglist.list;
9365 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
9366 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9368 *arglist.lastp = NULL;
9372 for (sp = arglist.list; sp; sp = sp->next) {
9373 setvar0(n->nfor.var, sp->text);
9374 status = evaltree(n->nfor.body, flags);
9375 if (skiploop() & ~SKIPCONT)
9384 evalcase(union node *n, int flags)
9388 struct arglist arglist;
9391 errlinno = lineno = n->ncase.linno;
9393 lineno -= funcline - 1;
9395 arglist.list = NULL;
9396 arglist.lastp = &arglist.list;
9397 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
9398 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
9399 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
9400 if (casematch(patp, arglist.list->text)) {
9401 /* Ensure body is non-empty as otherwise
9402 * EV_EXIT may prevent us from setting the
9405 if (evalskip == 0 && cp->nclist.body) {
9406 status = evaltree(cp->nclist.body, flags);
9417 * Kick off a subshell to evaluate a tree.
9420 evalsubshell(union node *n, int flags)
9423 int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
9426 errlinno = lineno = n->nredir.linno;
9428 lineno -= funcline - 1;
9430 expredir(n->nredir.redirect);
9431 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
9434 if (backgnd == FORK_FG)
9436 jp = makejob(/*n,*/ 1);
9437 if (forkshell(jp, n, backgnd) == 0) {
9442 flags &= ~EV_TESTED;
9444 redirect(n->nredir.redirect, 0);
9445 evaltreenr(n->nredir.n, flags);
9450 if (backgnd == FORK_FG)
9451 status = waitforjob(jp);
9457 * Compute the names of the files in a redirection list.
9459 static void fixredir(union node *, const char *, int);
9461 expredir(union node *n)
9465 for (redir = n; redir; redir = redir->nfile.next) {
9469 fn.lastp = &fn.list;
9470 switch (redir->type) {
9474 #if BASH_REDIR_OUTPUT
9479 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
9480 TRACE(("expredir expanded to '%s'\n", fn.list->text));
9481 #if BASH_REDIR_OUTPUT
9485 // By the design of stack allocator, the loop of this kind:
9486 // while true; do while true; do break; done </dev/null; done
9487 // will look like a memory leak: ash plans to free expfname's
9488 // of "/dev/null" as soon as it finishes running the loop
9489 // (in this case, never).
9490 // This "fix" is wrong:
9491 if (redir->nfile.expfname)
9492 stunalloc(redir->nfile.expfname);
9493 // It results in corrupted state of stacked allocations.
9495 redir->nfile.expfname = fn.list->text;
9498 case NTOFD: /* >& */
9499 if (redir->ndup.vname) {
9500 expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR);
9501 if (fn.list == NULL)
9502 ash_msg_and_raise_error("redir error");
9503 #if BASH_REDIR_OUTPUT
9504 if (!isdigit_str9(fn.list->text)) {
9505 /* >&file, not >&fd */
9506 if (redir->nfile.fd != 1) /* 123>&file - BAD */
9507 ash_msg_and_raise_error("redir error");
9509 goto store_expfname;
9512 fixredir(redir, fn.list->text, 1);
9520 * Evaluate a pipeline. All the processes in the pipeline are children
9521 * of the process creating the pipeline. (This differs from some versions
9522 * of the shell, which make the last process in a pipeline the parent
9526 evalpipe(union node *n, int flags)
9529 struct nodelist *lp;
9535 TRACE(("evalpipe(0x%lx) called\n", (long)n));
9537 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
9541 if (n->npipe.pipe_backgnd == 0)
9543 jp = makejob(/*n,*/ pipelen);
9545 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
9549 if (pipe(pip) < 0) {
9551 ash_msg_and_raise_perror("can't create pipe");
9554 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
9568 evaltreenr(lp->n, flags);
9575 /* Don't want to trigger debugging */
9579 if (n->npipe.pipe_backgnd == 0) {
9580 status = waitforjob(jp);
9581 TRACE(("evalpipe: job done exit status %d\n", status));
9588 /* setinteractive needs this forward reference */
9589 #if EDITING_HAS_get_exe_name
9590 static const char *get_builtin_name(int i) FAST_FUNC;
9594 * Controls whether the shell is interactive or not.
9597 setinteractive(int on)
9599 static smallint is_interactive;
9601 if (++on == is_interactive)
9603 is_interactive = on;
9607 if (is_interactive > 1) {
9608 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9609 /* Looks like they want an interactive shell */
9610 static smallint did_banner;
9613 /* note: ash and hush share this string */
9614 out1fmt("\n\n%s %s\n"
9615 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
9618 "built-in shell (ash)"
9623 #if ENABLE_FEATURE_EDITING
9624 if (!line_input_state) {
9625 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
9626 # if EDITING_HAS_get_exe_name
9627 line_input_state->get_exe_name = get_builtin_name;
9640 setinteractive(iflag);
9642 #if ENABLE_FEATURE_EDITING_VI
9643 if (line_input_state) {
9645 line_input_state->flags |= VI_MODE;
9647 line_input_state->flags &= ~VI_MODE;
9650 viflag = 0; /* forcibly keep the option off */
9654 struct localvar_list {
9655 struct localvar_list *next;
9656 struct localvar *lv;
9659 static struct localvar_list *localvar_stack;
9662 * Called after a function returns.
9663 * Interrupts must be off.
9666 poplocalvars(int keep)
9668 struct localvar_list *ll;
9669 struct localvar *lvp, *next;
9673 ll = localvar_stack;
9674 localvar_stack = ll->next;
9679 while ((lvp = next) != NULL) {
9682 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9684 int bits = VSTRFIXED;
9686 if (lvp->flags != VUNSET) {
9687 if (vp->var_text == lvp->text)
9689 else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
9690 free((char*)lvp->text);
9694 vp->flags |= (lvp->flags & bits);
9697 (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
9698 unsetvar(vp->var_text);
9699 } else if (vp == NULL) { /* $- saved */
9700 memcpy(optlist, lvp->text, sizeof(optlist));
9701 free((char*)lvp->text);
9703 } else if (lvp->flags == VUNSET) {
9704 vp->flags &= ~(VSTRFIXED|VREADONLY);
9705 unsetvar(vp->var_text);
9708 vp->var_func(var_end(lvp->text));
9709 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9710 free((char*)vp->var_text);
9711 vp->flags = lvp->flags;
9712 vp->var_text = lvp->text;
9720 * Create a new localvar environment.
9722 static struct localvar_list *
9723 pushlocalvars(int push)
9725 struct localvar_list *ll;
9726 struct localvar_list *top;
9728 top = localvar_stack;
9733 ll = ckzalloc(sizeof(*ll));
9734 /*ll->lv = NULL; - zalloc did it */
9736 localvar_stack = ll;
9743 unwindlocalvars(struct localvar_list *stop)
9745 while (localvar_stack != stop)
9750 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9752 volatile struct shparam saveparam;
9753 struct jmploc *volatile savehandler;
9754 struct jmploc jmploc;
9758 saveparam = shellparam;
9759 savefuncline = funcline;
9760 savehandler = exception_handler;
9761 e = setjmp(jmploc.loc);
9766 exception_handler = &jmploc;
9767 shellparam.malloced = 0;
9769 funcline = func->n.ndefun.linno;
9771 shellparam.nparam = argc - 1;
9772 shellparam.p = argv + 1;
9773 #if ENABLE_ASH_GETOPTS
9774 shellparam.optind = 1;
9775 shellparam.optoff = -1;
9777 evaltree(func->n.ndefun.body, flags & EV_TESTED);
9780 funcline = savefuncline;
9782 freeparam(&shellparam);
9783 shellparam = saveparam;
9784 exception_handler = savehandler;
9786 evalskip &= ~SKIPFUNC;
9791 * Make a variable a local variable. When a variable is made local, it's
9792 * value and flags are saved in a localvar structure. The saved values
9793 * will be restored when the shell function returns. We handle the name
9794 * "-" as a special case: it makes changes to "set +-options" local
9795 * (options will be restored on return from the function).
9798 mklocal(char *name, int flags)
9800 struct localvar *lvp;
9803 char *eq = strchr(name, '=');
9806 /* Cater for duplicate "local". Examples:
9807 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9808 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9810 lvp = localvar_stack->lv;
9812 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9816 * it's a duplicate "local VAR" declaration, do nothing
9823 lvp = ckzalloc(sizeof(*lvp));
9824 if (LONE_DASH(name)) {
9826 p = ckmalloc(sizeof(optlist));
9827 lvp->text = memcpy(p, optlist, sizeof(optlist));
9830 vpp = hashvar(name);
9831 vp = *findvar(vpp, name);
9833 /* variable did not exist yet */
9835 vp = setvareq(name, VSTRFIXED | flags);
9837 vp = setvar(name, NULL, VSTRFIXED | flags);
9838 lvp->flags = VUNSET;
9840 lvp->text = vp->var_text;
9841 lvp->flags = vp->flags;
9842 /* make sure neither "struct var" nor string gets freed
9843 * during (un)setting:
9845 vp->flags |= VSTRFIXED|VTEXTFIXED;
9847 setvareq(name, flags);
9849 /* "local VAR" unsets VAR: */
9850 setvar0(name, NULL);
9854 lvp->next = localvar_stack->lv;
9855 localvar_stack->lv = lvp;
9861 * The "local" command.
9863 static int FAST_FUNC
9864 localcmd(int argc UNUSED_PARAM, char **argv)
9868 if (!localvar_stack)
9869 ash_msg_and_raise_error("not in a function");
9872 while ((name = *argv++) != NULL) {
9878 static int FAST_FUNC
9879 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9884 static int FAST_FUNC
9885 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9890 static int FAST_FUNC
9891 execcmd(int argc UNUSED_PARAM, char **argv)
9894 while (nextopt("a:") != '\0')
9895 /* nextopt() sets optionarg to "-a ARGV0" */;
9901 iflag = 0; /* exit on error */
9904 /* We should set up signals for "exec CMD"
9905 * the same way as for "CMD" without "exec".
9906 * But optschanged->setinteractive->setsignal
9907 * still thought we are a root shell. Therefore, for example,
9908 * SIGQUIT is still set to IGN. Fix it:
9912 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9913 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9914 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9918 argv[0] = optionarg;
9919 shellexec(prog, argv, pathval(), 0);
9926 * The return command.
9928 static int FAST_FUNC
9929 returncmd(int argc UNUSED_PARAM, char **argv)
9932 * If called outside a function, do what ksh does;
9933 * skip the rest of the file.
9935 evalskip = SKIPFUNC;
9936 return argv[1] ? number(argv[1]) : exitstatus;
9939 /* Forward declarations for builtintab[] */
9940 static int breakcmd(int, char **) FAST_FUNC;
9941 static int dotcmd(int, char **) FAST_FUNC;
9942 static int evalcmd(int, char **, int) FAST_FUNC;
9943 static int exitcmd(int, char **) FAST_FUNC;
9944 static int exportcmd(int, char **) FAST_FUNC;
9945 #if ENABLE_ASH_GETOPTS
9946 static int getoptscmd(int, char **) FAST_FUNC;
9949 static int helpcmd(int, char **) FAST_FUNC;
9952 static int historycmd(int, char **) FAST_FUNC;
9954 #if ENABLE_FEATURE_SH_MATH
9955 static int letcmd(int, char **) FAST_FUNC;
9957 static int readcmd(int, char **) FAST_FUNC;
9958 static int setcmd(int, char **) FAST_FUNC;
9959 static int shiftcmd(int, char **) FAST_FUNC;
9960 static int timescmd(int, char **) FAST_FUNC;
9961 static int trapcmd(int, char **) FAST_FUNC;
9962 static int umaskcmd(int, char **) FAST_FUNC;
9963 static int unsetcmd(int, char **) FAST_FUNC;
9964 static int ulimitcmd(int, char **) FAST_FUNC;
9966 #define BUILTIN_NOSPEC "0"
9967 #define BUILTIN_SPECIAL "1"
9968 #define BUILTIN_REGULAR "2"
9969 #define BUILTIN_SPEC_REG "3"
9970 #define BUILTIN_ASSIGN "4"
9971 #define BUILTIN_SPEC_ASSG "5"
9972 #define BUILTIN_REG_ASSG "6"
9973 #define BUILTIN_SPEC_REG_ASSG "7"
9975 /* Stubs for calling non-FAST_FUNC's */
9977 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9979 #if ENABLE_ASH_PRINTF
9980 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9982 #if ENABLE_ASH_TEST || BASH_TEST2
9983 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9986 /* Keep these in proper order since it is searched via bsearch() */
9987 static const struct builtincmd builtintab[] = {
9988 { BUILTIN_SPEC_REG "." , dotcmd },
9989 { BUILTIN_SPEC_REG ":" , truecmd },
9991 { BUILTIN_REGULAR "[" , testcmd },
9994 { BUILTIN_REGULAR "[[" , testcmd },
9996 #if ENABLE_ASH_ALIAS
9997 { BUILTIN_REG_ASSG "alias" , aliascmd },
10000 { BUILTIN_REGULAR "bg" , fg_bgcmd },
10002 { BUILTIN_SPEC_REG "break" , breakcmd },
10003 { BUILTIN_REGULAR "cd" , cdcmd },
10004 { BUILTIN_NOSPEC "chdir" , cdcmd },
10005 #if ENABLE_ASH_CMDCMD
10006 { BUILTIN_REGULAR "command" , commandcmd },
10008 { BUILTIN_SPEC_REG "continue", breakcmd },
10009 #if ENABLE_ASH_ECHO
10010 { BUILTIN_REGULAR "echo" , echocmd },
10012 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
10013 { BUILTIN_SPEC_REG "exec" , execcmd },
10014 { BUILTIN_SPEC_REG "exit" , exitcmd },
10015 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
10016 { BUILTIN_REGULAR "false" , falsecmd },
10018 { BUILTIN_REGULAR "fg" , fg_bgcmd },
10020 #if ENABLE_ASH_GETOPTS
10021 { BUILTIN_REGULAR "getopts" , getoptscmd },
10023 { BUILTIN_REGULAR "hash" , hashcmd },
10024 #if ENABLE_ASH_HELP
10025 { BUILTIN_NOSPEC "help" , helpcmd },
10028 { BUILTIN_NOSPEC "history" , historycmd },
10031 { BUILTIN_REGULAR "jobs" , jobscmd },
10032 { BUILTIN_REGULAR "kill" , killcmd },
10034 #if ENABLE_FEATURE_SH_MATH
10035 { BUILTIN_NOSPEC "let" , letcmd },
10037 { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
10038 #if ENABLE_ASH_PRINTF
10039 { BUILTIN_REGULAR "printf" , printfcmd },
10041 { BUILTIN_REGULAR "pwd" , pwdcmd },
10042 { BUILTIN_REGULAR "read" , readcmd },
10043 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
10044 { BUILTIN_SPEC_REG "return" , returncmd },
10045 { BUILTIN_SPEC_REG "set" , setcmd },
10046 { BUILTIN_SPEC_REG "shift" , shiftcmd },
10048 { BUILTIN_SPEC_REG "source" , dotcmd },
10050 #if ENABLE_ASH_TEST
10051 { BUILTIN_REGULAR "test" , testcmd },
10053 { BUILTIN_SPEC_REG "times" , timescmd },
10054 { BUILTIN_SPEC_REG "trap" , trapcmd },
10055 { BUILTIN_REGULAR "true" , truecmd },
10056 { BUILTIN_REGULAR "type" , typecmd },
10057 { BUILTIN_REGULAR "ulimit" , ulimitcmd },
10058 { BUILTIN_REGULAR "umask" , umaskcmd },
10059 #if ENABLE_ASH_ALIAS
10060 { BUILTIN_REGULAR "unalias" , unaliascmd },
10062 { BUILTIN_SPEC_REG "unset" , unsetcmd },
10063 { BUILTIN_REGULAR "wait" , waitcmd },
10066 /* Should match the above table! */
10067 #define COMMANDCMD (builtintab + \
10069 /* [ */ 1 * ENABLE_ASH_TEST + \
10070 /* [[ */ 1 * BASH_TEST2 + \
10071 /* alias */ 1 * ENABLE_ASH_ALIAS + \
10072 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
10073 /* break cd cddir */ 3)
10074 #define EVALCMD (COMMANDCMD + \
10075 /* command */ 1 * ENABLE_ASH_CMDCMD + \
10076 /* continue */ 1 + \
10077 /* echo */ 1 * ENABLE_ASH_ECHO + \
10079 #define EXECCMD (EVALCMD + \
10083 * Search the table of builtin commands.
10086 pstrcmp1(const void *a, const void *b)
10088 return strcmp((char*)a, *(char**)b + 1);
10090 static struct builtincmd *
10091 find_builtin(const char *name)
10093 struct builtincmd *bp;
10096 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
10102 #if EDITING_HAS_get_exe_name
10103 static const char * FAST_FUNC
10104 get_builtin_name(int i)
10106 return /*i >= 0 &&*/ i < ARRAY_SIZE(builtintab) ? builtintab[i].name + 1 : NULL;
10111 * Execute a simple command.
10113 static void unwindfiles(struct parsefile *stop);
10115 isassignment(const char *p)
10117 const char *q = endofname(p);
10122 static int FAST_FUNC
10123 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10125 /* Preserve exitstatus of a previous possible redirection
10126 * as POSIX mandates */
10127 return back_exitstatus;
10130 evalcommand(union node *cmd, int flags)
10132 static const struct builtincmd null_bltin = {
10133 BUILTIN_REGULAR "", bltincmd
10135 struct localvar_list *localvar_stop;
10136 struct parsefile *file_stop;
10137 struct redirtab *redir_stop;
10139 struct arglist arglist;
10140 struct arglist varlist;
10143 struct strlist *osp;
10144 const struct strlist *sp;
10145 struct cmdentry cmdentry;
10153 smallint cmd_is_exec;
10157 errlinno = lineno = cmd->ncmd.linno;
10159 lineno -= funcline - 1;
10161 /* First expand the arguments. */
10162 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
10163 file_stop = g_parsefile;
10164 back_exitstatus = 0;
10166 cmdentry.cmdtype = CMDBUILTIN;
10167 cmdentry.u.cmd = &null_bltin;
10168 varlist.lastp = &varlist.list;
10169 *varlist.lastp = NULL;
10170 arglist.lastp = &arglist.list;
10171 *arglist.lastp = NULL;
10181 argp = cmd->ncmd.args;
10182 osp = fill_arglist(&arglist, &argp);
10184 int pseudovarflag = 0;
10187 find_command(arglist.list->text, &cmdentry,
10188 cmd_flag | DO_REGBLTIN, pathval());
10192 /* implement bltin and command here */
10193 if (cmdentry.cmdtype != CMDBUILTIN)
10196 pseudovarflag = IS_BUILTIN_ASSIGN(cmdentry.u.cmd);
10197 if (spclbltin < 0) {
10198 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
10199 vlocal = !spclbltin;
10201 cmd_is_exec = cmdentry.u.cmd == EXECCMD;
10202 if (cmdentry.u.cmd != COMMANDCMD)
10205 cmd_flag = parse_command_args(&arglist, &argp, &path);
10210 for (; argp; argp = argp->narg.next)
10211 expandarg(argp, &arglist,
10213 isassignment(argp->narg.text) ?
10214 EXP_VARTILDE : EXP_FULL | EXP_TILDE);
10216 for (sp = arglist.list; sp; sp = sp->next)
10219 if (cmd_is_exec && argc > 1)
10223 localvar_stop = pushlocalvars(vlocal);
10225 /* Reserve one extra spot at the front for shellexec. */
10226 nargv = stalloc(sizeof(char *) * (argc + 2));
10228 for (sp = arglist.list; sp; sp = sp->next) {
10229 TRACE(("evalcommand arg: %s\n", sp->text));
10230 *nargv++ = sp->text;
10235 if (iflag && funcline == 0 && argc > 0)
10236 lastarg = nargv[-1];
10238 expredir(cmd->ncmd.redirect);
10239 redir_stop = pushredir(cmd->ncmd.redirect);
10241 if (BASH_XTRACEFD && xflag) {
10242 /* NB: bash closes fd == $BASH_XTRACEFD when it is changed.
10243 * we do not emulate this. We only use its value.
10245 const char *xtracefd = lookupvar("BASH_XTRACEFD");
10246 if (xtracefd && is_number(xtracefd))
10247 preverrout_fd = atoi(xtracefd);
10250 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
10254 exitstatus = status;
10256 /* We have a redirection error. */
10258 raise_exception(EXERROR);
10263 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
10264 struct strlist **spp;
10266 spp = varlist.lastp;
10267 expandarg(argp, &varlist, EXP_VARTILDE);
10270 mklocal((*spp)->text, VEXPORT);
10272 setvareq((*spp)->text, vflags);
10275 /* Print the command if xflag is set. */
10277 const char *pfx = "";
10279 fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
10283 char *varval = sp->text;
10284 char *eq = strchrnul(varval, '=');
10287 fdprintf(preverrout_fd, "%s%.*s%s",
10289 (int)(eq - varval), varval,
10290 maybe_single_quote(eq)
10298 fdprintf(preverrout_fd, "%s%s",
10300 /* always quote if matches reserved word: */
10302 ? single_quote(sp->text)
10303 : maybe_single_quote(sp->text)
10308 safe_write(preverrout_fd, "\n", 1);
10311 /* Now locate the command. */
10312 if (cmdentry.cmdtype != CMDBUILTIN
10313 || !(IS_BUILTIN_REGULAR(cmdentry.u.cmd))
10315 path = path ? path : pathval();
10316 find_command(argv[0], &cmdentry, cmd_flag | DO_ERR, path);
10321 /* Execute the command. */
10322 switch (cmdentry.cmdtype) {
10325 flush_stdout_stderr();
10330 #if ENABLE_FEATURE_SH_STANDALONE \
10331 && ENABLE_FEATURE_SH_NOFORK \
10333 /* (1) BUG: if variables are set, we need to fork, or save/restore them
10334 * around run_nofork_applet() call.
10335 * (2) Should this check also be done in forkshell()?
10336 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
10338 /* find_command() encodes applet_no as (-2 - applet_no) */
10339 int applet_no = (- cmdentry.u.index - 2);
10340 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
10344 sv_environ = environ;
10345 environ = listvars(VEXPORT, VUNSET, varlist.list, /*end:*/ NULL);
10347 * Run <applet>_main().
10348 * Signals (^C) can't interrupt here.
10349 * Otherwise we can mangle stdio or malloc internal state.
10350 * This makes applets which can run for a long time
10351 * and/or wait for user input ineligible for NOFORK:
10352 * for example, "yes" or "rm" (rm -i waits for input).
10354 status = run_nofork_applet(applet_no, argv);
10355 environ = sv_environ;
10357 * Try enabling NOFORK for "yes" applet.
10358 * ^C _will_ stop it (write returns EINTR),
10359 * but this causes stdout FILE to be stuck
10360 * and needing clearerr(). What if other applets
10361 * also can get EINTRs? Do we need to switch
10362 * our signals to SA_RESTART?
10364 /*clearerr(stdout);*/
10369 /* Can we avoid forking? For example, very last command
10370 * in a script or a subshell does not need forking,
10371 * we can just exec it.
10373 if (!(flags & EV_EXIT) || may_have_traps) {
10374 /* No, forking off a child is necessary */
10377 jp = makejob(/*cmd,*/ 1);
10378 if (forkshell(jp, cmd, FORK_FG) != 0) {
10380 TRACE(("forked child exited with %d\n", status));
10385 /* fall through to exec'ing external program */
10387 shellexec(argv[0], argv, path, cmdentry.u.index);
10391 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)
10392 && !(exception_type == EXERROR && spclbltin <= 0)
10395 longjmp(exception_handler->loc, 1);
10400 if (evalfun(cmdentry.u.func, argc, argv, flags))
10405 status = waitforjob(jp);
10409 if (cmd->ncmd.redirect)
10410 popredir(/*drop:*/ cmd_is_exec);
10411 unwindredir(redir_stop);
10412 unwindfiles(file_stop);
10413 unwindlocalvars(localvar_stop);
10415 /* dsl: I think this is intended to be used to support
10416 * '_' in 'vi' command mode during line editing...
10417 * However I implemented that within libedit itself.
10419 setvar0("_", lastarg);
10426 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
10428 char *volatile savecmdname;
10429 struct jmploc *volatile savehandler;
10430 struct jmploc jmploc;
10434 savecmdname = commandname;
10435 savehandler = exception_handler;
10436 i = setjmp(jmploc.loc);
10439 exception_handler = &jmploc;
10440 commandname = argv[0];
10442 optptr = NULL; /* initialize nextopt */
10443 if (cmd == EVALCMD)
10444 status = evalcmd(argc, argv, flags);
10446 status = (*cmd->builtin)(argc, argv);
10447 flush_stdout_stderr();
10448 status |= ferror(stdout);
10449 exitstatus = status;
10452 commandname = savecmdname;
10453 exception_handler = savehandler;
10459 goodname(const char *p)
10461 return endofname(p)[0] == '\0';
10466 * Search for a command. This is called before we fork so that the
10467 * location of the command will be available in the parent as well as
10468 * the child. The check for "goodname" is an overly conservative
10469 * check that the name will not be subject to expansion.
10472 prehash(union node *n)
10474 struct cmdentry entry;
10476 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
10477 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
10481 /* ============ Builtin commands
10483 * Builtin commands whose functions are closely tied to evaluation
10484 * are implemented here.
10488 * Handle break and continue commands. Break, continue, and return are
10489 * all handled by setting the evalskip flag. The evaluation routines
10490 * above all check this flag, and if it is set they start skipping
10491 * commands rather than executing them. The variable skipcount is
10492 * the number of loops to break/continue, or the number of function
10493 * levels to return. (The latter is always 1.) It should probably
10494 * be an error to break out of more loops than exist, but it isn't
10495 * in the standard shell so we don't make it one here.
10497 static int FAST_FUNC
10498 breakcmd(int argc UNUSED_PARAM, char **argv)
10500 int n = argv[1] ? number(argv[1]) : 1;
10503 ash_msg_and_raise_error(msg_illnum, argv[1]);
10507 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
10515 * This implements the input routines used by the parser.
10519 INPUT_PUSH_FILE = 1,
10520 INPUT_NOFILE_OK = 2,
10523 static smallint checkkwd;
10524 /* values of checkkwd variable */
10525 #define CHKALIAS 0x1
10528 #define CHKEOFMARK 0x8
10531 * Push a string back onto the input at this current parsefile level.
10532 * We handle aliases this way.
10534 #if !ENABLE_ASH_ALIAS
10535 #define pushstring(s, ap) pushstring(s)
10538 pushstring(char *s, struct alias *ap)
10540 struct strpush *sp;
10545 if (g_parsefile->strpush) {
10546 sp = ckzalloc(sizeof(*sp));
10547 sp->prev = g_parsefile->strpush;
10549 sp = &(g_parsefile->basestrpush);
10551 g_parsefile->strpush = sp;
10552 sp->prev_string = g_parsefile->next_to_pgetc;
10553 sp->prev_left_in_line = g_parsefile->left_in_line;
10554 sp->unget = g_parsefile->unget;
10555 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
10556 #if ENABLE_ASH_ALIAS
10559 ap->flag |= ALIASINUSE;
10563 g_parsefile->next_to_pgetc = s;
10564 g_parsefile->left_in_line = len;
10565 g_parsefile->unget = 0;
10572 struct strpush *sp = g_parsefile->strpush;
10575 #if ENABLE_ASH_ALIAS
10577 if (g_parsefile->next_to_pgetc[-1] == ' '
10578 || g_parsefile->next_to_pgetc[-1] == '\t'
10580 checkkwd |= CHKALIAS;
10582 if (sp->string != sp->ap->val) {
10585 sp->ap->flag &= ~ALIASINUSE;
10586 if (sp->ap->flag & ALIASDEAD) {
10587 unalias(sp->ap->name);
10591 g_parsefile->next_to_pgetc = sp->prev_string;
10592 g_parsefile->left_in_line = sp->prev_left_in_line;
10593 g_parsefile->unget = sp->unget;
10594 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
10595 g_parsefile->strpush = sp->prev;
10596 if (sp != &(g_parsefile->basestrpush))
10605 char *buf = g_parsefile->buf;
10607 g_parsefile->next_to_pgetc = buf;
10608 #if ENABLE_FEATURE_EDITING
10610 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
10611 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10613 # if ENABLE_ASH_IDLE_TIMEOUT
10615 const char *tmout_var = lookupvar("TMOUT");
10617 timeout = atoi(tmout_var) * 1000;
10621 line_input_state->timeout = timeout;
10623 # if ENABLE_FEATURE_TAB_COMPLETION
10624 line_input_state->path_lookup = pathval();
10626 reinit_unicode_for_ash();
10627 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ);
10629 /* ^C pressed, "convert" to SIGINT */
10630 write(STDOUT_FILENO, "^C", 2);
10631 if (trap[SIGINT]) {
10637 exitstatus = 128 + SIGINT;
10643 /* Ctrl+D pressed */
10646 # if ENABLE_ASH_IDLE_TIMEOUT
10647 else if (errno == EAGAIN && timeout > 0) {
10648 puts("\007timed out waiting for input: auto-logout");
10655 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10658 #if 0 /* disabled: nonblock_immune_read() handles this problem */
10660 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
10661 int flags = fcntl(0, F_GETFL);
10662 if (flags >= 0 && (flags & O_NONBLOCK)) {
10663 flags &= ~O_NONBLOCK;
10664 if (fcntl(0, F_SETFL, flags) >= 0) {
10665 out2str("sh: turning off NDELAY mode\n");
10676 * Refill the input buffer and return the next input character:
10678 * 1) If a string was pushed back on the input, pop it;
10679 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
10680 * or we are reading from a string so we can't refill the buffer,
10682 * 3) If there is more stuff in this buffer, use it else call read to fill it.
10683 * 4) Process input up to the next newline, deleting nul characters.
10685 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
10686 #define pgetc_debug(...) ((void)0)
10687 static int pgetc(void);
10694 if (g_parsefile->strpush) {
10695 #if ENABLE_ASH_ALIAS
10696 if (g_parsefile->left_in_line == -1
10697 && g_parsefile->strpush->ap
10698 && g_parsefile->next_to_pgetc[-1] != ' '
10699 && g_parsefile->next_to_pgetc[-1] != '\t'
10701 pgetc_debug("preadbuffer PEOA");
10708 /* on both branches above g_parsefile->left_in_line < 0.
10709 * "pgetc" needs refilling.
10712 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
10713 * pungetc() may increment it a few times.
10714 * Assuming it won't increment it to less than -90.
10716 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
10717 pgetc_debug("preadbuffer PEOF1");
10718 /* even in failure keep left_in_line and next_to_pgetc
10719 * in lock step, for correct multi-layer pungetc.
10720 * left_in_line was decremented before preadbuffer(),
10721 * must inc next_to_pgetc: */
10722 g_parsefile->next_to_pgetc++;
10726 more = g_parsefile->left_in_buffer;
10728 flush_stdout_stderr();
10732 /* don't try reading again */
10733 g_parsefile->left_in_line = -99;
10734 pgetc_debug("preadbuffer PEOF2");
10735 g_parsefile->next_to_pgetc++;
10740 /* Find out where's the end of line.
10741 * Set g_parsefile->left_in_line
10742 * and g_parsefile->left_in_buffer acordingly.
10743 * NUL chars are deleted.
10745 q = g_parsefile->next_to_pgetc;
10753 memmove(q, q + 1, more);
10757 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10763 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10764 if (g_parsefile->left_in_line < 0)
10769 g_parsefile->left_in_buffer = more;
10774 out2str(g_parsefile->next_to_pgetc);
10778 pgetc_debug("preadbuffer at %d:%p'%s'",
10779 g_parsefile->left_in_line,
10780 g_parsefile->next_to_pgetc,
10781 g_parsefile->next_to_pgetc);
10782 return (unsigned char)*g_parsefile->next_to_pgetc++;
10788 g_parsefile->linno++;
10789 setprompt_if(doprompt, 2);
10794 g_parsefile->linno++;
10795 needprompt = doprompt;
10803 pgetc_debug("pgetc at %d:%p'%s'",
10804 g_parsefile->left_in_line,
10805 g_parsefile->next_to_pgetc,
10806 g_parsefile->next_to_pgetc);
10807 if (g_parsefile->unget)
10808 return g_parsefile->lastc[--g_parsefile->unget];
10810 if (--g_parsefile->left_in_line >= 0)
10811 c = (unsigned char)*g_parsefile->next_to_pgetc++;
10815 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10816 g_parsefile->lastc[0] = c;
10821 #if ENABLE_ASH_ALIAS
10823 pgetc_without_PEOA(void)
10827 pgetc_debug("pgetc at %d:%p'%s'",
10828 g_parsefile->left_in_line,
10829 g_parsefile->next_to_pgetc,
10830 g_parsefile->next_to_pgetc);
10832 } while (c == PEOA);
10836 # define pgetc_without_PEOA() pgetc()
10840 * Undo a call to pgetc. Only two characters may be pushed back.
10841 * PEOF may be pushed back.
10846 g_parsefile->unget++;
10849 /* This one eats backslash+newline */
10855 while ((c = pgetc()) == '\\') {
10856 if (pgetc() != '\n') {
10869 uint8_t innerdq :1;
10870 uint8_t varpushed :1;
10871 uint8_t dblquote :1;
10872 int varnest; /* levels of variables expansion */
10873 int dqvarnest; /* levels of variables expansion within double quotes */
10874 int parenlevel; /* levels of parens in arithmetic */
10875 struct synstack *prev;
10876 struct synstack *next;
10880 pgetc_top(struct synstack *stack)
10882 return stack->syntax == SQSYNTAX ? pgetc() : pgetc_eatbnl();
10886 synstack_push(struct synstack **stack, struct synstack *next, int syntax)
10888 memset(next, 0, sizeof(*next));
10889 next->syntax = syntax;
10890 next->next = *stack;
10891 (*stack)->prev = next;
10895 static ALWAYS_INLINE void
10896 synstack_pop(struct synstack **stack)
10898 *stack = (*stack)->next;
10902 * To handle the "." command, a stack of input files is used. Pushfile
10903 * adds a new entry to the stack and popfile restores the previous level.
10908 struct parsefile *pf;
10910 pf = ckzalloc(sizeof(*pf));
10911 pf->prev = g_parsefile;
10913 /*pf->strpush = NULL; - ckzalloc did it */
10914 /*pf->basestrpush.prev = NULL;*/
10922 struct parsefile *pf = g_parsefile;
10928 if (pf->pf_fd >= 0)
10931 while (pf->strpush)
10933 g_parsefile = pf->prev;
10939 unwindfiles(struct parsefile *stop)
10941 while (g_parsefile != stop)
10946 * Return to top level.
10951 unwindfiles(&basepf);
10955 * Close the file(s) that the shell is reading commands from. Called
10956 * after a fork is done.
10962 if (g_parsefile->pf_fd > 0) {
10963 close(g_parsefile->pf_fd);
10964 g_parsefile->pf_fd = 0;
10969 * Like setinputfile, but takes an open file descriptor. Call this with
10973 setinputfd(int fd, int push)
10977 g_parsefile->buf = NULL;
10979 g_parsefile->pf_fd = fd;
10980 if (g_parsefile->buf == NULL)
10981 g_parsefile->buf = ckmalloc(IBUFSIZ);
10982 g_parsefile->left_in_buffer = 0;
10983 g_parsefile->left_in_line = 0;
10984 g_parsefile->linno = 1;
10988 * Set the input to take input from a file. If push is set, push the
10989 * old input onto the stack first.
10992 setinputfile(const char *fname, int flags)
10997 fd = open(fname, O_RDONLY | O_CLOEXEC);
10999 if (flags & INPUT_NOFILE_OK)
11002 ash_msg_and_raise_perror("can't open '%s'", fname);
11006 else if (O_CLOEXEC == 0) /* old libc */
11007 close_on_exec_on(fd);
11009 setinputfd(fd, flags & INPUT_PUSH_FILE);
11016 * Like setinputfile, but takes input from a string.
11019 setinputstring(char *string)
11023 g_parsefile->next_to_pgetc = string;
11024 g_parsefile->left_in_line = strlen(string);
11025 g_parsefile->buf = NULL;
11026 g_parsefile->linno = 1;
11032 * Routines to check for mail.
11035 #if ENABLE_ASH_MAIL
11037 /* Hash of mtimes of mailboxes */
11038 static unsigned mailtime_hash;
11039 /* Set if MAIL or MAILPATH is changed. */
11040 static smallint mail_var_path_changed;
11043 * Print appropriate message(s) if mail has arrived.
11044 * If mail_var_path_changed is set,
11045 * then the value of MAIL has mail_var_path_changed,
11046 * so we just update the values.
11055 struct stackmark smark;
11058 setstackmark(&smark);
11059 mpath = mpathset() ? mpathval() : mailval();
11064 len = padvance_magic(&mpath, nullstr, 2);
11071 for (q = p; *q; q++)
11077 q[-1] = '\0'; /* delete trailing '/' */
11078 if (stat(p, &statb) < 0) {
11081 /* Very simplistic "hash": just a sum of all mtimes */
11082 new_hash += (unsigned)statb.st_mtime;
11084 if (!mail_var_path_changed && mailtime_hash != new_hash) {
11085 if (mailtime_hash != 0)
11086 out2str("you have mail\n");
11087 mailtime_hash = new_hash;
11089 mail_var_path_changed = 0;
11090 popstackmark(&smark);
11093 static void FAST_FUNC
11094 changemail(const char *val UNUSED_PARAM)
11096 mail_var_path_changed = 1;
11099 #endif /* ASH_MAIL */
11102 /* ============ ??? */
11105 * Set the shell parameters.
11108 setparam(char **argv)
11114 for (nparam = 0; argv[nparam]; nparam++)
11116 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
11118 *ap++ = ckstrdup(*argv++);
11121 freeparam(&shellparam);
11122 shellparam.malloced = 1;
11123 shellparam.nparam = nparam;
11124 shellparam.p = newparam;
11125 #if ENABLE_ASH_GETOPTS
11126 shellparam.optind = 1;
11127 shellparam.optoff = -1;
11132 * Process shell options. The global variable argptr contains a pointer
11133 * to the argument list; we advance it past the options.
11135 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
11136 * For a non-interactive shell, an error condition encountered
11137 * by a special built-in ... shall cause the shell to write a diagnostic message
11138 * to standard error and exit as shown in the following table:
11139 * Error Special Built-In
11141 * Utility syntax error (option or operand error) Shall exit
11143 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
11144 * we see that bash does not do that (set "finishes" with error code 1 instead,
11145 * and shell continues), and people rely on this behavior!
11147 * set -o barfoo 2>/dev/null
11150 * Oh well. Let's mimic that.
11153 plus_minus_o(char *name, int val)
11158 for (i = 0; i < NOPTS; i++) {
11159 if (strcmp(name, optnames(i)) == 0) {
11164 ash_msg("illegal option %co %s", val ? '-' : '+', name);
11167 for (i = 0; i < NOPTS; i++) {
11168 if (optnames(i)[0] == '\0')
11171 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
11173 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
11179 setoption(int flag, int val)
11183 for (i = 0; i < NOPTS; i++) {
11184 if (optletters(i) == flag && optnames(i)[0] != '\0') {
11189 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
11192 /* If login_sh is not NULL, we are called to parse command line opts,
11196 options(int *login_sh)
11204 while ((p = *argptr) != NULL) {
11206 if (c != '-' && c != '+')
11209 val = 0; /* val = 0 if c == '+' */
11212 if (p[0] == '\0' || LONE_DASH(p)) {
11214 /* "-" means turn off -x and -v */
11217 /* "--" means reset params */
11218 else if (*argptr == NULL)
11221 break; /* "-" or "--" terminates options */
11224 /* first char was + or - */
11225 while ((c = *p++) != '\0') {
11227 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
11229 minusc = p; /* command is after shell args */
11233 if (c == 's') { /* -s, +s */
11237 if (c == 'i') { /* -i, +i */
11242 *login_sh = 1; /* -l or +l == --login */
11245 /* bash does not accept +-login, we also won't */
11246 if (val && (c == '-')) { /* long options */
11247 if (strcmp(p, "login") == 0) {
11254 if (plus_minus_o(*argptr, val)) {
11255 /* it already printed err message */
11256 return 1; /* error */
11269 * The shift builtin command.
11271 static int FAST_FUNC
11272 shiftcmd(int argc UNUSED_PARAM, char **argv)
11279 n = number(argv[1]);
11280 if (n > shellparam.nparam)
11283 shellparam.nparam -= n;
11284 for (ap1 = shellparam.p; --n >= 0; ap1++) {
11285 if (shellparam.malloced)
11288 ap2 = shellparam.p;
11289 while ((*ap2++ = *ap1++) != NULL)
11291 #if ENABLE_ASH_GETOPTS
11292 shellparam.optind = 1;
11293 shellparam.optoff = -1;
11300 * POSIX requires that 'set' (but not export or readonly) output the
11301 * variables in lexicographic order - by the locale's collating order (sigh).
11302 * Maybe we could keep them in an ordered balanced binary tree
11303 * instead of hashed lists.
11304 * For now just roll 'em through qsort for printing...
11307 showvars(const char *sep_prefix, int on, int off)
11310 char **ep, **epend;
11312 ep = listvars(on, off, /*strlist:*/ NULL, &epend);
11313 qsort(ep, epend - ep, sizeof(char *), vpcmp);
11315 sep = *sep_prefix ? " " : sep_prefix;
11317 for (; ep < epend; ep++) {
11321 p = endofname(*ep);
11322 /* Used to have simple "p = strchrnul(*ep, '=')" here instead, but this
11323 * makes "export -p" to have output not suitable for "eval":
11325 * os.environ["test-test"]="test"
11326 * if os.fork() == 0:
11327 * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
11328 * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ])
11332 q = single_quote(++p);
11333 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
11339 * The set command builtin.
11341 static int FAST_FUNC
11342 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
11347 return showvars(nullstr, 0, VUNSET);
11350 retval = options(/*login_sh:*/ NULL);
11351 if (retval == 0) { /* if no parse error... */
11353 if (*argptr != NULL) {
11361 #if ENABLE_ASH_RANDOM_SUPPORT
11362 static void FAST_FUNC
11363 change_random(const char *value)
11367 if (value == NULL) {
11368 /* "get", generate */
11369 t = next_random(&random_gen);
11370 /* set without recursion */
11371 setvar(vrandom.var_text, utoa(t), VNOFUNC);
11372 vrandom.flags &= ~VNOFUNC;
11375 t = strtoul(value, NULL, 10);
11376 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
11381 #if BASH_EPOCH_VARS
11382 static void FAST_FUNC
11383 change_epoch(struct var *vepoch, const char *fmt)
11386 char buffer[sizeof("%lu.nnnnnn") + sizeof(long)*3];
11388 gettimeofday(&tv, NULL);
11389 sprintf(buffer, fmt, (unsigned long)tv.tv_sec, (unsigned)tv.tv_usec);
11390 setvar(vepoch->var_text, buffer, VNOFUNC);
11391 vepoch->flags &= ~VNOFUNC;
11394 static void FAST_FUNC
11395 change_seconds(const char *value UNUSED_PARAM)
11397 change_epoch(&vepochs, "%lu");
11400 static void FAST_FUNC
11401 change_realtime(const char *value UNUSED_PARAM)
11403 change_epoch(&vepochr, "%lu.%06u");
11407 #if ENABLE_ASH_GETOPTS
11409 getopts(char *optstr, char *optvar, char **optfirst)
11416 int ind = shellparam.optind;
11417 int off = shellparam.optoff;
11421 shellparam.optind = -1;
11422 optnext = optfirst + ind - 1;
11424 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
11427 p = optnext[-1] + off;
11428 if (p == NULL || *p == '\0') {
11429 /* Current word is done, advance */
11431 if (p == NULL || *p != '-' || *++p == '\0') {
11433 unsetvar("OPTARG");
11439 if (LONE_DASH(p)) /* check for "--" */
11444 for (q = optstr; *q != c;) {
11446 /* OPTERR is a bashism */
11447 const char *cp = lookupvar("OPTERR");
11448 if ((cp && LONE_CHAR(cp, '0'))
11449 || (optstr[0] == ':')
11452 /*sbuf[1] = '\0'; - already is */
11453 setvar0("OPTARG", sbuf);
11455 fprintf(stderr, "Illegal option -%c\n", c);
11456 unsetvar("OPTARG");
11466 if (*p == '\0' && (p = *optnext) == NULL) {
11467 /* OPTERR is a bashism */
11468 const char *cp = lookupvar("OPTERR");
11469 if ((cp && LONE_CHAR(cp, '0'))
11470 || (optstr[0] == ':')
11473 /*sbuf[1] = '\0'; - already is */
11474 setvar0("OPTARG", sbuf);
11477 fprintf(stderr, "No arg for -%c option\n", c);
11478 unsetvar("OPTARG");
11486 setvar0("OPTARG", p);
11489 setvar0("OPTARG", nullstr);
11491 ind = optnext - optfirst + 1;
11492 setvar("OPTIND", itoa(ind), VNOFUNC);
11494 /*sbuf[1] = '\0'; - already is */
11495 setvar0(optvar, sbuf);
11497 shellparam.optoff = p ? p - *(optnext - 1) : -1;
11498 shellparam.optind = ind;
11504 * The getopts builtin. Shellparam.optnext points to the next argument
11505 * to be processed. Shellparam.optptr points to the next character to
11506 * be processed in the current argument. If shellparam.optnext is NULL,
11507 * then it's the first time getopts has been called.
11509 static int FAST_FUNC
11510 getoptscmd(int argc, char **argv)
11515 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
11517 optbase = shellparam.p;
11518 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
11519 shellparam.optind = 1;
11520 shellparam.optoff = -1;
11523 optbase = &argv[3];
11524 if ((unsigned)shellparam.optind > argc - 2) {
11525 shellparam.optind = 1;
11526 shellparam.optoff = -1;
11530 return getopts(argv[1], argv[2], optbase);
11532 #endif /* ASH_GETOPTS */
11535 /* ============ Shell parser */
11538 struct heredoc *next; /* next here document in list */
11539 union node *here; /* redirection node */
11540 char *eofmark; /* string indicating end of input */
11541 smallint striptabs; /* if set, strip leading tabs */
11544 static smallint tokpushback; /* last token pushed back */
11545 static smallint quoteflag; /* set if (part of) last token was quoted */
11546 static token_id_t lasttoken; /* last token read (integer id Txxx) */
11547 static struct heredoc *heredoclist; /* list of here documents to read */
11548 static char *wordtext; /* text of last word returned by readtoken */
11549 static struct nodelist *backquotelist;
11550 static union node *redirnode;
11551 static struct heredoc *heredoc;
11553 static const char *
11554 tokname(char *buf, int tok)
11557 return tokname_array[tok];
11558 sprintf(buf, "\"%s\"", tokname_array[tok]);
11562 /* raise_error_unexpected_syntax:
11563 * Called when an unexpected token is read during the parse. The argument
11564 * is the token that is expected, or -1 if more than one type of token can
11565 * occur at this point.
11567 static void raise_error_unexpected_syntax(int) NORETURN;
11569 raise_error_unexpected_syntax(int token)
11575 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
11577 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
11578 raise_error_syntax(msg);
11582 /* parsing is heavily cross-recursive, need these forward decls */
11583 static union node *andor(void);
11584 static union node *pipeline(void);
11585 static union node *parse_command(void);
11586 static void parseheredoc(void);
11587 static int peektoken(void);
11588 static int readtoken(void);
11590 static union node *
11593 union node *n1, *n2, *n3;
11598 switch (peektoken()) {
11606 if (!n1 && (nlflag & 1))
11612 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11613 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
11619 if (tok == TBACKGND) {
11620 if (n2->type == NPIPE) {
11621 n2->npipe.pipe_backgnd = 1;
11623 if (n2->type != NREDIR) {
11624 n3 = stzalloc(sizeof(struct nredir));
11626 /*n3->nredir.redirect = NULL; - stzalloc did it */
11629 n2->type = NBACKGND;
11635 n3 = stzalloc(sizeof(struct nbinary));
11637 n3->nbinary.ch1 = n1;
11638 n3->nbinary.ch2 = n2;
11651 raise_error_unexpected_syntax(-1);
11658 static union node *
11661 union node *n1, *n2, *n3;
11669 } else if (t == TOR) {
11675 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11677 n3 = stzalloc(sizeof(struct nbinary));
11679 n3->nbinary.ch1 = n1;
11680 n3->nbinary.ch2 = n2;
11685 static union node *
11688 union node *n1, *n2, *pipenode;
11689 struct nodelist *lp, *prev;
11693 TRACE(("pipeline: entered\n"));
11694 if (readtoken() == TNOT) {
11696 checkkwd = CHKKWD | CHKALIAS;
11699 n1 = parse_command();
11700 if (readtoken() == TPIPE) {
11701 pipenode = stzalloc(sizeof(struct npipe));
11702 pipenode->type = NPIPE;
11703 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
11704 lp = stzalloc(sizeof(struct nodelist));
11705 pipenode->npipe.cmdlist = lp;
11709 lp = stzalloc(sizeof(struct nodelist));
11710 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11711 lp->n = parse_command();
11713 } while (readtoken() == TPIPE);
11719 n2 = stzalloc(sizeof(struct nnot));
11727 static union node *
11732 n = stzalloc(sizeof(struct narg));
11734 /*n->narg.next = NULL; - stzalloc did it */
11735 n->narg.text = wordtext;
11736 n->narg.backquote = backquotelist;
11741 fixredir(union node *n, const char *text, int err)
11745 TRACE(("Fix redir %s %d\n", text, err));
11747 n->ndup.vname = NULL;
11749 fd = bb_strtou(text, NULL, 10);
11750 if (!errno && fd >= 0)
11751 n->ndup.dupfd = fd;
11752 else if (LONE_DASH(text))
11753 n->ndup.dupfd = -1;
11756 raise_error_syntax("bad fd number");
11757 n->ndup.vname = makename();
11764 union node *n = redirnode;
11766 if (n->type == NHERE)
11767 checkkwd = CHKEOFMARK;
11768 if (readtoken() != TWORD)
11769 raise_error_unexpected_syntax(-1);
11770 if (n->type == NHERE) {
11771 struct heredoc *here = heredoc;
11774 if (quoteflag == 0)
11776 TRACE(("Here document %d\n", n->type));
11777 rmescapes(wordtext, 0, NULL);
11778 here->eofmark = wordtext;
11780 if (heredoclist == NULL)
11781 heredoclist = here;
11783 for (p = heredoclist; p->next; p = p->next)
11787 } else if (n->type == NTOFD || n->type == NFROMFD) {
11788 fixredir(n, wordtext, 0);
11790 n->nfile.fname = makename();
11794 static union node *
11797 union node *args, **app;
11798 union node *n = NULL;
11799 union node *vars, **vpp;
11800 union node **rpp, *redir;
11804 smallint double_brackets_flag = 0;
11806 IF_BASH_FUNCTION(smallint function_flag = 0;)
11815 savecheckkwd = CHKALIAS;
11816 savelinno = g_parsefile->linno;
11819 checkkwd = savecheckkwd;
11824 if (peektoken() != TWORD)
11825 raise_error_unexpected_syntax(TWORD);
11830 case TAND: /* "&&" */
11831 case TOR: /* "||" */
11832 if (!double_brackets_flag) {
11836 wordtext = (char *) (t == TAND ? "-a" : "-o");
11839 n = stzalloc(sizeof(struct narg));
11841 /*n->narg.next = NULL; - stzalloc did it */
11842 n->narg.text = wordtext;
11844 if (strcmp("[[", wordtext) == 0)
11845 double_brackets_flag = 1;
11846 else if (strcmp("]]", wordtext) == 0)
11847 double_brackets_flag = 0;
11849 n->narg.backquote = backquotelist;
11850 if (savecheckkwd && isassignment(wordtext)) {
11852 vpp = &n->narg.next;
11855 app = &n->narg.next;
11859 if (function_flag) {
11860 checkkwd = CHKNL | CHKKWD;
11861 switch (peektoken()) {
11874 if (strcmp("[[", wordtext) == 0)
11879 raise_error_unexpected_syntax(-1);
11885 *rpp = n = redirnode;
11886 rpp = &n->nfile.next;
11887 parsefname(); /* read name of redirection file */
11890 IF_BASH_FUNCTION(do_func:)
11891 if (args && app == &args->narg.next
11894 struct builtincmd *bcmd;
11897 /* We have a function */
11898 if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
11899 raise_error_unexpected_syntax(TRP);
11900 name = n->narg.text;
11901 if (!goodname(name)
11902 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11904 raise_error_syntax("bad function name");
11907 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11908 n->ndefun.text = n->narg.text;
11909 n->ndefun.linno = g_parsefile->linno;
11910 n->ndefun.body = parse_command();
11913 IF_BASH_FUNCTION(function_flag = 0;)
11924 n = stzalloc(sizeof(struct ncmd));
11927 n->ncmd.linno = savelinno;
11928 n->ncmd.args = args;
11929 n->ncmd.assign = vars;
11930 n->ncmd.redirect = redir;
11934 static union node *
11935 parse_command(void)
11937 union node *n1, *n2;
11938 union node *ap, **app;
11939 union node *cp, **cpp;
11940 union node *redir, **rpp;
11948 savelinno = g_parsefile->linno;
11950 switch (readtoken()) {
11952 raise_error_unexpected_syntax(-1);
11955 n1 = stzalloc(sizeof(struct nif));
11957 n1->nif.test = list(0);
11958 if (readtoken() != TTHEN)
11959 raise_error_unexpected_syntax(TTHEN);
11960 n1->nif.ifpart = list(0);
11962 while (readtoken() == TELIF) {
11963 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11964 n2 = n2->nif.elsepart;
11966 n2->nif.test = list(0);
11967 if (readtoken() != TTHEN)
11968 raise_error_unexpected_syntax(TTHEN);
11969 n2->nif.ifpart = list(0);
11971 if (lasttoken == TELSE)
11972 n2->nif.elsepart = list(0);
11974 n2->nif.elsepart = NULL;
11982 n1 = stzalloc(sizeof(struct nbinary));
11983 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11984 n1->nbinary.ch1 = list(0);
11987 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11988 got == TWORD ? wordtext : ""));
11989 raise_error_unexpected_syntax(TDO);
11991 n1->nbinary.ch2 = list(0);
11996 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11997 raise_error_syntax("bad for loop variable");
11998 n1 = stzalloc(sizeof(struct nfor));
12000 n1->nfor.linno = savelinno;
12001 n1->nfor.var = wordtext;
12002 checkkwd = CHKNL | CHKKWD | CHKALIAS;
12003 if (readtoken() == TIN) {
12005 while (readtoken() == TWORD) {
12006 n2 = stzalloc(sizeof(struct narg));
12008 /*n2->narg.next = NULL; - stzalloc did it */
12009 n2->narg.text = wordtext;
12010 n2->narg.backquote = backquotelist;
12012 app = &n2->narg.next;
12015 n1->nfor.args = ap;
12016 if (lasttoken != TNL && lasttoken != TSEMI)
12017 raise_error_unexpected_syntax(-1);
12019 n2 = stzalloc(sizeof(struct narg));
12021 /*n2->narg.next = NULL; - stzalloc did it */
12022 n2->narg.text = (char *)dolatstr;
12023 /*n2->narg.backquote = NULL;*/
12024 n1->nfor.args = n2;
12026 * Newline or semicolon here is optional (but note
12027 * that the original Bourne shell only allowed NL).
12029 if (lasttoken != TSEMI)
12032 checkkwd = CHKNL | CHKKWD | CHKALIAS;
12033 if (readtoken() != TDO)
12034 raise_error_unexpected_syntax(TDO);
12035 n1->nfor.body = list(0);
12039 n1 = stzalloc(sizeof(struct ncase));
12041 n1->ncase.linno = savelinno;
12042 if (readtoken() != TWORD)
12043 raise_error_unexpected_syntax(TWORD);
12044 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
12046 /*n2->narg.next = NULL; - stzalloc did it */
12047 n2->narg.text = wordtext;
12048 n2->narg.backquote = backquotelist;
12049 checkkwd = CHKNL | CHKKWD | CHKALIAS;
12050 if (readtoken() != TIN)
12051 raise_error_unexpected_syntax(TIN);
12052 cpp = &n1->ncase.cases;
12054 checkkwd = CHKNL | CHKKWD;
12056 while (t != TESAC) {
12057 if (lasttoken == TLP)
12059 *cpp = cp = stzalloc(sizeof(struct nclist));
12061 app = &cp->nclist.pattern;
12063 *app = ap = stzalloc(sizeof(struct narg));
12065 /*ap->narg.next = NULL; - stzalloc did it */
12066 ap->narg.text = wordtext;
12067 ap->narg.backquote = backquotelist;
12068 if (readtoken() != TPIPE)
12070 app = &ap->narg.next;
12073 //ap->narg.next = NULL;
12074 if (lasttoken != TRP)
12075 raise_error_unexpected_syntax(TRP);
12076 cp->nclist.body = list(2);
12078 cpp = &cp->nclist.next;
12080 checkkwd = CHKNL | CHKKWD;
12084 raise_error_unexpected_syntax(TENDCASE);
12091 n1 = stzalloc(sizeof(struct nredir));
12092 n1->type = NSUBSHELL;
12093 n1->nredir.linno = savelinno;
12094 n1->nredir.n = list(0);
12095 /*n1->nredir.redirect = NULL; - stzalloc did it */
12102 IF_BASH_FUNCTION(case TFUNCTION:)
12106 return simplecmd();
12109 if (readtoken() != t)
12110 raise_error_unexpected_syntax(t);
12113 /* Now check for redirection which may follow command */
12114 checkkwd = CHKKWD | CHKALIAS;
12116 while (readtoken() == TREDIR) {
12117 *rpp = n2 = redirnode;
12118 rpp = &n2->nfile.next;
12124 if (n1->type != NSUBSHELL) {
12125 n2 = stzalloc(sizeof(struct nredir));
12127 n2->nredir.linno = savelinno;
12131 n1->nredir.redirect = redir;
12136 #if BASH_DOLLAR_SQUOTE
12138 decode_dollar_squote(void)
12140 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
12146 p = strchr(C_escapes, c);
12151 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
12155 } while ((unsigned char)(c - '0') <= 7 && --cnt);
12157 } else if (c == 'x') { /* \xHH */
12161 } while (isxdigit(c) && --cnt);
12163 if (cnt == 3) { /* \x but next char is "bad" */
12167 } else { /* simple seq like \\ or \t */
12172 c = bb_process_escape_sequence((void*)&p);
12173 } else { /* unrecognized "\z": print both chars unless ' or " */
12174 if (c != '\'' && c != '"') {
12176 c |= 0x100; /* "please encode \, then me" */
12183 /* Used by expandstr to get here-doc like behaviour. */
12184 #define FAKEEOFMARK ((char*)(uintptr_t)1)
12186 static ALWAYS_INLINE int
12187 realeofmark(const char *eofmark)
12189 return eofmark && eofmark != FAKEEOFMARK;
12193 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
12194 * is not NULL, read a here document. In the latter case, eofmark is the
12195 * word which marks the end of the document and striptabs is true if
12196 * leading tabs should be stripped from the document. The argument c
12197 * is the first character of the input token or document.
12199 * Because C does not have internal subroutines, I have simulated them
12200 * using goto's to implement the subroutine linkage. The following macros
12201 * will run code that appears at the end of readtoken1.
12203 #define CHECKEND() {goto checkend; checkend_return:;}
12204 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
12205 #define PARSESUB() {goto parsesub; parsesub_return:;}
12206 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
12207 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
12208 #define PARSEARITH() {goto parsearith; parsearith_return:;}
12210 readtoken1(int c, int syntax, char *eofmark, int striptabs)
12212 /* NB: syntax parameter fits into smallint */
12213 /* c parameter is an unsigned char or PEOF or PEOA */
12216 struct nodelist *bqlist;
12219 smallint pssyntax; /* we are expanding a prompt string */
12220 IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
12222 struct synstack synbase = { };
12223 struct synstack *synstack = &synbase;
12225 #if ENABLE_ASH_EXPAND_PRMT
12226 pssyntax = (syntax == PSSYNTAX);
12230 pssyntax = 0; /* constant */
12232 synstack->syntax = syntax;
12234 if (syntax == DQSYNTAX)
12235 synstack->dblquote = 1;
12239 STARTSTACKSTR(out);
12241 /* For each line, until end of word */
12242 CHECKEND(); /* set c to PEOF if at end of here document */
12243 for (;;) { /* until end of line or end of word */
12244 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
12245 switch (SIT(c, synstack->syntax)) {
12246 case CNL: /* '\n' */
12247 if (synstack->syntax == BASESYNTAX
12248 && !synstack->varnest
12250 goto endword; /* exit outer loop */
12254 c = pgetc_top(synstack);
12255 goto loop; /* continue outer loop */
12260 #if BASH_DOLLAR_SQUOTE
12261 if (c == '\\' && bash_dollar_squote) {
12262 c = decode_dollar_squote();
12264 /* skip $'\000', $'\x00' (like bash) */
12268 /* Unknown escape. Encode as '\z' */
12269 c = (unsigned char)c;
12270 if (eofmark == NULL || synstack->dblquote)
12271 USTPUTC(CTLESC, out);
12272 USTPUTC('\\', out);
12276 if (!eofmark || synstack->dblquote || synstack->varnest)
12277 USTPUTC(CTLESC, out);
12280 case CBACK: /* backslash */
12281 c = pgetc_without_PEOA();
12283 USTPUTC(CTLESC, out);
12284 USTPUTC('\\', out);
12287 if (pssyntax && c == '$') {
12288 USTPUTC(CTLESC, out);
12289 USTPUTC('\\', out);
12291 /* Backslash is retained if we are in "str"
12292 * and next char isn't dquote-special.
12294 if (synstack->dblquote
12298 && (c != '"' || (eofmark != NULL && !synstack->varnest))
12299 && (c != '}' || !synstack->varnest)
12301 USTPUTC(CTLESC, out); /* protect '\' from glob */
12302 USTPUTC('\\', out);
12304 USTPUTC(CTLESC, out);
12310 synstack->syntax = SQSYNTAX;
12312 if (eofmark == NULL) {
12313 USTPUTC(CTLQUOTEMARK, out);
12317 synstack->syntax = DQSYNTAX;
12318 synstack->dblquote = 1;
12320 if (synstack->varnest)
12321 synstack->innerdq ^= 1;
12324 IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
12325 if (eofmark != NULL && synstack->varnest == 0) {
12330 if (synstack->dqvarnest == 0) {
12331 synstack->syntax = BASESYNTAX;
12332 synstack->dblquote = 0;
12341 case CVAR: /* '$' */
12342 PARSESUB(); /* parse substitution */
12344 case CENDVAR: /* '}' */
12345 if (!synstack->innerdq && synstack->varnest > 0) {
12346 if (!--synstack->varnest && synstack->varpushed)
12347 synstack_pop(&synstack);
12348 else if (synstack->dqvarnest > 0)
12349 synstack->dqvarnest--;
12354 #if ENABLE_FEATURE_SH_MATH
12355 case CLP: /* '(' in arithmetic */
12356 synstack->parenlevel++;
12359 case CRP: /* ')' in arithmetic */
12360 if (synstack->parenlevel > 0) {
12361 synstack->parenlevel--;
12363 if (pgetc_eatbnl() == ')') {
12365 synstack_pop(&synstack);
12368 * unbalanced parens
12369 * (don't 2nd guess - no error)
12377 case CBQUOTE: /* '`' */
12378 if (checkkwd & CHKEOFMARK) {
12387 goto endword; /* exit outer loop */
12391 if (synstack->varnest == 0) {
12392 #if BASH_REDIR_OUTPUT
12394 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
12395 if (pgetc() == '>')
12396 c = 0x100 + '>'; /* flag &> */
12400 goto endword; /* exit outer loop */
12402 IF_ASH_ALIAS(if (c != PEOA))
12405 c = pgetc_top(synstack);
12409 #if ENABLE_FEATURE_SH_MATH
12410 if (synstack->syntax == ARISYNTAX)
12411 raise_error_syntax("missing '))'");
12413 if (synstack->syntax != BASESYNTAX && eofmark == NULL)
12414 raise_error_syntax("unterminated quoted string");
12415 if (synstack->varnest != 0) {
12417 raise_error_syntax("missing '}'");
12419 USTPUTC('\0', out);
12420 len = out - (char *)stackblock();
12421 out = stackblock();
12422 if (eofmark == NULL) {
12423 if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
12426 if (isdigit_str9(out)) {
12427 PARSEREDIR(); /* passed as params: out, c */
12428 lasttoken = TREDIR;
12431 /* else: non-number X seen, interpret it
12432 * as "NNNX>file" = "NNNX >file" */
12436 quoteflag = quotef;
12437 backquotelist = bqlist;
12438 grabstackblock(len);
12442 /* end of readtoken routine */
12445 * Check to see whether we are at the end of the here document. When this
12446 * is called, c is set to the first character of the next input line. If
12447 * we are at the end of the here document, this routine sets the c to PEOF.
12450 if (realeofmark(eofmark)) {
12454 #if ENABLE_ASH_ALIAS
12456 c = pgetc_without_PEOA();
12459 while (c == '\t') {
12460 c = pgetc_without_PEOA();
12464 markloc = out - (char *)stackblock();
12465 for (p = eofmark; STPUTC(c, out), *p; p++) {
12468 /* FIXME: fails for backslash-newlined terminator:
12473 * (see heredoc_bkslash_newline2.tests)
12475 c = pgetc_without_PEOA();
12478 if (c == '\n' || c == PEOF) {
12480 g_parsefile->linno++;
12481 needprompt = doprompt;
12486 p = (char *)stackblock() + markloc + 1;
12487 len_here = out - p;
12490 len_here -= (c >= PEOF);
12496 str = alloca(len_here + 1);
12497 *(char *)mempcpy(str, p, len_here) = '\0';
12499 pushstring(str, NULL);
12504 STADJUST((char *)stackblock() + markloc - out, out);
12506 goto checkend_return;
12510 * Parse a redirection operator. The variable "out" points to a string
12511 * specifying the fd to be redirected. The variable "c" contains the
12512 * first character of the redirection operator.
12515 /* out is already checked to be a valid number or "" */
12516 int fd = (*out == '\0' ? -1 : atoi(out));
12519 np = stzalloc(sizeof(struct nfile));
12522 c = pgetc_eatbnl();
12524 np->type = NAPPEND;
12526 np->type = NCLOBBER;
12529 /* it also can be NTO2 (>&file), but we can't figure it out yet */
12535 #if BASH_REDIR_OUTPUT
12536 else if (c == 0x100 + '>') { /* this flags &> redirection */
12538 pgetc(); /* this is '>', no need to check */
12542 else { /* c == '<' */
12543 /*np->nfile.fd = 0; - stzalloc did it */
12544 c = pgetc_eatbnl();
12547 if (sizeof(struct nfile) != sizeof(struct nhere)) {
12548 np = stzalloc(sizeof(struct nhere));
12549 /*np->nfile.fd = 0; - stzalloc did it */
12552 heredoc = stzalloc(sizeof(struct heredoc));
12553 heredoc->here = np;
12554 c = pgetc_eatbnl();
12556 heredoc->striptabs = 1;
12558 /*heredoc->striptabs = 0; - stzalloc did it */
12564 np->type = NFROMFD;
12568 np->type = NFROMTO;
12580 goto parseredir_return;
12584 * Parse a substitution. At this point, we have read the dollar sign
12585 * and nothing else.
12588 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
12589 * (assuming ascii char codes, as the original implementation did) */
12590 #define is_special(c) \
12591 (((unsigned)(c) - 33 < 32) \
12592 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
12594 unsigned char subtype;
12597 c = pgetc_eatbnl();
12598 if ((checkkwd & CHKEOFMARK)
12599 || c > 255 /* PEOA or PEOF */
12600 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
12602 #if BASH_DOLLAR_SQUOTE
12603 if (synstack->syntax != DQSYNTAX && c == '\'')
12604 bash_dollar_squote = 1;
12609 } else if (c == '(') {
12610 /* $(command) or $((arith)) */
12611 if (pgetc_eatbnl() == '(') {
12612 #if ENABLE_FEATURE_SH_MATH
12615 raise_error_syntax("support for $((arith)) is disabled");
12622 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
12623 smalluint newsyn = synstack->syntax;
12625 USTPUTC(CTLVAR, out);
12626 typeloc = out - (char *)stackblock();
12628 subtype = VSNORMAL;
12630 c = pgetc_eatbnl();
12635 /* $[{[#]]NAME[}] */
12638 c = pgetc_eatbnl();
12639 } while (is_in_name(c));
12640 } else if (isdigit(c)) {
12641 /* $[{[#]]NUM[}] */
12644 c = pgetc_eatbnl();
12645 } while (!subtype && isdigit(c));
12646 } else if (c != '}') {
12647 /* $[{[#]]<specialchar>[}] */
12650 c = pgetc_eatbnl();
12651 if (!subtype && cc == '#') {
12652 subtype = VSLENGTH;
12653 if (c == '_' || isalnum(c))
12656 c = pgetc_eatbnl();
12657 if (cc == '}' || c != '}') {
12665 if (!is_special(cc)) {
12666 if (subtype == VSLENGTH)
12675 if (c != '}' && subtype == VSLENGTH) {
12676 /* ${#VAR didn't end with } */
12680 if (subtype == 0) {
12681 static const char types[] ALIGN1 = "}-+?=";
12682 /* ${VAR...} but not $VAR or ${#VAR} */
12683 /* c == first char after VAR */
12688 c = pgetc_eatbnl();
12690 /* This check is only needed to not misinterpret
12691 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
12694 if (!strchr(types, c)) {
12695 subtype = VSSUBSTR;
12697 break; /* "goto badsub" is bigger (!) */
12703 const char *p = strchr(types, c);
12706 subtype |= p - types + VSNORMAL;
12711 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
12712 c = pgetc_eatbnl();
12718 newsyn = BASESYNTAX;
12720 #if BASH_PATTERN_SUBST
12722 /* ${v/[/]pattern/repl} */
12723 //TODO: encode pattern and repl separately.
12724 // Currently cases like: v=1;echo ${v/$((1/1))/ONE}
12725 // are broken (should print "ONE")
12726 subtype = VSREPLACE;
12727 newsyn = BASESYNTAX;
12728 c = pgetc_eatbnl();
12731 subtype++; /* VSREPLACEALL */
12740 if (newsyn == ARISYNTAX)
12743 if ((newsyn != synstack->syntax || synstack->innerdq)
12744 && subtype != VSNORMAL
12746 synstack_push(&synstack,
12747 synstack->prev ?: alloca(sizeof(*synstack)),
12750 synstack->varpushed = 1;
12751 synstack->dblquote = newsyn != BASESYNTAX;
12754 ((unsigned char *)stackblock())[typeloc] = subtype;
12755 if (subtype != VSNORMAL) {
12756 synstack->varnest++;
12757 if (synstack->dblquote)
12758 synstack->dqvarnest++;
12762 goto parsesub_return;
12766 * Called to parse command substitutions. Newstyle is set if the command
12767 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
12768 * list of commands (passed by reference), and savelen is the number of
12769 * characters on the top of the stack which must be preserved.
12772 struct nodelist **nlpp;
12776 struct heredoc *saveheredoclist;
12777 smallint saveprompt = 0;
12780 savelen = out - (char *)stackblock();
12783 * FIXME: this can allocate very large block on stack and SEGV.
12785 * echo "..<100kbytes>..`true` $(true) `true` ..."
12786 * allocates 100kb for every command subst. With about
12787 * a hundred command substitutions stack overflows.
12788 * With larger prepended string, SEGV happens sooner.
12790 str = alloca(savelen);
12791 memcpy(str, stackblock(), savelen);
12795 /* We must read until the closing backquote, giving special
12796 * treatment to some slashes, and then push the string and
12797 * reread it as input, interpreting it normally.
12803 STARTSTACKSTR(pout);
12807 setprompt_if(needprompt, 2);
12808 pc = pgetc_eatbnl();
12814 pc = pgetc(); /* or pgetc_eatbnl()? why (example)? */
12815 if (pc != '\\' && pc != '`' && pc != '$'
12816 && (!synstack->dblquote || pc != '"')
12818 STPUTC('\\', pout);
12820 if (pc <= 255 /* not PEOA or PEOF */) {
12826 IF_ASH_ALIAS(case PEOA:)
12827 raise_error_syntax("EOF in backquote substitution");
12839 STPUTC('\0', pout);
12840 psavelen = pout - (char *)stackblock();
12841 if (psavelen > 0) {
12842 pstr = grabstackstr(pout);
12843 setinputstring(pstr);
12848 nlpp = &(*nlpp)->next;
12849 *nlpp = stzalloc(sizeof(**nlpp));
12850 /* (*nlpp)->next = NULL; - stzalloc did it */
12852 saveheredoclist = heredoclist;
12853 heredoclist = NULL;
12856 saveprompt = doprompt;
12863 doprompt = saveprompt;
12865 if (readtoken() != TRP)
12866 raise_error_unexpected_syntax(TRP);
12867 setinputstring(nullstr);
12871 heredoclist = saveheredoclist;
12874 /* Start reading from old file again. */
12876 /* Ignore any pushed back tokens left from the backquote parsing. */
12879 out = growstackto(savelen + 1);
12881 memcpy(out, str, savelen);
12882 STADJUST(savelen, out);
12884 USTPUTC(CTLBACKQ, out);
12886 goto parsebackq_oldreturn;
12887 goto parsebackq_newreturn;
12890 #if ENABLE_FEATURE_SH_MATH
12892 * Parse an arithmetic expansion (indicate start of one and set state)
12896 synstack_push(&synstack,
12897 synstack->prev ?: alloca(sizeof(*synstack)),
12899 synstack->dblquote = 1;
12900 USTPUTC(CTLARI, out);
12901 goto parsearith_return;
12904 } /* end of readtoken */
12907 * Read the next input token.
12908 * If the token is a word, we set backquotelist to the list of cmds in
12909 * backquotes. We set quoteflag to true if any part of the word was
12911 * If the token is TREDIR, then we set redirnode to a structure containing
12914 * [Change comment: here documents and internal procedures]
12915 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12916 * word parsing code into a separate routine. In this case, readtoken
12917 * doesn't need to have any internal procedures, but parseword does.
12918 * We could also make parseoperator in essence the main routine, and
12919 * have parseword (readtoken1?) handle both words and redirection.]
12921 #define NEW_xxreadtoken
12922 #ifdef NEW_xxreadtoken
12923 /* singles must be first! */
12924 static const char xxreadtoken_chars[7] ALIGN1 = {
12925 '\n', '(', ')', /* singles */
12926 '&', '|', ';', /* doubles */
12930 #define xxreadtoken_singles 3
12931 #define xxreadtoken_doubles 3
12933 static const char xxreadtoken_tokens[] ALIGN1 = {
12934 TNL, TLP, TRP, /* only single occurrence allowed */
12935 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12936 TEOF, /* corresponds to trailing nul */
12937 TAND, TOR, TENDCASE /* if double occurrence */
12949 setprompt_if(needprompt, 2);
12950 for (;;) { /* until token or start of word found */
12951 c = pgetc_eatbnl();
12952 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12956 while ((c = pgetc()) != '\n' && c != PEOF)
12959 } else if (c == '\\') {
12960 break; /* return readtoken1(...) */
12964 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12970 p = strchr(xxreadtoken_chars, c);
12972 break; /* return readtoken1(...) */
12974 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12975 int cc = pgetc_eatbnl();
12976 if (cc == c) { /* double occurrence? */
12977 p += xxreadtoken_doubles + 1;
12980 #if BASH_REDIR_OUTPUT
12981 if (c == '&' && cc == '>') /* &> */
12982 break; /* return readtoken1(...) */
12987 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12992 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12994 #else /* old xxreadtoken */
12995 #define RETURN(token) return lasttoken = token
13005 setprompt_if(needprompt, 2);
13006 for (;;) { /* until token or start of word found */
13007 c = pgetc_eatbnl();
13009 case ' ': case '\t':
13010 IF_ASH_ALIAS(case PEOA:)
13013 while ((c = pgetc()) != '\n' && c != PEOF)
13023 if (pgetc_eatbnl() == '&')
13028 if (pgetc_eatbnl() == '|')
13033 if (pgetc_eatbnl() == ';')
13044 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
13047 #endif /* old xxreadtoken */
13053 int kwd = checkkwd;
13055 smallint alreadyseen = tokpushback;
13058 #if ENABLE_ASH_ALIAS
13074 if (t != TWORD || quoteflag) {
13079 * check for keywords
13081 if (kwd & CHKKWD) {
13082 const char *const *pp;
13084 pp = findkwd(wordtext);
13086 lasttoken = t = pp - tokname_array;
13087 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
13092 if (checkkwd & CHKALIAS) {
13093 #if ENABLE_ASH_ALIAS
13095 ap = lookupalias(wordtext, 1);
13098 pushstring(ap->val, ap);
13108 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
13110 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
13126 * Read and parse a command. Returns NODE_EOF on end of file.
13127 * (NULL is a valid parse tree indicating a blank line.)
13129 static union node *
13130 parsecmd(int interact)
13135 doprompt = interact;
13136 setprompt_if(doprompt, doprompt);
13142 * Input any here documents.
13147 struct heredoc *here;
13150 here = heredoclist;
13151 heredoclist = NULL;
13155 setprompt_if(needprompt, 2);
13156 if (here->here->type == NHERE)
13157 readtoken1(pgetc(), SQSYNTAX, here->eofmark, here->striptabs);
13159 readtoken1(pgetc_eatbnl(), DQSYNTAX, here->eofmark, here->striptabs);
13160 n = stzalloc(sizeof(struct narg));
13161 n->narg.type = NARG;
13162 /*n->narg.next = NULL; - stzalloc did it */
13163 n->narg.text = wordtext;
13164 n->narg.backquote = backquotelist;
13165 here->here->nhere.doc = n;
13171 static const char *
13172 expandstr(const char *ps, int syntax_type)
13176 struct parsefile *file_stop = g_parsefile;
13177 volatile int saveint;
13178 struct jmploc *volatile savehandler = exception_handler;
13179 struct jmploc jmploc;
13180 const char *volatile result;
13183 /* XXX Fix (char *) cast. */
13184 setinputstring((char *)ps);
13186 saveprompt = doprompt;
13191 err = setjmp(jmploc.loc);
13195 /* readtoken1() might die horribly.
13196 * Try a prompt with syntactically wrong command:
13197 * PS1='$(date "+%H:%M:%S) > '
13199 exception_handler = &jmploc;
13200 readtoken1(pgetc(), syntax_type, FAKEEOFMARK, 0);
13202 n.narg.type = NARG;
13203 n.narg.next = NULL;
13204 n.narg.text = wordtext;
13205 n.narg.backquote = backquotelist;
13207 /* expandarg() might fail too:
13210 expandarg(&n, NULL, EXP_QUOTED);
13211 result = stackblock();
13214 exception_handler = savehandler;
13215 if (err && exception_type != EXERROR)
13216 longjmp(exception_handler->loc, 1);
13217 RESTORE_INT(saveint);
13219 doprompt = saveprompt;
13220 /* Try: PS1='`xxx(`' */
13221 unwindfiles(file_stop);
13229 return tokpushback && lasttoken == TEOF;
13233 * Execute a command or commands contained in a string.
13236 evalstring(char *s, int flags)
13238 struct jmploc *volatile savehandler;
13239 struct jmploc jmploc;
13243 struct stackmark smark;
13248 setstackmark(&smark);
13251 /* On exception inside execution loop, we must popfile().
13252 * Try interactively:
13254 * command eval "a=b" # throws "is read only" error
13255 * "command BLTIN" is not supposed to abort (even in non-interactive use).
13256 * But if we skip popfile(), we hit EOF in eval's string, and exit.
13258 savehandler = exception_handler;
13259 ex = setjmp(jmploc.loc);
13262 exception_handler = &jmploc;
13264 while ((n = parsecmd(0)) != NODE_EOF) {
13267 i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
13270 popstackmark(&smark);
13275 popstackmark(&smark);
13279 exception_handler = savehandler;
13281 longjmp(exception_handler->loc, ex);
13287 * The eval command.
13289 static int FAST_FUNC
13290 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
13299 STARTSTACKSTR(concat);
13301 concat = stack_putstr(p, concat);
13305 STPUTC(' ', concat);
13307 STPUTC('\0', concat);
13308 p = grabstackstr(concat);
13310 return evalstring(p, flags & EV_TESTED);
13316 * Read and execute commands.
13317 * "Top" is nonzero for the top level command loop;
13318 * it turns on prompting if the shell is interactive.
13324 struct stackmark smark;
13329 TRACE(("cmdloop(%d) called\n", top));
13333 setstackmark(&smark);
13336 showjobs(SHOW_CHANGED|SHOW_STDERR);
13339 if (iflag && top) {
13343 n = parsecmd(inter);
13345 if (DEBUG > 2 && debug && (n != NODE_EOF))
13348 if (n == NODE_EOF) {
13349 if (!top || numeof >= 50)
13351 if (!stoppedjobs()) {
13354 newline_and_flush(stderr);
13358 out2str("\nUse \"exit\" to leave shell.\n");
13361 } else if (nflag == 0) {
13364 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
13367 i = evaltree(n, 0);
13371 popstackmark(&smark);
13375 evalskip &= ~SKIPFUNC;
13383 * Take commands from a file. To be compatible we should do a path
13384 * search for the file, which is necessary to find sub-commands.
13387 find_dot_file(char *basename)
13390 const char *path = pathval();
13394 /* don't try this for absolute or relative paths */
13395 if (strchr(basename, '/'))
13398 while ((len = padvance(&path, basename)) >= 0) {
13399 fullname = stackblock();
13400 if ((!pathopt || *pathopt == 'f')
13401 && !stat(fullname, &statb) && S_ISREG(statb.st_mode)
13403 /* This will be freed by the caller. */
13404 return stalloc(len);
13407 /* not found in PATH */
13409 #if ENABLE_ASH_BASH_SOURCE_CURDIR
13412 ash_msg_and_raise_error("%s: not found", basename);
13417 static int FAST_FUNC
13418 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
13420 /* "false; . empty_file; echo $?" should print 0, not 1: */
13424 char *args_need_save;
13425 volatile struct shparam saveparam;
13428 // struct strlist *sp;
13429 // for (sp = cmdenviron; sp; sp = sp->next)
13430 // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
13432 nextopt(nullstr); /* handle possible "--" */
13436 /* bash says: "bash: .: filename argument required" */
13437 return 2; /* bash compat */
13440 /* This aborts if file isn't found, which is POSIXly correct.
13441 * bash returns exitcode 1 instead.
13443 fullname = find_dot_file(argv[0]);
13445 args_need_save = argv[0];
13446 if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
13448 saveparam = shellparam;
13449 shellparam.malloced = 0;
13453 shellparam.nparam = argc;
13454 shellparam.p = argv;
13457 /* This aborts if file can't be opened, which is POSIXly correct.
13458 * bash returns exitcode 1 instead.
13460 setinputfile(fullname, INPUT_PUSH_FILE);
13461 commandname = fullname;
13462 status = cmdloop(0);
13465 if (args_need_save) {
13466 freeparam(&shellparam);
13467 shellparam = saveparam;
13473 static int FAST_FUNC
13474 exitcmd(int argc UNUSED_PARAM, char **argv)
13480 savestatus = number(argv[1]);
13482 raise_exception(EXEXIT);
13487 * Read a file containing shell functions.
13490 readcmdfile(char *name)
13492 setinputfile(name, INPUT_PUSH_FILE);
13498 /* ============ find_command inplementation */
13501 * Resolve a command name. If you change this routine, you may have to
13502 * change the shellexec routine as well.
13505 find_command(char *name, struct cmdentry *entry, int act, const char *path)
13507 struct tblentry *cmdp;
13514 struct builtincmd *bcmd;
13517 /* If name contains a slash, don't use PATH or hash table */
13518 if (strchr(name, '/') != NULL) {
13519 entry->u.index = -1;
13520 if (act & DO_ABS) {
13521 while (stat(name, &statb) < 0) {
13523 if (errno == EINTR)
13526 entry->cmdtype = CMDUNKNOWN;
13530 entry->cmdtype = CMDNORMAL;
13534 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
13536 updatetbl = (path == pathval());
13540 /* If name is in the table, check answer will be ok */
13541 cmdp = cmdlookup(name, 0);
13542 if (cmdp != NULL) {
13545 switch (cmdp->cmdtype) {
13551 bit = DO_ALTPATH | DO_REGBLTIN;
13557 bit = IS_BUILTIN_REGULAR(cmdp->param.cmd) ? 0 : DO_REGBLTIN;
13561 if (act & bit & DO_REGBLTIN)
13566 } else if (cmdp->rehash == 0)
13567 /* if not invalidated by cd, we're done */
13571 /* If %builtin not in path, check for builtin next */
13572 bcmd = find_builtin(name);
13574 if (IS_BUILTIN_REGULAR(bcmd))
13575 goto builtin_success;
13576 if (act & DO_ALTPATH)
13577 goto builtin_success;
13578 if (builtinloc <= 0)
13579 goto builtin_success;
13582 if (act & DO_REGBLTIN)
13585 #if ENABLE_FEATURE_SH_STANDALONE
13587 int applet_no = find_applet_by_name(name);
13588 if (applet_no >= 0) {
13589 entry->cmdtype = CMDNORMAL;
13590 entry->u.index = -2 - applet_no;
13596 /* We have to search path. */
13597 prev = -1; /* where to start */
13598 if (cmdp && cmdp->rehash) { /* doing a rehash */
13599 if (cmdp->cmdtype == CMDBUILTIN)
13602 prev = cmdp->param.index;
13608 while ((len = padvance(&path, name)) >= 0) {
13609 const char *lpathopt = pathopt;
13611 fullname = stackblock();
13614 if (*lpathopt == 'b') {
13616 goto builtin_success;
13618 } else if (!(act & DO_NOFUNC)) {
13619 /* handled below */
13621 /* ignore unimplemented options */
13625 /* if rehash, don't redo absolute path names */
13626 if (fullname[0] == '/' && idx <= prev) {
13629 TRACE(("searchexec \"%s\": no change\n", name));
13632 while (stat(fullname, &statb) < 0) {
13634 if (errno == EINTR)
13637 if (errno != ENOENT && errno != ENOTDIR)
13641 e = EACCES; /* if we fail, this will be the error */
13642 if (!S_ISREG(statb.st_mode))
13644 if (lpathopt) { /* this is a %func directory */
13646 /* NB: stalloc will return space pointed by fullname
13647 * (because we don't have any intervening allocations
13648 * between stunalloc above and this stalloc) */
13649 readcmdfile(fullname);
13650 cmdp = cmdlookup(name, 0);
13651 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
13652 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
13653 stunalloc(fullname);
13656 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
13658 entry->cmdtype = CMDNORMAL;
13659 entry->u.index = idx;
13663 cmdp = cmdlookup(name, 1);
13664 cmdp->cmdtype = CMDNORMAL;
13665 cmdp->param.index = idx;
13670 /* We failed. If there was an entry for this command, delete it */
13671 if (cmdp && updatetbl)
13672 delete_cmd_entry();
13673 if (act & DO_ERR) {
13674 #if ENABLE_ASH_BASH_NOT_FOUND_HOOK
13675 struct tblentry *hookp = cmdlookup("command_not_found_handle", 0);
13676 if (hookp && hookp->cmdtype == CMDFUNCTION) {
13678 argv[0] = (char*) "command_not_found_handle";
13681 evalfun(hookp->param.func, 2, argv, 0);
13682 entry->cmdtype = CMDUNKNOWN;
13686 ash_msg("%s: %s", name, errmsg(e, "not found"));
13689 entry->cmdtype = CMDUNKNOWN;
13694 entry->cmdtype = CMDBUILTIN;
13695 entry->u.cmd = bcmd;
13699 cmdp = cmdlookup(name, 1);
13700 cmdp->cmdtype = CMDBUILTIN;
13701 cmdp->param.cmd = bcmd;
13705 entry->cmdtype = cmdp->cmdtype;
13706 entry->u = cmdp->param;
13711 * The trap builtin.
13713 static int FAST_FUNC
13714 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13718 int signo, exitcode;
13723 for (signo = 0; signo < NSIG; signo++) {
13724 char *tr = trap_ptr[signo];
13726 /* note: bash adds "SIG", but only if invoked
13727 * as "bash". If called as "sh", or if set -o posix,
13728 * then it prints short signal names.
13729 * We are printing short names: */
13730 out1fmt("trap -- %s %s\n",
13732 get_signame(signo));
13733 /* trap_ptr != trap only if we are in special-cased `trap` code.
13734 * In this case, we will exit very soon, no need to free(). */
13735 /* if (trap_ptr != trap && tp[0]) */
13740 if (trap_ptr != trap) {
13748 /* Why the second check?
13749 * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
13750 * In this case, NUM is signal no, not an action.
13753 if (ap[1] && !is_number(ap[0]))
13758 signo = get_signum(*ap);
13760 /* Mimic bash message exactly */
13761 ash_msg("%s: invalid signal specification", *ap);
13767 if (LONE_DASH(action))
13770 if (action[0]) /* not NULL and not "" and not "-" */
13771 may_have_traps = 1;
13772 action = ckstrdup(action);
13776 trap[signo] = action;
13787 /* ============ Builtins */
13789 #if ENABLE_ASH_HELP
13790 static int FAST_FUNC
13791 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13797 "Built-in commands:\n"
13798 "------------------\n");
13799 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
13800 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
13801 builtintab[i].name + 1);
13807 # if ENABLE_FEATURE_SH_STANDALONE
13809 const char *a = applet_names;
13811 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
13816 while (*a++ != '\0')
13821 newline_and_flush(stdout);
13822 return EXIT_SUCCESS;
13827 static int FAST_FUNC
13828 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13830 if (line_input_state)
13831 show_history(line_input_state);
13832 return EXIT_SUCCESS;
13837 * The export and readonly commands.
13839 static int FAST_FUNC
13840 exportcmd(int argc UNUSED_PARAM, char **argv)
13850 /* "readonly" in bash accepts, but ignores -n.
13851 * We do the same: it saves a conditional in nextopt's param.
13854 while ((opt = nextopt("np")) != '\0') {
13856 flag_off = VEXPORT;
13859 if (argv[0][0] == 'r') {
13861 flag_off = 0; /* readonly ignores -n */
13863 flag_off = ~flag_off;
13865 /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
13871 p = strchr(name, '=');
13875 vp = *findvar(hashvar(name), name);
13877 vp->flags = ((vp->flags | flag) & flag_off);
13881 setvar(name, p, (flag & flag_off));
13882 } while ((name = *++aptr) != NULL);
13887 /* No arguments. Show the list of exported or readonly vars.
13890 showvars(argv[0], flag, 0);
13895 * Delete a function if it exists.
13898 unsetfunc(const char *name)
13900 struct tblentry *cmdp;
13902 cmdp = cmdlookup(name, 0);
13903 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
13904 delete_cmd_entry();
13908 * The unset builtin command. We unset the function before we unset the
13909 * variable to allow a function to be unset when there is a readonly variable
13910 * with the same name.
13912 static int FAST_FUNC
13913 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13919 while ((i = nextopt("vf")) != 0) {
13923 for (ap = argptr; *ap; ap++) {
13934 static const unsigned char timescmd_str[] ALIGN1 = {
13935 ' ', offsetof(struct tms, tms_utime),
13936 '\n', offsetof(struct tms, tms_stime),
13937 ' ', offsetof(struct tms, tms_cutime),
13938 '\n', offsetof(struct tms, tms_cstime),
13941 static int FAST_FUNC
13942 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13945 const unsigned char *p;
13948 clk_tck = bb_clk_tck();
13953 unsigned sec, frac;
13955 t = *(clock_t *)(((char *) &buf) + p[1]);
13957 frac = t % clk_tck;
13958 out1fmt("%um%u.%03us%c",
13959 sec / 60, sec % 60,
13960 (frac * 1000) / clk_tck,
13968 #if ENABLE_FEATURE_SH_MATH
13970 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13971 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13973 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13975 static int FAST_FUNC
13976 letcmd(int argc UNUSED_PARAM, char **argv)
13982 ash_msg_and_raise_error("expression expected");
13984 i = ash_arith(*argv);
13992 * The read builtin. Options:
13993 * -r Do not interpret '\' specially
13994 * -s Turn off echo (tty only)
13995 * -n NCHARS Read NCHARS max
13996 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13997 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13998 * -u FD Read from given FD instead of fd 0
13999 * -d DELIM End on DELIM char, not newline
14000 * This uses unbuffered input, which may be avoidable in some cases.
14001 * TODO: bash also has:
14002 * -a ARRAY Read into array[0],[1],etc
14003 * -e Use line editing (tty only)
14005 static int FAST_FUNC
14006 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
14008 struct builtin_read_params params;
14012 memset(¶ms, 0, sizeof(params));
14014 while ((i = nextopt("p:u:rt:n:sd:")) != '\0') {
14017 params.opt_p = optionarg;
14020 params.opt_n = optionarg;
14023 params.read_flags |= BUILTIN_READ_SILENT;
14026 params.opt_t = optionarg;
14029 params.read_flags |= BUILTIN_READ_RAW;
14032 params.opt_u = optionarg;
14036 params.opt_d = optionarg;
14044 params.argv = argptr;
14045 params.setvar = setvar0;
14046 params.ifs = bltinlookup("IFS"); /* can be NULL */
14048 /* "read -s" needs to save/restore termios, can't allow ^C
14049 * to jump out of it.
14053 r = shell_builtin_read(¶ms);
14056 if ((uintptr_t)r == 1 && errno == EINTR) {
14057 /* To get SIGCHLD: sleep 1 & read x; echo $x
14058 * Correct behavior is to not exit "read"
14060 if (pending_sig == 0)
14064 if ((uintptr_t)r > 1)
14065 ash_msg_and_raise_error(r);
14067 return (uintptr_t)r;
14070 static int FAST_FUNC
14071 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
14073 static const char permuser[3] ALIGN1 = "ogu";
14076 int symbolic_mode = 0;
14078 while (nextopt("S") != '\0') {
14087 if (*argptr == NULL) {
14088 if (symbolic_mode) {
14089 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
14096 *p++ = permuser[i];
14098 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
14099 if (!(mask & 0400)) *p++ = 'r';
14100 if (!(mask & 0200)) *p++ = 'w';
14101 if (!(mask & 0100)) *p++ = 'x';
14109 out1fmt("%04o\n", mask);
14112 char *modestr = *argptr;
14113 /* numeric umasks are taken as-is */
14114 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
14115 if (!isdigit(modestr[0]))
14117 mask = bb_parse_mode(modestr, mask);
14118 if ((unsigned)mask > 0777) {
14119 ash_msg_and_raise_error("illegal mode: %s", modestr);
14121 if (!isdigit(modestr[0]))
14128 static int FAST_FUNC
14129 ulimitcmd(int argc UNUSED_PARAM, char **argv)
14131 return shell_builtin_ulimit(argv);
14134 /* ============ main() and helpers */
14137 * Called to exit the shell.
14145 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
14146 if (line_input_state)
14147 save_history(line_input_state);
14149 savestatus = exitstatus;
14150 TRACE(("pid %d, exitshell(%d)\n", getpid(), savestatus));
14151 if (setjmp(loc.loc))
14153 exception_handler = &loc;
14159 /*free(p); - we'll exit soon */
14162 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
14163 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
14166 flush_stdout_stderr();
14171 /* Don't inline: conserve stack of caller from having our locals too */
14172 static NOINLINE void
14175 /* we will never free this */
14176 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
14179 sigmode[SIGCHLD - 1] = S_DFL; /* ensure we install handler even if it is SIG_IGNed */
14180 setsignal(SIGCHLD);
14187 for (envp = environ; envp && *envp; envp++) {
14189 * p = endofname(*envp);
14190 * if (p != *envp && *p == '=') {
14191 * here to weed out badly-named variables, but this breaks
14192 * scenarios where people do want them passed to children:
14194 * os.environ["test-test"]="test"
14195 * if os.fork() == 0:
14196 * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
14197 * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ]) # breaks this
14199 if (strchr(*envp, '=')) {
14200 setvareq(*envp, VEXPORT|VTEXTFIXED);
14204 setvareq((char*)defifsvar, VTEXTFIXED);
14205 setvareq((char*)defoptindvar, VTEXTFIXED);
14207 setvar0("PPID", utoa(getppid()));
14209 p = lookupvar("SHLVL");
14210 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
14212 #if BASH_HOSTNAME_VAR
14213 if (!lookupvar("HOSTNAME")) {
14214 struct utsname uts;
14216 setvar0("HOSTNAME", uts.nodename);
14219 p = lookupvar("PWD");
14221 struct stat st1, st2;
14222 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
14223 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
14233 //usage:#define ash_trivial_usage
14234 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
14235 //usage:#define ash_full_usage "\n\n"
14236 //usage: "Unix shell interpreter"
14239 * Process the shell command line arguments.
14242 procargs(char **argv)
14245 const char *xminusc;
14250 login_sh = xargv[0] && xargv[0][0] == '-';
14251 #if NUM_SCRIPTS > 0
14256 /* if (xargv[0]) - mmm, this is always true! */
14259 for (i = 0; i < NOPTS; i++)
14261 if (options(&login_sh)) {
14262 /* it already printed err message */
14263 raise_exception(EXERROR);
14267 if (*xargv == NULL) {
14269 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
14272 if (iflag == 2 /* no explicit -i given */
14273 && sflag == 1 /* -s given (or implied) */
14274 && !minusc /* bash compat: ash -sc 'echo $-' is not interactive (dash is) */
14275 && isatty(0) && isatty(1) /* we are on tty */
14281 for (i = 0; i < NOPTS; i++)
14282 if (optlist[i] == 2)
14287 /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
14292 } else if (!sflag) {
14293 setinputfile(*xargv, 0);
14296 commandname = arg0;
14299 shellparam.p = xargv;
14300 #if ENABLE_ASH_GETOPTS
14301 shellparam.optind = 1;
14302 shellparam.optoff = -1;
14304 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
14306 shellparam.nparam++;
14315 * Read /etc/profile, ~/.profile, $ENV.
14318 read_profile(const char *name)
14320 name = expandstr(name, DQSYNTAX);
14321 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
14328 * This routine is called when an error or an interrupt occurs in an
14329 * interactive shell and control is returned to the main command loop
14330 * but prior to exitshell.
14338 if (savestatus >= 0) {
14339 exitstatus = savestatus;
14343 /* from expand.c: */
14346 /* from redir.c: */
14351 * This routine is called when an error or an interrupt occurs in an
14352 * interactive shell and control is returned to the main command loop.
14353 * (In dash, this function is auto-generated by build machinery).
14358 /* from input.c: */
14359 g_parsefile->left_in_buffer = 0;
14360 g_parsefile->left_in_line = 0; /* clear input buffer */
14364 unwindlocalvars(NULL);
14368 static short profile_buf[16384];
14369 extern int etext();
14373 * Main routine. We initialize things, parse the arguments, execute
14374 * profiles if we're a login shell, and then call cmdloop to execute
14375 * commands. The setjmp call sets up the location to jump to when an
14376 * exception occurs. When an exception occurs the variable "state"
14377 * is used to figure out how far we had gotten.
14379 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
14380 #if NUM_SCRIPTS > 0
14381 int ash_main(int argc, char **argv)
14383 int ash_main(int argc UNUSED_PARAM, char **argv)
14385 /* note: 'argc' is used only if embedded scripts are enabled */
14387 volatile smallint state;
14388 struct jmploc jmploc;
14389 struct stackmark smark;
14392 /* Initialize global data */
14396 #if ENABLE_ASH_ALIAS
14402 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
14406 if (setjmp(jmploc.loc)) {
14412 e = exception_type;
14414 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
14421 newline_and_flush(stderr);
14424 popstackmark(&smark);
14425 FORCE_INT_ON; /* enable interrupts */
14434 exception_handler = &jmploc;
14435 rootpid = getpid();
14438 setstackmark(&smark);
14440 #if NUM_SCRIPTS > 0
14442 /* Non-NULL minusc tells procargs that an embedded script is being run */
14443 minusc = get_script_content(-argc - 1);
14445 login_sh = procargs(argv);
14447 TRACE(("Shell args: "));
14448 trace_puts_args(argv);
14455 read_profile("/etc/profile");
14458 hp = lookupvar("HOME");
14460 read_profile("$HOME/.profile");
14466 getuid() == geteuid() && getgid() == getegid() &&
14470 const char *shinit = lookupvar("ENV");
14471 if (shinit != NULL && *shinit != '\0')
14472 read_profile(shinit);
14474 popstackmark(&smark);
14478 /* evalstring pushes parsefile stack.
14479 * Ensure we don't falsely claim that 0 (stdin)
14480 * is one of stacked source fds.
14481 * Testcase: ash -c 'exec 1>&0' must not complain. */
14483 // if (!sflag) g_parsefile->pf_fd = -1;
14484 // ^^ not necessary since now we special-case fd 0
14485 // in save_fd_on_redirect()
14487 // dash: evalstring(minusc, sflag ? 0 : EV_EXIT);
14489 // ash -sc 'echo $-'
14490 // continue reading input from stdin after running 'echo'.
14491 // bash does not do this: it prints "hBcs" and exits.
14492 evalstring(minusc, EV_EXIT);
14495 if (sflag || minusc == NULL) {
14496 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
14498 const char *hp = lookupvar("HISTFILE");
14500 hp = lookupvar("HOME");
14503 hp = concat_path_file(hp, ".ash_history");
14504 setvar0("HISTFILE", hp);
14507 hp = lookupvar("HISTFILE");
14511 line_input_state->hist_file = hp;
14512 # if ENABLE_FEATURE_SH_HISTFILESIZE
14513 hp = lookupvar("HISTFILESIZE");
14514 line_input_state->max_history = size_from_HISTFILESIZE(hp);
14518 state4: /* XXX ??? - why isn't this before the "if" statement */
14520 /* Interactive bash re-enables SIGHUP which is SIG_IGNed on entry.
14522 * trap '' hup; bash; echo RET # type "kill -hup $$", see SIGHUP having effect
14523 * trap '' hup; bash -c 'kill -hup $$; echo ALIVE' # here SIGHUP is SIG_IGNed
14525 signal(SIGHUP, SIG_DFL);
14534 extern void _mcleanup(void);
14538 TRACE(("End of main reached\n"));
14545 * Copyright (c) 1989, 1991, 1993, 1994
14546 * The Regents of the University of California. All rights reserved.
14548 * This code is derived from software contributed to Berkeley by
14549 * Kenneth Almquist.
14551 * Redistribution and use in source and binary forms, with or without
14552 * modification, are permitted provided that the following conditions
14554 * 1. Redistributions of source code must retain the above copyright
14555 * notice, this list of conditions and the following disclaimer.
14556 * 2. Redistributions in binary form must reproduce the above copyright
14557 * notice, this list of conditions and the following disclaimer in the
14558 * documentation and/or other materials provided with the distribution.
14559 * 3. Neither the name of the University nor the names of its contributors
14560 * may be used to endorse or promote products derived from this software
14561 * without specific prior written permission.
14563 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
14564 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
14565 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
14566 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
14567 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
14568 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
14569 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
14570 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
14571 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
14572 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF