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 * Called from CHECKSTRSPACE.
1747 makestrspace(size_t newlen, char *p)
1749 size_t len = p - g_stacknxt;
1755 size = stackblocksize();
1757 if (nleft >= newlen)
1761 return (char *)stackblock() + len;
1765 stack_nputstr(const char *s, size_t n, char *p)
1767 p = makestrspace(n, p);
1768 p = (char *)mempcpy(p, s, n);
1773 stack_putstr(const char *s, char *p)
1775 return stack_nputstr(s, strlen(s), p);
1779 _STPUTC(int c, char *p)
1787 #define STARTSTACKSTR(p) ((p) = stackblock())
1788 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1789 #define CHECKSTRSPACE(n, p) do { \
1792 size_t m = sstrend - q; \
1794 (p) = makestrspace(l, q); \
1796 #define USTPUTC(c, p) (*(p)++ = (c))
1797 #define STACKSTRNUL(p) do { \
1798 if ((p) == sstrend) \
1799 (p) = growstackstr(); \
1802 #define STUNPUTC(p) (--(p))
1803 #define STTOPC(p) ((p)[-1])
1804 #define STADJUST(amount, p) ((p) += (amount))
1806 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1807 #define ungrabstackstr(s, p) stunalloc(s)
1808 #define stackstrend() ((void *)sstrend)
1811 /* ============ String helpers */
1814 * prefix -- see if pfx is a prefix of string.
1817 prefix(const char *string, const char *pfx)
1820 if (*pfx++ != *string++)
1823 return (char *) string;
1827 * Check for a valid number. This should be elsewhere.
1830 is_number(const char *p)
1835 } while (*++p != '\0');
1840 * Convert a string of digits to an integer, printing an error message on
1844 number(const char *s)
1847 ash_msg_and_raise_error(msg_illnum, s);
1852 * Produce a single quoted string suitable as input to the shell.
1853 * The return string is allocated on the stack.
1856 single_quote(const char *s)
1866 len = strchrnul(s, '\'') - s;
1868 q = p = makestrspace(len + 3, p);
1871 q = (char *)mempcpy(q, s, len);
1880 do len++; while (*++s == '\'');
1882 q = p = makestrspace(len + 3, p);
1885 q = (char *)mempcpy(q, s - len, len);
1893 return stackblock();
1897 * Produce a possibly single quoted string suitable as input to the shell.
1898 * If quoting was done, the return string is allocated on the stack,
1899 * otherwise a pointer to the original string is returned.
1902 maybe_single_quote(const char *s)
1907 /* Assuming ACSII */
1908 /* quote ctrl_chars space !"#$%&'()* */
1912 if (*p >= ';' && *p <= '?')
1921 /* quote {|}~ DEL and high bytes */
1924 /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
1925 /* TODO: maybe avoid quoting % */
1931 return single_quote(s);
1935 /* ============ nextopt */
1937 static char **argptr; /* argument list for builtin commands */
1938 static char *optionarg; /* set by nextopt (like getopt) */
1939 static char *optptr; /* used by nextopt */
1942 * XXX - should get rid of. Have all builtins use getopt(3).
1943 * The library getopt must have the BSD extension static variable
1944 * "optreset", otherwise it can't be used within the shell safely.
1946 * Standard option processing (a la getopt) for builtin routines.
1947 * The only argument that is passed to nextopt is the option string;
1948 * the other arguments are unnecessary. It returns the character,
1949 * or '\0' on end of input.
1952 nextopt(const char *optstring)
1959 if (p == NULL || *p == '\0') {
1960 /* We ate entire "-param", take next one */
1966 if (*++p == '\0') /* just "-" ? */
1969 if (LONE_DASH(p)) /* "--" ? */
1971 /* p => next "-param" */
1973 /* p => some option char in the middle of a "-param" */
1975 for (q = optstring; *q != c;) {
1977 ash_msg_and_raise_error("illegal option -%c", c);
1985 ash_msg_and_raise_error("no arg for -%c option", c);
1995 /* ============ Shell variables */
1998 int nparam; /* # of positional parameters (without $0) */
1999 #if ENABLE_ASH_GETOPTS
2000 int optind; /* next parameter to be processed by getopts */
2001 int optoff; /* used by getopts */
2003 unsigned char malloced; /* if parameter list dynamically allocated */
2004 char **p; /* parameter list */
2008 * Free the list of positional parameters.
2011 freeparam(volatile struct shparam *param)
2013 if (param->malloced) {
2015 ap = ap1 = param->p;
2022 #if ENABLE_ASH_GETOPTS
2023 static void FAST_FUNC getoptsreset(const char *value);
2027 struct var *next; /* next entry in hash list */
2028 int flags; /* flags are defined above */
2029 const char *var_text; /* name=value */
2030 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
2031 /* the variable gets set/unset */
2035 struct localvar *next; /* next local variable in list */
2036 struct var *vp; /* the variable that was made local */
2037 int flags; /* saved flags */
2038 const char *text; /* saved text */
2042 #define VEXPORT 0x01 /* variable is exported */
2043 #define VREADONLY 0x02 /* variable cannot be modified */
2044 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
2045 #define VTEXTFIXED 0x08 /* text is statically allocated */
2046 #define VSTACK 0x10 /* text is allocated on the stack */
2047 #define VUNSET 0x20 /* the variable is not set */
2048 #define VNOFUNC 0x40 /* don't call the callback function */
2049 #define VNOSET 0x80 /* do not set variable - just readonly test */
2050 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
2051 #if ENABLE_ASH_RANDOM_SUPPORT
2052 # define VDYNAMIC 0x200 /* dynamic variable */
2058 /* Need to be before varinit_data[] */
2059 #if ENABLE_LOCALE_SUPPORT
2060 static void FAST_FUNC
2061 change_lc_all(const char *value)
2063 if (value && *value != '\0')
2064 setlocale(LC_ALL, value);
2066 static void FAST_FUNC
2067 change_lc_ctype(const char *value)
2069 if (value && *value != '\0')
2070 setlocale(LC_CTYPE, value);
2074 static void chkmail(void);
2075 static void changemail(const char *var_value) FAST_FUNC;
2077 # define chkmail() ((void)0)
2079 static void changepath(const char *) FAST_FUNC;
2080 #if ENABLE_ASH_RANDOM_SUPPORT
2081 static void change_random(const char *) FAST_FUNC;
2084 static void change_seconds(const char *) FAST_FUNC;
2085 static void change_realtime(const char *) FAST_FUNC;
2088 static const struct {
2090 const char *var_text;
2091 void (*var_func)(const char *) FAST_FUNC;
2092 } varinit_data[] = {
2094 * Note: VEXPORT would not work correctly here for NOFORK applets:
2095 * some environment strings may be constant.
2097 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
2099 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
2100 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
2102 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
2103 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
2104 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
2105 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
2106 #if ENABLE_ASH_GETOPTS
2107 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
2109 { VSTRFIXED|VTEXTFIXED , NULL /* inited to linenovar */, NULL },
2110 #if ENABLE_ASH_RANDOM_SUPPORT
2111 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
2114 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "EPOCHSECONDS", change_seconds },
2115 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "EPOCHREALTIME", change_realtime },
2117 #if ENABLE_LOCALE_SUPPORT
2118 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
2119 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
2121 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
2122 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
2128 struct globals_var {
2129 struct shparam shellparam; /* $@ current positional parameters */
2130 struct redirtab *redirlist;
2131 int preverrout_fd; /* stderr fd: usually 2, unless redirect moved it */
2132 struct var *vartab[VTABSIZE];
2133 struct var varinit[ARRAY_SIZE(varinit_data)];
2135 char linenovar[sizeof("LINENO=") + sizeof(int)*3];
2137 extern struct globals_var *BB_GLOBAL_CONST ash_ptr_to_globals_var;
2138 #define G_var (*ash_ptr_to_globals_var)
2139 #define shellparam (G_var.shellparam )
2140 //#define redirlist (G_var.redirlist )
2141 #define preverrout_fd (G_var.preverrout_fd)
2142 #define vartab (G_var.vartab )
2143 #define varinit (G_var.varinit )
2144 #define lineno (G_var.lineno )
2145 #define linenovar (G_var.linenovar )
2146 #define vifs varinit[0]
2148 # define vmail varinit[1]
2149 # define vmpath varinit[2]
2151 #define VAR_OFFSET1 (ENABLE_ASH_MAIL*2)
2152 #define vpath varinit[VAR_OFFSET1 + 1]
2153 #define vps1 varinit[VAR_OFFSET1 + 2]
2154 #define vps2 varinit[VAR_OFFSET1 + 3]
2155 #define vps4 varinit[VAR_OFFSET1 + 4]
2156 #if ENABLE_ASH_GETOPTS
2157 # define voptind varinit[VAR_OFFSET1 + 5]
2159 #define VAR_OFFSET2 (VAR_OFFSET1 + ENABLE_ASH_GETOPTS)
2160 #define vlineno varinit[VAR_OFFSET2 + 5]
2161 #if ENABLE_ASH_RANDOM_SUPPORT
2162 # define vrandom varinit[VAR_OFFSET2 + 6]
2164 #define VAR_OFFSET3 (VAR_OFFSET2 + ENABLE_ASH_RANDOM_SUPPORT)
2166 # define vepochs varinit[VAR_OFFSET3 + 6]
2167 # define vepochr varinit[VAR_OFFSET3 + 7]
2169 #define INIT_G_var() do { \
2171 (*(struct globals_var**)not_const_pp(&ash_ptr_to_globals_var)) = xzalloc(sizeof(G_var)); \
2173 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
2174 varinit[i].flags = varinit_data[i].flags; \
2175 varinit[i].var_text = varinit_data[i].var_text; \
2176 varinit[i].var_func = varinit_data[i].var_func; \
2178 strcpy(linenovar, "LINENO="); \
2179 vlineno.var_text = linenovar; \
2183 * The following macros access the values of the above variables.
2184 * They have to skip over the name. They return the null string
2185 * for unset variables.
2187 #define ifsval() (vifs.var_text + 4)
2188 #define ifsset() ((vifs.flags & VUNSET) == 0)
2190 # define mailval() (vmail.var_text + 5)
2191 # define mpathval() (vmpath.var_text + 9)
2192 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2194 #define pathval() (vpath.var_text + 5)
2195 #define ps1val() (vps1.var_text + 4)
2196 #define ps2val() (vps2.var_text + 4)
2197 #define ps4val() (vps4.var_text + 4)
2198 #if ENABLE_ASH_GETOPTS
2199 # define optindval() (voptind.var_text + 7)
2202 #if ENABLE_ASH_GETOPTS
2203 static void FAST_FUNC
2204 getoptsreset(const char *value)
2206 shellparam.optind = 1;
2207 if (is_number(value))
2208 shellparam.optind = number(value) ?: 1;
2209 shellparam.optoff = -1;
2214 * Compares two strings up to the first = or '\0'. The first
2215 * string must be terminated by '='; the second may be terminated by
2216 * either '=' or '\0'.
2219 varcmp(const char *p, const char *q)
2223 while ((c = *p) == (d = *q)) {
2224 if (c == '\0' || c == '=')
2238 * Find the appropriate entry in the hash table from the name.
2240 static struct var **
2241 hashvar(const char *p)
2245 hashval = ((unsigned char) *p) << 4;
2246 while (*p && *p != '=')
2247 hashval += (unsigned char) *p++;
2248 return &vartab[hashval % VTABSIZE];
2252 vpcmp(const void *a, const void *b)
2254 return varcmp(*(const char **)a, *(const char **)b);
2258 * This routine initializes the builtin variables.
2268 * PS1 depends on uid
2270 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2271 vps1.var_text = "PS1=\\w \\$ ";
2274 vps1.var_text = "PS1=# ";
2277 end = vp + ARRAY_SIZE(varinit);
2279 vpp = hashvar(vp->var_text);
2282 } while (++vp < end);
2285 static struct var **
2286 findvar(struct var **vpp, const char *name)
2288 for (; *vpp; vpp = &(*vpp)->next) {
2289 if (varcmp((*vpp)->var_text, name) == 0) {
2297 * Find the value of a variable. Returns NULL if not set.
2299 static const char* FAST_FUNC
2300 lookupvar(const char *name)
2304 v = *findvar(hashvar(name), name);
2306 #if ENABLE_ASH_RANDOM_SUPPORT || BASH_EPOCH_VARS
2308 * Dynamic variables are implemented roughly the same way they are
2309 * in bash. Namely, they're "special" so long as they aren't unset.
2310 * As soon as they're unset, they're no longer dynamic, and dynamic
2311 * lookup will no longer happen at that point. -- PFM.
2313 if (v->flags & VDYNAMIC)
2316 if (!(v->flags & VUNSET)) {
2317 if (v == &vlineno && v->var_text == linenovar) {
2318 fmtstr(linenovar+7, sizeof(linenovar)-7, "%d", lineno);
2320 return var_end(v->var_text);
2326 #if ENABLE_UNICODE_SUPPORT
2328 reinit_unicode_for_ash(void)
2330 /* Unicode support should be activated even if LANG is set
2331 * _during_ shell execution, not only if it was set when
2332 * shell was started. Therefore, re-check LANG every time:
2334 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2335 || ENABLE_UNICODE_USING_LOCALE
2337 const char *s = lookupvar("LC_ALL");
2338 if (!s) s = lookupvar("LC_CTYPE");
2339 if (!s) s = lookupvar("LANG");
2344 # define reinit_unicode_for_ash() ((void)0)
2348 * Search the environment of a builtin command.
2350 static ALWAYS_INLINE const char *
2351 bltinlookup(const char *name)
2353 return lookupvar(name);
2357 * Same as setvar except that the variable and value are passed in
2358 * the first argument as name=value. Since the first argument will
2359 * be actually stored in the table, it should not be a string that
2361 * Called with interrupts off.
2364 setvareq(char *s, int flags)
2366 struct var *vp, **vpp;
2369 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2370 vpp = findvar(vpp, s);
2373 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2376 if (flags & VNOSAVE)
2380 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2386 if (vp->var_func && !(flags & VNOFUNC))
2387 vp->var_func(var_end(s));
2389 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2390 free((char*)vp->var_text);
2392 if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
2396 if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
2401 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2402 #if ENABLE_ASH_RANDOM_SUPPORT || BASH_EPOCH_VARS
2407 /* variable s is not found */
2410 if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
2412 vp = ckzalloc(sizeof(*vp));
2414 /*vp->func = NULL; - ckzalloc did it */
2417 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2427 * Set the value of a variable. The flags argument is ored with the
2428 * flags of the variable. If val is NULL, the variable is unset.
2431 setvar(const char *name, const char *val, int flags)
2440 q = endofname(name);
2441 p = strchrnul(q, '=');
2443 if (!namelen || p != q)
2444 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2449 vallen = strlen(val);
2453 nameeq = ckzalloc(namelen + vallen + 2);
2454 p = mempcpy(nameeq, name, namelen);
2457 memcpy(p, val, vallen);
2459 vp = setvareq(nameeq, flags | VNOSAVE);
2465 static void FAST_FUNC
2466 setvar0(const char *name, const char *val)
2468 setvar(name, val, 0);
2472 * Unset the specified variable.
2475 unsetvar(const char *s)
2481 * Process a linked list of variable assignments.
2484 listsetvar(struct strlist *list_set_var, int flags)
2486 struct strlist *lp = list_set_var;
2492 setvareq(lp->text, flags);
2499 * Generate a list of variables satisfying the given conditions.
2501 #if !ENABLE_FEATURE_SH_NOFORK
2502 # define listvars(on, off, lp, end) listvars(on, off, end)
2505 listvars(int on, int off, struct strlist *lp, char ***end)
2516 for (vp = *vpp; vp; vp = vp->next) {
2517 if ((vp->flags & mask) == on) {
2518 #if ENABLE_FEATURE_SH_NOFORK
2519 /* If variable with the same name is both
2520 * exported and temporarily set for a command:
2523 * then "ZVAR=6" will be both in vartab and
2524 * lp lists. Do not pass it twice to printenv.
2526 struct strlist *lp1 = lp;
2528 if (strcmp(lp1->text, vp->var_text) == 0)
2533 if (ep == stackstrend())
2534 ep = growstackstr();
2535 *ep++ = (char*)vp->var_text;
2536 #if ENABLE_FEATURE_SH_NOFORK
2541 } while (++vpp < vartab + VTABSIZE);
2543 #if ENABLE_FEATURE_SH_NOFORK
2545 if (ep == stackstrend())
2546 ep = growstackstr();
2552 if (ep == stackstrend())
2553 ep = growstackstr();
2557 return grabstackstr(ep);
2561 /* ============ Path search helper
2563 * The variable path (passed by reference) should be set to the start
2564 * of the path before the first call; path_advance will update
2565 * this value as it proceeds. Successive calls to path_advance will return
2566 * the possible path expansions in sequence. If an option (indicated by
2567 * a percent sign) appears in the path entry then the global variable
2568 * pathopt will be set to point to it; otherwise pathopt will be set to
2571 static const char *pathopt; /* set by path_advance */
2574 path_advance(const char **path, const char *name)
2584 for (p = start; *p && *p != ':' && *p != '%'; p++)
2586 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2587 while (stackblocksize() < len)
2591 q = mempcpy(q, start, p - start);
2598 while (*p && *p != ':')
2605 return stalloc(len);
2609 /* ============ Prompt */
2611 static smallint doprompt; /* if set, prompt the user */
2612 static smallint needprompt; /* true if interactive and at start of line */
2614 #if ENABLE_FEATURE_EDITING
2615 static line_input_t *line_input_state;
2616 static const char *cmdedit_prompt;
2618 putprompt(const char *s)
2620 if (ENABLE_ASH_EXPAND_PRMT) {
2621 free((char*)cmdedit_prompt);
2622 cmdedit_prompt = ckstrdup(s);
2629 putprompt(const char *s)
2635 /* expandstr() needs parsing machinery, so it is far away ahead... */
2636 static const char *expandstr(const char *ps, int syntax_type);
2637 /* Values for syntax param */
2638 #define BASESYNTAX 0 /* not in quotes */
2639 #define DQSYNTAX 1 /* in double quotes */
2640 #define SQSYNTAX 2 /* in single quotes */
2641 #define ARISYNTAX 3 /* in arithmetic */
2642 #if ENABLE_ASH_EXPAND_PRMT
2643 # define PSSYNTAX 4 /* prompt. never passed to SIT() */
2645 /* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
2648 * called by editline -- any expansions to the prompt should be added here.
2651 setprompt_if(smallint do_set, int whichprompt)
2654 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2661 switch (whichprompt) {
2671 #if ENABLE_ASH_EXPAND_PRMT
2672 pushstackmark(&smark, stackblocksize());
2673 putprompt(expandstr(prompt, PSSYNTAX));
2674 popstackmark(&smark);
2681 /* ============ The cd and pwd commands */
2683 #define CD_PHYSICAL 1
2693 while ((i = nextopt("LP")) != '\0') {
2695 flags ^= CD_PHYSICAL;
2704 * Update curdir (the name of the current directory) in response to a
2708 updatepwd(const char *dir)
2715 cdcomppath = sstrdup(dir);
2718 if (curdir == nullstr)
2720 new = stack_putstr(curdir, new);
2722 new = makestrspace(strlen(dir) + 2, new);
2723 lim = (char *)stackblock() + 1;
2727 if (new > lim && *lim == '/')
2732 if (dir[1] == '/' && dir[2] != '/') {
2738 p = strtok(cdcomppath, "/");
2742 if (p[1] == '.' && p[2] == '\0') {
2754 new = stack_putstr(p, new);
2757 p = strtok(NULL, "/");
2762 return stackblock();
2766 * Find out what the current directory is. If we already know the current
2767 * directory, this routine returns immediately.
2772 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2773 return dir ? dir : nullstr;
2777 setpwd(const char *val, int setold)
2781 oldcur = dir = curdir;
2784 setvar("OLDPWD", oldcur, VEXPORT);
2787 if (physdir != nullstr) {
2788 if (physdir != oldcur)
2792 if (oldcur == val || !val) {
2798 dir = ckstrdup(val);
2799 if (oldcur != dir && oldcur != nullstr) {
2804 setvar("PWD", dir, VEXPORT);
2807 static void hashcd(void);
2810 * Actually do the chdir. We also call hashcd to let other routines
2811 * know that the current directory has changed.
2814 docd(const char *dest, int flags)
2816 const char *dir = NULL;
2819 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2822 if (!(flags & CD_PHYSICAL)) {
2823 dir = updatepwd(dest);
2837 static int FAST_FUNC
2838 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2850 dest = bltinlookup("HOME");
2851 else if (LONE_DASH(dest)) {
2852 dest = bltinlookup("OLDPWD");
2874 path = bltinlookup("CDPATH");
2877 p = path_advance(&path, dest);
2878 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2882 if (!docd(p, flags))
2893 ash_msg_and_raise_perror("can't cd to %s", dest);
2896 if (flags & CD_PRINT)
2897 out1fmt("%s\n", curdir);
2901 static int FAST_FUNC
2902 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2905 const char *dir = curdir;
2909 if (physdir == nullstr)
2913 out1fmt("%s\n", dir);
2918 /* ============ ... */
2921 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2923 /* Syntax classes */
2924 #define CWORD 0 /* character is nothing special */
2925 #define CNL 1 /* newline character */
2926 #define CBACK 2 /* a backslash character */
2927 #define CSQUOTE 3 /* single quote */
2928 #define CDQUOTE 4 /* double quote */
2929 #define CENDQUOTE 5 /* a terminating quote */
2930 #define CBQUOTE 6 /* backwards single quote */
2931 #define CVAR 7 /* a dollar sign */
2932 #define CENDVAR 8 /* a '}' character */
2933 #define CLP 9 /* a left paren in arithmetic */
2934 #define CRP 10 /* a right paren in arithmetic */
2935 #define CENDFILE 11 /* end of file */
2936 #define CCTL 12 /* like CWORD, except it must be escaped */
2937 #define CSPCL 13 /* these terminate a word */
2938 #define CIGN 14 /* character should be ignored */
2941 #if ENABLE_ASH_ALIAS
2945 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2947 #if ENABLE_FEATURE_SH_MATH
2948 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2950 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2952 static const uint16_t S_I_T[] ALIGN2 = {
2953 #if ENABLE_ASH_ALIAS
2954 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2956 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2957 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2958 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2959 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2960 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2961 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2962 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2963 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2964 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2965 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2966 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2967 #if !USE_SIT_FUNCTION
2968 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2969 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2970 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2974 /* Constants below must match table above */
2976 #if ENABLE_ASH_ALIAS
2977 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2979 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2980 CNL_CNL_CNL_CNL , /* 2 */
2981 CWORD_CCTL_CCTL_CWORD , /* 3 */
2982 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2983 CVAR_CVAR_CWORD_CVAR , /* 5 */
2984 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2985 CSPCL_CWORD_CWORD_CLP , /* 7 */
2986 CSPCL_CWORD_CWORD_CRP , /* 8 */
2987 CBACK_CBACK_CCTL_CBACK , /* 9 */
2988 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2989 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2990 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2991 CWORD_CWORD_CWORD_CWORD , /* 13 */
2992 CCTL_CCTL_CCTL_CCTL , /* 14 */
2995 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2996 * caller must ensure proper cast on it if c is *char_ptr!
2998 #if USE_SIT_FUNCTION
3001 SIT(int c, int syntax)
3003 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
3004 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
3006 * This causes '/' to be prepended with CTLESC in dquoted string,
3007 * making "./file"* treated incorrectly because we feed
3008 * ".\/file*" string to glob(), confusing it (see expandmeta func).
3009 * The "homegrown" glob implementation is okay with that,
3010 * but glibc one isn't. With '/' always treated as CWORD,
3013 # if ENABLE_ASH_ALIAS
3014 static const uint8_t syntax_index_table[] ALIGN1 = {
3015 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
3016 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
3017 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
3021 static const uint8_t syntax_index_table[] ALIGN1 = {
3022 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
3023 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
3024 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
3033 # if ENABLE_ASH_ALIAS
3039 /* Cast is purely for paranoia here,
3040 * just in case someone passed signed char to us */
3041 if ((unsigned char)c >= CTL_FIRST
3042 && (unsigned char)c <= CTL_LAST
3046 s = strchrnul(spec_symbls, c);
3049 indx = syntax_index_table[s - spec_symbls];
3051 return (S_I_T[indx] >> (syntax*4)) & 0xf;
3054 #else /* !USE_SIT_FUNCTION */
3056 static const uint8_t syntax_index_table[] ALIGN1 = {
3057 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
3058 /* 0 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 1 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 2 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 3 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 4 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 5 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 6 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 7 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 8 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
3068 /* 10 "\n" */ CNL_CNL_CNL_CNL,
3069 /* 11 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 12 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 13 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 14 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 15 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 16 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 17 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 18 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 19 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 20 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 21 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 22 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 23 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 24 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 25 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 26 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 27 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 28 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 29 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 30 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 31 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
3091 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
3092 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
3093 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
3094 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
3095 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
3096 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
3097 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
3098 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
3099 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
3100 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
3101 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
3102 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
3103 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
3104 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
3105 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
3106 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
3107 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
3108 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
3109 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
3110 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
3111 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
3112 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
3113 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
3114 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
3115 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
3116 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
3117 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
3118 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
3119 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
3120 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
3121 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
3122 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
3123 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
3124 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
3125 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
3126 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
3127 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
3128 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
3129 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
3130 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
3131 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
3132 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
3133 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
3134 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
3135 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
3136 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
3137 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
3138 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
3139 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
3140 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
3141 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
3142 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
3143 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
3144 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
3145 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
3146 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
3147 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
3148 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
3149 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
3150 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
3151 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
3152 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
3153 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
3154 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
3155 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
3156 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
3157 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
3158 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
3159 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
3160 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
3161 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
3162 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
3163 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
3164 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
3165 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
3166 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
3167 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
3168 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
3169 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
3170 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3171 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3172 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3173 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3174 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3175 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3176 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3177 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3178 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3179 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3180 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3181 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3182 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3183 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3184 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3185 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3186 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
3187 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
3188 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
3189 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
3190 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
3191 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
3192 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
3193 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3194 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3195 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3196 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3197 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3198 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3199 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3200 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3201 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3202 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3203 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3204 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3205 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3206 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3207 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3208 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3209 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3210 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3211 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3212 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3213 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3214 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3215 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3216 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3217 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3218 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3219 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3220 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3221 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3222 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3223 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3224 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3225 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3226 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3227 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3228 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3229 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3230 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3231 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3232 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3233 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3234 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3235 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3236 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3237 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3238 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3239 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3240 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3241 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3242 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3243 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3244 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3245 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3246 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3247 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3248 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3249 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3250 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3251 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3252 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3253 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3254 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3255 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3256 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3257 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3258 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3259 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3260 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3261 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3262 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3263 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3264 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3265 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3266 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3267 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3268 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3269 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3270 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3271 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3272 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3273 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3274 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3275 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3276 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3277 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3278 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3279 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3280 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3281 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3282 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3283 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3284 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3285 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3286 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3287 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3288 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3289 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3290 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3291 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3292 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3293 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3294 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3295 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3296 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3297 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3298 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3299 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3300 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3301 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3302 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3303 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3304 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3305 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3306 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3307 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3308 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3309 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3310 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3311 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3312 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3313 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3314 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3315 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3316 # if ENABLE_ASH_ALIAS
3317 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3322 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3323 #else /* debug version, caught one signed char bug */
3324 # define SIT(c, syntax) \
3326 if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
3327 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3328 if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
3329 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3330 ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
3334 #endif /* !USE_SIT_FUNCTION */
3337 /* ============ Alias handling */
3339 #if ENABLE_ASH_ALIAS
3341 #define ALIASINUSE 1
3352 static struct alias **atab; // [ATABSIZE];
3353 #define INIT_G_alias() do { \
3354 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3358 static struct alias **
3359 __lookupalias(const char *name)
3361 unsigned int hashval;
3368 ch = (unsigned char)*p;
3372 ch = (unsigned char)*++p;
3374 app = &atab[hashval % ATABSIZE];
3376 for (; *app; app = &(*app)->next) {
3377 if (strcmp(name, (*app)->name) == 0) {
3385 static struct alias *
3386 lookupalias(const char *name, int check)
3388 struct alias *ap = *__lookupalias(name);
3390 if (check && ap && (ap->flag & ALIASINUSE))
3395 static struct alias *
3396 freealias(struct alias *ap)
3400 if (ap->flag & ALIASINUSE) {
3401 ap->flag |= ALIASDEAD;
3413 setalias(const char *name, const char *val)
3415 struct alias *ap, **app;
3417 app = __lookupalias(name);
3421 if (!(ap->flag & ALIASINUSE)) {
3424 ap->val = ckstrdup(val);
3425 ap->flag &= ~ALIASDEAD;
3428 ap = ckzalloc(sizeof(struct alias));
3429 ap->name = ckstrdup(name);
3430 ap->val = ckstrdup(val);
3431 /*ap->flag = 0; - ckzalloc did it */
3432 /*ap->next = NULL;*/
3439 unalias(const char *name)
3443 app = __lookupalias(name);
3447 *app = freealias(*app);
3458 struct alias *ap, **app;
3462 for (i = 0; i < ATABSIZE; i++) {
3464 for (ap = *app; ap; ap = *app) {
3465 *app = freealias(*app);
3475 printalias(const struct alias *ap)
3477 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3481 * TODO - sort output
3483 static int FAST_FUNC
3484 aliascmd(int argc UNUSED_PARAM, char **argv)
3493 for (i = 0; i < ATABSIZE; i++) {
3494 for (ap = atab[i]; ap; ap = ap->next) {
3500 while ((n = *++argv) != NULL) {
3501 v = strchr(n+1, '=');
3502 if (v == NULL) { /* n+1: funny ksh stuff */
3503 ap = *__lookupalias(n);
3505 fprintf(stderr, "%s: %s not found\n", "alias", n);
3518 static int FAST_FUNC
3519 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3523 while (nextopt("a") != '\0') {
3527 for (i = 0; *argptr; argptr++) {
3528 if (unalias(*argptr)) {
3529 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3537 #endif /* ASH_ALIAS */
3540 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3543 #define FORK_NOJOB 2
3545 /* mode flags for showjob(s) */
3546 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3547 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3548 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3549 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3552 * A job structure contains information about a job. A job is either a
3553 * single process or a set of processes contained in a pipeline. In the
3554 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3558 pid_t ps_pid; /* process id */
3559 int ps_status; /* last process status from wait() */
3560 char *ps_cmd; /* text of command being run */
3564 struct procstat ps0; /* status of process */
3565 struct procstat *ps; /* status of processes when more than one */
3567 int stopstatus; /* status of a stopped job */
3569 unsigned nprocs; /* number of processes */
3571 #define JOBRUNNING 0 /* at least one proc running */
3572 #define JOBSTOPPED 1 /* all procs are stopped */
3573 #define JOBDONE 2 /* all procs are completed */
3577 sigint: 1, /* job was killed by SIGINT */
3578 jobctl: 1, /* job running under job control */
3580 waited: 1, /* true if this entry has been waited for */
3581 used: 1, /* true if this entry is in used */
3582 changed: 1; /* true if status has changed */
3583 struct job *prev_job; /* previous job */
3586 static struct job *makejob(/*union node *,*/ int);
3587 static int forkshell(struct job *, union node *, int);
3588 static int waitforjob(struct job *);
3591 enum { doing_jobctl = 0 };
3592 #define setjobctl(on) do {} while (0)
3594 static smallint doing_jobctl; //references:8
3595 static void setjobctl(int);
3602 ignoresig(int signo)
3604 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3605 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3606 /* No, need to do it */
3607 signal(signo, SIG_IGN);
3609 sigmode[signo - 1] = S_HARD_IGN;
3613 * Only one usage site - in setsignal()
3616 signal_handler(int signo)
3618 if (signo == SIGCHLD) {
3624 gotsig[signo - 1] = 1;
3625 pending_sig = signo;
3627 if (signo == SIGINT && !trap[SIGINT]) {
3628 if (!suppress_int) {
3630 raise_interrupt(); /* does not return */
3637 * Set the signal handler for the specified signal. The routine figures
3638 * out what it should be set to.
3641 setsignal(int signo)
3644 char cur_act, new_act;
3645 struct sigaction act;
3649 if (t != NULL) { /* trap for this sig is set */
3651 if (t[0] == '\0') /* trap is "": ignore this sig */
3655 if (rootshell && new_act == S_DFL) {
3658 if (iflag || minusc || sflag == 0)
3667 * "In all cases, bash ignores SIGQUIT. Non-builtin
3668 * commands run by bash have signal handlers
3669 * set to the values inherited by the shell
3670 * from its parent". */
3686 /* if !rootshell, we reset SIGQUIT to DFL,
3687 * whereas we have to restore it to what shell got on entry.
3688 * This is handled by the fact that if signal was IGNored on entry,
3689 * then cur_act is S_HARD_IGN and we never change its sigaction
3693 if (signo == SIGCHLD)
3696 t = &sigmode[signo - 1];
3699 /* current setting is not yet known */
3700 if (sigaction(signo, NULL, &act)) {
3701 /* pretend it worked; maybe we should give a warning,
3702 * but other shells don't. We don't alter sigmode,
3703 * so we retry every time.
3704 * btw, in Linux it never fails. --vda */
3707 if (act.sa_handler == SIG_IGN) {
3708 cur_act = S_HARD_IGN;
3710 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3712 cur_act = S_IGN; /* don't hard ignore these */
3715 if (act.sa_handler == SIG_DFL && new_act == S_DFL) {
3716 /* installing SIG_DFL over SIG_DFL is a no-op */
3717 /* saves one sigaction call in each "sh -c SCRIPT" invocation */
3722 if (cur_act == S_HARD_IGN || cur_act == new_act)
3727 act.sa_handler = SIG_DFL;
3730 act.sa_handler = signal_handler;
3733 act.sa_handler = SIG_IGN;
3736 /* flags and mask matter only if !DFL and !IGN, but we do it
3737 * for all cases for more deterministic behavior:
3739 act.sa_flags = 0; //TODO: why not SA_RESTART?
3740 sigfillset(&act.sa_mask);
3742 sigaction_set(signo, &act);
3745 /* mode flags for set_curjob */
3746 #define CUR_DELETE 2
3747 #define CUR_RUNNING 1
3748 #define CUR_STOPPED 0
3751 /* pgrp of shell on invocation */
3752 static int initialpgrp; //references:2
3753 static int ttyfd = -1; //5
3756 static struct job *jobtab; //5
3758 static unsigned njobs; //4
3760 static struct job *curjob; //lots
3761 /* number of presumed living untracked jobs */
3762 static int jobless; //4
3765 /* Bash has a feature: it restores termios after a successful wait for
3766 * a foreground job which had at least one stopped or sigkilled member.
3767 * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
3768 * properly restoring tty state. Should we do this too?
3769 * A reproducer: ^Z an interactive python:
3772 * Python 2.7.12 (...)
3774 * { python leaves tty in -icanon -echo state. We do survive that... }
3775 * [1]+ Stopped python
3776 * { ...however, next program (python #2) does not survive it well: }
3778 * Python 2.7.12 (...)
3779 * >>> Traceback (most recent call last):
3780 * { above, I typed "qwerty<CR>", but -echo state is still in effect }
3781 * File "<stdin>", line 1, in <module>
3782 * NameError: name 'qwerty' is not defined
3784 * The implementation below is modeled on bash code and seems to work.
3785 * However, I'm not sure we should do this. For one: what if I'd fg
3786 * the stopped python instead? It'll be confused by "restored" tty state.
3788 static struct termios shell_tty_info;
3792 if (rootshell && ttyfd >= 0)
3793 tcgetattr(ttyfd, &shell_tty_info);
3798 /* if (rootshell) - caller ensures this */
3800 tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
3803 job_signal_status(struct job *jp)
3807 struct procstat *ps = jp->ps;
3808 for (i = 0; i < jp->nprocs; i++) {
3809 status = ps[i].ps_status;
3810 if (WIFSIGNALED(status) || WIFSTOPPED(status))
3816 restore_tty_if_stopped_or_signaled(struct job *jp)
3818 //TODO: check what happens if we come from waitforjob() in expbackq()
3820 int s = job_signal_status(jp);
3821 if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
3826 # define get_tty_state() ((void)0)
3827 # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
3831 set_curjob(struct job *jp, unsigned mode)
3834 struct job **jpp, **curp;
3836 /* first remove from list */
3837 jpp = curp = &curjob;
3842 jpp = &jp1->prev_job;
3844 *jpp = jp1->prev_job;
3846 /* Then re-insert in correct position */
3854 /* job being deleted */
3857 /* newly created job or backgrounded job,
3858 * put after all stopped jobs.
3863 if (!jp1 || jp1->state != JOBSTOPPED)
3866 jpp = &jp1->prev_job;
3872 /* newly stopped job - becomes curjob */
3873 jp->prev_job = *jpp;
3881 jobno(const struct job *jp)
3883 return jp - jobtab + 1;
3888 * Convert a job name to a job structure.
3891 #define getjob(name, getctl) getjob(name)
3894 getjob(const char *name, int getctl)
3898 const char *err_msg = "%s: no such job";
3902 char *(*match)(const char *, const char *);
3917 if (c == '+' || c == '%') {
3919 err_msg = "No current job";
3925 err_msg = "No previous job";
3935 if (num > 0 && num <= njobs) {
3936 jp = jobtab + num - 1;
3951 if (match(jp->ps[0].ps_cmd, p)) {
3955 err_msg = "%s: ambiguous";
3965 err_msg = "job %s not created under job control";
3966 if (getctl && jp->jobctl == 0)
3971 ash_msg_and_raise_error(err_msg, name);
3975 * Mark a job structure as unused.
3978 freejob(struct job *jp)
3980 struct procstat *ps;
3984 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3985 if (ps->ps_cmd != nullstr)
3988 if (jp->ps != &jp->ps0)
3991 set_curjob(jp, CUR_DELETE);
3997 xtcsetpgrp(int fd, pid_t pgrp)
3999 if (tcsetpgrp(fd, pgrp))
4000 ash_msg_and_raise_perror("can't set tty process group");
4004 * Turn job control on and off.
4006 * Note: This code assumes that the third arg to ioctl is a character
4007 * pointer, which is true on Berkeley systems but not System V. Since
4008 * System V doesn't have job control yet, this isn't a problem now.
4010 * Called with interrupts off.
4018 if (on == doing_jobctl || rootshell == 0)
4022 ofd = fd = open(_PATH_TTY, O_RDWR);
4024 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
4025 * That sometimes helps to acquire controlling tty.
4026 * Obviously, a workaround for bugs when someone
4027 * failed to provide a controlling tty to bash! :) */
4033 /* fd is a tty at this point */
4034 fd = fcntl(fd, F_DUPFD_CLOEXEC, 10);
4035 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
4038 goto out; /* F_DUPFD failed */
4039 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
4040 close_on_exec_on(fd);
4041 while (1) { /* while we are in the background */
4042 pgrp = tcgetpgrp(fd);
4045 ash_msg("can't access tty; job control turned off");
4049 if (pgrp == getpgrp())
4060 xtcsetpgrp(fd, pgrp);
4062 /* turning job control off */
4065 /* was xtcsetpgrp, but this can make exiting ash
4066 * loop forever if pty is already deleted */
4067 tcsetpgrp(fd, pgrp);
4081 static int FAST_FUNC
4082 killcmd(int argc, char **argv)
4084 if (argv[1] && strcmp(argv[1], "-l") != 0) {
4087 if (argv[i][0] == '%') {
4089 * "kill %N" - job kill
4090 * Converting to pgrp / pid kill
4096 jp = getjob(argv[i], 0);
4098 * In jobs started under job control, we signal
4099 * entire process group by kill -PGRP_ID.
4100 * This happens, f.e., in interactive shell.
4102 * Otherwise, we signal each child via
4103 * kill PID1 PID2 PID3.
4105 * sh -c 'sleep 1|sleep 1 & kill %1'
4106 * sh -c 'true|sleep 2 & sleep 1; kill %1'
4107 * sh -c 'true|sleep 1 & sleep 2; kill %1'
4109 n = jp->nprocs; /* can't be 0 (I hope) */
4112 dst = alloca(n * sizeof(int)*4);
4114 for (j = 0; j < n; j++) {
4115 struct procstat *ps = &jp->ps[j];
4116 /* Skip non-running and not-stopped members
4117 * (i.e. dead members) of the job
4119 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
4122 * kill_main has matching code to expect
4123 * leading space. Needed to not confuse
4124 * negative pids with "kill -SIGNAL_NO" syntax
4126 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
4130 } while (argv[++i]);
4132 return kill_main(argc, argv);
4136 showpipe(struct job *jp /*, FILE *out*/)
4138 struct procstat *ps;
4139 struct procstat *psend;
4141 psend = jp->ps + jp->nprocs;
4142 for (ps = jp->ps + 1; ps < psend; ps++)
4143 printf(" | %s", ps->ps_cmd);
4144 newline_and_flush(stdout);
4145 flush_stdout_stderr();
4150 restartjob(struct job *jp, int mode)
4152 struct procstat *ps;
4158 if (jp->state == JOBDONE)
4160 jp->state = JOBRUNNING;
4161 pgid = jp->ps[0].ps_pid;
4162 if (mode == FORK_FG) {
4164 xtcsetpgrp(ttyfd, pgid);
4166 killpg(pgid, SIGCONT);
4170 if (WIFSTOPPED(ps->ps_status)) {
4176 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
4181 static int FAST_FUNC
4182 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
4188 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
4192 jp = getjob(*argv, 1);
4193 if (mode == FORK_BG) {
4194 set_curjob(jp, CUR_RUNNING);
4195 printf("[%d] ", jobno(jp));
4197 out1str(jp->ps[0].ps_cmd);
4198 showpipe(jp /*, stdout*/);
4199 retval = restartjob(jp, mode);
4200 } while (*argv && *++argv);
4206 sprint_status48(char *os, int status, int sigonly)
4211 if (!WIFEXITED(status)) {
4213 if (WIFSTOPPED(status))
4214 st = WSTOPSIG(status);
4217 st = WTERMSIG(status);
4219 if (st == SIGINT || st == SIGPIPE)
4222 if (WIFSTOPPED(status))
4227 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
4228 //s = stpncpy(s, strsignal(st), 32); //not all libc have stpncpy()
4229 s += fmtstr(s, 32, strsignal(st));
4230 if (WCOREDUMP(status)) {
4231 s = stpcpy(s, " (core dumped)");
4233 } else if (!sigonly) {
4234 st = WEXITSTATUS(status);
4235 s += fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
4242 wait_block_or_sig(int *status)
4249 /* Poll all children for changes in their state */
4251 /* if job control is active, accept stopped processes too */
4252 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
4254 break; /* Error (e.g. EINTR, ECHILD) or pid */
4256 /* Children exist, but none are ready. Sleep until interesting signal */
4259 sigprocmask2(SIG_SETMASK, &mask); /* mask is updated */
4260 while (!got_sigchld && !pending_sig)
4262 sigprocmask(SIG_SETMASK, &mask, NULL);
4263 #else /* unsafe: a signal can set pending_sig after check, but before pause() */
4264 while (!got_sigchld && !pending_sig)
4268 /* If it was SIGCHLD, poll children again */
4269 } while (got_sigchld);
4274 #define DOWAIT_NONBLOCK 0
4275 #define DOWAIT_BLOCK 1
4276 #define DOWAIT_BLOCK_OR_SIG 2
4278 # define DOWAIT_JOBSTATUS 0x10 /* OR this to get job's exitstatus instead of pid */
4282 dowait(int block, struct job *job)
4287 struct job *thisjob;
4289 bool want_jobexitstatus = (block & DOWAIT_JOBSTATUS);
4290 block = (block & ~DOWAIT_JOBSTATUS);
4293 TRACE(("dowait(0x%x) called\n", block));
4295 /* It's wrong to call waitpid() outside of INT_OFF region:
4296 * signal can arrive just after syscall return and handler can
4297 * longjmp away, losing stop/exit notification processing.
4298 * Thus, for "jobs" builtin, and for waiting for a fg job,
4299 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
4301 * However, for "wait" builtin it is wrong to simply call waitpid()
4302 * in INT_OFF region: "wait" needs to wait for any running job
4303 * to change state, but should exit on any trap too.
4304 * In INT_OFF region, a signal just before syscall entry can set
4305 * pending_sig variables, but we can't check them, and we would
4306 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
4308 * Because of this, we run inside INT_OFF, but use a special routine
4309 * which combines waitpid() and sigsuspend().
4310 * This is the reason why we need to have a handler for SIGCHLD:
4311 * SIG_DFL handler does not wake sigsuspend().
4314 if (block == DOWAIT_BLOCK_OR_SIG) {
4315 pid = wait_block_or_sig(&status);
4318 if (block == DOWAIT_NONBLOCK)
4319 wait_flags = WNOHANG;
4320 /* if job control is active, accept stopped processes too */
4322 wait_flags |= WUNTRACED;
4323 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4324 pid = waitpid(-1, &status, wait_flags);
4326 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4327 pid, status, errno, strerror(errno)));
4332 for (jp = curjob; jp; jp = jp->prev_job) {
4334 struct procstat *ps;
4335 struct procstat *psend;
4336 if (jp->state == JOBDONE)
4340 psend = ps + jp->nprocs;
4342 if (ps->ps_pid == pid) {
4343 TRACE(("Job %d: changing status of proc %d "
4344 "from 0x%x to 0x%x\n",
4345 jobno(jp), pid, ps->ps_status, status));
4346 ps->ps_status = status;
4349 if (ps->ps_status == -1)
4350 jobstate = JOBRUNNING;
4352 if (jobstate == JOBRUNNING)
4354 if (WIFSTOPPED(ps->ps_status)) {
4355 jp->stopstatus = ps->ps_status;
4356 jobstate = JOBSTOPPED;
4359 } while (++ps < psend);
4363 /* Found the job where one of its processes changed its state.
4364 * Is there at least one live and running process in this job? */
4365 if (jobstate != JOBRUNNING) {
4366 /* No. All live processes in the job are stopped
4367 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4369 thisjob->changed = 1;
4370 if (thisjob->state != jobstate) {
4371 TRACE(("Job %d: changing state from %d to %d\n",
4372 jobno(thisjob), thisjob->state, jobstate));
4373 thisjob->state = jobstate;
4375 if (jobstate == JOBSTOPPED)
4376 set_curjob(thisjob, CUR_STOPPED);
4382 /* The process wasn't found in job list */
4384 if (!WIFSTOPPED(status))
4391 if (want_jobexitstatus) {
4393 if (thisjob && thisjob->state == JOBDONE)
4394 pid = thisjob->ps[thisjob->nprocs - 1].ps_status;
4397 if (thisjob && thisjob == job) {
4401 len = sprint_status48(s, status, 1);
4413 showjob(struct job *jp, int mode)
4415 struct procstat *ps;
4416 struct procstat *psend;
4419 char s[16 + 16 + 48];
4420 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4424 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4425 /* just output process (group) id of pipeline */
4426 fprintf(out, "%d\n", ps->ps_pid);
4430 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4435 else if (curjob && jp == curjob->prev_job)
4438 if (mode & SHOW_PIDS)
4439 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4441 psend = ps + jp->nprocs;
4443 if (jp->state == JOBRUNNING) {
4444 strcpy(s + col, "Running");
4445 col += sizeof("Running") - 1;
4447 int status = psend[-1].ps_status;
4448 if (jp->state == JOBSTOPPED)
4449 status = jp->stopstatus;
4450 col += sprint_status48(s + col, status, 0);
4452 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4454 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4455 * or prints several "PID | <cmdN>" lines,
4456 * depending on SHOW_PIDS bit.
4457 * We do not print status of individual processes
4458 * between PID and <cmdN>. bash does it, but not very well:
4459 * first line shows overall job status, not process status,
4460 * making it impossible to know 1st process status.
4464 /* for each process */
4467 if (mode & SHOW_PIDS)
4468 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4470 fprintf(out, "%s%*c%s%s",
4472 33 - col >= 0 ? 33 - col : 0, ' ',
4473 ps == jp->ps ? "" : "| ",
4476 } while (++ps != psend);
4477 newline_and_flush(out);
4481 if (jp->state == JOBDONE) {
4482 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4488 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4489 * statuses have changed since the last call to showjobs.
4496 TRACE(("showjobs(0x%x) called\n", mode));
4498 /* Handle all finished jobs */
4499 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4502 for (jp = curjob; jp; jp = jp->prev_job) {
4503 if (!(mode & SHOW_CHANGED) || jp->changed) {
4509 static int FAST_FUNC
4510 jobscmd(int argc UNUSED_PARAM, char **argv)
4515 while ((m = nextopt("lp")) != '\0') {
4519 mode |= SHOW_ONLY_PGID;
4525 showjob(getjob(*argv, 0), mode);
4535 /* Called only on finished or stopped jobs (no members are running) */
4537 getstatus(struct job *job)
4541 struct procstat *ps;
4543 /* Fetch last member's status */
4544 ps = job->ps + job->nprocs - 1;
4545 status = ps->ps_status;
4547 /* "set -o pipefail" mode: use last _nonzero_ status */
4548 while (status == 0 && --ps >= job->ps)
4549 status = ps->ps_status;
4552 retval = WEXITSTATUS(status);
4553 if (!WIFEXITED(status)) {
4555 retval = WSTOPSIG(status);
4556 if (!WIFSTOPPED(status))
4559 /* XXX: limits number of signals */
4560 retval = WTERMSIG(status);
4562 if (retval == SIGINT)
4568 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4569 jobno(job), job->nprocs, status, retval));
4573 static int FAST_FUNC
4574 waitcmd(int argc UNUSED_PARAM, char **argv)
4581 char one = nextopt("n");
4589 /* wait for all jobs / one job if -n */
4594 /* exitcode of "wait -n" with nothing to wait for is 127, not 0 */
4598 if (!jp) /* no running procs */
4600 if (jp->state == JOBRUNNING)
4606 * "When bash is waiting for an asynchronous command via
4607 * the wait builtin, the reception of a signal for which a trap
4608 * has been set will cause the wait builtin to return immediately
4609 * with an exit status greater than 128, immediately after which
4610 * the trap is executed."
4613 status = dowait(DOWAIT_BLOCK_OR_SIG | DOWAIT_JOBSTATUS, NULL);
4615 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4617 /* if child sends us a signal *and immediately exits*,
4618 * dowait() returns pid > 0. Check this case,
4619 * not "if (dowait() < 0)"!
4625 /* wait -n waits for one _job_, not one _process_.
4626 * date; sleep 3 & sleep 2 | sleep 1 & wait -n; date
4627 * should wait for 2 seconds. Not 1 or 3.
4629 if (status != -1 && !WIFSTOPPED(status)) {
4630 retval = WEXITSTATUS(status);
4631 if (WIFSIGNALED(status))
4632 retval = WTERMSIG(status) + 128;
4642 if (**argv != '%') {
4643 pid_t pid = number(*argv);
4648 if (job->ps[job->nprocs - 1].ps_pid == pid)
4650 job = job->prev_job;
4653 job = getjob(*argv, 0);
4655 /* loop until process terminated or stopped */
4656 while (job->state == JOBRUNNING) {
4657 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4662 retval = getstatus(job);
4669 retval = 128 + pending_sig;
4678 struct job *jp, *jq;
4680 len = njobs * sizeof(*jp);
4682 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4684 offset = (char *)jp - (char *)jq;
4686 /* Relocate pointers */
4689 jq = (struct job *)((char *)jq + l);
4693 #define joff(p) ((struct job *)((char *)(p) + l))
4694 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4695 if (joff(jp)->ps == &jq->ps0)
4696 jmove(joff(jp)->ps);
4697 if (joff(jp)->prev_job)
4698 jmove(joff(jp)->prev_job);
4708 jp = (struct job *)((char *)jp + len);
4712 } while (--jq >= jp);
4717 * Return a new job structure.
4718 * Called with interrupts off.
4721 makejob(/*union node *node,*/ int nprocs)
4726 for (i = njobs, jp = jobtab; ; jp++) {
4733 if (jp->state != JOBDONE || !jp->waited)
4742 memset(jp, 0, sizeof(*jp));
4744 /* jp->jobctl is a bitfield.
4745 * "jp->jobctl |= doing_jobctl" likely to give awful code */
4749 jp->prev_job = curjob;
4754 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4756 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4763 * Return a string identifying a command (to be printed by the
4766 static char *cmdnextc;
4769 cmdputs(const char *s)
4771 static const char vstype[VSTYPE + 1][3] = {
4772 "", "}", "-", "+", "?", "=",
4773 "%", "%%", "#", "##"
4774 IF_BASH_SUBSTR(, ":")
4775 IF_BASH_PATTERN_SUBST(, "/", "//")
4778 const char *p, *str;
4782 unsigned char subtype = 0;
4786 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4788 while ((c = *p++) != '\0') {
4796 if ((subtype & VSTYPE) == VSLENGTH)
4802 str = "\"}" + !(quoted & 1);
4809 #if ENABLE_FEATURE_SH_MATH
4824 if ((subtype & VSTYPE) != VSNORMAL)
4826 str = vstype[subtype & VSTYPE];
4827 if (subtype & VSNUL)
4836 /* These can only happen inside quotes */
4842 // [1]+ Done true ${\$} <<=== BUG: ${\$} is not a valid way to write $$ (${$} would be ok)
4853 while ((c = *str++) != '\0') {
4856 } /* while *p++ not NUL */
4859 USTPUTC('"', nextc);
4865 /* cmdtxt() and cmdlist() call each other */
4866 static void cmdtxt(union node *n);
4869 cmdlist(union node *np, int sep)
4871 for (; np; np = np->narg.next) {
4875 if (sep && np->narg.next)
4881 cmdtxt(union node *n)
4884 struct nodelist *lp;
4895 lp = n->npipe.cmdlist;
4913 cmdtxt(n->nbinary.ch1);
4929 cmdtxt(n->nif.test);
4931 if (n->nif.elsepart) {
4932 cmdtxt(n->nif.ifpart);
4934 n = n->nif.elsepart;
4952 cmdtxt(n->nbinary.ch1);
4962 cmdputs(n->nfor.var);
4964 cmdlist(n->nfor.args, 1);
4969 cmdputs(n->ndefun.text);
4973 cmdlist(n->ncmd.args, 1);
4974 cmdlist(n->ncmd.redirect, 0);
4987 cmdputs(n->ncase.expr->narg.text);
4989 for (np = n->ncase.cases; np; np = np->nclist.next) {
4990 cmdtxt(np->nclist.pattern);
4992 cmdtxt(np->nclist.body);
5006 #if BASH_REDIR_OUTPUT
5021 cmdputs(utoa(n->nfile.fd));
5023 if (n->type == NTOFD || n->type == NFROMFD) {
5024 if (n->ndup.dupfd >= 0)
5025 cmdputs(utoa(n->ndup.dupfd));
5036 commandtext(union node *n)
5040 STARTSTACKSTR(cmdnextc);
5042 name = stackblock();
5043 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
5044 return ckstrdup(name);
5049 * Fork off a subshell. If we are doing job control, give the subshell its
5050 * own process group. Jp is a job structure that the job is to be added to.
5051 * N is the command that will be evaluated by the child. Both jp and n may
5052 * be NULL. The mode parameter can be one of the following:
5053 * FORK_FG - Fork off a foreground process.
5054 * FORK_BG - Fork off a background process.
5055 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
5056 * process group even if job control is on.
5058 * When job control is turned off, background processes have their standard
5059 * input redirected to /dev/null (except for the second and later processes
5062 * Called with interrupts off.
5065 * Clear traps on a fork.
5073 for (tp = trap; tp < &trap[NSIG]; tp++) {
5074 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
5075 if (trap_ptr == trap)
5077 /* else: it "belongs" to trap_ptr vector, don't free */
5079 if ((tp - trap) != 0)
5080 setsignal(tp - trap);
5087 /* Lives far away from here, needed for forkchild */
5088 static void closescript(void);
5090 /* Called after fork(), in child */
5091 /* jp and n are NULL when called by openhere() for heredoc support */
5092 static NOINLINE void
5093 forkchild(struct job *jp, union node *n, int mode)
5097 TRACE(("Child shell %d\n", getpid()));
5101 /* man bash: "Non-builtin commands run by bash have signal handlers
5102 * set to the values inherited by the shell from its parent".
5103 * Do we do it correctly? */
5107 if (mode == FORK_NOJOB /* is it `xxx` ? */
5108 && n && n->type == NCMD /* is it single cmd? */
5109 /* && n->ncmd.args->type == NARG - always true? */
5110 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
5111 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
5112 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
5114 TRACE(("Trap hack\n"));
5115 /* Awful hack for `trap` or $(trap).
5117 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5118 * contains an example where "trap" is executed in a subshell:
5120 * save_traps=$(trap)
5122 * eval "$save_traps"
5124 * Standard does not say that "trap" in subshell shall print
5125 * parent shell's traps. It only says that its output
5126 * must have suitable form, but then, in the above example
5127 * (which is not supposed to be normative), it implies that.
5129 * bash (and probably other shell) does implement it
5130 * (traps are reset to defaults, but "trap" still shows them),
5131 * but as a result, "trap" logic is hopelessly messed up:
5134 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5135 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5136 * # true | trap <--- trap is in subshell - no output (ditto)
5137 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5138 * trap -- 'echo Ho' SIGWINCH
5139 * # echo `(trap)` <--- in subshell in subshell - output
5140 * trap -- 'echo Ho' SIGWINCH
5141 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5142 * trap -- 'echo Ho' SIGWINCH
5144 * The rules when to forget and when to not forget traps
5145 * get really complex and nonsensical.
5147 * Our solution: ONLY bare $(trap) or `trap` is special.
5149 /* Save trap handler strings for trap builtin to print */
5150 trap_ptr = xmemdup(trap, sizeof(trap));
5151 /* Fall through into clearing traps */
5155 /* do job control only in root shell */
5157 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
5160 if (jp->nprocs == 0)
5163 pgrp = jp->ps[0].ps_pid;
5164 /* this can fail because we are doing it in the parent also */
5166 if (mode == FORK_FG)
5167 xtcsetpgrp(ttyfd, pgrp);
5172 if (mode == FORK_BG) {
5173 /* man bash: "When job control is not in effect,
5174 * asynchronous commands ignore SIGINT and SIGQUIT" */
5177 if (jp->nprocs == 0) {
5179 if (open(bb_dev_null, O_RDONLY) != 0)
5180 ash_msg_and_raise_perror("can't open '%s'", bb_dev_null);
5184 if (iflag) { /* why if iflag only? */
5189 * "In all cases, bash ignores SIGQUIT. Non-builtin
5190 * commands run by bash have signal handlers
5191 * set to the values inherited by the shell
5193 * Take care of the second rule: */
5197 if (n && n->type == NCMD
5198 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
5200 TRACE(("Job hack\n"));
5201 /* "jobs": we do not want to clear job list for it,
5202 * instead we remove only _its_ own_ job from job list.
5203 * This makes "jobs .... | cat" more useful.
5209 for (jp = curjob; jp; jp = jp->prev_job)
5214 /* Called after fork(), in parent */
5216 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
5219 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
5221 TRACE(("In parent shell: child = %d\n", pid));
5223 /* jp is NULL when called by openhere() for heredoc support */
5224 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
5230 if (mode != FORK_NOJOB && jp->jobctl) {
5233 if (jp->nprocs == 0)
5236 pgrp = jp->ps[0].ps_pid;
5237 /* This can fail because we are doing it in the child also */
5241 if (mode == FORK_BG) {
5242 backgndpid = pid; /* set $! */
5243 set_curjob(jp, CUR_RUNNING);
5246 struct procstat *ps = &jp->ps[jp->nprocs++];
5249 ps->ps_cmd = nullstr;
5251 if (doing_jobctl && n)
5252 ps->ps_cmd = commandtext(n);
5257 /* jp and n are NULL when called by openhere() for heredoc support */
5259 forkshell(struct job *jp, union node *n, int mode)
5263 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
5266 TRACE(("Fork failed, errno=%d", errno));
5269 ash_msg_and_raise_perror("can't fork");
5272 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
5273 forkchild(jp, n, mode);
5275 forkparent(jp, n, mode, pid);
5281 * Wait for job to finish.
5283 * Under job control we have the problem that while a child process
5284 * is running interrupts generated by the user are sent to the child
5285 * but not to the shell. This means that an infinite loop started by
5286 * an interactive user may be hard to kill. With job control turned off,
5287 * an interactive user may place an interactive program inside a loop.
5288 * If the interactive program catches interrupts, the user doesn't want
5289 * these interrupts to also abort the loop. The approach we take here
5290 * is to have the shell ignore interrupt signals while waiting for a
5291 * foreground process to terminate, and then send itself an interrupt
5292 * signal if the child process was terminated by an interrupt signal.
5293 * Unfortunately, some programs want to do a bit of cleanup and then
5294 * exit on interrupt; unless these processes terminate themselves by
5295 * sending a signal to themselves (instead of calling exit) they will
5296 * confuse this approach.
5298 * Called with interrupts off.
5301 waitforjob(struct job *jp)
5305 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
5308 while (jp->state == JOBRUNNING) {
5309 /* In non-interactive shells, we _can_ get
5310 * a keyboard signal here and be EINTRed,
5311 * but we just loop back, waiting for command to complete.
5314 * "If bash is waiting for a command to complete and receives
5315 * a signal for which a trap has been set, the trap
5316 * will not be executed until the command completes."
5318 * Reality is that even if trap is not set, bash
5319 * will not act on the signal until command completes.
5320 * Try this. sleep5intoff.c:
5321 * #include <signal.h>
5322 * #include <unistd.h>
5325 * sigemptyset(&set);
5326 * sigaddset(&set, SIGINT);
5327 * sigaddset(&set, SIGQUIT);
5328 * sigprocmask(SIG_BLOCK, &set, NULL);
5332 * $ bash -c './sleep5intoff; echo hi'
5333 * ^C^C^C^C <--- pressing ^C once a second
5335 * $ bash -c './sleep5intoff; echo hi'
5336 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
5339 dowait(DOWAIT_BLOCK, jp);
5346 xtcsetpgrp(ttyfd, rootpid);
5347 restore_tty_if_stopped_or_signaled(jp);
5350 * This is truly gross.
5351 * If we're doing job control, then we did a TIOCSPGRP which
5352 * caused us (the shell) to no longer be in the controlling
5353 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
5354 * intuit from the subprocess exit status whether a SIGINT
5355 * occurred, and if so interrupt ourselves. Yuck. - mycroft
5357 if (jp->sigint) /* TODO: do the same with all signals */
5358 raise(SIGINT); /* ... by raise(jp->sig) instead? */
5360 if (jp->state == JOBDONE)
5367 * return 1 if there are stopped jobs, otherwise 0
5379 if (jp && jp->state == JOBSTOPPED) {
5380 out2str("You have stopped jobs.\n");
5390 * Code for dealing with input/output redirection.
5395 #define EMPTY -2 /* marks an unused slot in redirtab */
5396 #define CLOSED -1 /* marks a slot of previously-closed fd */
5399 * Handle here documents. Normally we fork off a process to write the
5400 * data to a pipe. If the document is short, we can stuff the data in
5401 * the pipe without forking.
5403 /* openhere needs this forward reference */
5404 static void expandhere(union node *arg, int fd);
5406 openhere(union node *redir)
5412 ash_msg_and_raise_perror("can't create pipe");
5413 if (redir->type == NHERE) {
5414 len = strlen(redir->nhere.doc->narg.text);
5415 if (len <= PIPE_BUF) {
5416 full_write(pip[1], redir->nhere.doc->narg.text, len);
5420 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5423 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5424 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5425 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5426 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5427 signal(SIGPIPE, SIG_DFL);
5428 if (redir->type == NHERE)
5429 full_write(pip[1], redir->nhere.doc->narg.text, len);
5431 expandhere(redir->nhere.doc, pip[1]);
5432 _exit(EXIT_SUCCESS);
5440 openredirect(union node *redir)
5446 switch (redir->nfile.type) {
5447 /* Can't happen, our single caller does this itself */
5453 return openhere(redir);
5456 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5457 * allocated space. Do it only when we know it is safe.
5459 fname = redir->nfile.expfname;
5461 switch (redir->nfile.type) {
5467 f = open(fname, O_RDONLY);
5472 f = open(fname, O_RDWR|O_CREAT, 0666);
5477 #if BASH_REDIR_OUTPUT
5480 /* Take care of noclobber mode. */
5482 if (stat(fname, &sb) < 0) {
5483 f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5486 } else if (!S_ISREG(sb.st_mode)) {
5487 f = open(fname, O_WRONLY, 0666);
5490 if (!fstat(f, &sb) && S_ISREG(sb.st_mode)) {
5503 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5508 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5516 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5518 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5522 * Copy a file descriptor to be >= 10. Throws exception on error.
5530 newfd = fcntl(from, F_DUPFD_CLOEXEC, 10);
5531 err = newfd < 0 ? errno : 0;
5534 ash_msg_and_raise_perror("%d", from);
5536 if (F_DUPFD_CLOEXEC == F_DUPFD)
5537 close_on_exec_on(newfd);
5543 dup2_or_raise(int from, int to)
5547 newfd = (from != to) ? dup2(from, to) : to;
5549 /* Happens when source fd is not open: try "echo >&99" */
5550 ash_msg_and_raise_perror("%d", from);
5555 dup_CLOEXEC(int fd, int avoid_fd)
5559 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
5561 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
5562 close_on_exec_on(newfd);
5563 } else { /* newfd < 0 */
5572 xdup_CLOEXEC_and_close(int fd, int avoid_fd)
5576 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
5582 /* fd was not open? */
5585 ash_msg_and_raise_perror("%d", newfd);
5587 if (F_DUPFD_CLOEXEC == F_DUPFD)
5588 close_on_exec_on(newfd);
5593 /* Struct def and variable are moved down to the first usage site */
5599 struct redirtab *next;
5601 struct squirrel two_fd[];
5603 #define redirlist (G_var.redirlist)
5606 add_squirrel_closed(struct redirtab *sq, int fd)
5613 for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
5614 /* If we collide with an already moved fd... */
5615 if (fd == sq->two_fd[i].orig_fd) {
5617 * "echo 3>FILE 3>&- 3>FILE"
5618 * "echo 3>&- 3>FILE"
5619 * No need for last redirect to insert
5620 * another "need to close 3" indicator.
5622 TRACE(("redirect_fd %d: already moved or closed\n", fd));
5626 TRACE(("redirect_fd %d: previous fd was closed\n", fd));
5627 sq->two_fd[i].orig_fd = fd;
5628 sq->two_fd[i].moved_to = CLOSED;
5632 save_fd_on_redirect(int fd, int avoid_fd, struct redirtab *sq)
5636 if (avoid_fd < 9) /* the important case here is that it can be -1 */
5641 /* Testcase: "ls -l /proc/$$/fd 10>&-" should work */
5642 ttyfd = xdup_CLOEXEC_and_close(ttyfd, avoid_fd);
5643 TRACE(("redirect_fd %d: matches ttyfd, moving it to %d\n", fd, ttyfd));
5644 return 1; /* "we closed fd" */
5647 /* Are we called from redirect(0)? E.g. redirect
5648 * in a forked child. No need to save fds,
5649 * we aren't going to use them anymore, ok to trash.
5654 /* If this one of script's fds? */
5656 struct parsefile *pf = g_parsefile;
5658 /* We skip fd == 0 case because of the following:
5659 * $ ash # running ash interactively
5661 * and in script.sh: "exec 9>&0".
5662 * Even though top-level pf_fd _is_ 0,
5663 * it's still ok to use it: "read" builtin uses it,
5664 * why should we cripple "exec" builtin?
5666 if (fd == pf->pf_fd) {
5667 pf->pf_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
5668 return 1; /* "we closed fd" */
5674 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
5676 /* First: do we collide with some already moved fds? */
5677 for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
5678 /* If we collide with an already moved fd... */
5679 if (fd == sq->two_fd[i].moved_to) {
5680 new_fd = dup_CLOEXEC(fd, avoid_fd);
5681 sq->two_fd[i].moved_to = new_fd;
5682 TRACE(("redirect_fd %d: already busy, moving to %d\n", fd, new_fd));
5683 if (new_fd < 0) /* what? */
5685 return 0; /* "we did not close fd" */
5687 if (fd == sq->two_fd[i].orig_fd) {
5688 /* Example: echo Hello >/dev/null 1>&2 */
5689 TRACE(("redirect_fd %d: already moved\n", fd));
5690 return 0; /* "we did not close fd" */
5694 /* If this fd is open, we move and remember it; if it's closed, new_fd = CLOSED (-1) */
5695 new_fd = dup_CLOEXEC(fd, avoid_fd);
5696 TRACE(("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, new_fd));
5700 /* new_fd = CLOSED; - already is -1 */
5702 sq->two_fd[i].moved_to = new_fd;
5703 sq->two_fd[i].orig_fd = fd;
5705 /* if we move stderr, let "set -x" code know */
5706 if (fd == preverrout_fd)
5707 preverrout_fd = new_fd;
5709 return 0; /* "we did not close fd" */
5713 internally_opened_fd(int fd, struct redirtab *sq)
5720 /* If this one of script's fds? */
5722 struct parsefile *pf = g_parsefile;
5724 if (fd == pf->pf_fd)
5730 if (sq) for (i = 0; i < sq->pair_count && sq->two_fd[i].orig_fd != EMPTY; i++) {
5731 if (fd == sq->two_fd[i].moved_to)
5738 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5739 * old file descriptors are stashed away so that the redirection can be
5740 * undone by calling popredir.
5742 /* flags passed to redirect */
5743 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5745 redirect(union node *redir, int flags)
5747 struct redirtab *sv;
5754 if (flags & REDIR_PUSH)
5762 fd = redir->nfile.fd;
5763 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5764 //bb_error_msg("doing %d > %d", fd, newfd);
5765 newfd = redir->ndup.dupfd;
5768 newfd = openredirect(redir); /* always >= 0 */
5770 /* open() gave us precisely the fd we wanted.
5771 * This means that this fd was not busy
5772 * (not opened to anywhere).
5773 * Remember to close it on restore:
5775 add_squirrel_closed(sv, fd);
5784 /* if "N>FILE": move newfd to fd */
5785 /* if "N>&M": dup newfd to fd */
5786 /* if "N>&-": close fd (newfd is -1) */
5788 IF_BASH_REDIR_OUTPUT(redirect_more:)
5790 closed = save_fd_on_redirect(fd, /*avoid:*/ newfd, sv);
5792 /* "N>&-" means "close me" */
5794 /* ^^^ optimization: saving may already
5795 * have closed it. If not... */
5799 /* if newfd is a script fd or saved fd, simulate EBADF */
5800 if (internally_opened_fd(newfd, sv)) {
5802 ash_msg_and_raise_perror("%d", newfd);
5804 dup2_or_raise(newfd, fd);
5805 if (close_fd >= 0) /* "N>FILE" or ">&FILE" or heredoc? */
5807 #if BASH_REDIR_OUTPUT
5808 if (redir->nfile.type == NTO2 && fd == 1) {
5809 /* ">&FILE". we already redirected to 1, now copy 1 to 2 */
5817 } while ((redir = redir->nfile.next) != NULL);
5820 //dash:#define REDIR_SAVEFD2 03 /* set preverrout */
5821 #define REDIR_SAVEFD2 0
5822 // dash has a bug: since REDIR_SAVEFD2=3 and REDIR_PUSH=1, this test
5823 // triggers for pure REDIR_PUSH too. Thus, this is done almost always,
5824 // not only for calls with flags containing REDIR_SAVEFD2.
5825 // We do this unconditionally (see save_fd_on_redirect()).
5826 //if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5827 // preverrout_fd = copied_fd2;
5831 redirectsafe(union node *redir, int flags)
5834 volatile int saveint;
5835 struct jmploc *volatile savehandler = exception_handler;
5836 struct jmploc jmploc;
5839 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5840 err = setjmp(jmploc.loc); /* was = setjmp(jmploc.loc) * 2; */
5842 exception_handler = &jmploc;
5843 redirect(redir, flags);
5845 exception_handler = savehandler;
5846 if (err && exception_type != EXERROR)
5847 longjmp(exception_handler->loc, 1);
5848 RESTORE_INT(saveint);
5852 static struct redirtab*
5853 pushredir(union node *redir)
5855 struct redirtab *sv;
5864 #if BASH_REDIR_OUTPUT
5865 if (redir->nfile.type == NTO2)
5868 redir = redir->nfile.next;
5871 sv = ckzalloc(sizeof(*sv) + i * sizeof(sv->two_fd[0]));
5874 sv->two_fd[i].orig_fd = sv->two_fd[i].moved_to = EMPTY;
5875 sv->next = redirlist;
5881 * Undo the effects of the last redirection.
5886 struct redirtab *rp;
5889 if (redirlist == NULL)
5893 for (i = 0; i < rp->pair_count; i++) {
5894 int fd = rp->two_fd[i].orig_fd;
5895 int copy = rp->two_fd[i].moved_to;
5896 if (copy == CLOSED) {
5901 if (copy != EMPTY) {
5904 dup2_or_raise(copy, fd);
5909 redirlist = rp->next;
5915 unwindredir(struct redirtab *stop)
5917 while (redirlist != stop)
5918 popredir(/*drop:*/ 0);
5922 /* ============ Routines to expand arguments to commands
5924 * We have to deal with backquotes, shell variables, and file metacharacters.
5927 #if ENABLE_FEATURE_SH_MATH
5929 ash_arith(const char *s)
5931 arith_state_t math_state;
5934 math_state.lookupvar = lookupvar;
5935 math_state.setvar = setvar0;
5936 //math_state.endofname = endofname;
5939 result = arith(&math_state, s);
5940 if (math_state.errmsg)
5941 ash_msg_and_raise_error(math_state.errmsg);
5948 # if ENABLE_FEATURE_SH_MATH
5949 static int substr_atoi(const char *s)
5951 arith_t t = ash_arith(s);
5952 if (sizeof(t) > sizeof(int)) {
5953 /* clamp very large or very large negative nums for ${v:N:M}:
5954 * else "${v:0:0x100000001}" would work as "${v:0:1}"
5964 # define substr_atoi(s) number(s)
5971 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5972 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5973 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5974 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5975 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5976 * POSIX says for this case:
5977 * Pathname expansion shall not be performed on the word by a
5978 * non-interactive shell; an interactive shell may perform it, but shall
5979 * do so only when the expansion would result in one word.
5980 * Currently, our code complies to the above rule by never globbing
5981 * redirection filenames.
5982 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5983 * (this means that on a typical Linux distro, bash almost always
5984 * performs globbing, and thus diverges from what we do).
5986 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5987 #define EXP_VARTILDE2 0x20 /* expand tildes after colons only */
5988 #define EXP_WORD 0x40 /* expand word in parameter expansion */
5989 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5993 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5994 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5995 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5996 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5998 /* Add CTLESC when necessary. */
5999 #define QUOTES_ESC (EXP_FULL | EXP_CASE)
6000 /* Do not skip NUL characters. */
6001 #define QUOTES_KEEPNUL EXP_TILDE
6004 * Structure specifying which parts of the string should be searched
6005 * for IFS characters.
6008 struct ifsregion *next; /* next region in list */
6009 int begoff; /* offset of start of region */
6010 int endoff; /* offset of end of region */
6011 int nulonly; /* search for nul bytes only */
6015 struct strlist *list;
6016 struct strlist **lastp;
6019 /* output of current string */
6020 static char *expdest;
6021 /* list of back quote expressions */
6022 static struct nodelist *argbackq;
6023 /* first struct in list of ifs regions */
6024 static struct ifsregion ifsfirst;
6025 /* last struct in list */
6026 static struct ifsregion *ifslastp;
6027 /* holds expanded arg list */
6028 static struct arglist exparg;
6032 * cvtnum() is used even if math support is off (to prepare $? values and such).
6039 /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
6040 len = sizeof(arith_t) * 3;
6041 /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
6042 if (sizeof(arith_t) < 4) len += 2;
6044 expdest = makestrspace(len, expdest);
6045 len = fmtstr(expdest, len, ARITH_FMT, num);
6046 STADJUST(len, expdest);
6051 * Break the argument string into pieces based upon IFS and add the
6052 * strings to the argument list. The regions of the string to be
6053 * searched for IFS characters have been stored by recordregion.
6056 ifsbreakup(char *string, struct arglist *arglist)
6058 struct ifsregion *ifsp;
6063 const char *ifs, *realifs;
6068 if (ifslastp != NULL) {
6071 realifs = ifsset() ? ifsval() : defifs;
6076 p = string + ifsp->begoff;
6078 nulonly = ifsp->nulonly;
6079 ifs = nulonly ? nullstr : realifs;
6081 while (p < string + ifsp->endoff) {
6083 if ((unsigned char)*p == CTLESC)
6085 if (!strchr(ifs, *p)) {
6089 if (!(afternul || nulonly))
6090 ifsspc = (strchr(defifs, *p) != NULL);
6091 /* Ignore IFS whitespace at start */
6092 if (q == start && ifsspc) {
6098 sp = stzalloc(sizeof(*sp));
6100 *arglist->lastp = sp;
6101 arglist->lastp = &sp->next;
6105 if (p >= string + ifsp->endoff) {
6109 if ((unsigned char)*p == CTLESC)
6111 if (strchr(ifs, *p) == NULL) {
6115 if (strchr(defifs, *p) == NULL) {
6130 } while (ifsp != NULL);
6139 sp = stzalloc(sizeof(*sp));
6141 *arglist->lastp = sp;
6142 arglist->lastp = &sp->next;
6148 struct ifsregion *p = ifsfirst.next;
6155 struct ifsregion *ifsp;
6160 ifsfirst.next = NULL;
6167 esclen(const char *start, const char *p)
6171 while (p > start && (unsigned char)*--p == CTLESC) {
6178 * Remove any CTLESC characters from a string.
6180 #if !BASH_PATTERN_SUBST
6181 #define rmescapes(str, flag, slash_position) \
6182 rmescapes(str, flag)
6185 rmescapes(char *str, int flag, int *slash_position)
6187 static const char qchars[] ALIGN1 = {
6188 IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
6191 unsigned protect_against_glob;
6194 p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash_position));
6200 if (flag & RMESCAPE_ALLOC) {
6201 size_t len = p - str;
6202 size_t fulllen = len + strlen(p) + 1;
6204 if (flag & RMESCAPE_GROW) {
6205 int strloc = str - (char *)stackblock();
6206 r = makestrspace(fulllen, expdest);
6207 /* p and str may be invalidated by makestrspace */
6208 str = (char *)stackblock() + strloc;
6210 } else if (flag & RMESCAPE_HEAP) {
6211 r = ckmalloc(fulllen);
6213 r = stalloc(fulllen);
6217 q = (char *)mempcpy(q, str, len);
6221 globbing = flag & RMESCAPE_GLOB;
6222 protect_against_glob = globbing;
6224 if ((unsigned char)*p == CTLQUOTEMARK) {
6225 // Note: protect_against_glob only affect whether
6226 // CTLESC,<ch> gets converted to <ch> or to \<ch>
6228 protect_against_glob = globbing;
6232 /* naked back slash */
6233 protect_against_glob = 0;
6236 if ((unsigned char)*p == CTLESC) {
6240 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
6242 if (protect_against_glob) {
6244 * We used to trust glob() and fnmatch() to eat
6245 * superfluous escapes (\z where z has no
6246 * special meaning anyway). But this causes
6247 * bugs such as string of one greek letter rho
6248 * (unicode-encoded as two bytes "cf,81")
6249 * getting encoded as "cf,CTLESC,81"
6250 * and here, converted to "cf,\,81" -
6251 * which does not go well with some flavors
6252 * of fnmatch() in unicode locales
6253 * (for example, glibc <= 2.22).
6255 * Lets add "\" only on the chars which need it.
6256 * Testcases for less obvious chars are shown.
6261 || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
6262 || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
6263 || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
6264 || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
6265 /* Some libc support [^negate], that's why "^" also needs love */
6266 || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
6272 #if BASH_PATTERN_SUBST
6273 else if (slash_position && p == str + *slash_position) {
6274 /* stop handling globbing */
6276 *slash_position = q - r;
6277 slash_position = NULL;
6280 protect_against_glob = globbing;
6285 if (flag & RMESCAPE_GROW) {
6287 STADJUST(q - r + 1, expdest);
6291 #define pmatch(a, b) !fnmatch((a), (b), 0)
6294 * Prepare a pattern for a expmeta (internal glob(3)) call.
6296 * Returns an stalloced string.
6299 preglob(const char *pattern, int flag)
6301 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB, NULL);
6305 * Put a string on the stack.
6308 memtodest(const char *p, size_t len, int syntax, int quotes)
6315 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
6318 unsigned char c = *p++;
6320 if (quotes & QUOTES_ESC) {
6321 int n = SIT(c, syntax);
6323 || (syntax != BASESYNTAX && n == CBACK)
6328 } else if (!(quotes & QUOTES_KEEPNUL))
6337 strtodest(const char *p, int syntax, int quotes)
6339 size_t len = strlen(p);
6340 memtodest(p, len, syntax, quotes);
6345 * Record the fact that we have to scan this region of the
6346 * string for IFS characters.
6349 recordregion(int start, int end, int nulonly)
6351 struct ifsregion *ifsp;
6353 if (ifslastp == NULL) {
6357 ifsp = ckzalloc(sizeof(*ifsp));
6358 /*ifsp->next = NULL; - ckzalloc did it */
6359 ifslastp->next = ifsp;
6363 ifslastp->begoff = start;
6364 ifslastp->endoff = end;
6365 ifslastp->nulonly = nulonly;
6369 removerecordregions(int endoff)
6371 if (ifslastp == NULL)
6374 if (ifsfirst.endoff > endoff) {
6375 while (ifsfirst.next) {
6376 struct ifsregion *ifsp;
6378 ifsp = ifsfirst.next->next;
6379 free(ifsfirst.next);
6380 ifsfirst.next = ifsp;
6383 if (ifsfirst.begoff > endoff) {
6386 ifslastp = &ifsfirst;
6387 ifsfirst.endoff = endoff;
6392 ifslastp = &ifsfirst;
6393 while (ifslastp->next && ifslastp->next->begoff < endoff)
6394 ifslastp = ifslastp->next;
6395 while (ifslastp->next) {
6396 struct ifsregion *ifsp;
6398 ifsp = ifslastp->next->next;
6399 free(ifslastp->next);
6400 ifslastp->next = ifsp;
6403 if (ifslastp->endoff > endoff)
6404 ifslastp->endoff = endoff;
6408 exptilde(char *startp, char *p, int flags)
6414 int quotes = flags & QUOTES_ESC;
6418 while ((c = *++p) != '\0') {
6425 if (flags & EXP_VARTILDE)
6435 if (*name == '\0') {
6436 home = lookupvar("HOME");
6438 pw = getpwnam(name);
6446 strtodest(home, SQSYNTAX, quotes);
6454 * Execute a command inside back quotes. If it's a builtin command, we
6455 * want to save its output in a block obtained from malloc. Otherwise
6456 * we fork off a subprocess and get the output of the command via a pipe.
6457 * Should be called with interrupts off.
6459 struct backcmd { /* result of evalbackcmd */
6460 int fd; /* file descriptor to read from */
6461 int nleft; /* number of chars in buffer */
6462 char *buf; /* buffer */
6463 struct job *jp; /* job structure for command */
6466 /* These forward decls are needed to use "eval" code for backticks handling: */
6467 /* flags in argument to evaltree */
6468 #define EV_EXIT 01 /* exit after evaluating tree */
6469 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
6470 static int evaltree(union node *, int);
6472 /* An evaltree() which is known to never return.
6473 * Used to use an alias:
6474 * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
6475 * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
6477 static ALWAYS_INLINE NORETURN void
6478 evaltreenr(union node *n, int flags)
6481 bb_unreachable(abort());
6485 static void FAST_FUNC
6486 evalbackcmd(union node *n, struct backcmd *result)
6500 ash_msg_and_raise_perror("can't create pipe");
6501 jp = makejob(/*n,*/ 1);
6502 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6508 dup2_or_raise(pip[1], 1);
6511 /* TODO: eflag clearing makes the following not abort:
6512 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6513 * which is what bash does (unless it is in POSIX mode).
6514 * dash deleted "eflag = 0" line in the commit
6515 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6516 * [EVAL] Don't clear eflag in evalbackcmd
6517 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6521 evaltreenr(n, EV_EXIT);
6526 result->fd = pip[0];
6530 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6531 result->fd, result->buf, result->nleft, result->jp));
6535 * Expand stuff in backwards quotes.
6538 expbackq(union node *cmd, int flag)
6546 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6547 struct stackmark smark;
6550 startloc = expdest - (char *)stackblock();
6551 pushstackmark(&smark, startloc);
6552 evalbackcmd(cmd, &in);
6553 popstackmark(&smark);
6560 memtodest(p, i, syntax, flag & QUOTES_ESC);
6564 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6565 TRACE(("expbackq: read returns %d\n", i));
6574 back_exitstatus = waitforjob(in.jp);
6578 /* Eat all trailing newlines */
6580 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6584 if (!(flag & EXP_QUOTED))
6585 recordregion(startloc, dest - (char *)stackblock(), 0);
6586 TRACE(("evalbackq: size:%d:'%.*s'\n",
6587 (int)((dest - (char *)stackblock()) - startloc),
6588 (int)((dest - (char *)stackblock()) - startloc),
6589 stackblock() + startloc));
6592 #if ENABLE_FEATURE_SH_MATH
6594 * Expand arithmetic expression. Backup to start of expression,
6595 * evaluate, place result in (backed up) result, adjust string position.
6607 * This routine is slightly over-complicated for
6608 * efficiency. Next we scan backwards looking for the
6609 * start of arithmetic.
6611 start = stackblock();
6618 while ((unsigned char)*p != CTLARI) {
6622 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6627 esc = esclen(start, p);
6637 removerecordregions(begoff);
6641 if (flag & QUOTES_ESC)
6642 rmescapes(p + 1, 0, NULL);
6644 len = cvtnum(ash_arith(p + 1));
6646 if (!(flag & EXP_QUOTED))
6647 recordregion(begoff, begoff + len, 0);
6651 /* argstr needs it */
6652 static char *evalvar(char *p, int flags);
6655 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6656 * characters to allow for further processing. Otherwise treat
6657 * $@ like $* since no splitting will be performed.
6660 argstr(char *p, int flags)
6662 static const char spclchars[] ALIGN1 = {
6670 #if ENABLE_FEATURE_SH_MATH
6675 const char *reject = spclchars;
6676 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6681 if (!(flags & EXP_VARTILDE)) {
6683 } else if (flags & EXP_VARTILDE2) {
6688 if (flags & EXP_TILDE) {
6691 flags &= ~EXP_TILDE;
6695 p = exptilde(p, q, flags);
6698 startloc = expdest - (char *)stackblock();
6702 length += strcspn(p + length, reject);
6706 IF_FEATURE_SH_MATH(|| c == CTLENDARI)
6708 /* c == '=' || c == ':' || c == CTLENDARI */
6714 expdest = stack_nputstr(p, length, expdest);
6715 newloc = expdest - (char *)stackblock();
6716 if (breakall && !inquotes && newloc > startloc) {
6717 recordregion(startloc, newloc, 0);
6728 if (flags & EXP_VARTILDE2) {
6732 flags |= EXP_VARTILDE2;
6737 * sort of a hack - expand tildes in variable
6738 * assignments (after the first '=' and after ':'s).
6747 case CTLENDVAR: /* ??? */
6750 /* "$@" syntax adherence hack */
6751 if (!inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6752 p = evalvar(p + 1, flags | EXP_QUOTED) + 1;
6755 inquotes ^= EXP_QUOTED;
6757 if (flags & QUOTES_ESC) {
6768 TRACE(("argstr: evalvar('%s')\n", p));
6769 p = evalvar(p, flags | inquotes);
6770 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6773 expbackq(argbackq->n, flags | inquotes);
6774 argbackq = argbackq->next;
6776 #if ENABLE_FEATURE_SH_MATH
6779 expari(flags | inquotes);
6788 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6789 char *pattern, int quotes, int zero)
6798 const char *s = loc2;
6805 match = pmatch(pattern, s);
6810 if (quotes && (unsigned char)*loc == CTLESC)
6819 scanright(char *startp, char *rmesc, char *rmescend,
6820 char *pattern, int quotes, int match_at_start)
6822 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6823 int try2optimize = match_at_start;
6829 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6830 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6831 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6833 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6834 * and on each iteration they go back two/one char until they reach the beginning.
6835 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6837 /* TODO: document in what other circumstances we are called. */
6839 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6842 const char *s = loc2;
6843 if (match_at_start) {
6847 match = pmatch(pattern, s);
6848 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6852 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6854 /* Maybe we can optimize this:
6855 * if pattern ends with unescaped *, we can avoid checking
6856 * shorter strings: if "foo*" doesn't match "raw_value_of_v",
6857 * it won't match truncated "raw_value_of_" strings too.
6859 unsigned plen = strlen(pattern);
6860 /* Does it end with "*"? */
6861 if (plen != 0 && pattern[--plen] == '*') {
6862 /* "xxxx*" is not escaped */
6863 /* "xxx\*" is escaped */
6864 /* "xx\\*" is not escaped */
6865 /* "x\\\*" is escaped */
6867 while (plen != 0 && pattern[--plen] == '\\')
6870 break; /* ends with unescaped "*" */
6878 esc = esclen(startp, loc);
6889 static void varunset(const char *, const char *, const char *, int) NORETURN;
6891 varunset(const char *end, const char *var, const char *umsg, int varflags)
6897 msg = "parameter not set";
6899 if ((unsigned char)*end == CTLENDVAR) {
6900 if (varflags & VSNUL)
6906 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6910 subevalvar(char *p, char *varname, int strloc, int subtype,
6911 int startloc, int varflags, int flag)
6913 struct nodelist *saveargbackq = argbackq;
6914 int quotes = flag & QUOTES_ESC;
6917 char *rmesc, *rmescend;
6919 int amount, resetloc;
6921 IF_BASH_PATTERN_SUBST(int workloc;)
6922 IF_BASH_PATTERN_SUBST(int slash_pos;)
6923 IF_BASH_PATTERN_SUBST(char *repl;)
6925 char *(*scan)(char*, char*, char*, char*, int, int);
6927 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6928 // p, varname, strloc, subtype, startloc, varflags, quotes);
6930 #if BASH_PATTERN_SUBST
6931 /* For "${v/pattern/repl}", we must find the delimiter _before_
6932 * argstr() call expands possible variable references in pattern:
6933 * think about "v=a; a=a/; echo ${v/$a/r}" case.
6936 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6937 /* Find '/' and replace with NUL */
6939 /* The pattern can't be empty.
6940 * IOW: if the first char after "${v//" is a slash,
6941 * it does not terminate the pattern - it's the first char of the pattern:
6942 * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
6943 * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
6948 if (*repl == '\0') {
6956 /* Handle escaped slashes, e.g. "${v/\//_}" (they are CTLESC'ed by this point) */
6957 if ((unsigned char)*repl == CTLESC && repl[1])
6963 argstr_flags = EXP_TILDE;
6964 if (subtype != VSASSIGN
6965 && subtype != VSQUESTION
6967 && subtype != VSSUBSTR
6970 /* EXP_CASE keeps CTLESC's */
6971 argstr_flags = EXP_TILDE | EXP_CASE;
6973 argstr(p, argstr_flags);
6974 //bb_error_msg("str0:'%s'", (char *)stackblock() + strloc);
6975 #if BASH_PATTERN_SUBST
6978 slash_pos = expdest - ((char *)stackblock() + strloc);
6979 STPUTC('/', expdest);
6980 //bb_error_msg("repl+1:'%s'", repl + 1);
6981 argstr(repl + 1, EXP_TILDE); /* EXP_TILDE: echo "${v/x/~}" expands ~ ! */
6985 STPUTC('\0', expdest);
6986 argbackq = saveargbackq;
6987 startp = (char *)stackblock() + startloc;
6988 //bb_error_msg("str1:'%s'", (char *)stackblock() + strloc);
6992 setvar0(varname, startp);
6993 amount = startp - expdest;
6994 STADJUST(amount, expdest);
6998 varunset(p, varname, startp, varflags);
7003 int pos, len, orig_len;
7006 loc = str = stackblock() + strloc;
7008 /* Read POS in ${var:POS:LEN} */
7009 colon = strchr(loc, ':');
7010 if (colon) *colon = '\0';
7011 pos = substr_atoi(loc);
7012 if (colon) *colon = ':';
7014 /* Read LEN in ${var:POS:LEN} */
7015 len = str - startp - 1;
7016 /* *loc != '\0', guaranteed by parser */
7019 /* Adjust the length by the number of escapes */
7020 for (ptr = startp; ptr < (str - 1); ptr++) {
7021 if ((unsigned char)*ptr == CTLESC) {
7028 if (*loc++ == ':') {
7030 len = substr_atoi(loc);
7032 /* Skip POS in ${var:POS:LEN} */
7034 while (*loc && *loc != ':')
7037 len = substr_atoi(loc);
7040 /* ${VAR:$((-n)):l} starts n chars from the end */
7041 pos = orig_len + pos;
7043 if ((unsigned)pos >= orig_len) {
7044 /* apart from obvious ${VAR:999999:l},
7045 * covers ${VAR:$((-9999999)):l} - result is ""
7052 /* ${VAR:N:-M} sets LEN to strlen()-M */
7053 len = (orig_len - pos) + len;
7055 if ((unsigned)len > (orig_len - pos))
7056 len = orig_len - pos;
7058 for (str = startp; pos; str++, pos--) {
7059 if (quotes && (unsigned char)*str == CTLESC)
7062 for (loc = startp; len; len--) {
7063 if (quotes && (unsigned char)*str == CTLESC)
7068 amount = loc - expdest;
7069 STADJUST(amount, expdest);
7072 #endif /* BASH_SUBSTR */
7075 resetloc = expdest - (char *)stackblock();
7077 #if BASH_PATTERN_SUBST
7080 /* We'll comeback here if we grow the stack while handling
7081 * a VSREPLACE or VSREPLACEALL, since our pointers into the
7082 * stack will need rebasing, and we'll need to remove our work
7088 amount = expdest - ((char *)stackblock() + resetloc);
7089 STADJUST(-amount, expdest);
7090 startp = (char *)stackblock() + startloc;
7093 rmescend = (char *)stackblock() + strloc;
7094 //bb_error_msg("str7:'%s'", rmescend);
7096 //TODO: how to handle slash_pos here if string changes (shortens?)
7097 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW, NULL);
7098 if (rmesc != startp) {
7100 startp = (char *)stackblock() + startloc;
7104 str = (char *)stackblock() + strloc;
7106 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
7107 * The result is a_\_z_c (not a\_\_z_c)!
7109 * The search pattern and replace string treat backslashes differently!
7110 * "&slash_pos" causes rmescapes() to work differently on the pattern
7111 * and string. It's only used on the first call.
7113 //bb_error_msg("str8:'%s' slash_pos:%d", str, slash_pos);
7114 rmescapes(str, RMESCAPE_GLOB,
7115 repl ? NULL : (slash_pos < 0 ? NULL : &slash_pos)
7118 #if BASH_PATTERN_SUBST
7119 workloc = expdest - (char *)stackblock();
7120 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
7125 //bb_error_msg("str9:'%s' slash_pos:%d", str, slash_pos);
7127 if (slash_pos >= 0) {
7128 repl = str + slash_pos;
7132 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
7134 /* If there's no pattern to match, return the expansion unmolested */
7143 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
7144 //bb_error_msg("scanright('%s'):'%s'", str, loc);
7146 /* No match, advance */
7147 char *restart_detect = stackblock();
7149 STPUTC(*idx, expdest);
7150 if (quotes && (unsigned char)*idx == CTLESC) {
7153 STPUTC(*idx, expdest);
7155 if (stackblock() != restart_detect)
7160 /* continue; - prone to quadratic behavior, smarter code: */
7163 if (str[0] == '*') {
7164 /* Pattern is "*foo". If "*foo" does not match "long_string",
7165 * it would never match "ong_string" etc, no point in trying.
7172 if (subtype == VSREPLACEALL) {
7174 if (quotes && (unsigned char)*idx == CTLESC)
7183 //bb_error_msg("repl:'%s'", repl);
7184 for (loc = (char*)repl; *loc; loc++) {
7185 char *restart_detect = stackblock();
7186 if (quotes && *loc == '\\') {
7187 STPUTC(CTLESC, expdest);
7190 STPUTC(*loc, expdest);
7191 if (stackblock() != restart_detect)
7196 if (subtype == VSREPLACE) {
7197 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
7199 char *restart_detect = stackblock();
7200 STPUTC(*idx, expdest);
7201 if (stackblock() != restart_detect)
7210 /* We've put the replaced text into a buffer at workloc, now
7211 * move it to the right place and adjust the stack.
7213 STPUTC('\0', expdest);
7214 startp = (char *)stackblock() + startloc;
7215 memmove(startp, (char *)stackblock() + workloc, len + 1);
7216 //bb_error_msg("startp:'%s'", startp);
7217 amount = expdest - (startp + len);
7218 STADJUST(-amount, expdest);
7221 #endif /* BASH_PATTERN_SUBST */
7223 subtype -= VSTRIMRIGHT;
7225 if (subtype < 0 || subtype > 7)
7228 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
7229 zero = subtype >> 1;
7230 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
7231 scan = (subtype & 1) ^ zero ? scanleft : scanright;
7233 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
7236 memmove(startp, loc, str - loc);
7237 loc = startp + (str - loc) - 1;
7240 amount = loc - expdest;
7241 STADJUST(amount, expdest);
7247 * Add the value of a specialized variable to the stack string.
7248 * name parameter (examples):
7249 * ash -c 'echo $1' name:'1='
7250 * ash -c 'echo $qwe' name:'qwe='
7251 * ash -c 'echo $$' name:'$='
7252 * ash -c 'echo ${$}' name:'$='
7253 * ash -c 'echo ${$##q}' name:'$=q'
7254 * ash -c 'echo ${#$}' name:'$='
7255 * note: examples with bad shell syntax:
7256 * ash -c 'echo ${#$1}' name:'$=1'
7257 * ash -c 'echo ${#1#}' name:'1=#'
7259 static NOINLINE ssize_t
7260 varvalue(char *name, int varflags, int flags, int quoted)
7267 int subtype = varflags & VSTYPE;
7268 int discard = subtype == VSPLUS || subtype == VSLENGTH;
7269 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
7272 sep = (flags & EXP_FULL) << CHAR_BIT;
7273 syntax = quoted ? DQSYNTAX : BASESYNTAX;
7283 num = shellparam.nparam;
7291 goto check_1char_name;
7293 expdest = makestrspace(NOPTS, expdest);
7294 for (i = NOPTS - 1; i >= 0; i--) {
7295 if (optlist[i] && optletters(i)) {
7296 USTPUTC(optletters(i), expdest);
7302 /* handles cases similar to ${#$1} */
7303 if (name[2] != '\0')
7304 raise_error_syntax("bad substitution");
7316 /* We will set c to 0 or ~0 depending on whether
7317 * we're doing field splitting. We won't do field
7318 * splitting if either we're quoted or sep is zero.
7320 * Instead of testing (quoted || !sep) the following
7321 * trick optimises away any branches by using the
7322 * fact that EXP_QUOTED (which is the only bit that
7323 * can be set in quoted) is the same as EXP_FULL <<
7324 * CHAR_BIT (which is the only bit that can be set
7327 #if EXP_QUOTED >> CHAR_BIT != EXP_FULL
7328 #error The following two lines expect EXP_QUOTED == EXP_FULL << CHAR_BIT
7330 c = !((quoted | ~sep) & EXP_QUOTED) - 1;
7332 sep |= ifsset() ? (unsigned char)(c & ifsval()[0]) : ' ';
7338 while ((p = *ap++) != NULL) {
7339 len += strtodest(p, syntax, quotes);
7343 memtodest(&sepc, 1, syntax, quotes);
7358 num = atoi(name); /* number(name) fails on ${N#str} etc */
7359 if (num < 0 || num > shellparam.nparam)
7361 p = num ? shellparam.p[num - 1] : arg0;
7364 /* NB: name has form "VAR=..." */
7365 p = lookupvar(name);
7370 len = strtodest(p, syntax, quotes);
7371 #if ENABLE_UNICODE_SUPPORT
7372 if (subtype == VSLENGTH && len > 0) {
7373 reinit_unicode_for_ash();
7374 if (unicode_status == UNICODE_ON) {
7375 STADJUST(-len, expdest);
7377 len = unicode_strlen(p);
7385 STADJUST(-len, expdest);
7390 * Expand a variable, and return a pointer to the next character in the
7394 evalvar(char *p, int flag)
7404 varflags = (unsigned char) *p++;
7405 subtype = varflags & VSTYPE;
7408 raise_error_syntax("bad substitution");
7410 quoted = flag & EXP_QUOTED;
7412 startloc = expdest - (char *)stackblock();
7413 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
7416 varlen = varvalue(var, varflags, flag, quoted);
7417 if (varflags & VSNUL)
7420 if (subtype == VSPLUS) {
7421 varlen = -1 - varlen;
7425 if (subtype == VSMINUS) {
7430 flag | EXP_TILDE | EXP_WORD
7437 if (subtype == VSASSIGN || subtype == VSQUESTION) {
7441 subevalvar(p, var, 0, subtype, startloc, varflags,
7442 flag & ~QUOTES_ESC);
7445 * Remove any recorded regions beyond
7448 removerecordregions(startloc);
7452 if (varlen < 0 && uflag)
7453 varunset(p, var, 0, 0);
7455 if (subtype == VSLENGTH) {
7456 cvtnum(varlen > 0 ? varlen : 0);
7460 if (subtype == VSNORMAL) {
7463 quoted = *var == '@' && shellparam.nparam;
7467 recordregion(startloc, expdest - (char *)stackblock(), quoted);
7476 case VSTRIMRIGHTMAX:
7480 #if BASH_PATTERN_SUBST
7492 * Terminate the string and start recording the pattern
7495 STPUTC('\0', expdest);
7496 patloc = expdest - (char *)stackblock();
7497 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
7498 startloc, varflags, flag)) {
7499 int amount = expdest - (
7500 (char *)stackblock() + patloc - 1
7502 STADJUST(-amount, expdest);
7504 /* Remove any recorded regions beyond start of variable */
7505 removerecordregions(startloc);
7510 if (subtype != VSNORMAL) { /* skip to end of alternative */
7513 unsigned char c = *p++;
7516 else if (c == CTLBACKQ) {
7518 argbackq = argbackq->next;
7519 } else if (c == CTLVAR) {
7520 if ((*p++ & VSTYPE) != VSNORMAL)
7522 } else if (c == CTLENDVAR) {
7532 * Add a file name to the list.
7535 addfname(const char *name)
7539 sp = stzalloc(sizeof(*sp));
7540 sp->text = sstrdup(name);
7542 exparg.lastp = &sp->next;
7545 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7547 hasmeta(const char *p)
7549 static const char chars[] ALIGN1 = {
7550 '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
7554 p = strpbrk(p, chars);
7557 switch ((unsigned char)*p) {
7561 if ((unsigned char)*p == CTLQUOTEMARK)
7563 if ((unsigned char)*p == CTLESC)
7565 if (*p == '\0') /* huh? */
7576 if (!strchr(p + 1, ']')) {
7577 /* It's not a properly closed [] pattern,
7578 * but other metas may follow. Continue checking.
7579 * my[file* _is_ globbed by bash
7580 * and matches filenames like "my[file1".
7596 /* If we want to use glob() from libc... */
7597 #if !ENABLE_ASH_INTERNAL_GLOB
7599 /* Add the result of glob() to the list */
7601 addglob(const glob_t *pglob)
7603 char **p = pglob->gl_pathv;
7610 expandmeta(struct strlist *str /*, int flag*/)
7612 /* TODO - EXP_REDIR */
7622 if (!hasmeta(str->text))
7626 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7627 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7628 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7630 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7631 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7632 // Which means you need to unescape the string, right? Not so fast:
7633 // if there _is_ a file named "file\?" (with backslash), it is returned
7634 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7635 // You DON'T KNOW by looking at the result whether you need to unescape it.
7637 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7638 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7639 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7640 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7641 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7642 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7643 i = glob(p, 0, NULL, &pglob);
7644 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7649 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7650 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7651 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7663 *exparg.lastp = str;
7664 rmescapes(str->text, 0, NULL);
7665 exparg.lastp = &str->next;
7667 default: /* GLOB_NOSPACE */
7670 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7677 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7680 * Do metacharacter (i.e. *, ?, [...]) expansion.
7682 typedef struct exp_t {
7687 expmeta(exp_t *exp, char *name, unsigned name_len, unsigned expdir_len)
7689 #define expdir exp->dir
7690 #define expdir_max exp->dir_max
7691 char *enddir = expdir + expdir_len;
7706 for (p = name; esc = 0, *p; p += esc + 1) {
7707 if (*p == '*' || *p == '?')
7709 else if (*p == '[') {
7716 if (*q == '/' || *q == '\0')
7724 if (*p == '\\' && p[1])
7726 if (p[esc] == '/') {
7729 start = p + esc + 1;
7733 if (metaflag == 0) { /* we've reached the end of the file name */
7738 if (*p == '\\' && p[1])
7742 if (lstat(expdir, &statb) == 0)
7750 if (*p == '\\' && p[1])
7753 } while (p < start);
7757 expdir_len = enddir - cp;
7763 if (*endname == 0) {
7770 name_len -= endname - name;
7777 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7778 if (dp->d_name[0] == '.' && !matchdot)
7780 if (pmatch(start, dp->d_name)) {
7782 strcpy(enddir, dp->d_name);
7788 p = stpcpy(enddir, dp->d_name);
7791 offset = p - expdir + 1;
7792 len = offset + name_len + NAME_MAX;
7793 if (len > expdir_max) {
7795 expdir = ckrealloc(expdir, len);
7799 expmeta(exp, endname, name_len, offset);
7800 enddir = expdir + expdir_len;
7806 endname[-esc - 1] = esc ? '\\' : '/';
7811 static struct strlist *
7812 msort(struct strlist *list, int len)
7814 struct strlist *p, *q = NULL;
7815 struct strlist **lpp;
7823 for (n = half; --n >= 0;) {
7827 q->next = NULL; /* terminate first half of list */
7828 q = msort(list, half); /* sort first half of list */
7829 p = msort(p, len - half); /* sort second half */
7832 #if ENABLE_LOCALE_SUPPORT
7833 if (strcoll(p->text, q->text) < 0)
7835 if (strcmp(p->text, q->text) < 0)
7859 * Sort the results of file name expansion. It calculates the number of
7860 * strings to sort and then calls msort (short for merge sort) to do the
7863 static struct strlist *
7864 expsort(struct strlist *str)
7870 for (sp = str; sp; sp = sp->next)
7872 return msort(str, len);
7876 expandmeta(struct strlist *str /*, int flag*/)
7878 /* TODO - EXP_REDIR */
7882 struct strlist **savelastp;
7889 if (!hasmeta(str->text))
7891 savelastp = exparg.lastp;
7894 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7896 exp.dir_max = len + PATH_MAX;
7897 exp.dir = ckmalloc(exp.dir_max);
7899 expmeta(&exp, p, len, 0);
7904 if (exparg.lastp == savelastp) {
7909 *exparg.lastp = str;
7910 rmescapes(str->text, 0, NULL);
7911 exparg.lastp = &str->next;
7913 *exparg.lastp = NULL;
7914 *savelastp = sp = expsort(*savelastp);
7915 while (sp->next != NULL)
7917 exparg.lastp = &sp->next;
7922 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7925 * Perform variable substitution and command substitution on an argument,
7926 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7927 * perform splitting and file name expansion. When arglist is NULL, perform
7928 * here document expansion.
7931 expandarg(union node *arg, struct arglist *arglist, int flag)
7936 argbackq = arg->narg.backquote;
7937 STARTSTACKSTR(expdest);
7938 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7939 argstr(arg->narg.text, flag);
7940 p = _STPUTC('\0', expdest);
7942 if (arglist == NULL) {
7943 /* here document expanded */
7946 p = grabstackstr(p);
7947 TRACE(("expandarg: p:'%s'\n", p));
7948 exparg.lastp = &exparg.list;
7952 if (flag & EXP_FULL) {
7953 ifsbreakup(p, &exparg);
7954 *exparg.lastp = NULL;
7955 exparg.lastp = &exparg.list;
7956 expandmeta(exparg.list /*, flag*/);
7958 sp = stzalloc(sizeof(*sp));
7961 exparg.lastp = &sp->next;
7963 *exparg.lastp = NULL;
7965 *arglist->lastp = exparg.list;
7966 arglist->lastp = exparg.lastp;
7974 * Expand shell variables and backquotes inside a here document.
7977 expandhere(union node *arg, int fd)
7979 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7980 full_write(fd, stackblock(), expdest - (char *)stackblock());
7984 * Returns true if the pattern matches the string.
7987 patmatch(char *pattern, const char *string)
7989 char *p = preglob(pattern, 0);
7990 int r = pmatch(p, string);
7991 //bb_error_msg("!fnmatch(pattern:'%s',str:'%s',0):%d", p, string, r);
7996 * See if a pattern matches in a case statement.
7999 casematch(union node *pattern, char *val)
8001 struct stackmark smark;
8004 setstackmark(&smark);
8005 argbackq = pattern->narg.backquote;
8006 STARTSTACKSTR(expdest);
8007 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
8008 STACKSTRNUL(expdest);
8010 result = patmatch(stackblock(), val);
8011 popstackmark(&smark);
8016 /* ============ find_command */
8020 int (*builtin)(int, char **) FAST_FUNC;
8021 /* unsigned flags; */
8023 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
8024 /* "regular" builtins always take precedence over commands,
8025 * regardless of PATH=....%builtin... position */
8026 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
8027 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
8030 smallint cmdtype; /* CMDxxx */
8033 /* index >= 0 for commands without path (slashes) */
8034 /* (TODO: what exactly does the value mean? PATH position?) */
8035 /* index == -1 for commands with slashes */
8036 /* index == (-2 - applet_no) for NOFORK applets */
8037 const struct builtincmd *cmd;
8038 struct funcnode *func;
8041 /* values of cmdtype */
8042 #define CMDUNKNOWN -1 /* no entry in table for command */
8043 #define CMDNORMAL 0 /* command is an executable program */
8044 #define CMDFUNCTION 1 /* command is a shell function */
8045 #define CMDBUILTIN 2 /* command is a shell builtin */
8047 /* action to find_command() */
8048 #define DO_ERR 0x01 /* prints errors */
8049 #define DO_ABS 0x02 /* checks absolute paths */
8050 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
8051 #define DO_ALTPATH 0x08 /* using alternate path */
8052 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
8054 static void find_command(char *, struct cmdentry *, int, const char *);
8057 /* ============ Hashing commands */
8060 * When commands are first encountered, they are entered in a hash table.
8061 * This ensures that a full path search will not have to be done for them
8062 * on each invocation.
8064 * We should investigate converting to a linear search, even though that
8065 * would make the command name "hash" a misnomer.
8069 struct tblentry *next; /* next entry in hash chain */
8070 union param param; /* definition of builtin function */
8071 smallint cmdtype; /* CMDxxx */
8072 char rehash; /* if set, cd done since entry created */
8073 char cmdname[1]; /* name of command */
8076 static struct tblentry **cmdtable;
8077 #define INIT_G_cmdtable() do { \
8078 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
8081 static int builtinloc = -1; /* index in path of %builtin, or -1 */
8085 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
8087 #if ENABLE_FEATURE_SH_STANDALONE
8088 if (applet_no >= 0) {
8089 if (APPLET_IS_NOEXEC(applet_no)) {
8093 popredir(/*drop:*/ 1);
8094 run_noexec_applet_and_exit(applet_no, cmd, argv);
8096 /* re-exec ourselves with the new arguments */
8097 execve(bb_busybox_exec_path, argv, envp);
8098 /* If they called chroot or otherwise made the binary no longer
8099 * executable, fall through */
8106 execve(cmd, argv, envp);
8107 } while (errno == EINTR);
8109 execve(cmd, argv, envp);
8112 if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
8113 /* Run "cmd" as a shell script:
8114 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
8115 * "If the execve() function fails with ENOEXEC, the shell
8116 * shall execute a command equivalent to having a shell invoked
8117 * with the command name as its first operand,
8118 * with any remaining arguments passed to the new shell"
8120 * That is, do not use $SHELL, user's shell, or /bin/sh;
8121 * just call ourselves.
8123 * Note that bash reads ~80 chars of the file, and if it sees
8124 * a zero byte before it sees newline, it doesn't try to
8125 * interpret it, but fails with "cannot execute binary file"
8126 * message and exit code 126. For one, this prevents attempts
8127 * to interpret foreign ELF binaries as shell scripts.
8129 argv[0] = (char*) cmd;
8130 cmd = bb_busybox_exec_path;
8131 /* NB: this is only possible because all callers of shellexec()
8132 * ensure that the argv[-1] slot exists!
8135 argv[0] = (char*) "ash";
8141 * Exec a program. Never returns. If you change this routine, you may
8142 * have to change the find_command routine as well.
8143 * argv[-1] must exist and be writable! See tryexec() for why.
8145 static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
8146 static void shellexec(char *prog, char **argv, const char *path, int idx)
8152 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
8154 envp = listvars(VEXPORT, VUNSET, /*strlist:*/ NULL, /*end:*/ NULL);
8155 if (strchr(prog, '/') != NULL
8156 #if ENABLE_FEATURE_SH_STANDALONE
8157 || (applet_no = find_applet_by_name(prog)) >= 0
8160 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
8161 if (applet_no >= 0) {
8162 /* We tried execing ourself, but it didn't work.
8163 * Maybe /proc/self/exe doesn't exist?
8172 while ((cmdname = path_advance(&path, prog)) != NULL) {
8173 if (--idx < 0 && pathopt == NULL) {
8174 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
8175 if (errno != ENOENT && errno != ENOTDIR)
8182 /* Map to POSIX errors */
8194 exitstatus = exerrno;
8195 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
8196 prog, e, suppress_int));
8197 ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
8202 printentry(struct tblentry *cmdp)
8208 idx = cmdp->param.index;
8211 name = path_advance(&path, cmdp->cmdname);
8213 } while (--idx >= 0);
8214 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
8218 * Clear out command entries. The argument specifies the first entry in
8219 * PATH which has changed.
8222 clearcmdentry(int firstchange)
8224 struct tblentry **tblp;
8225 struct tblentry **pp;
8226 struct tblentry *cmdp;
8229 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
8231 while ((cmdp = *pp) != NULL) {
8232 if ((cmdp->cmdtype == CMDNORMAL &&
8233 cmdp->param.index >= firstchange)
8234 || (cmdp->cmdtype == CMDBUILTIN &&
8235 builtinloc >= firstchange)
8248 * Locate a command in the command hash table. If "add" is nonzero,
8249 * add the command to the table if it is not already present. The
8250 * variable "lastcmdentry" is set to point to the address of the link
8251 * pointing to the entry, so that delete_cmd_entry can delete the
8254 * Interrupts must be off if called with add != 0.
8256 static struct tblentry **lastcmdentry;
8258 static struct tblentry *
8259 cmdlookup(const char *name, int add)
8261 unsigned int hashval;
8263 struct tblentry *cmdp;
8264 struct tblentry **pp;
8267 hashval = (unsigned char)*p << 4;
8269 hashval += (unsigned char)*p++;
8271 pp = &cmdtable[hashval % CMDTABLESIZE];
8272 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8273 if (strcmp(cmdp->cmdname, name) == 0)
8277 if (add && cmdp == NULL) {
8278 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
8280 /* + 1 - already done because
8281 * tblentry::cmdname is char[1] */);
8282 /*cmdp->next = NULL; - ckzalloc did it */
8283 cmdp->cmdtype = CMDUNKNOWN;
8284 strcpy(cmdp->cmdname, name);
8291 * Delete the command entry returned on the last lookup.
8294 delete_cmd_entry(void)
8296 struct tblentry *cmdp;
8299 cmdp = *lastcmdentry;
8300 *lastcmdentry = cmdp->next;
8301 if (cmdp->cmdtype == CMDFUNCTION)
8302 freefunc(cmdp->param.func);
8308 * Add a new command entry, replacing any existing command entry for
8309 * the same name - except special builtins.
8312 addcmdentry(char *name, struct cmdentry *entry)
8314 struct tblentry *cmdp;
8316 cmdp = cmdlookup(name, 1);
8317 if (cmdp->cmdtype == CMDFUNCTION) {
8318 freefunc(cmdp->param.func);
8320 cmdp->cmdtype = entry->cmdtype;
8321 cmdp->param = entry->u;
8325 static int FAST_FUNC
8326 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8328 struct tblentry **pp;
8329 struct tblentry *cmdp;
8331 struct cmdentry entry;
8334 if (nextopt("r") != '\0') {
8339 if (*argptr == NULL) {
8340 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8341 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8342 if (cmdp->cmdtype == CMDNORMAL)
8350 while ((name = *argptr) != NULL) {
8351 cmdp = cmdlookup(name, 0);
8353 && (cmdp->cmdtype == CMDNORMAL
8354 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
8358 find_command(name, &entry, DO_ERR, pathval());
8359 if (entry.cmdtype == CMDUNKNOWN)
8367 * Called when a cd is done. Marks all commands so the next time they
8368 * are executed they will be rehashed.
8373 struct tblentry **pp;
8374 struct tblentry *cmdp;
8376 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8377 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8378 if (cmdp->cmdtype == CMDNORMAL
8379 || (cmdp->cmdtype == CMDBUILTIN
8380 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
8390 * Fix command hash table when PATH changed.
8391 * Called before PATH is changed. The argument is the new value of PATH;
8392 * pathval() still returns the old value at this point.
8393 * Called with interrupts off.
8395 static void FAST_FUNC
8396 changepath(const char *new)
8404 firstchange = 9999; /* assume no change */
8410 if ((*old == '\0' && *new == ':')
8411 || (*old == ':' && *new == '\0')
8415 old = new; /* ignore subsequent differences */
8419 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
8426 if (builtinloc < 0 && idx_bltin >= 0)
8427 builtinloc = idx_bltin; /* zap builtins */
8428 if (builtinloc >= 0 && idx_bltin < 0)
8430 clearcmdentry(firstchange);
8431 builtinloc = idx_bltin;
8467 typedef smallint token_id_t;
8469 /* Nth bit indicates if token marks the end of a list */
8472 /* 0 */ | (1u << TEOF)
8473 /* 1 */ | (0u << TNL)
8474 /* 2 */ | (0u << TREDIR)
8475 /* 3 */ | (0u << TWORD)
8476 /* 4 */ | (0u << TSEMI)
8477 /* 5 */ | (0u << TBACKGND)
8478 /* 6 */ | (0u << TAND)
8479 /* 7 */ | (0u << TOR)
8480 /* 8 */ | (0u << TPIPE)
8481 /* 9 */ | (0u << TLP)
8482 /* 10 */ | (1u << TRP)
8483 /* 11 */ | (1u << TENDCASE)
8484 /* 12 */ | (1u << TENDBQUOTE)
8485 /* 13 */ | (0u << TNOT)
8486 /* 14 */ | (0u << TCASE)
8487 /* 15 */ | (1u << TDO)
8488 /* 16 */ | (1u << TDONE)
8489 /* 17 */ | (1u << TELIF)
8490 /* 18 */ | (1u << TELSE)
8491 /* 19 */ | (1u << TESAC)
8492 /* 20 */ | (1u << TFI)
8493 /* 21 */ | (0u << TFOR)
8495 /* 22 */ | (0u << TFUNCTION)
8497 /* 23 */ | (0u << TIF)
8498 /* 24 */ | (0u << TIN)
8499 /* 25 */ | (1u << TTHEN)
8500 /* 26 */ | (0u << TUNTIL)
8501 /* 27 */ | (0u << TWHILE)
8502 /* 28 */ | (0u << TBEGIN)
8503 /* 29 */ | (1u << TEND)
8504 , /* thus far 29 bits used */
8507 static const char *const tokname_array[] = {
8521 #define KWDOFFSET 13
8522 /* the following are keywords */
8544 /* Wrapper around strcmp for qsort/bsearch/... */
8546 pstrcmp(const void *a, const void *b)
8548 return strcmp((char*)a, *(char**)b);
8551 static const char *const *
8552 findkwd(const char *s)
8554 return bsearch(s, tokname_array + KWDOFFSET,
8555 ARRAY_SIZE(tokname_array) - KWDOFFSET,
8556 sizeof(tokname_array[0]), pstrcmp);
8560 * Locate and print what a word is...
8563 describe_command(char *command, const char *path, int describe_command_verbose)
8565 struct cmdentry entry;
8566 #if ENABLE_ASH_ALIAS
8567 const struct alias *ap;
8570 path = path ? path : pathval();
8572 if (describe_command_verbose) {
8576 /* First look at the keywords */
8577 if (findkwd(command)) {
8578 out1str(describe_command_verbose ? " is a shell keyword" : command);
8582 #if ENABLE_ASH_ALIAS
8583 /* Then look at the aliases */
8584 ap = lookupalias(command, 0);
8586 if (!describe_command_verbose) {
8591 out1fmt(" is an alias for %s", ap->val);
8596 find_command(command, &entry, DO_ABS, path);
8598 switch (entry.cmdtype) {
8600 int j = entry.u.index;
8606 p = path_advance(&path, command);
8610 if (describe_command_verbose) {
8611 out1fmt(" is %s", p);
8619 if (describe_command_verbose) {
8620 /*out1str(" is a shell function");*/
8621 out1str(" is a function"); /* bash says this */
8628 if (describe_command_verbose) {
8629 out1fmt(" is a %sshell builtin",
8630 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8631 "special " : nullstr
8639 if (describe_command_verbose) {
8640 out1str(": not found\n");
8649 static int FAST_FUNC
8650 typecmd(int argc UNUSED_PARAM, char **argv)
8656 /* type -p ... ? (we don't bother checking for 'p') */
8657 if (argv[1] && argv[1][0] == '-') {
8662 err |= describe_command(argv[i++], NULL, verbose);
8667 #if ENABLE_ASH_CMDCMD
8668 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8670 parse_command_args(char **argv, const char **path)
8683 if (c == '-' && !*cp) {
8691 *path = bb_default_path;
8694 /* run 'typecmd' for other options */
8703 static int FAST_FUNC
8704 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8712 const char *path = NULL;
8714 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8715 * never reaches this function.
8718 while ((c = nextopt("pvV")) != '\0')
8720 verify |= VERIFY_VERBOSE;
8722 /*verify |= VERIFY_BRIEF*/;
8728 path = bb_default_path;
8730 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8732 if (/*verify && */ cmd)
8733 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8740 /*static int funcblocksize; // size of structures in function */
8741 /*static int funcstringsize; // size of strings in node */
8742 static void *funcblock; /* block to allocate function from */
8743 static char *funcstring_end; /* end of block to allocate strings from */
8745 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8746 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8747 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8748 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8749 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8750 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8751 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8752 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8753 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8754 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8755 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8756 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8757 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8758 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8759 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8760 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8761 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8762 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8763 #if BASH_REDIR_OUTPUT
8764 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8766 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8767 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8768 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8769 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8770 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8771 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8772 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8773 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8774 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8777 static int calcsize(int funcblocksize, union node *n);
8780 sizenodelist(int funcblocksize, struct nodelist *lp)
8783 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8784 funcblocksize = calcsize(funcblocksize, lp->n);
8787 return funcblocksize;
8791 calcsize(int funcblocksize, union node *n)
8794 return funcblocksize;
8795 funcblocksize += nodesize[n->type];
8798 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8799 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8800 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8803 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8808 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8809 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8816 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8817 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8820 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8821 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8822 funcblocksize = calcsize(funcblocksize, n->nif.test);
8825 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8826 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8827 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8830 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8831 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8834 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8835 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8836 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8839 funcblocksize = calcsize(funcblocksize, n->ndefun.body);
8840 funcblocksize += SHELL_ALIGN(strlen(n->ndefun.text) + 1);
8843 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8844 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8845 funcblocksize = calcsize(funcblocksize, n->narg.next);
8848 #if BASH_REDIR_OUTPUT
8855 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8856 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8860 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8861 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8865 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8866 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8869 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8872 return funcblocksize;
8876 nodeckstrdup(char *s)
8878 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8879 return strcpy(funcstring_end, s);
8882 static union node *copynode(union node *);
8884 static struct nodelist *
8885 copynodelist(struct nodelist *lp)
8887 struct nodelist *start;
8888 struct nodelist **lpp;
8893 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8894 (*lpp)->n = copynode(lp->n);
8896 lpp = &(*lpp)->next;
8903 copynode(union node *n)
8910 funcblock = (char *) funcblock + nodesize[n->type];
8914 new->ncmd.redirect = copynode(n->ncmd.redirect);
8915 new->ncmd.args = copynode(n->ncmd.args);
8916 new->ncmd.assign = copynode(n->ncmd.assign);
8917 new->ncmd.linno = n->ncmd.linno;
8920 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8921 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8926 new->nredir.redirect = copynode(n->nredir.redirect);
8927 new->nredir.n = copynode(n->nredir.n);
8928 new->nredir.linno = n->nredir.linno;
8935 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8936 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8939 new->nif.elsepart = copynode(n->nif.elsepart);
8940 new->nif.ifpart = copynode(n->nif.ifpart);
8941 new->nif.test = copynode(n->nif.test);
8944 new->nfor.var = nodeckstrdup(n->nfor.var);
8945 new->nfor.body = copynode(n->nfor.body);
8946 new->nfor.args = copynode(n->nfor.args);
8947 new->nfor.linno = n->nfor.linno;
8950 new->ncase.cases = copynode(n->ncase.cases);
8951 new->ncase.expr = copynode(n->ncase.expr);
8952 new->ncase.linno = n->ncase.linno;
8955 new->nclist.body = copynode(n->nclist.body);
8956 new->nclist.pattern = copynode(n->nclist.pattern);
8957 new->nclist.next = copynode(n->nclist.next);
8960 new->ndefun.body = copynode(n->ndefun.body);
8961 new->ndefun.text = nodeckstrdup(n->ndefun.text);
8962 new->ndefun.linno = n->ndefun.linno;
8965 new->narg.backquote = copynodelist(n->narg.backquote);
8966 new->narg.text = nodeckstrdup(n->narg.text);
8967 new->narg.next = copynode(n->narg.next);
8970 #if BASH_REDIR_OUTPUT
8977 new->nfile.fname = copynode(n->nfile.fname);
8978 new->nfile.fd = n->nfile.fd;
8979 new->nfile.next = copynode(n->nfile.next);
8983 new->ndup.vname = copynode(n->ndup.vname);
8984 new->ndup.dupfd = n->ndup.dupfd;
8985 new->ndup.fd = n->ndup.fd;
8986 new->ndup.next = copynode(n->ndup.next);
8990 new->nhere.doc = copynode(n->nhere.doc);
8991 new->nhere.fd = n->nhere.fd;
8992 new->nhere.next = copynode(n->nhere.next);
8995 new->nnot.com = copynode(n->nnot.com);
8998 new->type = n->type;
9003 * Make a copy of a parse tree.
9005 static struct funcnode *
9006 copyfunc(union node *n)
9011 /*funcstringsize = 0;*/
9012 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
9013 f = ckzalloc(blocksize /* + funcstringsize */);
9014 funcblock = (char *) f + offsetof(struct funcnode, n);
9015 funcstring_end = (char *) f + blocksize;
9017 /* f->count = 0; - ckzalloc did it */
9022 * Define a shell function.
9025 defun(union node *func)
9027 struct cmdentry entry;
9030 entry.cmdtype = CMDFUNCTION;
9031 entry.u.func = copyfunc(func);
9032 addcmdentry(func->ndefun.text, &entry);
9036 /* Reasons for skipping commands (see comment on breakcmd routine) */
9037 #define SKIPBREAK (1 << 0)
9038 #define SKIPCONT (1 << 1)
9039 #define SKIPFUNC (1 << 2)
9040 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
9041 static int skipcount; /* number of levels to skip */
9042 static int loopnest; /* current loop nesting level */
9043 static int funcline; /* starting line number of current function, or 0 if not in a function */
9045 /* Forward decl way out to parsing code - dotrap needs it */
9046 static int evalstring(char *s, int flags);
9048 /* Called to execute a trap.
9049 * Single callsite - at the end of evaltree().
9050 * If we return non-zero, evaltree raises EXEXIT exception.
9052 * Perhaps we should avoid entering new trap handlers
9053 * while we are executing a trap handler. [is it a TODO?]
9060 int status, last_status;
9065 status = savestatus;
9066 last_status = status;
9068 status = exitstatus;
9069 savestatus = status;
9074 TRACE(("dotrap entered\n"));
9075 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
9087 /* non-trapped SIGINT is handled separately by raise_interrupt,
9088 * don't upset it by resetting gotsig[SIGINT-1] */
9089 if (sig == SIGINT && !p)
9092 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
9097 exitstatus = status;
9100 savestatus = last_status;
9101 TRACE(("dotrap returns\n"));
9104 /* forward declarations - evaluation is fairly recursive business... */
9105 static int evalloop(union node *, int);
9106 static int evalfor(union node *, int);
9107 static int evalcase(union node *, int);
9108 static int evalsubshell(union node *, int);
9109 static void expredir(union node *);
9110 static int evalpipe(union node *, int);
9111 static int evalcommand(union node *, int);
9112 static int evalbltin(const struct builtincmd *, int, char **, int);
9113 static void prehash(union node *);
9116 * Evaluate a parse tree. The value is left in the global variable
9120 evaltree(union node *n, int flags)
9123 int (*evalfn)(union node *, int);
9124 struct stackmark smark;
9127 setstackmark(&smark);
9130 TRACE(("evaltree(NULL) called\n"));
9133 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
9140 out1fmt("Node type = %d\n", n->type);
9145 status = !evaltree(n->nnot.com, EV_TESTED);
9148 errlinno = lineno = n->nredir.linno;
9150 lineno -= funcline - 1;
9151 expredir(n->nredir.redirect);
9152 pushredir(n->nredir.redirect);
9153 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
9155 status = evaltree(n->nredir.n, flags & EV_TESTED);
9157 if (n->nredir.redirect)
9158 popredir(/*drop:*/ 0);
9161 evalfn = evalcommand;
9163 if (eflag && !(flags & EV_TESTED))
9175 evalfn = evalsubshell;
9188 #error NAND + 1 != NOR
9190 #if NOR + 1 != NSEMI
9191 #error NOR + 1 != NSEMI
9193 unsigned is_or = n->type - NAND;
9196 (flags | ((is_or >> 1) - 1)) & EV_TESTED
9198 if ((!status) == is_or || evalskip)
9204 status = evalfn(n, flags);
9208 status = evaltree(n->nif.test, EV_TESTED);
9215 if (n->nif.elsepart) {
9216 n = n->nif.elsepart;
9223 /* Not necessary. To test it:
9224 * "false; f() { qwerty; }; echo $?" should print 0.
9228 exitstatus = status;
9232 /* Order of checks below is important:
9233 * signal handlers trigger before exit caused by "set -e".
9237 if (checkexit & status)
9238 raise_exception(EXEXIT);
9239 if (flags & EV_EXIT)
9240 raise_exception(EXEXIT);
9242 popstackmark(&smark);
9243 TRACE(("leaving evaltree (no interrupts)\n"));
9250 int skip = evalskip;
9257 if (--skipcount <= 0) {
9268 evalloop(union node *n, int flags)
9279 i = evaltree(n->nbinary.ch1, EV_TESTED);
9281 if (skip == SKIPFUNC)
9285 if (n->type != NWHILE)
9289 status = evaltree(n->nbinary.ch2, flags);
9291 } while (!(skip & ~SKIPCONT));
9298 evalfor(union node *n, int flags)
9300 struct arglist arglist;
9305 errlinno = lineno = n->ncase.linno;
9307 lineno -= funcline - 1;
9309 arglist.list = NULL;
9310 arglist.lastp = &arglist.list;
9311 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
9312 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9314 *arglist.lastp = NULL;
9318 for (sp = arglist.list; sp; sp = sp->next) {
9319 setvar0(n->nfor.var, sp->text);
9320 status = evaltree(n->nfor.body, flags);
9321 if (skiploop() & ~SKIPCONT)
9330 evalcase(union node *n, int flags)
9334 struct arglist arglist;
9337 errlinno = lineno = n->ncase.linno;
9339 lineno -= funcline - 1;
9341 arglist.list = NULL;
9342 arglist.lastp = &arglist.list;
9343 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
9344 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
9345 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
9346 if (casematch(patp, arglist.list->text)) {
9347 /* Ensure body is non-empty as otherwise
9348 * EV_EXIT may prevent us from setting the
9351 if (evalskip == 0 && cp->nclist.body) {
9352 status = evaltree(cp->nclist.body, flags);
9363 * Kick off a subshell to evaluate a tree.
9366 evalsubshell(union node *n, int flags)
9369 int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
9372 errlinno = lineno = n->nredir.linno;
9374 lineno -= funcline - 1;
9376 expredir(n->nredir.redirect);
9377 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
9380 if (backgnd == FORK_FG)
9382 jp = makejob(/*n,*/ 1);
9383 if (forkshell(jp, n, backgnd) == 0) {
9388 flags &= ~EV_TESTED;
9390 redirect(n->nredir.redirect, 0);
9391 evaltreenr(n->nredir.n, flags);
9396 if (backgnd == FORK_FG)
9397 status = waitforjob(jp);
9403 * Compute the names of the files in a redirection list.
9405 static void fixredir(union node *, const char *, int);
9407 expredir(union node *n)
9411 for (redir = n; redir; redir = redir->nfile.next) {
9415 fn.lastp = &fn.list;
9416 switch (redir->type) {
9420 #if BASH_REDIR_OUTPUT
9425 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
9426 TRACE(("expredir expanded to '%s'\n", fn.list->text));
9427 #if BASH_REDIR_OUTPUT
9431 // By the design of stack allocator, the loop of this kind:
9432 // while true; do while true; do break; done </dev/null; done
9433 // will look like a memory leak: ash plans to free expfname's
9434 // of "/dev/null" as soon as it finishes running the loop
9435 // (in this case, never).
9436 // This "fix" is wrong:
9437 if (redir->nfile.expfname)
9438 stunalloc(redir->nfile.expfname);
9439 // It results in corrupted state of stacked allocations.
9441 redir->nfile.expfname = fn.list->text;
9444 case NTOFD: /* >& */
9445 if (redir->ndup.vname) {
9446 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
9447 if (fn.list == NULL)
9448 ash_msg_and_raise_error("redir error");
9449 #if BASH_REDIR_OUTPUT
9450 //FIXME: we used expandarg with different args!
9451 if (!isdigit_str9(fn.list->text)) {
9452 /* >&file, not >&fd */
9453 if (redir->nfile.fd != 1) /* 123>&file - BAD */
9454 ash_msg_and_raise_error("redir error");
9456 goto store_expfname;
9459 fixredir(redir, fn.list->text, 1);
9467 * Evaluate a pipeline. All the processes in the pipeline are children
9468 * of the process creating the pipeline. (This differs from some versions
9469 * of the shell, which make the last process in a pipeline the parent
9473 evalpipe(union node *n, int flags)
9476 struct nodelist *lp;
9482 TRACE(("evalpipe(0x%lx) called\n", (long)n));
9484 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
9488 if (n->npipe.pipe_backgnd == 0)
9490 jp = makejob(/*n,*/ pipelen);
9492 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
9496 if (pipe(pip) < 0) {
9498 ash_msg_and_raise_perror("can't create pipe");
9501 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
9515 evaltreenr(lp->n, flags);
9522 /* Don't want to trigger debugging */
9526 if (n->npipe.pipe_backgnd == 0) {
9527 status = waitforjob(jp);
9528 TRACE(("evalpipe: job done exit status %d\n", status));
9535 /* setinteractive needs this forward reference */
9536 #if EDITING_HAS_get_exe_name
9537 static const char *get_builtin_name(int i) FAST_FUNC;
9541 * Controls whether the shell is interactive or not.
9544 setinteractive(int on)
9546 static smallint is_interactive;
9548 if (++on == is_interactive)
9550 is_interactive = on;
9554 if (is_interactive > 1) {
9555 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9556 /* Looks like they want an interactive shell */
9557 static smallint did_banner;
9560 /* note: ash and hush share this string */
9561 out1fmt("\n\n%s %s\n"
9562 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
9565 "built-in shell (ash)"
9570 #if ENABLE_FEATURE_EDITING
9571 if (!line_input_state) {
9572 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
9573 # if EDITING_HAS_get_exe_name
9574 line_input_state->get_exe_name = get_builtin_name;
9587 setinteractive(iflag);
9589 #if ENABLE_FEATURE_EDITING_VI
9590 if (line_input_state) {
9592 line_input_state->flags |= VI_MODE;
9594 line_input_state->flags &= ~VI_MODE;
9597 viflag = 0; /* forcibly keep the option off */
9601 struct localvar_list {
9602 struct localvar_list *next;
9603 struct localvar *lv;
9606 static struct localvar_list *localvar_stack;
9609 * Called after a function returns.
9610 * Interrupts must be off.
9613 poplocalvars(int keep)
9615 struct localvar_list *ll;
9616 struct localvar *lvp, *next;
9620 ll = localvar_stack;
9621 localvar_stack = ll->next;
9626 while ((lvp = next) != NULL) {
9629 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9631 int bits = VSTRFIXED;
9633 if (lvp->flags != VUNSET) {
9634 if (vp->var_text == lvp->text)
9636 else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
9637 free((char*)lvp->text);
9641 vp->flags |= (lvp->flags & bits);
9644 (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
9645 unsetvar(vp->var_text);
9646 } else if (vp == NULL) { /* $- saved */
9647 memcpy(optlist, lvp->text, sizeof(optlist));
9648 free((char*)lvp->text);
9650 } else if (lvp->flags == VUNSET) {
9651 vp->flags &= ~(VSTRFIXED|VREADONLY);
9652 unsetvar(vp->var_text);
9655 vp->var_func(var_end(lvp->text));
9656 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9657 free((char*)vp->var_text);
9658 vp->flags = lvp->flags;
9659 vp->var_text = lvp->text;
9667 * Create a new localvar environment.
9669 static struct localvar_list *
9672 struct localvar_list *ll;
9675 ll = ckzalloc(sizeof(*ll));
9676 /*ll->lv = NULL; - zalloc did it */
9677 ll->next = localvar_stack;
9678 localvar_stack = ll;
9685 unwindlocalvars(struct localvar_list *stop)
9687 while (localvar_stack != stop)
9692 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9694 volatile struct shparam saveparam;
9695 struct jmploc *volatile savehandler;
9696 struct jmploc jmploc;
9700 saveparam = shellparam;
9701 savefuncline = funcline;
9702 savehandler = exception_handler;
9703 e = setjmp(jmploc.loc);
9708 exception_handler = &jmploc;
9709 shellparam.malloced = 0;
9711 funcline = func->n.ndefun.linno;
9713 shellparam.nparam = argc - 1;
9714 shellparam.p = argv + 1;
9715 #if ENABLE_ASH_GETOPTS
9716 shellparam.optind = 1;
9717 shellparam.optoff = -1;
9719 evaltree(func->n.ndefun.body, flags & EV_TESTED);
9722 funcline = savefuncline;
9724 freeparam(&shellparam);
9725 shellparam = saveparam;
9726 exception_handler = savehandler;
9728 evalskip &= ~SKIPFUNC;
9733 * Make a variable a local variable. When a variable is made local, it's
9734 * value and flags are saved in a localvar structure. The saved values
9735 * will be restored when the shell function returns. We handle the name
9736 * "-" as a special case: it makes changes to "set +-options" local
9737 * (options will be restored on return from the function).
9742 struct localvar *lvp;
9745 char *eq = strchr(name, '=');
9748 /* Cater for duplicate "local". Examples:
9749 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9750 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9752 lvp = localvar_stack->lv;
9754 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9758 * it's a duplicate "local VAR" declaration, do nothing
9765 lvp = ckzalloc(sizeof(*lvp));
9766 if (LONE_DASH(name)) {
9768 p = ckmalloc(sizeof(optlist));
9769 lvp->text = memcpy(p, optlist, sizeof(optlist));
9772 vpp = hashvar(name);
9773 vp = *findvar(vpp, name);
9775 /* variable did not exist yet */
9777 vp = setvareq(name, VSTRFIXED);
9779 vp = setvar(name, NULL, VSTRFIXED);
9780 lvp->flags = VUNSET;
9782 lvp->text = vp->var_text;
9783 lvp->flags = vp->flags;
9784 /* make sure neither "struct var" nor string gets freed
9785 * during (un)setting:
9787 vp->flags |= VSTRFIXED|VTEXTFIXED;
9791 /* "local VAR" unsets VAR: */
9792 setvar0(name, NULL);
9796 lvp->next = localvar_stack->lv;
9797 localvar_stack->lv = lvp;
9803 * The "local" command.
9805 static int FAST_FUNC
9806 localcmd(int argc UNUSED_PARAM, char **argv)
9810 if (!localvar_stack)
9811 ash_msg_and_raise_error("not in a function");
9814 while ((name = *argv++) != NULL) {
9820 static int FAST_FUNC
9821 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9826 static int FAST_FUNC
9827 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9832 static int FAST_FUNC
9833 execcmd(int argc UNUSED_PARAM, char **argv)
9836 while (nextopt("a:") != '\0')
9837 /* nextopt() sets optionarg to "-a ARGV0" */;
9843 iflag = 0; /* exit on error */
9846 /* We should set up signals for "exec CMD"
9847 * the same way as for "CMD" without "exec".
9848 * But optschanged->setinteractive->setsignal
9849 * still thought we are a root shell. Therefore, for example,
9850 * SIGQUIT is still set to IGN. Fix it:
9854 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9855 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9856 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9860 argv[0] = optionarg;
9861 shellexec(prog, argv, pathval(), 0);
9868 * The return command.
9870 static int FAST_FUNC
9871 returncmd(int argc UNUSED_PARAM, char **argv)
9874 * If called outside a function, do what ksh does;
9875 * skip the rest of the file.
9877 evalskip = SKIPFUNC;
9878 return argv[1] ? number(argv[1]) : exitstatus;
9881 /* Forward declarations for builtintab[] */
9882 static int breakcmd(int, char **) FAST_FUNC;
9883 static int dotcmd(int, char **) FAST_FUNC;
9884 static int evalcmd(int, char **, int) FAST_FUNC;
9885 static int exitcmd(int, char **) FAST_FUNC;
9886 static int exportcmd(int, char **) FAST_FUNC;
9887 #if ENABLE_ASH_GETOPTS
9888 static int getoptscmd(int, char **) FAST_FUNC;
9891 static int helpcmd(int, char **) FAST_FUNC;
9894 static int historycmd(int, char **) FAST_FUNC;
9896 #if ENABLE_FEATURE_SH_MATH
9897 static int letcmd(int, char **) FAST_FUNC;
9899 static int readcmd(int, char **) FAST_FUNC;
9900 static int setcmd(int, char **) FAST_FUNC;
9901 static int shiftcmd(int, char **) FAST_FUNC;
9902 static int timescmd(int, char **) FAST_FUNC;
9903 static int trapcmd(int, char **) FAST_FUNC;
9904 static int umaskcmd(int, char **) FAST_FUNC;
9905 static int unsetcmd(int, char **) FAST_FUNC;
9906 static int ulimitcmd(int, char **) FAST_FUNC;
9908 #define BUILTIN_NOSPEC "0"
9909 #define BUILTIN_SPECIAL "1"
9910 #define BUILTIN_REGULAR "2"
9911 #define BUILTIN_SPEC_REG "3"
9912 #define BUILTIN_ASSIGN "4"
9913 #define BUILTIN_SPEC_ASSG "5"
9914 #define BUILTIN_REG_ASSG "6"
9915 #define BUILTIN_SPEC_REG_ASSG "7"
9917 /* Stubs for calling non-FAST_FUNC's */
9919 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9921 #if ENABLE_ASH_PRINTF
9922 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9924 #if ENABLE_ASH_TEST || BASH_TEST2
9925 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9928 /* Keep these in proper order since it is searched via bsearch() */
9929 static const struct builtincmd builtintab[] = {
9930 { BUILTIN_SPEC_REG "." , dotcmd },
9931 { BUILTIN_SPEC_REG ":" , truecmd },
9933 { BUILTIN_REGULAR "[" , testcmd },
9936 { BUILTIN_REGULAR "[[" , testcmd },
9938 #if ENABLE_ASH_ALIAS
9939 { BUILTIN_REG_ASSG "alias" , aliascmd },
9942 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9944 { BUILTIN_SPEC_REG "break" , breakcmd },
9945 { BUILTIN_REGULAR "cd" , cdcmd },
9946 { BUILTIN_NOSPEC "chdir" , cdcmd },
9947 #if ENABLE_ASH_CMDCMD
9948 { BUILTIN_REGULAR "command" , commandcmd },
9950 { BUILTIN_SPEC_REG "continue", breakcmd },
9952 { BUILTIN_REGULAR "echo" , echocmd },
9954 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9955 { BUILTIN_SPEC_REG "exec" , execcmd },
9956 { BUILTIN_SPEC_REG "exit" , exitcmd },
9957 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9958 { BUILTIN_REGULAR "false" , falsecmd },
9960 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9962 #if ENABLE_ASH_GETOPTS
9963 { BUILTIN_REGULAR "getopts" , getoptscmd },
9965 { BUILTIN_REGULAR "hash" , hashcmd },
9967 { BUILTIN_NOSPEC "help" , helpcmd },
9970 { BUILTIN_NOSPEC "history" , historycmd },
9973 { BUILTIN_REGULAR "jobs" , jobscmd },
9974 { BUILTIN_REGULAR "kill" , killcmd },
9976 #if ENABLE_FEATURE_SH_MATH
9977 { BUILTIN_NOSPEC "let" , letcmd },
9979 { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
9980 #if ENABLE_ASH_PRINTF
9981 { BUILTIN_REGULAR "printf" , printfcmd },
9983 { BUILTIN_REGULAR "pwd" , pwdcmd },
9984 { BUILTIN_REGULAR "read" , readcmd },
9985 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9986 { BUILTIN_SPEC_REG "return" , returncmd },
9987 { BUILTIN_SPEC_REG "set" , setcmd },
9988 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9990 { BUILTIN_SPEC_REG "source" , dotcmd },
9993 { BUILTIN_REGULAR "test" , testcmd },
9995 { BUILTIN_SPEC_REG "times" , timescmd },
9996 { BUILTIN_SPEC_REG "trap" , trapcmd },
9997 { BUILTIN_REGULAR "true" , truecmd },
9998 { BUILTIN_REGULAR "type" , typecmd },
9999 { BUILTIN_REGULAR "ulimit" , ulimitcmd },
10000 { BUILTIN_REGULAR "umask" , umaskcmd },
10001 #if ENABLE_ASH_ALIAS
10002 { BUILTIN_REGULAR "unalias" , unaliascmd },
10004 { BUILTIN_SPEC_REG "unset" , unsetcmd },
10005 { BUILTIN_REGULAR "wait" , waitcmd },
10008 /* Should match the above table! */
10009 #define COMMANDCMD (builtintab + \
10011 /* [ */ 1 * ENABLE_ASH_TEST + \
10012 /* [[ */ 1 * BASH_TEST2 + \
10013 /* alias */ 1 * ENABLE_ASH_ALIAS + \
10014 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
10015 /* break cd cddir */ 3)
10016 #define EVALCMD (COMMANDCMD + \
10017 /* command */ 1 * ENABLE_ASH_CMDCMD + \
10018 /* continue */ 1 + \
10019 /* echo */ 1 * ENABLE_ASH_ECHO + \
10021 #define EXECCMD (EVALCMD + \
10025 * Search the table of builtin commands.
10028 pstrcmp1(const void *a, const void *b)
10030 return strcmp((char*)a, *(char**)b + 1);
10032 static struct builtincmd *
10033 find_builtin(const char *name)
10035 struct builtincmd *bp;
10038 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
10044 #if EDITING_HAS_get_exe_name
10045 static const char * FAST_FUNC
10046 get_builtin_name(int i)
10048 return /*i >= 0 &&*/ i < ARRAY_SIZE(builtintab) ? builtintab[i].name + 1 : NULL;
10053 * Execute a simple command.
10055 static void unwindfiles(struct parsefile *stop);
10057 isassignment(const char *p)
10059 const char *q = endofname(p);
10064 static int FAST_FUNC
10065 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10067 /* Preserve exitstatus of a previous possible redirection
10068 * as POSIX mandates */
10069 return back_exitstatus;
10072 evalcommand(union node *cmd, int flags)
10074 static const struct builtincmd null_bltin = {
10075 "\0\0", bltincmd /* why three NULs? */
10077 struct localvar_list *localvar_stop;
10078 struct parsefile *file_stop;
10079 struct redirtab *redir_stop;
10081 struct arglist arglist;
10082 struct arglist varlist;
10085 const struct strlist *sp;
10086 struct cmdentry cmdentry;
10093 smallint cmd_is_exec;
10095 errlinno = lineno = cmd->ncmd.linno;
10097 lineno -= funcline - 1;
10099 /* First expand the arguments. */
10100 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
10101 localvar_stop = pushlocalvars();
10102 file_stop = g_parsefile;
10103 back_exitstatus = 0;
10105 cmdentry.cmdtype = CMDBUILTIN;
10106 cmdentry.u.cmd = &null_bltin;
10107 varlist.lastp = &varlist.list;
10108 *varlist.lastp = NULL;
10109 arglist.lastp = &arglist.list;
10110 *arglist.lastp = NULL;
10113 if (cmd->ncmd.args) {
10114 struct builtincmd *bcmd;
10115 smallint pseudovarflag;
10117 bcmd = find_builtin(cmd->ncmd.args->narg.text);
10118 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
10120 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
10121 struct strlist **spp;
10123 spp = arglist.lastp;
10124 if (pseudovarflag && isassignment(argp->narg.text))
10125 expandarg(argp, &arglist, EXP_VARTILDE);
10127 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
10129 for (sp = *spp; sp; sp = sp->next)
10134 /* Reserve one extra spot at the front for shellexec. */
10135 nargv = stalloc(sizeof(char *) * (argc + 2));
10137 for (sp = arglist.list; sp; sp = sp->next) {
10138 TRACE(("evalcommand arg: %s\n", sp->text));
10139 *nargv++ = sp->text;
10144 if (iflag && funcline == 0 && argc > 0)
10145 lastarg = nargv[-1];
10147 expredir(cmd->ncmd.redirect);
10148 redir_stop = pushredir(cmd->ncmd.redirect);
10150 if (BASH_XTRACEFD && xflag) {
10151 /* NB: bash closes fd == $BASH_XTRACEFD when it is changed.
10152 * we do not emulate this. We only use its value.
10154 const char *xtracefd = lookupvar("BASH_XTRACEFD");
10155 if (xtracefd && is_number(xtracefd))
10156 preverrout_fd = atoi(xtracefd);
10159 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
10161 path = vpath.var_text;
10162 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
10163 struct strlist **spp;
10166 spp = varlist.lastp;
10167 expandarg(argp, &varlist, EXP_VARTILDE);
10169 mklocal((*spp)->text);
10172 * Modify the command lookup path, if a PATH= assignment
10176 if (varcmp(p, path) == 0)
10180 /* Print the command if xflag is set. */
10182 const char *pfx = "";
10184 fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
10188 char *varval = sp->text;
10189 char *eq = strchrnul(varval, '=');
10192 fdprintf(preverrout_fd, "%s%.*s%s",
10194 (int)(eq - varval), varval,
10195 maybe_single_quote(eq)
10203 fdprintf(preverrout_fd, "%s%s",
10205 /* always quote if matches reserved word: */
10207 ? single_quote(sp->text)
10208 : maybe_single_quote(sp->text)
10213 safe_write(preverrout_fd, "\n", 1);
10219 /* Now locate the command. */
10221 int cmd_flag = DO_ERR;
10222 #if ENABLE_ASH_CMDCMD
10223 const char *oldpath = path + 5;
10227 find_command(argv[0], &cmdentry, cmd_flag, path);
10228 if (cmdentry.cmdtype == CMDUNKNOWN) {
10229 flush_stdout_stderr();
10234 /* implement bltin and command here */
10235 if (cmdentry.cmdtype != CMDBUILTIN)
10238 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
10239 if (cmdentry.u.cmd == EXECCMD)
10241 #if ENABLE_ASH_CMDCMD
10242 if (cmdentry.u.cmd == COMMANDCMD) {
10244 nargv = parse_command_args(argv, &path);
10247 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
10248 * nargv => "PROG". path is updated if -p.
10250 argc -= nargv - argv;
10252 cmd_flag |= DO_NOFUNC;
10261 exitstatus = status;
10263 /* We have a redirection error. */
10265 raise_exception(EXERROR);
10270 /* Execute the command. */
10271 switch (cmdentry.cmdtype) {
10274 #if ENABLE_FEATURE_SH_STANDALONE \
10275 && ENABLE_FEATURE_SH_NOFORK \
10277 /* (1) BUG: if variables are set, we need to fork, or save/restore them
10278 * around run_nofork_applet() call.
10279 * (2) Should this check also be done in forkshell()?
10280 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
10282 /* find_command() encodes applet_no as (-2 - applet_no) */
10283 int applet_no = (- cmdentry.u.index - 2);
10284 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
10288 sv_environ = environ;
10289 environ = listvars(VEXPORT, VUNSET, varlist.list, /*end:*/ NULL);
10291 * Run <applet>_main().
10292 * Signals (^C) can't interrupt here.
10293 * Otherwise we can mangle stdio or malloc internal state.
10294 * This makes applets which can run for a long time
10295 * and/or wait for user input ineligible for NOFORK:
10296 * for example, "yes" or "rm" (rm -i waits for input).
10298 status = run_nofork_applet(applet_no, argv);
10299 environ = sv_environ;
10301 * Try enabling NOFORK for "yes" applet.
10302 * ^C _will_ stop it (write returns EINTR),
10303 * but this causes stdout FILE to be stuck
10304 * and needing clearerr(). What if other applets
10305 * also can get EINTRs? Do we need to switch
10306 * our signals to SA_RESTART?
10308 /*clearerr(stdout);*/
10313 /* Can we avoid forking? For example, very last command
10314 * in a script or a subshell does not need forking,
10315 * we can just exec it.
10317 if (!(flags & EV_EXIT) || may_have_traps) {
10318 /* No, forking off a child is necessary */
10321 jp = makejob(/*cmd,*/ 1);
10322 if (forkshell(jp, cmd, FORK_FG) != 0) {
10324 status = waitforjob(jp);
10326 TRACE(("forked child exited with %d\n", status));
10331 /* fall through to exec'ing external program */
10333 listsetvar(varlist.list, VEXPORT|VSTACK);
10334 shellexec(argv[0], argv, path, cmdentry.u.index);
10338 if (spclbltin > 0 || argc == 0) {
10340 if (cmd_is_exec && argc > 1)
10341 listsetvar(varlist.list, VEXPORT);
10344 /* Tight loop with builtins only:
10345 * "while kill -0 $child; do true; done"
10346 * will never exit even if $child died, unless we do this
10347 * to reap the zombie and make kill detect that it's gone: */
10348 dowait(DOWAIT_NONBLOCK, NULL);
10350 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
10351 if (exception_type == EXERROR && spclbltin <= 0) {
10356 longjmp(exception_handler->loc, 1);
10361 /* See above for the rationale */
10362 dowait(DOWAIT_NONBLOCK, NULL);
10363 if (evalfun(cmdentry.u.func, argc, argv, flags))
10366 status = exitstatus;
10371 if (cmd->ncmd.redirect)
10372 popredir(/*drop:*/ cmd_is_exec);
10373 unwindredir(redir_stop);
10374 unwindfiles(file_stop);
10375 unwindlocalvars(localvar_stop);
10377 /* dsl: I think this is intended to be used to support
10378 * '_' in 'vi' command mode during line editing...
10379 * However I implemented that within libedit itself.
10381 setvar0("_", lastarg);
10388 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
10390 char *volatile savecmdname;
10391 struct jmploc *volatile savehandler;
10392 struct jmploc jmploc;
10396 savecmdname = commandname;
10397 savehandler = exception_handler;
10398 i = setjmp(jmploc.loc);
10401 exception_handler = &jmploc;
10402 commandname = argv[0];
10404 optptr = NULL; /* initialize nextopt */
10405 if (cmd == EVALCMD)
10406 status = evalcmd(argc, argv, flags);
10408 status = (*cmd->builtin)(argc, argv);
10409 flush_stdout_stderr();
10410 status |= ferror(stdout);
10411 exitstatus = status;
10414 commandname = savecmdname;
10415 exception_handler = savehandler;
10421 goodname(const char *p)
10423 return endofname(p)[0] == '\0';
10428 * Search for a command. This is called before we fork so that the
10429 * location of the command will be available in the parent as well as
10430 * the child. The check for "goodname" is an overly conservative
10431 * check that the name will not be subject to expansion.
10434 prehash(union node *n)
10436 struct cmdentry entry;
10438 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
10439 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
10443 /* ============ Builtin commands
10445 * Builtin commands whose functions are closely tied to evaluation
10446 * are implemented here.
10450 * Handle break and continue commands. Break, continue, and return are
10451 * all handled by setting the evalskip flag. The evaluation routines
10452 * above all check this flag, and if it is set they start skipping
10453 * commands rather than executing them. The variable skipcount is
10454 * the number of loops to break/continue, or the number of function
10455 * levels to return. (The latter is always 1.) It should probably
10456 * be an error to break out of more loops than exist, but it isn't
10457 * in the standard shell so we don't make it one here.
10459 static int FAST_FUNC
10460 breakcmd(int argc UNUSED_PARAM, char **argv)
10462 int n = argv[1] ? number(argv[1]) : 1;
10465 ash_msg_and_raise_error(msg_illnum, argv[1]);
10469 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
10477 * This implements the input routines used by the parser.
10481 INPUT_PUSH_FILE = 1,
10482 INPUT_NOFILE_OK = 2,
10485 static smallint checkkwd;
10486 /* values of checkkwd variable */
10487 #define CHKALIAS 0x1
10490 #define CHKEOFMARK 0x8
10493 * Push a string back onto the input at this current parsefile level.
10494 * We handle aliases this way.
10496 #if !ENABLE_ASH_ALIAS
10497 #define pushstring(s, ap) pushstring(s)
10500 pushstring(char *s, struct alias *ap)
10502 struct strpush *sp;
10507 if (g_parsefile->strpush) {
10508 sp = ckzalloc(sizeof(*sp));
10509 sp->prev = g_parsefile->strpush;
10511 sp = &(g_parsefile->basestrpush);
10513 g_parsefile->strpush = sp;
10514 sp->prev_string = g_parsefile->next_to_pgetc;
10515 sp->prev_left_in_line = g_parsefile->left_in_line;
10516 sp->unget = g_parsefile->unget;
10517 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
10518 #if ENABLE_ASH_ALIAS
10521 ap->flag |= ALIASINUSE;
10525 g_parsefile->next_to_pgetc = s;
10526 g_parsefile->left_in_line = len;
10527 g_parsefile->unget = 0;
10534 struct strpush *sp = g_parsefile->strpush;
10537 #if ENABLE_ASH_ALIAS
10539 if (g_parsefile->next_to_pgetc[-1] == ' '
10540 || g_parsefile->next_to_pgetc[-1] == '\t'
10542 checkkwd |= CHKALIAS;
10544 if (sp->string != sp->ap->val) {
10547 sp->ap->flag &= ~ALIASINUSE;
10548 if (sp->ap->flag & ALIASDEAD) {
10549 unalias(sp->ap->name);
10553 g_parsefile->next_to_pgetc = sp->prev_string;
10554 g_parsefile->left_in_line = sp->prev_left_in_line;
10555 g_parsefile->unget = sp->unget;
10556 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
10557 g_parsefile->strpush = sp->prev;
10558 if (sp != &(g_parsefile->basestrpush))
10567 char *buf = g_parsefile->buf;
10569 g_parsefile->next_to_pgetc = buf;
10570 #if ENABLE_FEATURE_EDITING
10572 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
10573 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10575 # if ENABLE_ASH_IDLE_TIMEOUT
10577 const char *tmout_var = lookupvar("TMOUT");
10579 timeout = atoi(tmout_var) * 1000;
10583 line_input_state->timeout = timeout;
10585 # if ENABLE_FEATURE_TAB_COMPLETION
10586 line_input_state->path_lookup = pathval();
10588 reinit_unicode_for_ash();
10589 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ);
10591 /* ^C pressed, "convert" to SIGINT */
10592 write(STDOUT_FILENO, "^C", 2);
10593 if (trap[SIGINT]) {
10599 exitstatus = 128 + SIGINT;
10605 /* Ctrl+D pressed */
10608 # if ENABLE_ASH_IDLE_TIMEOUT
10609 else if (errno == EAGAIN && timeout > 0) {
10610 puts("\007timed out waiting for input: auto-logout");
10617 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10620 #if 0 /* disabled: nonblock_immune_read() handles this problem */
10622 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
10623 int flags = fcntl(0, F_GETFL);
10624 if (flags >= 0 && (flags & O_NONBLOCK)) {
10625 flags &= ~O_NONBLOCK;
10626 if (fcntl(0, F_SETFL, flags) >= 0) {
10627 out2str("sh: turning off NDELAY mode\n");
10638 * Refill the input buffer and return the next input character:
10640 * 1) If a string was pushed back on the input, pop it;
10641 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
10642 * or we are reading from a string so we can't refill the buffer,
10644 * 3) If there is more stuff in this buffer, use it else call read to fill it.
10645 * 4) Process input up to the next newline, deleting nul characters.
10647 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
10648 #define pgetc_debug(...) ((void)0)
10649 static int pgetc(void);
10656 if (g_parsefile->strpush) {
10657 #if ENABLE_ASH_ALIAS
10658 if (g_parsefile->left_in_line == -1
10659 && g_parsefile->strpush->ap
10660 && g_parsefile->next_to_pgetc[-1] != ' '
10661 && g_parsefile->next_to_pgetc[-1] != '\t'
10663 pgetc_debug("preadbuffer PEOA");
10670 /* on both branches above g_parsefile->left_in_line < 0.
10671 * "pgetc" needs refilling.
10674 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
10675 * pungetc() may increment it a few times.
10676 * Assuming it won't increment it to less than -90.
10678 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
10679 pgetc_debug("preadbuffer PEOF1");
10680 /* even in failure keep left_in_line and next_to_pgetc
10681 * in lock step, for correct multi-layer pungetc.
10682 * left_in_line was decremented before preadbuffer(),
10683 * must inc next_to_pgetc: */
10684 g_parsefile->next_to_pgetc++;
10688 more = g_parsefile->left_in_buffer;
10690 flush_stdout_stderr();
10694 /* don't try reading again */
10695 g_parsefile->left_in_line = -99;
10696 pgetc_debug("preadbuffer PEOF2");
10697 g_parsefile->next_to_pgetc++;
10702 /* Find out where's the end of line.
10703 * Set g_parsefile->left_in_line
10704 * and g_parsefile->left_in_buffer acordingly.
10705 * NUL chars are deleted.
10707 q = g_parsefile->next_to_pgetc;
10715 memmove(q, q + 1, more);
10719 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10725 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10726 if (g_parsefile->left_in_line < 0)
10731 g_parsefile->left_in_buffer = more;
10736 out2str(g_parsefile->next_to_pgetc);
10740 pgetc_debug("preadbuffer at %d:%p'%s'",
10741 g_parsefile->left_in_line,
10742 g_parsefile->next_to_pgetc,
10743 g_parsefile->next_to_pgetc);
10744 return (unsigned char)*g_parsefile->next_to_pgetc++;
10750 g_parsefile->linno++;
10751 setprompt_if(doprompt, 2);
10756 g_parsefile->linno++;
10757 needprompt = doprompt;
10765 pgetc_debug("pgetc at %d:%p'%s'",
10766 g_parsefile->left_in_line,
10767 g_parsefile->next_to_pgetc,
10768 g_parsefile->next_to_pgetc);
10769 if (g_parsefile->unget)
10770 return g_parsefile->lastc[--g_parsefile->unget];
10772 if (--g_parsefile->left_in_line >= 0)
10773 c = (unsigned char)*g_parsefile->next_to_pgetc++;
10777 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10778 g_parsefile->lastc[0] = c;
10783 #if ENABLE_ASH_ALIAS
10785 pgetc_without_PEOA(void)
10789 pgetc_debug("pgetc at %d:%p'%s'",
10790 g_parsefile->left_in_line,
10791 g_parsefile->next_to_pgetc,
10792 g_parsefile->next_to_pgetc);
10794 } while (c == PEOA);
10798 # define pgetc_without_PEOA() pgetc()
10802 * Undo a call to pgetc. Only two characters may be pushed back.
10803 * PEOF may be pushed back.
10808 g_parsefile->unget++;
10811 /* This one eats backslash+newline */
10817 while ((c = pgetc()) == '\\') {
10818 if (pgetc() != '\n') {
10831 uint8_t innerdq :1;
10832 uint8_t varpushed :1;
10833 uint8_t dblquote :1;
10834 int varnest; /* levels of variables expansion */
10835 int dqvarnest; /* levels of variables expansion within double quotes */
10836 int parenlevel; /* levels of parens in arithmetic */
10837 struct synstack *prev;
10838 struct synstack *next;
10842 pgetc_top(struct synstack *stack)
10844 return stack->syntax == SQSYNTAX ? pgetc() : pgetc_eatbnl();
10848 synstack_push(struct synstack **stack, struct synstack *next, int syntax)
10850 memset(next, 0, sizeof(*next));
10851 next->syntax = syntax;
10852 next->next = *stack;
10853 (*stack)->prev = next;
10857 static ALWAYS_INLINE void
10858 synstack_pop(struct synstack **stack)
10860 *stack = (*stack)->next;
10864 * To handle the "." command, a stack of input files is used. Pushfile
10865 * adds a new entry to the stack and popfile restores the previous level.
10870 struct parsefile *pf;
10872 pf = ckzalloc(sizeof(*pf));
10873 pf->prev = g_parsefile;
10875 /*pf->strpush = NULL; - ckzalloc did it */
10876 /*pf->basestrpush.prev = NULL;*/
10884 struct parsefile *pf = g_parsefile;
10890 if (pf->pf_fd >= 0)
10893 while (pf->strpush)
10895 g_parsefile = pf->prev;
10901 unwindfiles(struct parsefile *stop)
10903 while (g_parsefile != stop)
10908 * Return to top level.
10913 unwindfiles(&basepf);
10917 * Close the file(s) that the shell is reading commands from. Called
10918 * after a fork is done.
10924 if (g_parsefile->pf_fd > 0) {
10925 close(g_parsefile->pf_fd);
10926 g_parsefile->pf_fd = 0;
10931 * Like setinputfile, but takes an open file descriptor. Call this with
10935 setinputfd(int fd, int push)
10939 g_parsefile->buf = NULL;
10941 g_parsefile->pf_fd = fd;
10942 if (g_parsefile->buf == NULL)
10943 g_parsefile->buf = ckmalloc(IBUFSIZ);
10944 g_parsefile->left_in_buffer = 0;
10945 g_parsefile->left_in_line = 0;
10946 g_parsefile->linno = 1;
10950 * Set the input to take input from a file. If push is set, push the
10951 * old input onto the stack first.
10954 setinputfile(const char *fname, int flags)
10959 fd = open(fname, O_RDONLY | O_CLOEXEC);
10961 if (flags & INPUT_NOFILE_OK)
10964 ash_msg_and_raise_perror("can't open '%s'", fname);
10968 else if (O_CLOEXEC == 0) /* old libc */
10969 close_on_exec_on(fd);
10971 setinputfd(fd, flags & INPUT_PUSH_FILE);
10978 * Like setinputfile, but takes input from a string.
10981 setinputstring(char *string)
10985 g_parsefile->next_to_pgetc = string;
10986 g_parsefile->left_in_line = strlen(string);
10987 g_parsefile->buf = NULL;
10988 g_parsefile->linno = 1;
10994 * Routines to check for mail.
10997 #if ENABLE_ASH_MAIL
10999 /* Hash of mtimes of mailboxes */
11000 static unsigned mailtime_hash;
11001 /* Set if MAIL or MAILPATH is changed. */
11002 static smallint mail_var_path_changed;
11005 * Print appropriate message(s) if mail has arrived.
11006 * If mail_var_path_changed is set,
11007 * then the value of MAIL has mail_var_path_changed,
11008 * so we just update the values.
11017 struct stackmark smark;
11020 setstackmark(&smark);
11021 mpath = mpathset() ? mpathval() : mailval();
11024 p = path_advance(&mpath, nullstr);
11029 for (q = p; *q; q++)
11035 q[-1] = '\0'; /* delete trailing '/' */
11036 if (stat(p, &statb) < 0) {
11039 /* Very simplistic "hash": just a sum of all mtimes */
11040 new_hash += (unsigned)statb.st_mtime;
11042 if (!mail_var_path_changed && mailtime_hash != new_hash) {
11043 if (mailtime_hash != 0)
11044 out2str("you have mail\n");
11045 mailtime_hash = new_hash;
11047 mail_var_path_changed = 0;
11048 popstackmark(&smark);
11051 static void FAST_FUNC
11052 changemail(const char *val UNUSED_PARAM)
11054 mail_var_path_changed = 1;
11057 #endif /* ASH_MAIL */
11060 /* ============ ??? */
11063 * Set the shell parameters.
11066 setparam(char **argv)
11072 for (nparam = 0; argv[nparam]; nparam++)
11074 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
11076 *ap++ = ckstrdup(*argv++);
11079 freeparam(&shellparam);
11080 shellparam.malloced = 1;
11081 shellparam.nparam = nparam;
11082 shellparam.p = newparam;
11083 #if ENABLE_ASH_GETOPTS
11084 shellparam.optind = 1;
11085 shellparam.optoff = -1;
11090 * Process shell options. The global variable argptr contains a pointer
11091 * to the argument list; we advance it past the options.
11093 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
11094 * For a non-interactive shell, an error condition encountered
11095 * by a special built-in ... shall cause the shell to write a diagnostic message
11096 * to standard error and exit as shown in the following table:
11097 * Error Special Built-In
11099 * Utility syntax error (option or operand error) Shall exit
11101 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
11102 * we see that bash does not do that (set "finishes" with error code 1 instead,
11103 * and shell continues), and people rely on this behavior!
11105 * set -o barfoo 2>/dev/null
11108 * Oh well. Let's mimic that.
11111 plus_minus_o(char *name, int val)
11116 for (i = 0; i < NOPTS; i++) {
11117 if (strcmp(name, optnames(i)) == 0) {
11122 ash_msg("illegal option %co %s", val ? '-' : '+', name);
11125 for (i = 0; i < NOPTS; i++) {
11126 if (optnames(i)[0] == '\0')
11129 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
11131 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
11137 setoption(int flag, int val)
11141 for (i = 0; i < NOPTS; i++) {
11142 if (optletters(i) == flag && optnames(i)[0] != '\0') {
11147 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
11150 /* If login_sh is not NULL, we are called to parse command line opts,
11154 options(int *login_sh)
11162 while ((p = *argptr) != NULL) {
11164 if (c != '-' && c != '+')
11167 val = 0; /* val = 0 if c == '+' */
11170 if (p[0] == '\0' || LONE_DASH(p)) {
11172 /* "-" means turn off -x and -v */
11175 /* "--" means reset params */
11176 else if (*argptr == NULL)
11179 break; /* "-" or "--" terminates options */
11182 /* first char was + or - */
11183 while ((c = *p++) != '\0') {
11185 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
11187 minusc = p; /* command is after shell args */
11191 if (c == 's') { /* -s, +s */
11195 if (c == 'i') { /* -i, +i */
11200 *login_sh = 1; /* -l or +l == --login */
11203 /* bash does not accept +-login, we also won't */
11204 if (val && (c == '-')) { /* long options */
11205 if (strcmp(p, "login") == 0) {
11212 if (plus_minus_o(*argptr, val)) {
11213 /* it already printed err message */
11214 return 1; /* error */
11227 * The shift builtin command.
11229 static int FAST_FUNC
11230 shiftcmd(int argc UNUSED_PARAM, char **argv)
11237 n = number(argv[1]);
11238 if (n > shellparam.nparam)
11241 shellparam.nparam -= n;
11242 for (ap1 = shellparam.p; --n >= 0; ap1++) {
11243 if (shellparam.malloced)
11246 ap2 = shellparam.p;
11247 while ((*ap2++ = *ap1++) != NULL)
11249 #if ENABLE_ASH_GETOPTS
11250 shellparam.optind = 1;
11251 shellparam.optoff = -1;
11258 * POSIX requires that 'set' (but not export or readonly) output the
11259 * variables in lexicographic order - by the locale's collating order (sigh).
11260 * Maybe we could keep them in an ordered balanced binary tree
11261 * instead of hashed lists.
11262 * For now just roll 'em through qsort for printing...
11265 showvars(const char *sep_prefix, int on, int off)
11268 char **ep, **epend;
11270 ep = listvars(on, off, /*strlist:*/ NULL, &epend);
11271 qsort(ep, epend - ep, sizeof(char *), vpcmp);
11273 sep = *sep_prefix ? " " : sep_prefix;
11275 for (; ep < epend; ep++) {
11279 p = endofname(*ep);
11280 /* Used to have simple "p = strchrnul(*ep, '=')" here instead, but this
11281 * makes "export -p" to have output not suitable for "eval":
11283 * os.environ["test-test"]="test"
11284 * if os.fork() == 0:
11285 * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
11286 * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ])
11290 q = single_quote(++p);
11291 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
11297 * The set command builtin.
11299 static int FAST_FUNC
11300 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
11305 return showvars(nullstr, 0, VUNSET);
11308 retval = options(/*login_sh:*/ NULL);
11309 if (retval == 0) { /* if no parse error... */
11311 if (*argptr != NULL) {
11319 #if ENABLE_ASH_RANDOM_SUPPORT
11320 static void FAST_FUNC
11321 change_random(const char *value)
11325 if (value == NULL) {
11326 /* "get", generate */
11327 t = next_random(&random_gen);
11328 /* set without recursion */
11329 setvar(vrandom.var_text, utoa(t), VNOFUNC);
11330 vrandom.flags &= ~VNOFUNC;
11333 t = strtoul(value, NULL, 10);
11334 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
11339 #if BASH_EPOCH_VARS
11340 static void FAST_FUNC
11341 change_epoch(struct var *vepoch, const char *fmt)
11344 char buffer[sizeof("%lu.nnnnnn") + sizeof(long)*3];
11346 gettimeofday(&tv, NULL);
11347 sprintf(buffer, fmt, (unsigned long)tv.tv_sec, (unsigned)tv.tv_usec);
11348 setvar(vepoch->var_text, buffer, VNOFUNC);
11349 vepoch->flags &= ~VNOFUNC;
11352 static void FAST_FUNC
11353 change_seconds(const char *value UNUSED_PARAM)
11355 change_epoch(&vepochs, "%lu");
11358 static void FAST_FUNC
11359 change_realtime(const char *value UNUSED_PARAM)
11361 change_epoch(&vepochr, "%lu.%06u");
11365 #if ENABLE_ASH_GETOPTS
11367 getopts(char *optstr, char *optvar, char **optfirst)
11374 int ind = shellparam.optind;
11375 int off = shellparam.optoff;
11379 shellparam.optind = -1;
11380 optnext = optfirst + ind - 1;
11382 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
11385 p = optnext[-1] + off;
11386 if (p == NULL || *p == '\0') {
11387 /* Current word is done, advance */
11389 if (p == NULL || *p != '-' || *++p == '\0') {
11391 unsetvar("OPTARG");
11397 if (LONE_DASH(p)) /* check for "--" */
11402 for (q = optstr; *q != c;) {
11404 /* OPTERR is a bashism */
11405 const char *cp = lookupvar("OPTERR");
11406 if ((cp && LONE_CHAR(cp, '0'))
11407 || (optstr[0] == ':')
11410 /*sbuf[1] = '\0'; - already is */
11411 setvar0("OPTARG", sbuf);
11413 fprintf(stderr, "Illegal option -%c\n", c);
11414 unsetvar("OPTARG");
11424 if (*p == '\0' && (p = *optnext) == NULL) {
11425 /* OPTERR is a bashism */
11426 const char *cp = lookupvar("OPTERR");
11427 if ((cp && LONE_CHAR(cp, '0'))
11428 || (optstr[0] == ':')
11431 /*sbuf[1] = '\0'; - already is */
11432 setvar0("OPTARG", sbuf);
11435 fprintf(stderr, "No arg for -%c option\n", c);
11436 unsetvar("OPTARG");
11444 setvar0("OPTARG", p);
11447 setvar0("OPTARG", nullstr);
11449 ind = optnext - optfirst + 1;
11450 setvar("OPTIND", itoa(ind), VNOFUNC);
11452 /*sbuf[1] = '\0'; - already is */
11453 setvar0(optvar, sbuf);
11455 shellparam.optoff = p ? p - *(optnext - 1) : -1;
11456 shellparam.optind = ind;
11462 * The getopts builtin. Shellparam.optnext points to the next argument
11463 * to be processed. Shellparam.optptr points to the next character to
11464 * be processed in the current argument. If shellparam.optnext is NULL,
11465 * then it's the first time getopts has been called.
11467 static int FAST_FUNC
11468 getoptscmd(int argc, char **argv)
11473 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
11475 optbase = shellparam.p;
11476 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
11477 shellparam.optind = 1;
11478 shellparam.optoff = -1;
11481 optbase = &argv[3];
11482 if ((unsigned)shellparam.optind > argc - 2) {
11483 shellparam.optind = 1;
11484 shellparam.optoff = -1;
11488 return getopts(argv[1], argv[2], optbase);
11490 #endif /* ASH_GETOPTS */
11493 /* ============ Shell parser */
11496 struct heredoc *next; /* next here document in list */
11497 union node *here; /* redirection node */
11498 char *eofmark; /* string indicating end of input */
11499 smallint striptabs; /* if set, strip leading tabs */
11502 static smallint tokpushback; /* last token pushed back */
11503 static smallint quoteflag; /* set if (part of) last token was quoted */
11504 static token_id_t lasttoken; /* last token read (integer id Txxx) */
11505 static struct heredoc *heredoclist; /* list of here documents to read */
11506 static char *wordtext; /* text of last word returned by readtoken */
11507 static struct nodelist *backquotelist;
11508 static union node *redirnode;
11509 static struct heredoc *heredoc;
11511 static const char *
11512 tokname(char *buf, int tok)
11515 return tokname_array[tok];
11516 sprintf(buf, "\"%s\"", tokname_array[tok]);
11520 /* raise_error_unexpected_syntax:
11521 * Called when an unexpected token is read during the parse. The argument
11522 * is the token that is expected, or -1 if more than one type of token can
11523 * occur at this point.
11525 static void raise_error_unexpected_syntax(int) NORETURN;
11527 raise_error_unexpected_syntax(int token)
11533 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
11535 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
11536 raise_error_syntax(msg);
11540 /* parsing is heavily cross-recursive, need these forward decls */
11541 static union node *andor(void);
11542 static union node *pipeline(void);
11543 static union node *parse_command(void);
11544 static void parseheredoc(void);
11545 static int peektoken(void);
11546 static int readtoken(void);
11548 static union node *
11551 union node *n1, *n2, *n3;
11556 switch (peektoken()) {
11564 if (!n1 && (nlflag & 1))
11570 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11571 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
11577 if (tok == TBACKGND) {
11578 if (n2->type == NPIPE) {
11579 n2->npipe.pipe_backgnd = 1;
11581 if (n2->type != NREDIR) {
11582 n3 = stzalloc(sizeof(struct nredir));
11584 /*n3->nredir.redirect = NULL; - stzalloc did it */
11587 n2->type = NBACKGND;
11593 n3 = stzalloc(sizeof(struct nbinary));
11595 n3->nbinary.ch1 = n1;
11596 n3->nbinary.ch2 = n2;
11609 raise_error_unexpected_syntax(-1);
11616 static union node *
11619 union node *n1, *n2, *n3;
11627 } else if (t == TOR) {
11633 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11635 n3 = stzalloc(sizeof(struct nbinary));
11637 n3->nbinary.ch1 = n1;
11638 n3->nbinary.ch2 = n2;
11643 static union node *
11646 union node *n1, *n2, *pipenode;
11647 struct nodelist *lp, *prev;
11651 TRACE(("pipeline: entered\n"));
11652 if (readtoken() == TNOT) {
11654 checkkwd = CHKKWD | CHKALIAS;
11657 n1 = parse_command();
11658 if (readtoken() == TPIPE) {
11659 pipenode = stzalloc(sizeof(struct npipe));
11660 pipenode->type = NPIPE;
11661 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
11662 lp = stzalloc(sizeof(struct nodelist));
11663 pipenode->npipe.cmdlist = lp;
11667 lp = stzalloc(sizeof(struct nodelist));
11668 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11669 lp->n = parse_command();
11671 } while (readtoken() == TPIPE);
11677 n2 = stzalloc(sizeof(struct nnot));
11685 static union node *
11690 n = stzalloc(sizeof(struct narg));
11692 /*n->narg.next = NULL; - stzalloc did it */
11693 n->narg.text = wordtext;
11694 n->narg.backquote = backquotelist;
11699 fixredir(union node *n, const char *text, int err)
11703 TRACE(("Fix redir %s %d\n", text, err));
11705 n->ndup.vname = NULL;
11707 fd = bb_strtou(text, NULL, 10);
11708 if (!errno && fd >= 0)
11709 n->ndup.dupfd = fd;
11710 else if (LONE_DASH(text))
11711 n->ndup.dupfd = -1;
11714 raise_error_syntax("bad fd number");
11715 n->ndup.vname = makename();
11722 union node *n = redirnode;
11724 if (n->type == NHERE)
11725 checkkwd = CHKEOFMARK;
11726 if (readtoken() != TWORD)
11727 raise_error_unexpected_syntax(-1);
11728 if (n->type == NHERE) {
11729 struct heredoc *here = heredoc;
11732 if (quoteflag == 0)
11734 TRACE(("Here document %d\n", n->type));
11735 rmescapes(wordtext, 0, NULL);
11736 here->eofmark = wordtext;
11738 if (heredoclist == NULL)
11739 heredoclist = here;
11741 for (p = heredoclist; p->next; p = p->next)
11745 } else if (n->type == NTOFD || n->type == NFROMFD) {
11746 fixredir(n, wordtext, 0);
11748 n->nfile.fname = makename();
11752 static union node *
11755 union node *args, **app;
11756 union node *n = NULL;
11757 union node *vars, **vpp;
11758 union node **rpp, *redir;
11762 smallint double_brackets_flag = 0;
11764 IF_BASH_FUNCTION(smallint function_flag = 0;)
11773 savecheckkwd = CHKALIAS;
11774 savelinno = g_parsefile->linno;
11777 checkkwd = savecheckkwd;
11782 if (peektoken() != TWORD)
11783 raise_error_unexpected_syntax(TWORD);
11788 case TAND: /* "&&" */
11789 case TOR: /* "||" */
11790 if (!double_brackets_flag) {
11794 wordtext = (char *) (t == TAND ? "-a" : "-o");
11797 n = stzalloc(sizeof(struct narg));
11799 /*n->narg.next = NULL; - stzalloc did it */
11800 n->narg.text = wordtext;
11802 if (strcmp("[[", wordtext) == 0)
11803 double_brackets_flag = 1;
11804 else if (strcmp("]]", wordtext) == 0)
11805 double_brackets_flag = 0;
11807 n->narg.backquote = backquotelist;
11808 if (savecheckkwd && isassignment(wordtext)) {
11810 vpp = &n->narg.next;
11813 app = &n->narg.next;
11817 if (function_flag) {
11818 checkkwd = CHKNL | CHKKWD;
11819 switch (peektoken()) {
11832 if (strcmp("[[", wordtext) == 0)
11837 raise_error_unexpected_syntax(-1);
11843 *rpp = n = redirnode;
11844 rpp = &n->nfile.next;
11845 parsefname(); /* read name of redirection file */
11848 IF_BASH_FUNCTION(do_func:)
11849 if (args && app == &args->narg.next
11852 struct builtincmd *bcmd;
11855 /* We have a function */
11856 if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
11857 raise_error_unexpected_syntax(TRP);
11858 name = n->narg.text;
11859 if (!goodname(name)
11860 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11862 raise_error_syntax("bad function name");
11865 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11866 n->ndefun.text = n->narg.text;
11867 n->ndefun.linno = g_parsefile->linno;
11868 n->ndefun.body = parse_command();
11871 IF_BASH_FUNCTION(function_flag = 0;)
11882 n = stzalloc(sizeof(struct ncmd));
11885 n->ncmd.linno = savelinno;
11886 n->ncmd.args = args;
11887 n->ncmd.assign = vars;
11888 n->ncmd.redirect = redir;
11892 static union node *
11893 parse_command(void)
11895 union node *n1, *n2;
11896 union node *ap, **app;
11897 union node *cp, **cpp;
11898 union node *redir, **rpp;
11906 savelinno = g_parsefile->linno;
11908 switch (readtoken()) {
11910 raise_error_unexpected_syntax(-1);
11913 n1 = stzalloc(sizeof(struct nif));
11915 n1->nif.test = list(0);
11916 if (readtoken() != TTHEN)
11917 raise_error_unexpected_syntax(TTHEN);
11918 n1->nif.ifpart = list(0);
11920 while (readtoken() == TELIF) {
11921 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11922 n2 = n2->nif.elsepart;
11924 n2->nif.test = list(0);
11925 if (readtoken() != TTHEN)
11926 raise_error_unexpected_syntax(TTHEN);
11927 n2->nif.ifpart = list(0);
11929 if (lasttoken == TELSE)
11930 n2->nif.elsepart = list(0);
11932 n2->nif.elsepart = NULL;
11940 n1 = stzalloc(sizeof(struct nbinary));
11941 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11942 n1->nbinary.ch1 = list(0);
11945 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11946 got == TWORD ? wordtext : ""));
11947 raise_error_unexpected_syntax(TDO);
11949 n1->nbinary.ch2 = list(0);
11954 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11955 raise_error_syntax("bad for loop variable");
11956 n1 = stzalloc(sizeof(struct nfor));
11958 n1->nfor.linno = savelinno;
11959 n1->nfor.var = wordtext;
11960 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11961 if (readtoken() == TIN) {
11963 while (readtoken() == TWORD) {
11964 n2 = stzalloc(sizeof(struct narg));
11966 /*n2->narg.next = NULL; - stzalloc did it */
11967 n2->narg.text = wordtext;
11968 n2->narg.backquote = backquotelist;
11970 app = &n2->narg.next;
11973 n1->nfor.args = ap;
11974 if (lasttoken != TNL && lasttoken != TSEMI)
11975 raise_error_unexpected_syntax(-1);
11977 n2 = stzalloc(sizeof(struct narg));
11979 /*n2->narg.next = NULL; - stzalloc did it */
11980 n2->narg.text = (char *)dolatstr;
11981 /*n2->narg.backquote = NULL;*/
11982 n1->nfor.args = n2;
11984 * Newline or semicolon here is optional (but note
11985 * that the original Bourne shell only allowed NL).
11987 if (lasttoken != TSEMI)
11990 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11991 if (readtoken() != TDO)
11992 raise_error_unexpected_syntax(TDO);
11993 n1->nfor.body = list(0);
11997 n1 = stzalloc(sizeof(struct ncase));
11999 n1->ncase.linno = savelinno;
12000 if (readtoken() != TWORD)
12001 raise_error_unexpected_syntax(TWORD);
12002 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
12004 /*n2->narg.next = NULL; - stzalloc did it */
12005 n2->narg.text = wordtext;
12006 n2->narg.backquote = backquotelist;
12007 checkkwd = CHKNL | CHKKWD | CHKALIAS;
12008 if (readtoken() != TIN)
12009 raise_error_unexpected_syntax(TIN);
12010 cpp = &n1->ncase.cases;
12012 checkkwd = CHKNL | CHKKWD;
12014 while (t != TESAC) {
12015 if (lasttoken == TLP)
12017 *cpp = cp = stzalloc(sizeof(struct nclist));
12019 app = &cp->nclist.pattern;
12021 *app = ap = stzalloc(sizeof(struct narg));
12023 /*ap->narg.next = NULL; - stzalloc did it */
12024 ap->narg.text = wordtext;
12025 ap->narg.backquote = backquotelist;
12026 if (readtoken() != TPIPE)
12028 app = &ap->narg.next;
12031 //ap->narg.next = NULL;
12032 if (lasttoken != TRP)
12033 raise_error_unexpected_syntax(TRP);
12034 cp->nclist.body = list(2);
12036 cpp = &cp->nclist.next;
12038 checkkwd = CHKNL | CHKKWD;
12042 raise_error_unexpected_syntax(TENDCASE);
12049 n1 = stzalloc(sizeof(struct nredir));
12050 n1->type = NSUBSHELL;
12051 n1->nredir.linno = savelinno;
12052 n1->nredir.n = list(0);
12053 /*n1->nredir.redirect = NULL; - stzalloc did it */
12060 IF_BASH_FUNCTION(case TFUNCTION:)
12064 return simplecmd();
12067 if (readtoken() != t)
12068 raise_error_unexpected_syntax(t);
12071 /* Now check for redirection which may follow command */
12072 checkkwd = CHKKWD | CHKALIAS;
12074 while (readtoken() == TREDIR) {
12075 *rpp = n2 = redirnode;
12076 rpp = &n2->nfile.next;
12082 if (n1->type != NSUBSHELL) {
12083 n2 = stzalloc(sizeof(struct nredir));
12085 n2->nredir.linno = savelinno;
12089 n1->nredir.redirect = redir;
12094 #if BASH_DOLLAR_SQUOTE
12096 decode_dollar_squote(void)
12098 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
12104 p = strchr(C_escapes, c);
12109 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
12113 } while ((unsigned char)(c - '0') <= 7 && --cnt);
12115 } else if (c == 'x') { /* \xHH */
12119 } while (isxdigit(c) && --cnt);
12121 if (cnt == 3) { /* \x but next char is "bad" */
12125 } else { /* simple seq like \\ or \t */
12130 c = bb_process_escape_sequence((void*)&p);
12131 } else { /* unrecognized "\z": print both chars unless ' or " */
12132 if (c != '\'' && c != '"') {
12134 c |= 0x100; /* "please encode \, then me" */
12141 /* Used by expandstr to get here-doc like behaviour. */
12142 #define FAKEEOFMARK ((char*)(uintptr_t)1)
12144 static ALWAYS_INLINE int
12145 realeofmark(const char *eofmark)
12147 return eofmark && eofmark != FAKEEOFMARK;
12151 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
12152 * is not NULL, read a here document. In the latter case, eofmark is the
12153 * word which marks the end of the document and striptabs is true if
12154 * leading tabs should be stripped from the document. The argument c
12155 * is the first character of the input token or document.
12157 * Because C does not have internal subroutines, I have simulated them
12158 * using goto's to implement the subroutine linkage. The following macros
12159 * will run code that appears at the end of readtoken1.
12161 #define CHECKEND() {goto checkend; checkend_return:;}
12162 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
12163 #define PARSESUB() {goto parsesub; parsesub_return:;}
12164 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
12165 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
12166 #define PARSEARITH() {goto parsearith; parsearith_return:;}
12168 readtoken1(int c, int syntax, char *eofmark, int striptabs)
12170 /* NB: syntax parameter fits into smallint */
12171 /* c parameter is an unsigned char or PEOF or PEOA */
12174 struct nodelist *bqlist;
12177 smallint pssyntax; /* we are expanding a prompt string */
12178 IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
12180 struct synstack synbase = { };
12181 struct synstack *synstack = &synbase;
12183 #if ENABLE_ASH_EXPAND_PRMT
12184 pssyntax = (syntax == PSSYNTAX);
12188 pssyntax = 0; /* constant */
12190 synstack->syntax = syntax;
12192 if (syntax == DQSYNTAX)
12193 synstack->dblquote = 1;
12197 STARTSTACKSTR(out);
12199 /* For each line, until end of word */
12200 CHECKEND(); /* set c to PEOF if at end of here document */
12201 for (;;) { /* until end of line or end of word */
12202 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
12203 switch (SIT(c, synstack->syntax)) {
12204 case CNL: /* '\n' */
12205 if (synstack->syntax == BASESYNTAX
12206 && !synstack->varnest
12208 goto endword; /* exit outer loop */
12212 c = pgetc_top(synstack);
12213 goto loop; /* continue outer loop */
12218 #if BASH_DOLLAR_SQUOTE
12219 if (c == '\\' && bash_dollar_squote) {
12220 c = decode_dollar_squote();
12222 /* skip $'\000', $'\x00' (like bash) */
12226 /* Unknown escape. Encode as '\z' */
12227 c = (unsigned char)c;
12228 if (eofmark == NULL || synstack->dblquote)
12229 USTPUTC(CTLESC, out);
12230 USTPUTC('\\', out);
12234 if (!eofmark || synstack->dblquote || synstack->varnest)
12235 USTPUTC(CTLESC, out);
12238 case CBACK: /* backslash */
12239 c = pgetc_without_PEOA();
12241 USTPUTC(CTLESC, out);
12242 USTPUTC('\\', out);
12245 if (pssyntax && c == '$') {
12246 USTPUTC(CTLESC, out);
12247 USTPUTC('\\', out);
12249 /* Backslash is retained if we are in "str"
12250 * and next char isn't dquote-special.
12252 if (synstack->dblquote
12256 && (c != '"' || (eofmark != NULL && !synstack->varnest))
12257 && (c != '}' || !synstack->varnest)
12259 USTPUTC(CTLESC, out); /* protect '\' from glob */
12260 USTPUTC('\\', out);
12262 USTPUTC(CTLESC, out);
12268 synstack->syntax = SQSYNTAX;
12270 if (eofmark == NULL) {
12271 USTPUTC(CTLQUOTEMARK, out);
12275 synstack->syntax = DQSYNTAX;
12276 synstack->dblquote = 1;
12278 if (synstack->varnest)
12279 synstack->innerdq ^= 1;
12282 IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
12283 if (eofmark != NULL && synstack->varnest == 0) {
12288 if (synstack->dqvarnest == 0) {
12289 synstack->syntax = BASESYNTAX;
12290 synstack->dblquote = 0;
12299 case CVAR: /* '$' */
12300 PARSESUB(); /* parse substitution */
12302 case CENDVAR: /* '}' */
12303 if (!synstack->innerdq && synstack->varnest > 0) {
12304 if (!--synstack->varnest && synstack->varpushed)
12305 synstack_pop(&synstack);
12306 else if (synstack->dqvarnest > 0)
12307 synstack->dqvarnest--;
12312 #if ENABLE_FEATURE_SH_MATH
12313 case CLP: /* '(' in arithmetic */
12314 synstack->parenlevel++;
12317 case CRP: /* ')' in arithmetic */
12318 if (synstack->parenlevel > 0) {
12319 synstack->parenlevel--;
12321 if (pgetc_eatbnl() == ')') {
12323 synstack_pop(&synstack);
12326 * unbalanced parens
12327 * (don't 2nd guess - no error)
12335 case CBQUOTE: /* '`' */
12336 if (checkkwd & CHKEOFMARK) {
12345 goto endword; /* exit outer loop */
12349 if (synstack->varnest == 0) {
12350 #if BASH_REDIR_OUTPUT
12352 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
12353 if (pgetc() == '>')
12354 c = 0x100 + '>'; /* flag &> */
12358 goto endword; /* exit outer loop */
12360 IF_ASH_ALIAS(if (c != PEOA))
12363 c = pgetc_top(synstack);
12367 #if ENABLE_FEATURE_SH_MATH
12368 if (synstack->syntax == ARISYNTAX)
12369 raise_error_syntax("missing '))'");
12371 if (synstack->syntax != BASESYNTAX && eofmark == NULL)
12372 raise_error_syntax("unterminated quoted string");
12373 if (synstack->varnest != 0) {
12375 raise_error_syntax("missing '}'");
12377 USTPUTC('\0', out);
12378 len = out - (char *)stackblock();
12379 out = stackblock();
12380 if (eofmark == NULL) {
12381 if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
12384 if (isdigit_str9(out)) {
12385 PARSEREDIR(); /* passed as params: out, c */
12386 lasttoken = TREDIR;
12389 /* else: non-number X seen, interpret it
12390 * as "NNNX>file" = "NNNX >file" */
12394 quoteflag = quotef;
12395 backquotelist = bqlist;
12396 grabstackblock(len);
12400 /* end of readtoken routine */
12403 * Check to see whether we are at the end of the here document. When this
12404 * is called, c is set to the first character of the next input line. If
12405 * we are at the end of the here document, this routine sets the c to PEOF.
12408 if (realeofmark(eofmark)) {
12412 #if ENABLE_ASH_ALIAS
12414 c = pgetc_without_PEOA();
12417 while (c == '\t') {
12418 c = pgetc_without_PEOA();
12422 markloc = out - (char *)stackblock();
12423 for (p = eofmark; STPUTC(c, out), *p; p++) {
12426 /* FIXME: fails for backslash-newlined terminator:
12431 * (see heredoc_bkslash_newline2.tests)
12433 c = pgetc_without_PEOA();
12436 if (c == '\n' || c == PEOF) {
12438 g_parsefile->linno++;
12439 needprompt = doprompt;
12444 p = (char *)stackblock() + markloc + 1;
12445 len_here = out - p;
12448 len_here -= (c >= PEOF);
12454 str = alloca(len_here + 1);
12455 *(char *)mempcpy(str, p, len_here) = '\0';
12457 pushstring(str, NULL);
12462 STADJUST((char *)stackblock() + markloc - out, out);
12464 goto checkend_return;
12468 * Parse a redirection operator. The variable "out" points to a string
12469 * specifying the fd to be redirected. The variable "c" contains the
12470 * first character of the redirection operator.
12473 /* out is already checked to be a valid number or "" */
12474 int fd = (*out == '\0' ? -1 : atoi(out));
12477 np = stzalloc(sizeof(struct nfile));
12480 c = pgetc_eatbnl();
12482 np->type = NAPPEND;
12484 np->type = NCLOBBER;
12487 /* it also can be NTO2 (>&file), but we can't figure it out yet */
12493 #if BASH_REDIR_OUTPUT
12494 else if (c == 0x100 + '>') { /* this flags &> redirection */
12496 pgetc(); /* this is '>', no need to check */
12500 else { /* c == '<' */
12501 /*np->nfile.fd = 0; - stzalloc did it */
12502 c = pgetc_eatbnl();
12505 if (sizeof(struct nfile) != sizeof(struct nhere)) {
12506 np = stzalloc(sizeof(struct nhere));
12507 /*np->nfile.fd = 0; - stzalloc did it */
12510 heredoc = stzalloc(sizeof(struct heredoc));
12511 heredoc->here = np;
12512 c = pgetc_eatbnl();
12514 heredoc->striptabs = 1;
12516 /*heredoc->striptabs = 0; - stzalloc did it */
12522 np->type = NFROMFD;
12526 np->type = NFROMTO;
12538 goto parseredir_return;
12542 * Parse a substitution. At this point, we have read the dollar sign
12543 * and nothing else.
12546 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
12547 * (assuming ascii char codes, as the original implementation did) */
12548 #define is_special(c) \
12549 (((unsigned)(c) - 33 < 32) \
12550 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
12552 unsigned char subtype;
12555 c = pgetc_eatbnl();
12556 if ((checkkwd & CHKEOFMARK)
12557 || c > 255 /* PEOA or PEOF */
12558 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
12560 #if BASH_DOLLAR_SQUOTE
12561 if (synstack->syntax != DQSYNTAX && c == '\'')
12562 bash_dollar_squote = 1;
12567 } else if (c == '(') {
12568 /* $(command) or $((arith)) */
12569 if (pgetc_eatbnl() == '(') {
12570 #if ENABLE_FEATURE_SH_MATH
12573 raise_error_syntax("support for $((arith)) is disabled");
12580 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
12581 smalluint newsyn = synstack->syntax;
12583 USTPUTC(CTLVAR, out);
12584 typeloc = out - (char *)stackblock();
12586 subtype = VSNORMAL;
12588 c = pgetc_eatbnl();
12593 /* $[{[#]]NAME[}] */
12596 c = pgetc_eatbnl();
12597 } while (is_in_name(c));
12598 } else if (isdigit(c)) {
12599 /* $[{[#]]NUM[}] */
12602 c = pgetc_eatbnl();
12603 } while (isdigit(c));
12604 } else if (c != '}') {
12605 /* $[{[#]]<specialchar>[}] */
12608 c = pgetc_eatbnl();
12609 if (!subtype && cc == '#') {
12610 subtype = VSLENGTH;
12611 if (c == '_' || isalnum(c))
12614 c = pgetc_eatbnl();
12615 if (cc == '}' || c != '}') {
12623 if (!is_special(cc)) {
12624 if (subtype == VSLENGTH)
12633 if (c != '}' && subtype == VSLENGTH) {
12634 /* ${#VAR didn't end with } */
12638 if (subtype == 0) {
12639 static const char types[] ALIGN1 = "}-+?=";
12640 /* ${VAR...} but not $VAR or ${#VAR} */
12641 /* c == first char after VAR */
12646 c = pgetc_eatbnl();
12648 /* This check is only needed to not misinterpret
12649 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
12652 if (!strchr(types, c)) {
12653 subtype = VSSUBSTR;
12655 break; /* "goto badsub" is bigger (!) */
12661 const char *p = strchr(types, c);
12664 subtype |= p - types + VSNORMAL;
12669 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
12670 c = pgetc_eatbnl();
12676 newsyn = BASESYNTAX;
12678 #if BASH_PATTERN_SUBST
12680 /* ${v/[/]pattern/repl} */
12681 //TODO: encode pattern and repl separately.
12682 // Currently cases like: v=1;echo ${v/$((1/1))/ONE}
12683 // are broken (should print "ONE")
12684 subtype = VSREPLACE;
12685 newsyn = BASESYNTAX;
12686 c = pgetc_eatbnl();
12689 subtype++; /* VSREPLACEALL */
12698 if (newsyn == ARISYNTAX)
12701 if ((newsyn != synstack->syntax || synstack->innerdq)
12702 && subtype != VSNORMAL
12704 synstack_push(&synstack,
12705 synstack->prev ?: alloca(sizeof(*synstack)),
12708 synstack->varpushed = 1;
12709 synstack->dblquote = newsyn != BASESYNTAX;
12712 ((unsigned char *)stackblock())[typeloc] = subtype;
12713 if (subtype != VSNORMAL) {
12714 synstack->varnest++;
12715 if (synstack->dblquote)
12716 synstack->dqvarnest++;
12720 goto parsesub_return;
12724 * Called to parse command substitutions. Newstyle is set if the command
12725 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
12726 * list of commands (passed by reference), and savelen is the number of
12727 * characters on the top of the stack which must be preserved.
12730 struct nodelist **nlpp;
12734 smallint saveprompt = 0;
12737 savelen = out - (char *)stackblock();
12740 * FIXME: this can allocate very large block on stack and SEGV.
12742 * echo "..<100kbytes>..`true` $(true) `true` ..."
12743 * allocates 100kb for every command subst. With about
12744 * a hundred command substitutions stack overflows.
12745 * With larger prepended string, SEGV happens sooner.
12747 str = alloca(savelen);
12748 memcpy(str, stackblock(), savelen);
12752 /* We must read until the closing backquote, giving special
12753 * treatment to some slashes, and then push the string and
12754 * reread it as input, interpreting it normally.
12760 STARTSTACKSTR(pout);
12764 setprompt_if(needprompt, 2);
12765 pc = pgetc_eatbnl();
12771 pc = pgetc(); /* or pgetc_eatbnl()? why (example)? */
12772 if (pc != '\\' && pc != '`' && pc != '$'
12773 && (!synstack->dblquote || pc != '"')
12775 STPUTC('\\', pout);
12777 if (pc <= 255 /* not PEOA or PEOF */) {
12783 IF_ASH_ALIAS(case PEOA:)
12784 raise_error_syntax("EOF in backquote substitution");
12796 STPUTC('\0', pout);
12797 psavelen = pout - (char *)stackblock();
12798 if (psavelen > 0) {
12799 pstr = grabstackstr(pout);
12800 setinputstring(pstr);
12805 nlpp = &(*nlpp)->next;
12806 *nlpp = stzalloc(sizeof(**nlpp));
12807 /* (*nlpp)->next = NULL; - stzalloc did it */
12810 saveprompt = doprompt;
12817 doprompt = saveprompt;
12818 else if (readtoken() != TRP)
12819 raise_error_unexpected_syntax(TRP);
12824 * Start reading from old file again, ignoring any pushed back
12825 * tokens left from the backquote parsing
12830 while (stackblocksize() <= savelen)
12832 STARTSTACKSTR(out);
12834 memcpy(out, str, savelen);
12835 STADJUST(savelen, out);
12837 USTPUTC(CTLBACKQ, out);
12839 goto parsebackq_oldreturn;
12840 goto parsebackq_newreturn;
12843 #if ENABLE_FEATURE_SH_MATH
12845 * Parse an arithmetic expansion (indicate start of one and set state)
12849 synstack_push(&synstack,
12850 synstack->prev ?: alloca(sizeof(*synstack)),
12852 synstack->dblquote = 1;
12853 USTPUTC(CTLARI, out);
12854 goto parsearith_return;
12857 } /* end of readtoken */
12860 * Read the next input token.
12861 * If the token is a word, we set backquotelist to the list of cmds in
12862 * backquotes. We set quoteflag to true if any part of the word was
12864 * If the token is TREDIR, then we set redirnode to a structure containing
12867 * [Change comment: here documents and internal procedures]
12868 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12869 * word parsing code into a separate routine. In this case, readtoken
12870 * doesn't need to have any internal procedures, but parseword does.
12871 * We could also make parseoperator in essence the main routine, and
12872 * have parseword (readtoken1?) handle both words and redirection.]
12874 #define NEW_xxreadtoken
12875 #ifdef NEW_xxreadtoken
12876 /* singles must be first! */
12877 static const char xxreadtoken_chars[7] ALIGN1 = {
12878 '\n', '(', ')', /* singles */
12879 '&', '|', ';', /* doubles */
12883 #define xxreadtoken_singles 3
12884 #define xxreadtoken_doubles 3
12886 static const char xxreadtoken_tokens[] ALIGN1 = {
12887 TNL, TLP, TRP, /* only single occurrence allowed */
12888 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12889 TEOF, /* corresponds to trailing nul */
12890 TAND, TOR, TENDCASE /* if double occurrence */
12902 setprompt_if(needprompt, 2);
12903 for (;;) { /* until token or start of word found */
12904 c = pgetc_eatbnl();
12905 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12909 while ((c = pgetc()) != '\n' && c != PEOF)
12912 } else if (c == '\\') {
12913 break; /* return readtoken1(...) */
12917 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12923 p = strchr(xxreadtoken_chars, c);
12925 break; /* return readtoken1(...) */
12927 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12928 int cc = pgetc_eatbnl();
12929 if (cc == c) { /* double occurrence? */
12930 p += xxreadtoken_doubles + 1;
12933 #if BASH_REDIR_OUTPUT
12934 if (c == '&' && cc == '>') /* &> */
12935 break; /* return readtoken1(...) */
12940 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12945 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12947 #else /* old xxreadtoken */
12948 #define RETURN(token) return lasttoken = token
12958 setprompt_if(needprompt, 2);
12959 for (;;) { /* until token or start of word found */
12960 c = pgetc_eatbnl();
12962 case ' ': case '\t':
12963 IF_ASH_ALIAS(case PEOA:)
12966 while ((c = pgetc()) != '\n' && c != PEOF)
12976 if (pgetc_eatbnl() == '&')
12981 if (pgetc_eatbnl() == '|')
12986 if (pgetc_eatbnl() == ';')
12997 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
13000 #endif /* old xxreadtoken */
13006 int kwd = checkkwd;
13008 smallint alreadyseen = tokpushback;
13011 #if ENABLE_ASH_ALIAS
13027 if (t != TWORD || quoteflag) {
13032 * check for keywords
13034 if (kwd & CHKKWD) {
13035 const char *const *pp;
13037 pp = findkwd(wordtext);
13039 lasttoken = t = pp - tokname_array;
13040 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
13045 if (checkkwd & CHKALIAS) {
13046 #if ENABLE_ASH_ALIAS
13048 ap = lookupalias(wordtext, 1);
13051 pushstring(ap->val, ap);
13061 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
13063 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
13079 * Read and parse a command. Returns NODE_EOF on end of file.
13080 * (NULL is a valid parse tree indicating a blank line.)
13082 static union node *
13083 parsecmd(int interact)
13088 doprompt = interact;
13089 setprompt_if(doprompt, doprompt);
13095 * Input any here documents.
13100 struct heredoc *here;
13103 here = heredoclist;
13104 heredoclist = NULL;
13108 setprompt_if(needprompt, 2);
13109 if (here->here->type == NHERE)
13110 readtoken1(pgetc(), SQSYNTAX, here->eofmark, here->striptabs);
13112 readtoken1(pgetc_eatbnl(), DQSYNTAX, here->eofmark, here->striptabs);
13113 n = stzalloc(sizeof(struct narg));
13114 n->narg.type = NARG;
13115 /*n->narg.next = NULL; - stzalloc did it */
13116 n->narg.text = wordtext;
13117 n->narg.backquote = backquotelist;
13118 here->here->nhere.doc = n;
13124 static const char *
13125 expandstr(const char *ps, int syntax_type)
13129 struct parsefile *file_stop = g_parsefile;
13130 volatile int saveint;
13131 struct jmploc *volatile savehandler = exception_handler;
13132 struct jmploc jmploc;
13133 const char *volatile result;
13136 /* XXX Fix (char *) cast. */
13137 setinputstring((char *)ps);
13139 saveprompt = doprompt;
13144 err = setjmp(jmploc.loc);
13148 /* readtoken1() might die horribly.
13149 * Try a prompt with syntactically wrong command:
13150 * PS1='$(date "+%H:%M:%S) > '
13152 exception_handler = &jmploc;
13153 readtoken1(pgetc(), syntax_type, FAKEEOFMARK, 0);
13155 n.narg.type = NARG;
13156 n.narg.next = NULL;
13157 n.narg.text = wordtext;
13158 n.narg.backquote = backquotelist;
13160 /* expandarg() might fail too:
13163 expandarg(&n, NULL, EXP_QUOTED);
13164 result = stackblock();
13167 exception_handler = savehandler;
13168 if (err && exception_type != EXERROR)
13169 longjmp(exception_handler->loc, 1);
13170 RESTORE_INT(saveint);
13172 doprompt = saveprompt;
13173 /* Try: PS1='`xxx(`' */
13174 unwindfiles(file_stop);
13182 return tokpushback && lasttoken == TEOF;
13186 * Execute a command or commands contained in a string.
13189 evalstring(char *s, int flags)
13191 struct jmploc *volatile savehandler;
13192 struct jmploc jmploc;
13196 struct stackmark smark;
13201 setstackmark(&smark);
13204 /* On exception inside execution loop, we must popfile().
13205 * Try interactively:
13207 * command eval "a=b" # throws "is read only" error
13208 * "command BLTIN" is not supposed to abort (even in non-interactive use).
13209 * But if we skip popfile(), we hit EOF in eval's string, and exit.
13211 savehandler = exception_handler;
13212 ex = setjmp(jmploc.loc);
13215 exception_handler = &jmploc;
13217 while ((n = parsecmd(0)) != NODE_EOF) {
13220 i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
13223 popstackmark(&smark);
13228 popstackmark(&smark);
13232 exception_handler = savehandler;
13234 longjmp(exception_handler->loc, ex);
13240 * The eval command.
13242 static int FAST_FUNC
13243 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
13252 STARTSTACKSTR(concat);
13254 concat = stack_putstr(p, concat);
13258 STPUTC(' ', concat);
13260 STPUTC('\0', concat);
13261 p = grabstackstr(concat);
13263 return evalstring(p, flags & EV_TESTED);
13269 * Read and execute commands.
13270 * "Top" is nonzero for the top level command loop;
13271 * it turns on prompting if the shell is interactive.
13277 struct stackmark smark;
13282 TRACE(("cmdloop(%d) called\n", top));
13286 setstackmark(&smark);
13289 showjobs(SHOW_CHANGED|SHOW_STDERR);
13292 if (iflag && top) {
13296 n = parsecmd(inter);
13298 if (DEBUG > 2 && debug && (n != NODE_EOF))
13301 if (n == NODE_EOF) {
13302 if (!top || numeof >= 50)
13304 if (!stoppedjobs()) {
13307 out2str("\nUse \"exit\" to leave shell.\n");
13310 } else if (nflag == 0) {
13313 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
13316 i = evaltree(n, 0);
13320 popstackmark(&smark);
13324 evalskip &= ~SKIPFUNC;
13332 * Take commands from a file. To be compatible we should do a path
13333 * search for the file, which is necessary to find sub-commands.
13336 find_dot_file(char *name)
13339 const char *path = pathval();
13342 /* don't try this for absolute or relative paths */
13343 if (strchr(name, '/'))
13346 while ((fullname = path_advance(&path, name)) != NULL) {
13347 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
13349 * Don't bother freeing here, since it will
13350 * be freed by the caller.
13354 if (fullname != name)
13355 stunalloc(fullname);
13357 /* not found in PATH */
13359 #if ENABLE_ASH_BASH_SOURCE_CURDIR
13362 ash_msg_and_raise_error("%s: not found", name);
13367 static int FAST_FUNC
13368 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
13370 /* "false; . empty_file; echo $?" should print 0, not 1: */
13374 char *args_need_save;
13375 volatile struct shparam saveparam;
13378 // struct strlist *sp;
13379 // for (sp = cmdenviron; sp; sp = sp->next)
13380 // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
13382 nextopt(nullstr); /* handle possible "--" */
13386 /* bash says: "bash: .: filename argument required" */
13387 return 2; /* bash compat */
13390 /* This aborts if file isn't found, which is POSIXly correct.
13391 * bash returns exitcode 1 instead.
13393 fullname = find_dot_file(argv[0]);
13395 args_need_save = argv[0];
13396 if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
13398 saveparam = shellparam;
13399 shellparam.malloced = 0;
13403 shellparam.nparam = argc;
13404 shellparam.p = argv;
13407 /* This aborts if file can't be opened, which is POSIXly correct.
13408 * bash returns exitcode 1 instead.
13410 setinputfile(fullname, INPUT_PUSH_FILE);
13411 commandname = fullname;
13412 status = cmdloop(0);
13415 if (args_need_save) {
13416 freeparam(&shellparam);
13417 shellparam = saveparam;
13423 static int FAST_FUNC
13424 exitcmd(int argc UNUSED_PARAM, char **argv)
13430 savestatus = number(argv[1]);
13432 raise_exception(EXEXIT);
13437 * Read a file containing shell functions.
13440 readcmdfile(char *name)
13442 setinputfile(name, INPUT_PUSH_FILE);
13448 /* ============ find_command inplementation */
13451 * Resolve a command name. If you change this routine, you may have to
13452 * change the shellexec routine as well.
13455 find_command(char *name, struct cmdentry *entry, int act, const char *path)
13457 struct tblentry *cmdp;
13464 struct builtincmd *bcmd;
13466 /* If name contains a slash, don't use PATH or hash table */
13467 if (strchr(name, '/') != NULL) {
13468 entry->u.index = -1;
13469 if (act & DO_ABS) {
13470 while (stat(name, &statb) < 0) {
13472 if (errno == EINTR)
13475 entry->cmdtype = CMDUNKNOWN;
13479 entry->cmdtype = CMDNORMAL;
13483 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
13485 updatetbl = (path == pathval());
13488 if (strstr(path, "%builtin") != NULL)
13489 act |= DO_ALTBLTIN;
13492 /* If name is in the table, check answer will be ok */
13493 cmdp = cmdlookup(name, 0);
13494 if (cmdp != NULL) {
13497 switch (cmdp->cmdtype) {
13515 } else if (cmdp->rehash == 0)
13516 /* if not invalidated by cd, we're done */
13520 /* If %builtin not in path, check for builtin next */
13521 bcmd = find_builtin(name);
13523 if (IS_BUILTIN_REGULAR(bcmd))
13524 goto builtin_success;
13525 if (act & DO_ALTPATH) {
13526 if (!(act & DO_ALTBLTIN))
13527 goto builtin_success;
13528 } else if (builtinloc <= 0) {
13529 goto builtin_success;
13533 #if ENABLE_FEATURE_SH_STANDALONE
13535 int applet_no = find_applet_by_name(name);
13536 if (applet_no >= 0) {
13537 entry->cmdtype = CMDNORMAL;
13538 entry->u.index = -2 - applet_no;
13544 /* We have to search path. */
13545 prev = -1; /* where to start */
13546 if (cmdp && cmdp->rehash) { /* doing a rehash */
13547 if (cmdp->cmdtype == CMDBUILTIN)
13550 prev = cmdp->param.index;
13556 while ((fullname = path_advance(&path, name)) != NULL) {
13557 stunalloc(fullname);
13558 /* NB: code below will still use fullname
13559 * despite it being "unallocated" */
13562 if (prefix(pathopt, "builtin")) {
13564 goto builtin_success;
13567 if ((act & DO_NOFUNC)
13568 || !prefix(pathopt, "func")
13569 ) { /* ignore unimplemented options */
13573 /* if rehash, don't redo absolute path names */
13574 if (fullname[0] == '/' && idx <= prev) {
13577 TRACE(("searchexec \"%s\": no change\n", name));
13580 while (stat(fullname, &statb) < 0) {
13582 if (errno == EINTR)
13585 if (errno != ENOENT && errno != ENOTDIR)
13589 e = EACCES; /* if we fail, this will be the error */
13590 if (!S_ISREG(statb.st_mode))
13592 if (pathopt) { /* this is a %func directory */
13593 stalloc(strlen(fullname) + 1);
13594 /* NB: stalloc will return space pointed by fullname
13595 * (because we don't have any intervening allocations
13596 * between stunalloc above and this stalloc) */
13597 readcmdfile(fullname);
13598 cmdp = cmdlookup(name, 0);
13599 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
13600 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
13601 stunalloc(fullname);
13604 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
13606 entry->cmdtype = CMDNORMAL;
13607 entry->u.index = idx;
13611 cmdp = cmdlookup(name, 1);
13612 cmdp->cmdtype = CMDNORMAL;
13613 cmdp->param.index = idx;
13618 /* We failed. If there was an entry for this command, delete it */
13619 if (cmdp && updatetbl)
13620 delete_cmd_entry();
13621 if (act & DO_ERR) {
13622 #if ENABLE_ASH_BASH_NOT_FOUND_HOOK
13623 struct tblentry *hookp = cmdlookup("command_not_found_handle", 0);
13624 if (hookp && hookp->cmdtype == CMDFUNCTION) {
13626 argv[0] = (char*) "command_not_found_handle";
13629 evalfun(hookp->param.func, 2, argv, 0);
13630 entry->cmdtype = CMDUNKNOWN;
13634 ash_msg("%s: %s", name, errmsg(e, "not found"));
13636 entry->cmdtype = CMDUNKNOWN;
13641 entry->cmdtype = CMDBUILTIN;
13642 entry->u.cmd = bcmd;
13646 cmdp = cmdlookup(name, 1);
13647 cmdp->cmdtype = CMDBUILTIN;
13648 cmdp->param.cmd = bcmd;
13652 entry->cmdtype = cmdp->cmdtype;
13653 entry->u = cmdp->param;
13658 * The trap builtin.
13660 static int FAST_FUNC
13661 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13665 int signo, exitcode;
13670 for (signo = 0; signo < NSIG; signo++) {
13671 char *tr = trap_ptr[signo];
13673 /* note: bash adds "SIG", but only if invoked
13674 * as "bash". If called as "sh", or if set -o posix,
13675 * then it prints short signal names.
13676 * We are printing short names: */
13677 out1fmt("trap -- %s %s\n",
13679 get_signame(signo));
13680 /* trap_ptr != trap only if we are in special-cased `trap` code.
13681 * In this case, we will exit very soon, no need to free(). */
13682 /* if (trap_ptr != trap && tp[0]) */
13687 if (trap_ptr != trap) {
13695 /* Why the second check?
13696 * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
13697 * In this case, NUM is signal no, not an action.
13700 if (ap[1] && !is_number(ap[0]))
13705 signo = get_signum(*ap);
13707 /* Mimic bash message exactly */
13708 ash_msg("%s: invalid signal specification", *ap);
13714 if (LONE_DASH(action))
13717 if (action[0]) /* not NULL and not "" and not "-" */
13718 may_have_traps = 1;
13719 action = ckstrdup(action);
13723 trap[signo] = action;
13734 /* ============ Builtins */
13736 #if ENABLE_ASH_HELP
13737 static int FAST_FUNC
13738 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13744 "Built-in commands:\n"
13745 "------------------\n");
13746 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
13747 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
13748 builtintab[i].name + 1);
13754 # if ENABLE_FEATURE_SH_STANDALONE
13756 const char *a = applet_names;
13758 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
13763 while (*a++ != '\0')
13768 newline_and_flush(stdout);
13769 return EXIT_SUCCESS;
13774 static int FAST_FUNC
13775 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13777 if (line_input_state)
13778 show_history(line_input_state);
13779 return EXIT_SUCCESS;
13784 * The export and readonly commands.
13786 static int FAST_FUNC
13787 exportcmd(int argc UNUSED_PARAM, char **argv)
13797 /* "readonly" in bash accepts, but ignores -n.
13798 * We do the same: it saves a conditional in nextopt's param.
13801 while ((opt = nextopt("np")) != '\0') {
13803 flag_off = VEXPORT;
13806 if (argv[0][0] == 'r') {
13808 flag_off = 0; /* readonly ignores -n */
13810 flag_off = ~flag_off;
13812 /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
13818 p = strchr(name, '=');
13822 vp = *findvar(hashvar(name), name);
13824 vp->flags = ((vp->flags | flag) & flag_off);
13828 setvar(name, p, (flag & flag_off));
13829 } while ((name = *++aptr) != NULL);
13834 /* No arguments. Show the list of exported or readonly vars.
13837 showvars(argv[0], flag, 0);
13842 * Delete a function if it exists.
13845 unsetfunc(const char *name)
13847 struct tblentry *cmdp;
13849 cmdp = cmdlookup(name, 0);
13850 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
13851 delete_cmd_entry();
13855 * The unset builtin command. We unset the function before we unset the
13856 * variable to allow a function to be unset when there is a readonly variable
13857 * with the same name.
13859 static int FAST_FUNC
13860 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13866 while ((i = nextopt("vf")) != 0) {
13870 for (ap = argptr; *ap; ap++) {
13881 static const unsigned char timescmd_str[] ALIGN1 = {
13882 ' ', offsetof(struct tms, tms_utime),
13883 '\n', offsetof(struct tms, tms_stime),
13884 ' ', offsetof(struct tms, tms_cutime),
13885 '\n', offsetof(struct tms, tms_cstime),
13888 static int FAST_FUNC
13889 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13892 const unsigned char *p;
13895 clk_tck = bb_clk_tck();
13900 unsigned sec, frac;
13902 t = *(clock_t *)(((char *) &buf) + p[1]);
13904 frac = t % clk_tck;
13905 out1fmt("%um%u.%03us%c",
13906 sec / 60, sec % 60,
13907 (frac * 1000) / clk_tck,
13915 #if ENABLE_FEATURE_SH_MATH
13917 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13918 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13920 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13922 static int FAST_FUNC
13923 letcmd(int argc UNUSED_PARAM, char **argv)
13929 ash_msg_and_raise_error("expression expected");
13931 i = ash_arith(*argv);
13939 * The read builtin. Options:
13940 * -r Do not interpret '\' specially
13941 * -s Turn off echo (tty only)
13942 * -n NCHARS Read NCHARS max
13943 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13944 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13945 * -u FD Read from given FD instead of fd 0
13946 * -d DELIM End on DELIM char, not newline
13947 * This uses unbuffered input, which may be avoidable in some cases.
13948 * TODO: bash also has:
13949 * -a ARRAY Read into array[0],[1],etc
13950 * -e Use line editing (tty only)
13952 static int FAST_FUNC
13953 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13955 struct builtin_read_params params;
13959 memset(¶ms, 0, sizeof(params));
13961 while ((i = nextopt("p:u:rt:n:sd:")) != '\0') {
13964 params.opt_p = optionarg;
13967 params.opt_n = optionarg;
13970 params.read_flags |= BUILTIN_READ_SILENT;
13973 params.opt_t = optionarg;
13976 params.read_flags |= BUILTIN_READ_RAW;
13979 params.opt_u = optionarg;
13983 params.opt_d = optionarg;
13991 params.argv = argptr;
13992 params.setvar = setvar0;
13993 params.ifs = bltinlookup("IFS"); /* can be NULL */
13995 /* "read -s" needs to save/restore termios, can't allow ^C
13996 * to jump out of it.
14000 r = shell_builtin_read(¶ms);
14003 if ((uintptr_t)r == 1 && errno == EINTR) {
14004 /* To get SIGCHLD: sleep 1 & read x; echo $x
14005 * Correct behavior is to not exit "read"
14007 if (pending_sig == 0)
14011 if ((uintptr_t)r > 1)
14012 ash_msg_and_raise_error(r);
14014 return (uintptr_t)r;
14017 static int FAST_FUNC
14018 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
14020 static const char permuser[3] ALIGN1 = "ogu";
14023 int symbolic_mode = 0;
14025 while (nextopt("S") != '\0') {
14034 if (*argptr == NULL) {
14035 if (symbolic_mode) {
14036 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
14043 *p++ = permuser[i];
14045 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
14046 if (!(mask & 0400)) *p++ = 'r';
14047 if (!(mask & 0200)) *p++ = 'w';
14048 if (!(mask & 0100)) *p++ = 'x';
14056 out1fmt("%04o\n", mask);
14059 char *modestr = *argptr;
14060 /* numeric umasks are taken as-is */
14061 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
14062 if (!isdigit(modestr[0]))
14064 mask = bb_parse_mode(modestr, mask);
14065 if ((unsigned)mask > 0777) {
14066 ash_msg_and_raise_error("illegal mode: %s", modestr);
14068 if (!isdigit(modestr[0]))
14075 static int FAST_FUNC
14076 ulimitcmd(int argc UNUSED_PARAM, char **argv)
14078 return shell_builtin_ulimit(argv);
14081 /* ============ main() and helpers */
14084 * Called to exit the shell.
14092 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
14093 if (line_input_state)
14094 save_history(line_input_state);
14096 savestatus = exitstatus;
14097 TRACE(("pid %d, exitshell(%d)\n", getpid(), savestatus));
14098 if (setjmp(loc.loc))
14100 exception_handler = &loc;
14106 /*free(p); - we'll exit soon */
14109 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
14110 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
14113 flush_stdout_stderr();
14118 /* Don't inline: conserve stack of caller from having our locals too */
14119 static NOINLINE void
14122 /* we will never free this */
14123 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
14126 sigmode[SIGCHLD - 1] = S_DFL; /* ensure we install handler even if it is SIG_IGNed */
14127 setsignal(SIGCHLD);
14129 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
14130 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
14132 signal(SIGHUP, SIG_DFL);
14139 for (envp = environ; envp && *envp; envp++) {
14141 * p = endofname(*envp);
14142 * if (p != *envp && *p == '=') {
14143 * here to weed out badly-named variables, but this breaks
14144 * scenarios where people do want them passed to children:
14146 * os.environ["test-test"]="test"
14147 * if os.fork() == 0:
14148 * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
14149 * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ]) # breaks this
14151 if (strchr(*envp, '=')) {
14152 setvareq(*envp, VEXPORT|VTEXTFIXED);
14156 setvareq((char*)defifsvar, VTEXTFIXED);
14157 setvareq((char*)defoptindvar, VTEXTFIXED);
14159 setvar0("PPID", utoa(getppid()));
14161 p = lookupvar("SHLVL");
14162 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
14164 #if BASH_HOSTNAME_VAR
14165 if (!lookupvar("HOSTNAME")) {
14166 struct utsname uts;
14168 setvar0("HOSTNAME", uts.nodename);
14171 p = lookupvar("PWD");
14173 struct stat st1, st2;
14174 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
14175 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
14185 //usage:#define ash_trivial_usage
14186 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
14187 //usage:#define ash_full_usage "\n\n"
14188 //usage: "Unix shell interpreter"
14191 * Process the shell command line arguments.
14194 procargs(char **argv)
14197 const char *xminusc;
14202 login_sh = xargv[0] && xargv[0][0] == '-';
14203 #if NUM_SCRIPTS > 0
14208 /* if (xargv[0]) - mmm, this is always true! */
14211 for (i = 0; i < NOPTS; i++)
14213 if (options(&login_sh)) {
14214 /* it already printed err message */
14215 raise_exception(EXERROR);
14219 if (*xargv == NULL) {
14221 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
14224 if (iflag == 2 /* no explicit -i given */
14225 && sflag == 1 /* -s given (or implied) */
14226 && !minusc /* bash compat: ash -sc 'echo $-' is not interactive (dash is) */
14227 && isatty(0) && isatty(1) /* we are on tty */
14233 for (i = 0; i < NOPTS; i++)
14234 if (optlist[i] == 2)
14239 /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
14244 } else if (!sflag) {
14245 setinputfile(*xargv, 0);
14248 commandname = arg0;
14251 shellparam.p = xargv;
14252 #if ENABLE_ASH_GETOPTS
14253 shellparam.optind = 1;
14254 shellparam.optoff = -1;
14256 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
14258 shellparam.nparam++;
14267 * Read /etc/profile, ~/.profile, $ENV.
14270 read_profile(const char *name)
14272 name = expandstr(name, DQSYNTAX);
14273 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
14280 * This routine is called when an error or an interrupt occurs in an
14281 * interactive shell and control is returned to the main command loop.
14282 * (In dash, this function is auto-generated by build machinery).
14290 if (savestatus >= 0) {
14291 exitstatus = savestatus;
14295 /* from expand.c: */
14298 /* from input.c: */
14299 g_parsefile->left_in_buffer = 0;
14300 g_parsefile->left_in_line = 0; /* clear input buffer */
14303 /* from redir.c: */
14307 unwindlocalvars(NULL);
14311 static short profile_buf[16384];
14312 extern int etext();
14316 * Main routine. We initialize things, parse the arguments, execute
14317 * profiles if we're a login shell, and then call cmdloop to execute
14318 * commands. The setjmp call sets up the location to jump to when an
14319 * exception occurs. When an exception occurs the variable "state"
14320 * is used to figure out how far we had gotten.
14322 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
14323 #if NUM_SCRIPTS > 0
14324 int ash_main(int argc, char **argv)
14326 int ash_main(int argc UNUSED_PARAM, char **argv)
14328 /* note: 'argc' is used only if embedded scripts are enabled */
14330 volatile smallint state;
14331 struct jmploc jmploc;
14332 struct stackmark smark;
14335 /* Initialize global data */
14339 #if ENABLE_ASH_ALIAS
14345 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
14349 if (setjmp(jmploc.loc)) {
14355 e = exception_type;
14357 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
14361 newline_and_flush(stderr);
14364 popstackmark(&smark);
14365 FORCE_INT_ON; /* enable interrupts */
14374 exception_handler = &jmploc;
14375 rootpid = getpid();
14378 setstackmark(&smark);
14380 #if NUM_SCRIPTS > 0
14382 /* Non-NULL minusc tells procargs that an embedded script is being run */
14383 minusc = get_script_content(-argc - 1);
14385 login_sh = procargs(argv);
14387 TRACE(("Shell args: "));
14388 trace_puts_args(argv);
14395 read_profile("/etc/profile");
14398 hp = lookupvar("HOME");
14400 read_profile("$HOME/.profile");
14406 getuid() == geteuid() && getgid() == getegid() &&
14410 const char *shinit = lookupvar("ENV");
14411 if (shinit != NULL && *shinit != '\0')
14412 read_profile(shinit);
14414 popstackmark(&smark);
14418 /* evalstring pushes parsefile stack.
14419 * Ensure we don't falsely claim that 0 (stdin)
14420 * is one of stacked source fds.
14421 * Testcase: ash -c 'exec 1>&0' must not complain. */
14423 // if (!sflag) g_parsefile->pf_fd = -1;
14424 // ^^ not necessary since now we special-case fd 0
14425 // in save_fd_on_redirect()
14427 // dash: evalstring(minusc, sflag ? 0 : EV_EXIT);
14429 // ash -sc 'echo $-'
14430 // continue reading input from stdin after running 'echo'.
14431 // bash does not do this: it prints "hBcs" and exits.
14432 evalstring(minusc, EV_EXIT);
14435 if (sflag || minusc == NULL) {
14436 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
14438 const char *hp = lookupvar("HISTFILE");
14440 hp = lookupvar("HOME");
14443 hp = concat_path_file(hp, ".ash_history");
14444 setvar0("HISTFILE", hp);
14447 hp = lookupvar("HISTFILE");
14451 line_input_state->hist_file = hp;
14452 # if ENABLE_FEATURE_SH_HISTFILESIZE
14453 hp = lookupvar("HISTFILESIZE");
14454 line_input_state->max_history = size_from_HISTFILESIZE(hp);
14458 state4: /* XXX ??? - why isn't this before the "if" statement */
14466 extern void _mcleanup(void);
14470 TRACE(("End of main reached\n"));
14477 * Copyright (c) 1989, 1991, 1993, 1994
14478 * The Regents of the University of California. All rights reserved.
14480 * This code is derived from software contributed to Berkeley by
14481 * Kenneth Almquist.
14483 * Redistribution and use in source and binary forms, with or without
14484 * modification, are permitted provided that the following conditions
14486 * 1. Redistributions of source code must retain the above copyright
14487 * notice, this list of conditions and the following disclaimer.
14488 * 2. Redistributions in binary form must reproduce the above copyright
14489 * notice, this list of conditions and the following disclaimer in the
14490 * documentation and/or other materials provided with the distribution.
14491 * 3. Neither the name of the University nor the names of its contributors
14492 * may be used to endorse or promote products derived from this software
14493 * without specific prior written permission.
14495 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
14496 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
14497 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
14498 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
14499 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
14500 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
14501 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
14502 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
14503 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
14504 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF