1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * This code is derived from software contributed to Berkeley by
8 * Original BSD copyright notice is retained at the end of this file.
10 * Copyright (c) 1989, 1991, 1993, 1994
11 * The Regents of the University of California. All rights reserved.
13 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
14 * was re-ported from NetBSD and debianized.
16 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
19 //config: bool "ash (78 kb)"
21 //config: depends on !NOMMU
23 //config: The most complete and most pedantically correct shell included with
24 //config: busybox. This shell is actually a derivative of the Debian 'dash'
25 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
26 //config: (written by Kenneth Almquist) from NetBSD.
28 //config:# ash options
29 //config:# note: Don't remove !NOMMU part in the next line; it would break
30 //config:# menuconfig's indenting.
31 //config:if !NOMMU && (ASH || SH_IS_ASH || BASH_IS_ASH)
33 //config:config ASH_OPTIMIZE_FOR_SIZE
34 //config: bool "Optimize for size instead of speed"
36 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
38 //config:config ASH_INTERNAL_GLOB
39 //config: bool "Use internal glob() implementation"
40 //config: default y # Y is bigger, but because of uclibc glob() bug, let Y be default for now
41 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
43 //config: Do not use glob() function from libc, use internal implementation.
44 //config: Use this if you are getting "glob.h: No such file or directory"
45 //config: or similar build errors.
46 //config: Note that as of now (2017-01), uclibc and musl glob() both have bugs
47 //config: which would break ash if you select N here.
49 //config:config ASH_BASH_COMPAT
50 //config: bool "bash-compatible extensions"
52 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
54 //config:config ASH_BASH_SOURCE_CURDIR
55 //config: bool "'source' and '.' builtins search current directory after $PATH"
56 //config: default n # do not encourage non-standard behavior
57 //config: depends on ASH_BASH_COMPAT
59 //config: This is not compliant with standards. Avoid if possible.
61 //config:config ASH_BASH_NOT_FOUND_HOOK
62 //config: bool "command_not_found_handle hook support"
64 //config: depends on ASH_BASH_COMPAT
66 //config: Enable support for the 'command_not_found_handle' hook function,
67 //config: from GNU bash, which allows for alternative command not found
70 //config:config ASH_JOB_CONTROL
71 //config: bool "Job control"
73 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
75 //config:config ASH_ALIAS
76 //config: bool "Alias support"
78 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
80 //config:config ASH_RANDOM_SUPPORT
81 //config: bool "Pseudorandom generator and $RANDOM variable"
83 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
85 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
86 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
87 //config: You can reset the generator by using a specified start value.
88 //config: After "unset RANDOM" the generator will switch off and this
89 //config: variable will no longer have special treatment.
91 //config:config ASH_EXPAND_PRMT
92 //config: bool "Expand prompt string"
94 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
96 //config: $PS# may contain volatile content, such as backquote commands.
97 //config: This option recreates the prompt string from the environment
98 //config: variable each time it is displayed.
100 //config:config ASH_IDLE_TIMEOUT
101 //config: bool "Idle timeout variable $TMOUT"
103 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
105 //config: Enable bash-like auto-logout after $TMOUT seconds of idle time.
107 //config:config ASH_MAIL
108 //config: bool "Check for new mail in interactive shell"
110 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
112 //config: Enable "check for new mail" function:
113 //config: if set, $MAIL file and $MAILPATH list of files
114 //config: are checked for mtime changes, and "you have mail"
115 //config: message is printed if change is detected.
117 //config:config ASH_ECHO
118 //config: bool "echo builtin"
120 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
122 //config:config ASH_PRINTF
123 //config: bool "printf builtin"
125 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
127 //config:config ASH_TEST
128 //config: bool "test builtin"
130 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
132 //config:config ASH_HELP
133 //config: bool "help builtin"
135 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
137 //config:config ASH_GETOPTS
138 //config: bool "getopts builtin"
140 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
142 //config:config ASH_CMDCMD
143 //config: bool "command builtin"
145 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
147 //config: Enable support for the 'command' builtin, which allows
148 //config: you to run the specified command or builtin,
149 //config: even when there is a function with the same name.
151 //config:endif # ash options
153 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
154 // APPLET_ODDNAME:name main location suid_type help
155 //applet:IF_SH_IS_ASH( APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
156 //applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
158 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
159 //kbuild:lib-$(CONFIG_SH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
160 //kbuild:lib-$(CONFIG_BASH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
161 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
164 * DEBUG=1 to compile in debugging ('set -o debug' turns on)
165 * DEBUG=2 to compile in and turn on debugging.
166 * When debugging is on ("set -o debug" was executed, or DEBUG=2),
167 * debugging info is written to ./trace, quit signal generates core dump.
170 /* Tweak debug output verbosity here */
174 #define DEBUG_INTONOFF 0
178 #define JOBS ENABLE_ASH_JOB_CONTROL
181 #include <sys/times.h>
182 #include <sys/utsname.h> /* for setting $HOSTNAME */
183 #include "busybox.h" /* for applet_names */
184 #if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS
185 # include "embedded_scripts.h"
187 # define NUM_SCRIPTS 0
190 /* So far, all bash compat is controlled by one config option */
191 /* Separate defines document which part of code implements what */
192 /* function keyword */
193 #define BASH_FUNCTION ENABLE_ASH_BASH_COMPAT
194 #define IF_BASH_FUNCTION IF_ASH_BASH_COMPAT
196 #define BASH_REDIR_OUTPUT ENABLE_ASH_BASH_COMPAT
197 #define IF_BASH_REDIR_OUTPUT IF_ASH_BASH_COMPAT
199 #define BASH_DOLLAR_SQUOTE ENABLE_ASH_BASH_COMPAT
200 #define IF_BASH_DOLLAR_SQUOTE IF_ASH_BASH_COMPAT
201 #define BASH_PATTERN_SUBST ENABLE_ASH_BASH_COMPAT
202 #define IF_BASH_PATTERN_SUBST IF_ASH_BASH_COMPAT
203 #define BASH_SUBSTR ENABLE_ASH_BASH_COMPAT
204 #define IF_BASH_SUBSTR IF_ASH_BASH_COMPAT
205 /* BASH_TEST2: [[ EXPR ]]
206 * Status of [[ support:
207 * We replace && and || with -a and -o
209 * singleword+noglob expansion:
210 * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
211 * [[ /bin/n* ]]; echo 0:$?
212 * -a/-o are not AND/OR ops! (they are just strings)
213 * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
214 * = is glob match operator, not equality operator: STR = GLOB
215 * (in GLOB, quoting is significant on char-by-char basis: a*cd"*")
217 * add =~ regex match operator: STR =~ REGEX
219 #define BASH_TEST2 (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)
220 #define BASH_SOURCE ENABLE_ASH_BASH_COMPAT
221 #define BASH_PIPEFAIL ENABLE_ASH_BASH_COMPAT
222 #define BASH_HOSTNAME_VAR ENABLE_ASH_BASH_COMPAT
223 #define BASH_EPOCH_VARS ENABLE_ASH_BASH_COMPAT
224 #define BASH_SHLVL_VAR ENABLE_ASH_BASH_COMPAT
225 #define BASH_XTRACEFD ENABLE_ASH_BASH_COMPAT
226 #define BASH_READ_D ENABLE_ASH_BASH_COMPAT
227 #define IF_BASH_READ_D IF_ASH_BASH_COMPAT
228 #define BASH_WAIT_N ENABLE_ASH_BASH_COMPAT
230 #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
231 /* Bionic at least up to version 24 has no glob() */
232 # undef ENABLE_ASH_INTERNAL_GLOB
233 # define ENABLE_ASH_INTERNAL_GLOB 1
236 #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
237 # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
238 # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
239 # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
240 # error glob() should unbackslash them and match. uClibc does not unbackslash,
241 # error fails to match dirname, subsequently not expanding <pattern> in it.
243 // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
244 // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
247 #if !ENABLE_ASH_INTERNAL_GLOB
252 #include "shell_common.h"
253 #if ENABLE_FEATURE_SH_MATH
256 typedef long arith_t;
257 # define ARITH_FMT "%ld"
259 #if ENABLE_ASH_RANDOM_SUPPORT
262 # define CLEAR_RANDOM_T(rnd) ((void)0)
265 #include "NUM_APPLETS.h"
267 /* STANDALONE does not make sense, and won't compile */
268 # undef CONFIG_FEATURE_SH_STANDALONE
269 # undef ENABLE_FEATURE_SH_STANDALONE
270 # undef IF_FEATURE_SH_STANDALONE
271 # undef IF_NOT_FEATURE_SH_STANDALONE
272 # define ENABLE_FEATURE_SH_STANDALONE 0
273 # define IF_FEATURE_SH_STANDALONE(...)
274 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
277 #ifndef F_DUPFD_CLOEXEC
278 # define F_DUPFD_CLOEXEC F_DUPFD
284 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
288 # error "Do not even bother, ash will not run on NOMMU machine"
291 /* We use a trick to have more optimized code (fewer pointer reloads):
292 * ash.c: extern struct globals *const ash_ptr_to_globals;
293 * ash_ptr_hack.c: struct globals *ash_ptr_to_globals;
294 * This way, compiler in ash.c knows the pointer can not change.
296 * However, this may break on weird arches or toolchains. In this case,
297 * set "-DBB_GLOBAL_CONST=''" in CONFIG_EXTRA_CFLAGS to disable
300 #ifndef BB_GLOBAL_CONST
301 # define BB_GLOBAL_CONST const
305 /* ============ Hash table sizes. Configurable. */
309 #define CMDTABLESIZE 31 /* should be prime */
312 /* ============ Shell options */
314 static const char *const optletters_optnames[] = {
318 /* The below allowed this invocation:
319 * ash -c 'set -i; echo $-; sleep 5; echo $-'
320 * to be ^C-ed and get to interactive ash prompt.
321 * bash does not support such "set -i".
322 * In our code, this is denoted by empty long name:
327 /* Ditto: bash has no "set -s" */
345 //bash 4.4.23 also has these opts (with these defaults):
353 //interactive-comments on
360 #define optletters(n) optletters_optnames[n][0]
361 #define optnames(n) (optletters_optnames[n] + 1)
363 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
366 /* ============ Misc data */
368 #define msg_illnum "Illegal number: %s"
371 * We enclose jmp_buf in a structure so that we can declare pointers to
372 * jump locations. The global variable handler contains the location to
373 * jump to when an exception occurs, and the global variable exception_type
374 * contains a code identifying the exception. To implement nested
375 * exception handlers, the user should save the value of handler on entry
376 * to an inner scope, set handler to point to a jmploc structure for the
377 * inner scope, and restore handler on exit from the scope.
383 struct globals_misc {
384 uint8_t exitstatus; /* exit status of last command */
385 uint8_t back_exitstatus;/* exit status of backquoted command */
386 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
387 int savestatus; /* exit status of last command outside traps */
388 int rootpid; /* pid of main shell */
389 /* shell level: 0 for the main shell, 1 for its children, and so on */
391 #define rootshell (!shlvl)
394 char *minusc; /* argument to -c option */
396 char *curdir; // = nullstr; /* current working directory */
397 char *physdir; // = nullstr; /* physical working directory */
399 char *arg0; /* value of $0 */
401 struct jmploc *exception_handler;
403 volatile int suppress_int; /* counter */
404 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
405 volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
406 volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
407 smallint exception_type; /* kind of exception (0..5) */
409 #define EXINT 0 /* SIGINT received */
410 #define EXERROR 1 /* a generic error */
411 #define EXEXIT 4 /* exit the shell */
413 char nullstr[1]; /* zero length string */
416 #define eflag optlist[0]
417 #define fflag optlist[1]
418 #define Iflag optlist[2]
419 #define iflag optlist[3]
420 #define mflag optlist[4]
421 #define nflag optlist[5]
422 #define sflag optlist[6]
423 #define cflag optlist[7]
424 #define xflag optlist[8]
425 #define vflag optlist[9]
426 #define Cflag optlist[10]
427 #define aflag optlist[11]
428 #define bflag optlist[12]
429 #define uflag optlist[13]
430 #define viflag optlist[14]
432 # define pipefail optlist[15]
437 # define nolog optlist[15 + BASH_PIPEFAIL]
438 # define debug optlist[16 + BASH_PIPEFAIL]
441 /* trap handler commands */
443 * Sigmode records the current value of the signal handlers for the various
444 * modes. A value of zero means that the current handler is not known.
445 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
447 char sigmode[NSIG - 1];
448 #define S_DFL 1 /* default signal handling (SIG_DFL) */
449 #define S_CATCH 2 /* signal is caught */
450 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
451 #define S_HARD_IGN 4 /* signal is ignored permanently (it was SIG_IGN on entry to shell) */
453 /* indicates specified signal received */
454 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
455 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
457 char **trap_ptr; /* used only by "trap hack" */
459 /* Rarely referenced stuff */
460 #if ENABLE_ASH_RANDOM_SUPPORT
463 pid_t backgndpid; /* pid of last background process */
465 extern struct globals_misc *BB_GLOBAL_CONST ash_ptr_to_globals_misc;
466 #define G_misc (*ash_ptr_to_globals_misc)
467 #define exitstatus (G_misc.exitstatus )
468 #define back_exitstatus (G_misc.back_exitstatus )
469 #define job_warning (G_misc.job_warning)
470 #define savestatus (G_misc.savestatus )
471 #define rootpid (G_misc.rootpid )
472 #define shlvl (G_misc.shlvl )
473 #define errlinno (G_misc.errlinno )
474 #define minusc (G_misc.minusc )
475 #define curdir (G_misc.curdir )
476 #define physdir (G_misc.physdir )
477 #define arg0 (G_misc.arg0 )
478 #define exception_handler (G_misc.exception_handler)
479 #define exception_type (G_misc.exception_type )
480 #define suppress_int (G_misc.suppress_int )
481 #define pending_int (G_misc.pending_int )
482 #define got_sigchld (G_misc.got_sigchld )
483 #define pending_sig (G_misc.pending_sig )
484 #define nullstr (G_misc.nullstr )
485 #define optlist (G_misc.optlist )
486 #define sigmode (G_misc.sigmode )
487 #define gotsig (G_misc.gotsig )
488 #define may_have_traps (G_misc.may_have_traps )
489 #define trap (G_misc.trap )
490 #define trap_ptr (G_misc.trap_ptr )
491 #define random_gen (G_misc.random_gen )
492 #define backgndpid (G_misc.backgndpid )
493 #define INIT_G_misc() do { \
494 (*(struct globals_misc**)not_const_pp(&ash_ptr_to_globals_misc)) = xzalloc(sizeof(G_misc)); \
503 /* ============ DEBUG */
505 static void trace_printf(const char *fmt, ...);
506 static void trace_vprintf(const char *fmt, va_list va);
507 # define TRACE(param) trace_printf param
508 # define TRACEV(param) trace_vprintf param
509 # define close(fd) do { \
511 if (close(dfd) < 0) \
512 bb_error_msg("bug on %d: closing %d(0x%x)", \
513 __LINE__, dfd, dfd); \
516 # define TRACE(param)
517 # define TRACEV(param)
521 /* ============ Utility functions */
522 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
523 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
526 isdigit_str9(const char *str)
528 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
529 while (--maxlen && isdigit(*str))
531 return (*str == '\0');
535 var_end(const char *var)
544 /* ============ Interrupts / exceptions */
546 static void exitshell(void) NORETURN;
549 * These macros allow the user to suspend the handling of interrupt signals
550 * over a period of time. This is similar to SIGHOLD or to sigblock, but
551 * much more efficient and portable. (But hacking the kernel is so much
552 * more fun than worrying about efficiency and portability. :-))
555 # define INT_OFF do { \
556 TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
561 # define INT_OFF do { \
568 * Called to raise an exception. Since C doesn't include exceptions, we
569 * just do a longjmp to the exception handler. The type of exception is
570 * stored in the global variable "exception_type".
572 static void raise_exception(int) NORETURN;
574 raise_exception(int e)
577 if (exception_handler == NULL)
582 longjmp(exception_handler->loc, 1);
585 #define raise_exception(e) do { \
586 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
587 raise_exception(e); \
592 * Called when a SIGINT is received. (If the user specifies
593 * that SIGINT is to be trapped or ignored using the trap builtin, then
594 * this routine is not called.) Suppressint is nonzero when interrupts
595 * are held using the INT_OFF macro. (The test for iflag is just
596 * defensive programming.)
598 static void raise_interrupt(void) NORETURN;
600 raise_interrupt(void)
603 /* Signal is not automatically unmasked after it is raised,
604 * do it ourself - unmask all signals */
605 sigprocmask_allsigs(SIG_UNBLOCK);
606 /* pending_sig = 0; - now done in signal_handler() */
608 if (!(rootshell && iflag)) {
609 /* Kill ourself with SIGINT */
610 signal(SIGINT, SIG_DFL);
613 /* bash: ^C even on empty command line sets $? */
614 exitstatus = SIGINT + 128;
615 raise_exception(EXINT);
619 #define raise_interrupt() do { \
620 TRACE(("raising interrupt on line %d\n", __LINE__)); \
625 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
629 if (--suppress_int == 0 && pending_int) {
634 # define INT_ON do { \
635 TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
639 # define INT_ON int_on()
641 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
649 #define FORCE_INT_ON force_int_on()
651 #define SAVE_INT(v) ((v) = suppress_int)
653 #define RESTORE_INT(v) do { \
655 suppress_int = (v); \
656 if (suppress_int == 0 && pending_int) \
661 /* ============ Stdout/stderr output */
664 outstr(const char *p, FILE *file)
672 flush_stdout_stderr(void)
679 /* Was called outcslow(c,FILE*), but c was always '\n' */
681 newline_and_flush(FILE *dest)
689 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
691 out1fmt(const char *fmt, ...)
698 r = vprintf(fmt, ap);
704 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
706 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
713 ret = vsnprintf(outbuf, length, fmt, ap);
716 return ret > (int)length ? length : ret;
720 out1str(const char *p)
726 out2str(const char *p)
729 flush_stdout_stderr();
733 /* ============ Parser structures */
735 /* control characters in argument strings */
736 #define CTL_FIRST CTLESC
737 #define CTLESC ((unsigned char)'\201') /* escape next character */
738 #define CTLVAR ((unsigned char)'\202') /* variable defn */
739 #define CTLENDVAR ((unsigned char)'\203')
740 #define CTLBACKQ ((unsigned char)'\204')
741 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
742 #define CTLENDARI ((unsigned char)'\207')
743 #define CTLQUOTEMARK ((unsigned char)'\210')
744 #define CTL_LAST CTLQUOTEMARK
746 /* variable substitution byte (follows CTLVAR) */
747 #define VSTYPE 0x0f /* type of variable substitution */
748 #define VSNUL 0x10 /* colon--treat the empty string as unset */
750 /* values of VSTYPE field */
751 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
752 #define VSMINUS 0x2 /* ${var-text} */
753 #define VSPLUS 0x3 /* ${var+text} */
754 #define VSQUESTION 0x4 /* ${var?message} */
755 #define VSASSIGN 0x5 /* ${var=text} */
756 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
757 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
758 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
759 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
760 #define VSLENGTH 0xa /* ${#var} */
762 #define VSSUBSTR 0xc /* ${var:position:length} */
764 #if BASH_PATTERN_SUBST
765 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
766 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
769 static const char dolatstr[] ALIGN1 = {
770 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
772 #define DOLATSTRLEN 6
791 #if BASH_REDIR_OUTPUT
808 smallint type; /* Nxxxx */
812 union node *redirect;
817 smallint pipe_backgnd;
818 struct nodelist *cmdlist;
825 union node *redirect;
838 union node *elsepart;
874 struct nodelist *backquote;
877 /* nfile and ndup layout must match!
878 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
879 * that it is actually NTO2 (>&file), and change its type.
896 char *_unused_expfname;
915 struct nredir nredir;
916 struct nbinary nbinary;
920 struct nclist nclist;
921 struct ndefun ndefun;
930 * NODE_EOF is returned by parsecmd when it encounters an end of file.
931 * It must be distinct from NULL.
933 #define NODE_EOF ((union node *) -1L)
936 struct nodelist *next;
949 freefunc(struct funcnode *f)
951 if (f && --f->count < 0)
956 /* ============ Debugging output */
960 static FILE *tracefile;
963 trace_printf(const char *fmt, ...)
970 fprintf(tracefile, "%u ", (int) time(NULL));
972 fprintf(tracefile, "[%u] ", (int) getpid());
974 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
976 vfprintf(tracefile, fmt, va);
981 trace_vprintf(const char *fmt, va_list va)
985 vfprintf(tracefile, fmt, va);
986 fprintf(tracefile, "\n");
990 trace_puts(const char *s)
998 trace_puts_quoted(char *s)
1005 putc('"', tracefile);
1006 for (p = s; *p; p++) {
1007 switch ((unsigned char)*p) {
1008 case '\n': c = 'n'; goto backslash;
1009 case '\t': c = 't'; goto backslash;
1010 case '\r': c = 'r'; goto backslash;
1011 case '\"': c = '\"'; goto backslash;
1012 case '\\': c = '\\'; goto backslash;
1013 case CTLESC: c = 'e'; goto backslash;
1014 case CTLVAR: c = 'v'; goto backslash;
1015 case CTLBACKQ: c = 'q'; goto backslash;
1017 putc('\\', tracefile);
1021 if (*p >= ' ' && *p <= '~')
1022 putc(*p, tracefile);
1024 putc('\\', tracefile);
1025 putc((*p >> 6) & 03, tracefile);
1026 putc((*p >> 3) & 07, tracefile);
1027 putc(*p & 07, tracefile);
1032 putc('"', tracefile);
1036 trace_puts_args(char **ap)
1043 trace_puts_quoted(*ap);
1045 putc('\n', tracefile);
1048 putc(' ', tracefile);
1063 /* leave open because libedit might be using it */
1066 strcpy(s, "./trace");
1068 if (!freopen(s, "a", tracefile)) {
1069 fprintf(stderr, "Can't re-open %s\n", s);
1074 tracefile = fopen(s, "a");
1075 if (tracefile == NULL) {
1076 fprintf(stderr, "Can't open %s\n", s);
1082 flags = fcntl(fileno(tracefile), F_GETFL);
1084 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
1086 setlinebuf(tracefile);
1087 fputs("\nTracing started.\n", tracefile);
1091 indent(int amount, char *pfx, FILE *fp)
1095 for (i = 0; i < amount; i++) {
1096 if (pfx && i == amount - 1)
1102 /* little circular references here... */
1103 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
1106 sharg(union node *arg, FILE *fp)
1109 struct nodelist *bqlist;
1110 unsigned char subtype;
1112 if (arg->type != NARG) {
1113 out1fmt("<node type %d>\n", arg->type);
1116 bqlist = arg->narg.backquote;
1117 for (p = arg->narg.text; *p; p++) {
1118 switch ((unsigned char)*p) {
1127 if (subtype == VSLENGTH)
1135 if (subtype & VSNUL)
1138 switch (subtype & VSTYPE) {
1164 case VSTRIMRIGHTMAX:
1171 out1fmt("<subtype %d>", subtype);
1180 shtree(bqlist->n, -1, NULL, fp);
1191 shcmd(union node *cmd, FILE *fp)
1199 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1205 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1209 switch (np->nfile.type) {
1210 case NTO: s = ">>"+1; dftfd = 1; break;
1211 case NCLOBBER: s = ">|"; dftfd = 1; break;
1212 case NAPPEND: s = ">>"; dftfd = 1; break;
1213 #if BASH_REDIR_OUTPUT
1216 case NTOFD: s = ">&"; dftfd = 1; break;
1217 case NFROM: s = "<"; break;
1218 case NFROMFD: s = "<&"; break;
1219 case NFROMTO: s = "<>"; break;
1220 default: s = "*error*"; break;
1222 if (np->nfile.fd != dftfd)
1223 fprintf(fp, "%d", np->nfile.fd);
1225 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1226 fprintf(fp, "%d", np->ndup.dupfd);
1228 sharg(np->nfile.fname, fp);
1235 shtree(union node *n, int ind, char *pfx, FILE *fp)
1237 struct nodelist *lp;
1243 indent(ind, pfx, fp);
1245 if (n == NODE_EOF) {
1260 shtree(n->nbinary.ch1, ind, NULL, fp);
1263 shtree(n->nbinary.ch2, ind, NULL, fp);
1271 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1272 shtree(lp->n, 0, NULL, fp);
1276 if (n->npipe.pipe_backgnd)
1282 fprintf(fp, "<node type %d>", n->type);
1290 showtree(union node *n)
1292 trace_puts("showtree called\n");
1293 shtree(n, 1, NULL, stderr);
1299 /* ============ Parser data */
1302 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1305 struct strlist *next;
1312 struct strpush *prev; /* preceding string on stack */
1314 int prev_left_in_line;
1315 #if ENABLE_ASH_ALIAS
1316 struct alias *ap; /* if push was associated with an alias */
1318 char *string; /* remember the string since it may change */
1320 /* Remember last two characters for pungetc. */
1323 /* Number of outstanding calls to pungetc. */
1328 * The parsefile structure pointed to by the global variable parsefile
1329 * contains information about the current file being read.
1332 struct parsefile *prev; /* preceding file on stack */
1333 int linno; /* current line */
1334 int pf_fd; /* file descriptor (or -1 if string) */
1335 int left_in_line; /* number of chars left in this line */
1336 int left_in_buffer; /* number of chars left in this buffer past the line */
1337 char *next_to_pgetc; /* next char in buffer */
1338 char *buf; /* input buffer */
1339 struct strpush *strpush; /* for pushing strings at this level */
1340 struct strpush basestrpush; /* so pushing one is fast */
1342 /* Remember last two characters for pungetc. */
1345 /* Number of outstanding calls to pungetc. */
1349 static struct parsefile basepf; /* top level input file */
1350 static struct parsefile *g_parsefile = &basepf; /* current input file */
1351 static char *commandname; /* currently executing command */
1354 /* ============ Message printing */
1357 ash_vmsg(const char *msg, va_list ap)
1359 fprintf(stderr, "%s: ", arg0);
1361 if (strcmp(arg0, commandname))
1362 fprintf(stderr, "%s: ", commandname);
1363 if (!iflag || g_parsefile->pf_fd > 0)
1364 fprintf(stderr, "line %d: ", errlinno);
1366 vfprintf(stderr, msg, ap);
1367 newline_and_flush(stderr);
1371 * Exverror is called to raise the error exception. If the second argument
1372 * is not NULL then error prints an error message using printf style
1373 * formatting. It then raises the error exception.
1375 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1377 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1381 TRACE(("ash_vmsg_and_raise(%d):", cond));
1384 TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
1389 flush_stdout_stderr();
1390 raise_exception(cond);
1394 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1396 ash_msg_and_raise_error(const char *msg, ...)
1403 ash_vmsg_and_raise(EXERROR, msg, ap);
1409 * 'fmt' must be a string literal.
1411 #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": "STRERROR_FMT, ##__VA_ARGS__ STRERROR_ERRNO)
1413 static void raise_error_syntax(const char *) NORETURN;
1415 raise_error_syntax(const char *msg)
1417 errlinno = g_parsefile->linno;
1418 ash_msg_and_raise_error("syntax error: %s", msg);
1422 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1424 ash_msg_and_raise(int cond, const char *msg, ...)
1429 ash_vmsg_and_raise(cond, msg, ap);
1435 * error/warning routines for external builtins
1438 ash_msg(const char *fmt, ...)
1448 * Return a string describing an error. The returned string may be a
1449 * pointer to a static buffer that will be overwritten on the next call.
1450 * Action describes the operation that got the error.
1453 errmsg(int e, const char *em)
1455 if (e == ENOENT || e == ENOTDIR) {
1462 /* ============ Memory allocation */
1465 /* I consider these wrappers nearly useless:
1466 * ok, they return you to nearest exception handler, but
1467 * how much memory do you leak in the process, making
1468 * memory starvation worse?
1471 ckrealloc(void * p, size_t nbytes)
1473 p = realloc(p, nbytes);
1475 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1480 ckmalloc(size_t nbytes)
1482 return ckrealloc(NULL, nbytes);
1486 ckzalloc(size_t nbytes)
1488 return memset(ckmalloc(nbytes), 0, nbytes);
1492 ckstrdup(const char *s)
1494 char *p = strdup(s);
1496 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1500 /* Using bbox equivalents. They exit if out of memory */
1501 # define ckrealloc xrealloc
1502 # define ckmalloc xmalloc
1503 # define ckzalloc xzalloc
1504 # define ckstrdup xstrdup
1508 * It appears that grabstackstr() will barf with such alignments
1509 * because stalloc() will return a string allocated in a new stackblock.
1511 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1513 /* Most machines require the value returned from malloc to be aligned
1514 * in some way. The following macro will get this right
1515 * on many machines. */
1516 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1517 /* Minimum size of a block */
1518 MINSIZE = SHELL_ALIGN(504),
1521 struct stack_block {
1522 struct stack_block *prev;
1523 char space[MINSIZE];
1527 struct stack_block *stackp;
1533 struct globals_memstack {
1534 struct stack_block *g_stackp; // = &stackbase;
1535 char *g_stacknxt; // = stackbase.space;
1536 char *sstrend; // = stackbase.space + MINSIZE;
1537 size_t g_stacknleft; // = MINSIZE;
1538 struct stack_block stackbase;
1540 extern struct globals_memstack *BB_GLOBAL_CONST ash_ptr_to_globals_memstack;
1541 #define G_memstack (*ash_ptr_to_globals_memstack)
1542 #define g_stackp (G_memstack.g_stackp )
1543 #define g_stacknxt (G_memstack.g_stacknxt )
1544 #define sstrend (G_memstack.sstrend )
1545 #define g_stacknleft (G_memstack.g_stacknleft)
1546 #define stackbase (G_memstack.stackbase )
1547 #define INIT_G_memstack() do { \
1548 (*(struct globals_memstack**)not_const_pp(&ash_ptr_to_globals_memstack)) = xzalloc(sizeof(G_memstack)); \
1550 g_stackp = &stackbase; \
1551 g_stacknxt = stackbase.space; \
1552 g_stacknleft = MINSIZE; \
1553 sstrend = stackbase.space + MINSIZE; \
1557 #define stackblock() ((void *)g_stacknxt)
1558 #define stackblocksize() g_stacknleft
1561 * Parse trees for commands are allocated in lifo order, so we use a stack
1562 * to make this more efficient, and also to avoid all sorts of exception
1563 * handling code to handle interrupts in the middle of a parse.
1565 * The size 504 was chosen because the Ultrix malloc handles that size
1569 stalloc(size_t nbytes)
1574 aligned = SHELL_ALIGN(nbytes);
1575 if (aligned > g_stacknleft) {
1578 struct stack_block *sp;
1580 blocksize = aligned;
1581 if (blocksize < MINSIZE)
1582 blocksize = MINSIZE;
1583 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1584 if (len < blocksize)
1585 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1588 sp->prev = g_stackp;
1589 g_stacknxt = sp->space;
1590 g_stacknleft = blocksize;
1591 sstrend = g_stacknxt + blocksize;
1596 g_stacknxt += aligned;
1597 g_stacknleft -= aligned;
1602 stzalloc(size_t nbytes)
1604 return memset(stalloc(nbytes), 0, nbytes);
1611 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1612 write(STDERR_FILENO, "stunalloc\n", 10);
1616 g_stacknleft += g_stacknxt - (char *)p;
1621 * Like strdup but works with the ash stack.
1624 sstrdup(const char *p)
1626 size_t len = strlen(p) + 1;
1627 return memcpy(stalloc(len), p, len);
1630 static ALWAYS_INLINE void
1631 grabstackblock(size_t len)
1637 pushstackmark(struct stackmark *mark, size_t len)
1639 mark->stackp = g_stackp;
1640 mark->stacknxt = g_stacknxt;
1641 mark->stacknleft = g_stacknleft;
1642 grabstackblock(len);
1646 setstackmark(struct stackmark *mark)
1648 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1652 popstackmark(struct stackmark *mark)
1654 struct stack_block *sp;
1660 while (g_stackp != mark->stackp) {
1662 g_stackp = sp->prev;
1665 g_stacknxt = mark->stacknxt;
1666 g_stacknleft = mark->stacknleft;
1667 sstrend = mark->stacknxt + mark->stacknleft;
1672 * When the parser reads in a string, it wants to stick the string on the
1673 * stack and only adjust the stack pointer when it knows how big the
1674 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1675 * of space on top of the stack and stackblocklen returns the length of
1676 * this block. Growstackblock will grow this space by at least one byte,
1677 * possibly moving it (like realloc). Grabstackblock actually allocates the
1678 * part of the block that has been used.
1681 growstackblock(void)
1685 newlen = g_stacknleft * 2;
1686 if (newlen < g_stacknleft)
1687 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1691 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1692 struct stack_block *sp;
1693 struct stack_block *prevstackp;
1698 prevstackp = sp->prev;
1699 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1700 sp = ckrealloc(sp, grosslen);
1701 sp->prev = prevstackp;
1703 g_stacknxt = sp->space;
1704 g_stacknleft = newlen;
1705 sstrend = sp->space + newlen;
1708 char *oldspace = g_stacknxt;
1709 size_t oldlen = g_stacknleft;
1710 char *p = stalloc(newlen);
1712 /* free the space we just allocated */
1713 g_stacknxt = memcpy(p, oldspace, oldlen);
1714 g_stacknleft += newlen;
1719 * The following routines are somewhat easier to use than the above.
1720 * The user declares a variable of type STACKSTR, which may be declared
1721 * to be a register. The macro STARTSTACKSTR initializes things. Then
1722 * the user uses the macro STPUTC to add characters to the string. In
1723 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1724 * grown as necessary. When the user is done, she can just leave the
1725 * string there and refer to it using stackblock(). Or she can allocate
1726 * the space for it using grabstackstr(). If it is necessary to allow
1727 * someone else to use the stack temporarily and then continue to grow
1728 * the string, the user should use grabstack to allocate the space, and
1729 * then call ungrabstr(p) to return to the previous mode of operation.
1731 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1732 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1733 * is space for at least one character.
1738 size_t len = stackblocksize();
1740 return (char *)stackblock() + len;
1744 growstackto(size_t len)
1746 while (stackblocksize() < len)
1749 return stackblock();
1753 * Called from CHECKSTRSPACE.
1756 makestrspace(size_t newlen, char *p)
1758 size_t len = p - g_stacknxt;
1760 return growstackto(len + newlen) + len;
1764 stack_nputstr(const char *s, size_t n, char *p)
1766 p = makestrspace(n, p);
1767 p = (char *)mempcpy(p, s, n);
1772 stack_putstr(const char *s, char *p)
1774 return stack_nputstr(s, strlen(s), p);
1778 _STPUTC(int c, char *p)
1786 #define STARTSTACKSTR(p) ((p) = stackblock())
1787 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1788 #define CHECKSTRSPACE(n, p) do { \
1791 size_t m = sstrend - q; \
1793 (p) = makestrspace(l, q); \
1795 #define USTPUTC(c, p) (*(p)++ = (c))
1796 #define STACKSTRNUL(p) do { \
1797 if ((p) == sstrend) \
1798 (p) = growstackstr(); \
1801 #define STUNPUTC(p) (--(p))
1802 #define STTOPC(p) ((p)[-1])
1803 #define STADJUST(amount, p) ((p) += (amount))
1805 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1806 #define ungrabstackstr(s, p) stunalloc(s)
1807 #define stackstrend() ((void *)sstrend)
1810 /* ============ String helpers */
1813 * prefix -- see if pfx is a prefix of string.
1816 prefix(const char *string, const char *pfx)
1819 if (*pfx++ != *string++)
1822 return (char *) string;
1826 * Check for a valid number. This should be elsewhere.
1829 is_number(const char *p)
1834 } while (*++p != '\0');
1839 * Convert a string of digits to an integer, printing an error message on
1843 number(const char *s)
1846 ash_msg_and_raise_error(msg_illnum, s);
1851 * Produce a single quoted string suitable as input to the shell.
1852 * The return string is allocated on the stack.
1855 single_quote(const char *s)
1865 len = strchrnul(s, '\'') - s;
1867 q = p = makestrspace(len + 3, p);
1870 q = (char *)mempcpy(q, s, len);
1879 do len++; while (*++s == '\'');
1881 q = p = makestrspace(len + 3, p);
1884 q = (char *)mempcpy(q, s - len, len);
1892 return stackblock();
1896 * Produce a possibly single quoted string suitable as input to the shell.
1897 * If quoting was done, the return string is allocated on the stack,
1898 * otherwise a pointer to the original string is returned.
1901 maybe_single_quote(const char *s)
1906 /* Assuming ACSII */
1907 /* quote ctrl_chars space !"#$%&'()* */
1911 if (*p >= ';' && *p <= '?')
1920 /* quote {|}~ DEL and high bytes */
1923 /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
1924 /* TODO: maybe avoid quoting % */
1930 return single_quote(s);
1934 /* ============ nextopt */
1936 static char **argptr; /* argument list for builtin commands */
1937 static char *optionarg; /* set by nextopt (like getopt) */
1938 static char *optptr; /* used by nextopt */
1941 * XXX - should get rid of. Have all builtins use getopt(3).
1942 * The library getopt must have the BSD extension static variable
1943 * "optreset", otherwise it can't be used within the shell safely.
1945 * Standard option processing (a la getopt) for builtin routines.
1946 * The only argument that is passed to nextopt is the option string;
1947 * the other arguments are unnecessary. It returns the character,
1948 * or '\0' on end of input.
1951 nextopt(const char *optstring)
1958 if (p == NULL || *p == '\0') {
1959 /* We ate entire "-param", take next one */
1965 if (*++p == '\0') /* just "-" ? */
1968 if (LONE_DASH(p)) /* "--" ? */
1970 /* p => next "-param" */
1972 /* p => some option char in the middle of a "-param" */
1974 for (q = optstring; *q != c;) {
1976 ash_msg_and_raise_error("illegal option -%c", c);
1984 ash_msg_and_raise_error("no arg for -%c option", c);
1994 /* ============ Shell variables */
1997 int nparam; /* # of positional parameters (without $0) */
1998 #if ENABLE_ASH_GETOPTS
1999 int optind; /* next parameter to be processed by getopts */
2000 int optoff; /* used by getopts */
2002 unsigned char malloced; /* if parameter list dynamically allocated */
2003 char **p; /* parameter list */
2007 * Free the list of positional parameters.
2010 freeparam(volatile struct shparam *param)
2012 if (param->malloced) {
2014 ap = ap1 = param->p;
2021 #if ENABLE_ASH_GETOPTS
2022 static void FAST_FUNC getoptsreset(const char *value);
2026 struct var *next; /* next entry in hash list */
2027 int flags; /* flags are defined above */
2028 const char *var_text; /* name=value */
2029 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
2030 /* the variable gets set/unset */
2034 struct localvar *next; /* next local variable in list */
2035 struct var *vp; /* the variable that was made local */
2036 int flags; /* saved flags */
2037 const char *text; /* saved text */
2041 #define VEXPORT 0x01 /* variable is exported */
2042 #define VREADONLY 0x02 /* variable cannot be modified */
2043 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
2044 #define VTEXTFIXED 0x08 /* text is statically allocated */
2045 #define VSTACK 0x10 /* text is allocated on the stack */
2046 #define VUNSET 0x20 /* the variable is not set */
2047 #define VNOFUNC 0x40 /* don't call the callback function */
2048 #define VNOSET 0x80 /* do not set variable - just readonly test */
2049 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
2050 #if ENABLE_ASH_RANDOM_SUPPORT
2051 # define VDYNAMIC 0x200 /* dynamic variable */
2057 /* Need to be before varinit_data[] */
2058 #if ENABLE_LOCALE_SUPPORT
2059 static void FAST_FUNC
2060 change_lc_all(const char *value)
2062 if (value && *value != '\0')
2063 setlocale(LC_ALL, value);
2065 static void FAST_FUNC
2066 change_lc_ctype(const char *value)
2068 if (value && *value != '\0')
2069 setlocale(LC_CTYPE, value);
2073 static void chkmail(void);
2074 static void changemail(const char *var_value) FAST_FUNC;
2076 # define chkmail() ((void)0)
2078 static void changepath(const char *) FAST_FUNC;
2079 #if ENABLE_ASH_RANDOM_SUPPORT
2080 static void change_random(const char *) FAST_FUNC;
2083 static void change_seconds(const char *) FAST_FUNC;
2084 static void change_realtime(const char *) FAST_FUNC;
2087 static const struct {
2089 const char *var_text;
2090 void (*var_func)(const char *) FAST_FUNC;
2091 } varinit_data[] = {
2093 * Note: VEXPORT would not work correctly here for NOFORK applets:
2094 * some environment strings may be constant.
2096 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
2098 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
2099 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
2101 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
2102 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
2103 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
2104 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
2105 #if ENABLE_ASH_GETOPTS
2106 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
2108 { VSTRFIXED|VTEXTFIXED , NULL /* inited to linenovar */, NULL },
2109 #if ENABLE_ASH_RANDOM_SUPPORT
2110 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
2113 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "EPOCHSECONDS", change_seconds },
2114 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "EPOCHREALTIME", change_realtime },
2116 #if ENABLE_LOCALE_SUPPORT
2117 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
2118 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
2120 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
2121 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
2127 struct globals_var {
2128 struct shparam shellparam; /* $@ current positional parameters */
2129 struct redirtab *redirlist;
2130 int preverrout_fd; /* stderr fd: usually 2, unless redirect moved it */
2131 struct var *vartab[VTABSIZE];
2132 struct var varinit[ARRAY_SIZE(varinit_data)];
2134 char linenovar[sizeof("LINENO=") + sizeof(int)*3];
2136 extern struct globals_var *BB_GLOBAL_CONST ash_ptr_to_globals_var;
2137 #define G_var (*ash_ptr_to_globals_var)
2138 #define shellparam (G_var.shellparam )
2139 //#define redirlist (G_var.redirlist )
2140 #define preverrout_fd (G_var.preverrout_fd)
2141 #define vartab (G_var.vartab )
2142 #define varinit (G_var.varinit )
2143 #define lineno (G_var.lineno )
2144 #define linenovar (G_var.linenovar )
2145 #define vifs varinit[0]
2147 # define vmail varinit[1]
2148 # define vmpath varinit[2]
2150 #define VAR_OFFSET1 (ENABLE_ASH_MAIL*2)
2151 #define vpath varinit[VAR_OFFSET1 + 1]
2152 #define vps1 varinit[VAR_OFFSET1 + 2]
2153 #define vps2 varinit[VAR_OFFSET1 + 3]
2154 #define vps4 varinit[VAR_OFFSET1 + 4]
2155 #if ENABLE_ASH_GETOPTS
2156 # define voptind varinit[VAR_OFFSET1 + 5]
2158 #define VAR_OFFSET2 (VAR_OFFSET1 + ENABLE_ASH_GETOPTS)
2159 #define vlineno varinit[VAR_OFFSET2 + 5]
2160 #if ENABLE_ASH_RANDOM_SUPPORT
2161 # define vrandom varinit[VAR_OFFSET2 + 6]
2163 #define VAR_OFFSET3 (VAR_OFFSET2 + ENABLE_ASH_RANDOM_SUPPORT)
2165 # define vepochs varinit[VAR_OFFSET3 + 6]
2166 # define vepochr varinit[VAR_OFFSET3 + 7]
2168 #define INIT_G_var() do { \
2170 (*(struct globals_var**)not_const_pp(&ash_ptr_to_globals_var)) = xzalloc(sizeof(G_var)); \
2172 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
2173 varinit[i].flags = varinit_data[i].flags; \
2174 varinit[i].var_text = varinit_data[i].var_text; \
2175 varinit[i].var_func = varinit_data[i].var_func; \
2177 strcpy(linenovar, "LINENO="); \
2178 vlineno.var_text = linenovar; \
2182 * The following macros access the values of the above variables.
2183 * They have to skip over the name. They return the null string
2184 * for unset variables.
2186 #define ifsval() (vifs.var_text + 4)
2187 #define ifsset() ((vifs.flags & VUNSET) == 0)
2189 # define mailval() (vmail.var_text + 5)
2190 # define mpathval() (vmpath.var_text + 9)
2191 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2193 #define pathval() (vpath.var_text + 5)
2194 #define ps1val() (vps1.var_text + 4)
2195 #define ps2val() (vps2.var_text + 4)
2196 #define ps4val() (vps4.var_text + 4)
2197 #if ENABLE_ASH_GETOPTS
2198 # define optindval() (voptind.var_text + 7)
2201 #if ENABLE_ASH_GETOPTS
2202 static void FAST_FUNC
2203 getoptsreset(const char *value)
2205 shellparam.optind = 1;
2206 if (is_number(value))
2207 shellparam.optind = number(value) ?: 1;
2208 shellparam.optoff = -1;
2213 * Compares two strings up to the first = or '\0'. The first
2214 * string must be terminated by '='; the second may be terminated by
2215 * either '=' or '\0'.
2218 varcmp(const char *p, const char *q)
2222 while ((c = *p) == (d = *q)) {
2223 if (c == '\0' || c == '=')
2237 * Find the appropriate entry in the hash table from the name.
2239 static struct var **
2240 hashvar(const char *p)
2244 hashval = ((unsigned char) *p) << 4;
2245 while (*p && *p != '=')
2246 hashval += (unsigned char) *p++;
2247 return &vartab[hashval % VTABSIZE];
2251 vpcmp(const void *a, const void *b)
2253 return varcmp(*(const char **)a, *(const char **)b);
2257 * This routine initializes the builtin variables.
2267 * PS1 depends on uid
2269 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2270 vps1.var_text = "PS1=\\w \\$ ";
2273 vps1.var_text = "PS1=# ";
2276 end = vp + ARRAY_SIZE(varinit);
2278 vpp = hashvar(vp->var_text);
2281 } while (++vp < end);
2284 static struct var **
2285 findvar(struct var **vpp, const char *name)
2287 for (; *vpp; vpp = &(*vpp)->next) {
2288 if (varcmp((*vpp)->var_text, name) == 0) {
2296 * Find the value of a variable. Returns NULL if not set.
2298 static const char* FAST_FUNC
2299 lookupvar(const char *name)
2303 v = *findvar(hashvar(name), name);
2305 #if ENABLE_ASH_RANDOM_SUPPORT || BASH_EPOCH_VARS
2307 * Dynamic variables are implemented roughly the same way they are
2308 * in bash. Namely, they're "special" so long as they aren't unset.
2309 * As soon as they're unset, they're no longer dynamic, and dynamic
2310 * lookup will no longer happen at that point. -- PFM.
2312 if (v->flags & VDYNAMIC)
2315 if (!(v->flags & VUNSET)) {
2316 if (v == &vlineno && v->var_text == linenovar) {
2317 fmtstr(linenovar+7, sizeof(linenovar)-7, "%d", lineno);
2319 return var_end(v->var_text);
2325 #if ENABLE_UNICODE_SUPPORT
2327 reinit_unicode_for_ash(void)
2329 /* Unicode support should be activated even if LANG is set
2330 * _during_ shell execution, not only if it was set when
2331 * shell was started. Therefore, re-check LANG every time:
2333 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2334 || ENABLE_UNICODE_USING_LOCALE
2336 const char *s = lookupvar("LC_ALL");
2337 if (!s) s = lookupvar("LC_CTYPE");
2338 if (!s) s = lookupvar("LANG");
2343 # define reinit_unicode_for_ash() ((void)0)
2347 * Search the environment of a builtin command.
2349 static ALWAYS_INLINE const char *
2350 bltinlookup(const char *name)
2352 return lookupvar(name);
2356 * Same as setvar except that the variable and value are passed in
2357 * the first argument as name=value. Since the first argument will
2358 * be actually stored in the table, it should not be a string that
2360 * Called with interrupts off.
2363 setvareq(char *s, int flags)
2365 struct var *vp, **vpp;
2368 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2369 vpp = findvar(vpp, s);
2372 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2375 if (flags & VNOSAVE)
2379 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2385 if (vp->var_func && !(flags & VNOFUNC))
2386 vp->var_func(var_end(s));
2388 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2389 free((char*)vp->var_text);
2391 if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
2395 if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
2400 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2401 #if ENABLE_ASH_RANDOM_SUPPORT || BASH_EPOCH_VARS
2406 /* variable s is not found */
2409 if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
2411 vp = ckzalloc(sizeof(*vp));
2413 /*vp->func = NULL; - ckzalloc did it */
2416 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2426 * Set the value of a variable. The flags argument is ored with the
2427 * flags of the variable. If val is NULL, the variable is unset.
2430 setvar(const char *name, const char *val, int flags)
2439 q = endofname(name);
2440 p = strchrnul(q, '=');
2442 if (!namelen || p != q)
2443 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2448 vallen = strlen(val);
2452 nameeq = ckzalloc(namelen + vallen + 2);
2453 p = mempcpy(nameeq, name, namelen);
2456 memcpy(p, val, vallen);
2458 vp = setvareq(nameeq, flags | VNOSAVE);
2464 static void FAST_FUNC
2465 setvar0(const char *name, const char *val)
2467 setvar(name, val, 0);
2471 * Unset the specified variable.
2474 unsetvar(const char *s)
2480 * Process a linked list of variable assignments.
2483 listsetvar(struct strlist *list_set_var, int flags)
2485 struct strlist *lp = list_set_var;
2491 setvareq(lp->text, flags);
2498 * Generate a list of variables satisfying the given conditions.
2500 #if !ENABLE_FEATURE_SH_NOFORK
2501 # define listvars(on, off, lp, end) listvars(on, off, end)
2504 listvars(int on, int off, struct strlist *lp, char ***end)
2515 for (vp = *vpp; vp; vp = vp->next) {
2516 if ((vp->flags & mask) == on) {
2517 #if ENABLE_FEATURE_SH_NOFORK
2518 /* If variable with the same name is both
2519 * exported and temporarily set for a command:
2522 * then "ZVAR=6" will be both in vartab and
2523 * lp lists. Do not pass it twice to printenv.
2525 struct strlist *lp1 = lp;
2527 if (strcmp(lp1->text, vp->var_text) == 0)
2532 if (ep == stackstrend())
2533 ep = growstackstr();
2534 *ep++ = (char*)vp->var_text;
2535 #if ENABLE_FEATURE_SH_NOFORK
2540 } while (++vpp < vartab + VTABSIZE);
2542 #if ENABLE_FEATURE_SH_NOFORK
2544 if (ep == stackstrend())
2545 ep = growstackstr();
2551 if (ep == stackstrend())
2552 ep = growstackstr();
2556 return grabstackstr(ep);
2560 /* ============ Path search helper
2562 * The variable path (passed by reference) should be set to the start
2563 * of the path before the first call; padvance will update
2564 * this value as it proceeds. Successive calls to padvance will return
2565 * the possible path expansions in sequence. If an option (indicated by
2566 * a percent sign) appears in the path entry then the global variable
2567 * pathopt will be set to point to it; otherwise pathopt will be set to
2570 static const char *pathopt; /* set by padvance */
2573 padvance(const char **path, const char *name)
2583 for (p = start; *p && *p != ':' && *p != '%'; p++)
2585 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2586 q = growstackto(len);
2588 q = mempcpy(q, start, p - start);
2595 while (*p && *p != ':')
2606 /* ============ Prompt */
2608 static smallint doprompt; /* if set, prompt the user */
2609 static smallint needprompt; /* true if interactive and at start of line */
2611 #if ENABLE_FEATURE_EDITING
2612 static line_input_t *line_input_state;
2613 static const char *cmdedit_prompt;
2615 putprompt(const char *s)
2617 if (ENABLE_ASH_EXPAND_PRMT) {
2618 free((char*)cmdedit_prompt);
2619 cmdedit_prompt = ckstrdup(s);
2626 putprompt(const char *s)
2632 /* expandstr() needs parsing machinery, so it is far away ahead... */
2633 static const char *expandstr(const char *ps, int syntax_type);
2634 /* Values for syntax param */
2635 #define BASESYNTAX 0 /* not in quotes */
2636 #define DQSYNTAX 1 /* in double quotes */
2637 #define SQSYNTAX 2 /* in single quotes */
2638 #define ARISYNTAX 3 /* in arithmetic */
2639 #if ENABLE_ASH_EXPAND_PRMT
2640 # define PSSYNTAX 4 /* prompt. never passed to SIT() */
2642 /* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
2645 * called by editline -- any expansions to the prompt should be added here.
2648 setprompt_if(smallint do_set, int whichprompt)
2651 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2658 switch (whichprompt) {
2668 #if ENABLE_ASH_EXPAND_PRMT
2669 pushstackmark(&smark, stackblocksize());
2670 putprompt(expandstr(prompt, PSSYNTAX));
2671 popstackmark(&smark);
2678 /* ============ The cd and pwd commands */
2680 #define CD_PHYSICAL 1
2690 while ((i = nextopt("LP")) != '\0') {
2692 flags ^= CD_PHYSICAL;
2701 * Update curdir (the name of the current directory) in response to a
2705 updatepwd(const char *dir)
2712 cdcomppath = sstrdup(dir);
2715 if (curdir == nullstr)
2717 new = stack_putstr(curdir, new);
2719 new = makestrspace(strlen(dir) + 2, new);
2720 lim = (char *)stackblock() + 1;
2724 if (new > lim && *lim == '/')
2729 if (dir[1] == '/' && dir[2] != '/') {
2735 p = strtok(cdcomppath, "/");
2739 if (p[1] == '.' && p[2] == '\0') {
2751 new = stack_putstr(p, new);
2754 p = strtok(NULL, "/");
2759 return stackblock();
2763 * Find out what the current directory is. If we already know the current
2764 * directory, this routine returns immediately.
2769 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2770 return dir ? dir : nullstr;
2774 setpwd(const char *val, int setold)
2778 oldcur = dir = curdir;
2781 setvar("OLDPWD", oldcur, VEXPORT);
2784 if (physdir != nullstr) {
2785 if (physdir != oldcur)
2789 if (oldcur == val || !val) {
2795 dir = ckstrdup(val);
2796 if (oldcur != dir && oldcur != nullstr) {
2801 setvar("PWD", dir, VEXPORT);
2804 static void hashcd(void);
2807 * Actually do the chdir. We also call hashcd to let other routines
2808 * know that the current directory has changed.
2811 docd(const char *dest, int flags)
2813 const char *dir = NULL;
2816 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2819 if (!(flags & CD_PHYSICAL)) {
2820 dir = updatepwd(dest);
2834 static int FAST_FUNC
2835 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2848 dest = bltinlookup("HOME");
2849 else if (LONE_DASH(dest)) {
2850 dest = bltinlookup("OLDPWD");
2872 path = bltinlookup("CDPATH");
2873 while (p = path, (len = padvance(&path, dest)) >= 0) {
2877 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2881 if (!docd(p, flags))
2892 ash_msg_and_raise_perror("can't cd to %s", dest);
2895 if (flags & CD_PRINT)
2896 out1fmt("%s\n", curdir);
2900 static int FAST_FUNC
2901 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2904 const char *dir = curdir;
2908 if (physdir == nullstr)
2912 out1fmt("%s\n", dir);
2917 /* ============ ... */
2920 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2922 /* Syntax classes */
2923 #define CWORD 0 /* character is nothing special */
2924 #define CNL 1 /* newline character */
2925 #define CBACK 2 /* a backslash character */
2926 #define CSQUOTE 3 /* single quote */
2927 #define CDQUOTE 4 /* double quote */
2928 #define CENDQUOTE 5 /* a terminating quote */
2929 #define CBQUOTE 6 /* backwards single quote */
2930 #define CVAR 7 /* a dollar sign */
2931 #define CENDVAR 8 /* a '}' character */
2932 #define CLP 9 /* a left paren in arithmetic */
2933 #define CRP 10 /* a right paren in arithmetic */
2934 #define CENDFILE 11 /* end of file */
2935 #define CCTL 12 /* like CWORD, except it must be escaped */
2936 #define CSPCL 13 /* these terminate a word */
2937 #define CIGN 14 /* character should be ignored */
2940 #if ENABLE_ASH_ALIAS
2944 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2946 #if ENABLE_FEATURE_SH_MATH
2947 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2949 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2951 static const uint16_t S_I_T[] ALIGN2 = {
2952 #if ENABLE_ASH_ALIAS
2953 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2955 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2956 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2957 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2958 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2959 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2960 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2961 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2962 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2963 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2964 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2965 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2966 #if !USE_SIT_FUNCTION
2967 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2968 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2969 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2973 /* Constants below must match table above */
2975 #if ENABLE_ASH_ALIAS
2976 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2978 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2979 CNL_CNL_CNL_CNL , /* 2 */
2980 CWORD_CCTL_CCTL_CWORD , /* 3 */
2981 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2982 CVAR_CVAR_CWORD_CVAR , /* 5 */
2983 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2984 CSPCL_CWORD_CWORD_CLP , /* 7 */
2985 CSPCL_CWORD_CWORD_CRP , /* 8 */
2986 CBACK_CBACK_CCTL_CBACK , /* 9 */
2987 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2988 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2989 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2990 CWORD_CWORD_CWORD_CWORD , /* 13 */
2991 CCTL_CCTL_CCTL_CCTL , /* 14 */
2994 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2995 * caller must ensure proper cast on it if c is *char_ptr!
2997 #if USE_SIT_FUNCTION
3000 SIT(int c, int syntax)
3002 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
3003 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
3005 * This causes '/' to be prepended with CTLESC in dquoted string,
3006 * making "./file"* treated incorrectly because we feed
3007 * ".\/file*" string to glob(), confusing it (see expandmeta func).
3008 * The "homegrown" glob implementation is okay with that,
3009 * but glibc one isn't. With '/' always treated as CWORD,
3012 # if ENABLE_ASH_ALIAS
3013 static const uint8_t syntax_index_table[] ALIGN1 = {
3014 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
3015 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
3016 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
3020 static const uint8_t syntax_index_table[] ALIGN1 = {
3021 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
3022 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
3023 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
3032 # if ENABLE_ASH_ALIAS
3038 /* Cast is purely for paranoia here,
3039 * just in case someone passed signed char to us */
3040 if ((unsigned char)c >= CTL_FIRST
3041 && (unsigned char)c <= CTL_LAST
3045 s = strchrnul(spec_symbls, c);
3048 indx = syntax_index_table[s - spec_symbls];
3050 return (S_I_T[indx] >> (syntax*4)) & 0xf;
3053 #else /* !USE_SIT_FUNCTION */
3055 static const uint8_t syntax_index_table[] ALIGN1 = {
3056 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
3057 /* 0 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 1 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 2 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 3 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 4 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 5 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 6 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 7 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 8 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
3067 /* 10 "\n" */ CNL_CNL_CNL_CNL,
3068 /* 11 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 12 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 13 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 14 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 15 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 16 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 17 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 18 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 19 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 20 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 21 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 22 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 23 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 24 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 25 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 26 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 27 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 28 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 29 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 30 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 31 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
3090 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
3091 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
3092 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
3093 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
3094 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
3095 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
3096 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
3097 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
3098 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
3099 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
3100 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
3101 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
3102 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
3103 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
3104 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
3105 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
3106 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
3107 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
3108 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
3109 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
3110 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
3111 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
3112 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
3113 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
3114 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
3115 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
3116 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
3117 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
3118 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
3119 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
3120 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
3121 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
3122 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
3123 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
3124 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
3125 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
3126 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
3127 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
3128 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
3129 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
3130 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
3131 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
3132 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
3133 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
3134 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
3135 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
3136 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
3137 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
3138 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
3139 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
3140 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
3141 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
3142 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
3143 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
3144 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
3145 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
3146 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
3147 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
3148 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
3149 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
3150 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
3151 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
3152 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
3153 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
3154 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
3155 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
3156 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
3157 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
3158 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
3159 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
3160 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
3161 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
3162 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
3163 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
3164 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
3165 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
3166 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
3167 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
3168 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
3169 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3170 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3171 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3172 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3173 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3174 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3175 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3176 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3177 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3178 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3179 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3180 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3181 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3182 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3183 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3184 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3185 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
3186 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
3187 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
3188 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
3189 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
3190 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
3191 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
3192 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3193 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3194 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3195 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3196 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3197 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3198 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3199 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3200 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3201 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3202 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3203 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3204 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3205 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3206 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3207 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3208 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3209 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3210 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3211 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3212 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3213 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3214 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3215 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3216 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3217 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3218 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3219 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3220 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3221 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3222 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3223 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3224 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3225 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3226 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3227 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3228 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3229 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3230 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3231 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3232 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3233 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3234 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3235 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3236 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3237 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3238 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3239 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3240 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3241 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3242 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3243 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3244 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3245 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3246 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3247 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3248 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3249 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3250 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3251 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3252 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3253 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3254 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3255 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3256 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3257 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3258 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3259 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3260 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3261 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3262 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3263 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3264 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3265 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3266 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3267 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3268 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3269 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3270 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3271 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3272 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3273 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3274 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3275 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3276 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3277 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3278 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3279 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3280 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3281 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3282 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3283 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3284 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3285 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3286 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3287 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3288 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3289 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3290 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3291 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3292 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3293 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3294 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3295 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3296 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3297 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3298 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3299 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3300 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3301 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3302 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3303 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3304 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3305 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3306 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3307 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3308 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3309 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3310 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3311 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3312 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3313 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3314 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3315 # if ENABLE_ASH_ALIAS
3316 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3321 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3322 #else /* debug version, caught one signed char bug */
3323 # define SIT(c, syntax) \
3325 if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
3326 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3327 if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
3328 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3329 ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
3333 #endif /* !USE_SIT_FUNCTION */
3336 /* ============ Alias handling */
3338 #if ENABLE_ASH_ALIAS
3340 #define ALIASINUSE 1
3351 static struct alias **atab; // [ATABSIZE];
3352 #define INIT_G_alias() do { \
3353 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3357 static struct alias **
3358 __lookupalias(const char *name)
3360 unsigned int hashval;
3367 ch = (unsigned char)*p;
3371 ch = (unsigned char)*++p;
3373 app = &atab[hashval % ATABSIZE];
3375 for (; *app; app = &(*app)->next) {
3376 if (strcmp(name, (*app)->name) == 0) {
3384 static struct alias *
3385 lookupalias(const char *name, int check)
3387 struct alias *ap = *__lookupalias(name);
3389 if (check && ap && (ap->flag & ALIASINUSE))
3394 static struct alias *
3395 freealias(struct alias *ap)
3399 if (ap->flag & ALIASINUSE) {
3400 ap->flag |= ALIASDEAD;
3412 setalias(const char *name, const char *val)
3414 struct alias *ap, **app;
3416 app = __lookupalias(name);
3420 if (!(ap->flag & ALIASINUSE)) {
3423 ap->val = ckstrdup(val);
3424 ap->flag &= ~ALIASDEAD;
3427 ap = ckzalloc(sizeof(struct alias));
3428 ap->name = ckstrdup(name);
3429 ap->val = ckstrdup(val);
3430 /*ap->flag = 0; - ckzalloc did it */
3431 /*ap->next = NULL;*/
3438 unalias(const char *name)
3442 app = __lookupalias(name);
3446 *app = freealias(*app);
3457 struct alias *ap, **app;
3461 for (i = 0; i < ATABSIZE; i++) {
3463 for (ap = *app; ap; ap = *app) {
3464 *app = freealias(*app);
3474 printalias(const struct alias *ap)
3476 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3480 * TODO - sort output
3482 static int FAST_FUNC
3483 aliascmd(int argc UNUSED_PARAM, char **argv)
3492 for (i = 0; i < ATABSIZE; i++) {
3493 for (ap = atab[i]; ap; ap = ap->next) {
3499 while ((n = *++argv) != NULL) {
3500 v = strchr(n+1, '=');
3501 if (v == NULL) { /* n+1: funny ksh stuff */
3502 ap = *__lookupalias(n);
3504 fprintf(stderr, "%s: %s not found\n", "alias", n);
3517 static int FAST_FUNC
3518 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3522 while (nextopt("a") != '\0') {
3526 for (i = 0; *argptr; argptr++) {
3527 if (unalias(*argptr)) {
3528 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3536 #endif /* ASH_ALIAS */
3539 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3542 #define FORK_NOJOB 2
3544 /* mode flags for showjob(s) */
3545 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3546 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3547 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3548 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3551 * A job structure contains information about a job. A job is either a
3552 * single process or a set of processes contained in a pipeline. In the
3553 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3557 pid_t ps_pid; /* process id */
3558 int ps_status; /* last process status from wait() */
3559 char *ps_cmd; /* text of command being run */
3563 struct procstat ps0; /* status of process */
3564 struct procstat *ps; /* status of processes when more than one */
3566 int stopstatus; /* status of a stopped job */
3568 unsigned nprocs; /* number of processes */
3570 #define JOBRUNNING 0 /* at least one proc running */
3571 #define JOBSTOPPED 1 /* all procs are stopped */
3572 #define JOBDONE 2 /* all procs are completed */
3576 sigint: 1, /* job was killed by SIGINT */
3577 jobctl: 1, /* job running under job control */
3579 waited: 1, /* true if this entry has been waited for */
3580 used: 1, /* true if this entry is in used */
3581 changed: 1; /* true if status has changed */
3582 struct job *prev_job; /* previous job */
3585 static struct job *makejob(/*union node *,*/ int);
3586 static int forkshell(struct job *, union node *, int);
3587 static int waitforjob(struct job *);
3590 enum { doing_jobctl = 0 };
3591 #define setjobctl(on) do {} while (0)
3593 static smallint doing_jobctl; //references:8
3594 static void setjobctl(int);
3601 ignoresig(int signo)
3603 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3604 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3605 /* No, need to do it */
3606 signal(signo, SIG_IGN);
3608 sigmode[signo - 1] = S_HARD_IGN;
3612 * Only one usage site - in setsignal()
3615 signal_handler(int signo)
3617 if (signo == SIGCHLD) {
3623 gotsig[signo - 1] = 1;
3624 pending_sig = signo;
3626 if (signo == SIGINT && !trap[SIGINT]) {
3627 if (!suppress_int) {
3629 raise_interrupt(); /* does not return */
3636 * Set the signal handler for the specified signal. The routine figures
3637 * out what it should be set to.
3640 setsignal(int signo)
3643 char cur_act, new_act;
3644 struct sigaction act;
3648 if (t != NULL) { /* trap for this sig is set */
3650 if (t[0] == '\0') /* trap is "": ignore this sig */
3654 if (rootshell && new_act == S_DFL) {
3657 if (iflag || minusc || sflag == 0)
3666 * "In all cases, bash ignores SIGQUIT. Non-builtin
3667 * commands run by bash have signal handlers
3668 * set to the values inherited by the shell
3669 * from its parent". */
3685 /* if !rootshell, we reset SIGQUIT to DFL,
3686 * whereas we have to restore it to what shell got on entry.
3687 * This is handled by the fact that if signal was IGNored on entry,
3688 * then cur_act is S_HARD_IGN and we never change its sigaction
3692 if (signo == SIGCHLD)
3695 t = &sigmode[signo - 1];
3698 /* current setting is not yet known */
3699 if (sigaction(signo, NULL, &act)) {
3700 /* pretend it worked; maybe we should give a warning,
3701 * but other shells don't. We don't alter sigmode,
3702 * so we retry every time.
3703 * btw, in Linux it never fails. --vda */
3706 if (act.sa_handler == SIG_IGN) {
3707 cur_act = S_HARD_IGN;
3709 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3711 cur_act = S_IGN; /* don't hard ignore these */
3714 if (act.sa_handler == SIG_DFL && new_act == S_DFL) {
3715 /* installing SIG_DFL over SIG_DFL is a no-op */
3716 /* saves one sigaction call in each "sh -c SCRIPT" invocation */
3721 if (cur_act == S_HARD_IGN || cur_act == new_act)
3726 act.sa_handler = SIG_DFL;
3729 act.sa_handler = signal_handler;
3732 act.sa_handler = SIG_IGN;
3735 /* flags and mask matter only if !DFL and !IGN, but we do it
3736 * for all cases for more deterministic behavior:
3738 act.sa_flags = 0; //TODO: why not SA_RESTART?
3739 sigfillset(&act.sa_mask);
3741 sigaction_set(signo, &act);
3744 /* mode flags for set_curjob */
3745 #define CUR_DELETE 2
3746 #define CUR_RUNNING 1
3747 #define CUR_STOPPED 0
3750 /* pgrp of shell on invocation */
3751 static int initialpgrp; //references:2
3752 static int ttyfd = -1; //5
3755 static struct job *jobtab; //5
3757 static unsigned njobs; //4
3759 static struct job *curjob; //lots
3760 /* number of presumed living untracked jobs */
3761 static int jobless; //4
3764 /* Bash has a feature: it restores termios after a successful wait for
3765 * a foreground job which had at least one stopped or sigkilled member.
3766 * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
3767 * properly restoring tty state. Should we do this too?
3768 * A reproducer: ^Z an interactive python:
3771 * Python 2.7.12 (...)
3773 * { python leaves tty in -icanon -echo state. We do survive that... }
3774 * [1]+ Stopped python
3775 * { ...however, next program (python #2) does not survive it well: }
3777 * Python 2.7.12 (...)
3778 * >>> Traceback (most recent call last):
3779 * { above, I typed "qwerty<CR>", but -echo state is still in effect }
3780 * File "<stdin>", line 1, in <module>
3781 * NameError: name 'qwerty' is not defined
3783 * The implementation below is modeled on bash code and seems to work.
3784 * However, I'm not sure we should do this. For one: what if I'd fg
3785 * the stopped python instead? It'll be confused by "restored" tty state.
3787 static struct termios shell_tty_info;
3791 if (rootshell && ttyfd >= 0)
3792 tcgetattr(ttyfd, &shell_tty_info);
3797 /* if (rootshell) - caller ensures this */
3799 tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
3802 job_signal_status(struct job *jp)
3806 struct procstat *ps = jp->ps;
3807 for (i = 0; i < jp->nprocs; i++) {
3808 status = ps[i].ps_status;
3809 if (WIFSIGNALED(status) || WIFSTOPPED(status))
3815 restore_tty_if_stopped_or_signaled(struct job *jp)
3817 //TODO: check what happens if we come from waitforjob() in expbackq()
3819 int s = job_signal_status(jp);
3820 if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
3825 # define get_tty_state() ((void)0)
3826 # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
3830 set_curjob(struct job *jp, unsigned mode)
3833 struct job **jpp, **curp;
3835 /* first remove from list */
3836 jpp = curp = &curjob;
3841 jpp = &jp1->prev_job;
3843 *jpp = jp1->prev_job;
3845 /* Then re-insert in correct position */
3853 /* job being deleted */
3856 /* newly created job or backgrounded job,
3857 * put after all stopped jobs.
3862 if (!jp1 || jp1->state != JOBSTOPPED)
3865 jpp = &jp1->prev_job;
3871 /* newly stopped job - becomes curjob */
3872 jp->prev_job = *jpp;
3880 jobno(const struct job *jp)
3882 return jp - jobtab + 1;
3887 * Convert a job name to a job structure.
3890 #define getjob(name, getctl) getjob(name)
3893 getjob(const char *name, int getctl)
3897 const char *err_msg = "%s: no such job";
3901 char *(*match)(const char *, const char *);
3916 if (c == '+' || c == '%') {
3918 err_msg = "No current job";
3924 err_msg = "No previous job";
3934 if (num > 0 && num <= njobs) {
3935 jp = jobtab + num - 1;
3950 if (match(jp->ps[0].ps_cmd, p)) {
3954 err_msg = "%s: ambiguous";
3964 err_msg = "job %s not created under job control";
3965 if (getctl && jp->jobctl == 0)
3970 ash_msg_and_raise_error(err_msg, name);
3974 * Mark a job structure as unused.
3977 freejob(struct job *jp)
3979 struct procstat *ps;
3983 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3984 if (ps->ps_cmd != nullstr)
3987 if (jp->ps != &jp->ps0)
3990 set_curjob(jp, CUR_DELETE);
3996 xtcsetpgrp(int fd, pid_t pgrp)
3998 if (tcsetpgrp(fd, pgrp))
3999 ash_msg_and_raise_perror("can't set tty process group");
4003 * Turn job control on and off.
4005 * Note: This code assumes that the third arg to ioctl is a character
4006 * pointer, which is true on Berkeley systems but not System V. Since
4007 * System V doesn't have job control yet, this isn't a problem now.
4009 * Called with interrupts off.
4017 if (on == doing_jobctl || rootshell == 0)
4021 ofd = fd = open(_PATH_TTY, O_RDWR);
4023 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
4024 * That sometimes helps to acquire controlling tty.
4025 * Obviously, a workaround for bugs when someone
4026 * failed to provide a controlling tty to bash! :) */
4032 /* fd is a tty at this point */
4033 fd = fcntl(fd, F_DUPFD_CLOEXEC, 10);
4034 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
4037 goto out; /* F_DUPFD failed */
4038 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
4039 close_on_exec_on(fd);
4040 while (1) { /* while we are in the background */
4041 pgrp = tcgetpgrp(fd);
4044 ash_msg("can't access tty; job control turned off");
4048 if (pgrp == getpgrp())
4059 xtcsetpgrp(fd, pgrp);
4061 /* turning job control off */
4064 /* was xtcsetpgrp, but this can make exiting ash
4065 * loop forever if pty is already deleted */
4066 tcsetpgrp(fd, pgrp);
4080 static int FAST_FUNC
4081 killcmd(int argc, char **argv)
4083 if (argv[1] && strcmp(argv[1], "-l") != 0) {
4086 if (argv[i][0] == '%') {
4088 * "kill %N" - job kill
4089 * Converting to pgrp / pid kill
4095 jp = getjob(argv[i], 0);
4097 * In jobs started under job control, we signal
4098 * entire process group by kill -PGRP_ID.
4099 * This happens, f.e., in interactive shell.
4101 * Otherwise, we signal each child via
4102 * kill PID1 PID2 PID3.
4104 * sh -c 'sleep 1|sleep 1 & kill %1'
4105 * sh -c 'true|sleep 2 & sleep 1; kill %1'
4106 * sh -c 'true|sleep 1 & sleep 2; kill %1'
4108 n = jp->nprocs; /* can't be 0 (I hope) */
4111 dst = alloca(n * sizeof(int)*4);
4113 for (j = 0; j < n; j++) {
4114 struct procstat *ps = &jp->ps[j];
4115 /* Skip non-running and not-stopped members
4116 * (i.e. dead members) of the job
4118 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
4121 * kill_main has matching code to expect
4122 * leading space. Needed to not confuse
4123 * negative pids with "kill -SIGNAL_NO" syntax
4125 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
4129 } while (argv[++i]);
4131 return kill_main(argc, argv);
4135 showpipe(struct job *jp /*, FILE *out*/)
4137 struct procstat *ps;
4138 struct procstat *psend;
4140 psend = jp->ps + jp->nprocs;
4141 for (ps = jp->ps + 1; ps < psend; ps++)
4142 printf(" | %s", ps->ps_cmd);
4143 newline_and_flush(stdout);
4144 flush_stdout_stderr();
4149 restartjob(struct job *jp, int mode)
4151 struct procstat *ps;
4157 if (jp->state == JOBDONE)
4159 jp->state = JOBRUNNING;
4160 pgid = jp->ps[0].ps_pid;
4161 if (mode == FORK_FG) {
4163 xtcsetpgrp(ttyfd, pgid);
4165 killpg(pgid, SIGCONT);
4169 if (WIFSTOPPED(ps->ps_status)) {
4175 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
4180 static int FAST_FUNC
4181 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
4187 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
4191 jp = getjob(*argv, 1);
4192 if (mode == FORK_BG) {
4193 set_curjob(jp, CUR_RUNNING);
4194 printf("[%d] ", jobno(jp));
4196 out1str(jp->ps[0].ps_cmd);
4197 showpipe(jp /*, stdout*/);
4198 retval = restartjob(jp, mode);
4199 } while (*argv && *++argv);
4205 sprint_status48(char *os, int status, int sigonly)
4210 if (!WIFEXITED(status)) {
4212 if (WIFSTOPPED(status))
4213 st = WSTOPSIG(status);
4216 st = WTERMSIG(status);
4218 if (st == SIGINT || st == SIGPIPE)
4221 if (WIFSTOPPED(status))
4226 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
4227 //s = stpncpy(s, strsignal(st), 32); //not all libc have stpncpy()
4228 s += fmtstr(s, 32, strsignal(st));
4229 if (WCOREDUMP(status)) {
4230 s = stpcpy(s, " (core dumped)");
4232 } else if (!sigonly) {
4233 st = WEXITSTATUS(status);
4234 s += fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
4241 wait_block_or_sig(int *status)
4248 /* Poll all children for changes in their state */
4250 /* if job control is active, accept stopped processes too */
4251 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
4253 break; /* Error (e.g. EINTR, ECHILD) or pid */
4255 /* Children exist, but none are ready. Sleep until interesting signal */
4258 sigprocmask2(SIG_SETMASK, &mask); /* mask is updated */
4259 while (!got_sigchld && !pending_sig)
4261 sigprocmask(SIG_SETMASK, &mask, NULL);
4262 #else /* unsafe: a signal can set pending_sig after check, but before pause() */
4263 while (!got_sigchld && !pending_sig)
4267 /* If it was SIGCHLD, poll children again */
4268 } while (got_sigchld);
4273 #define DOWAIT_NONBLOCK 0
4274 #define DOWAIT_BLOCK 1
4275 #define DOWAIT_BLOCK_OR_SIG 2
4277 # define DOWAIT_JOBSTATUS 0x10 /* OR this to get job's exitstatus instead of pid */
4281 dowait(int block, struct job *job)
4286 struct job *thisjob;
4288 bool want_jobexitstatus = (block & DOWAIT_JOBSTATUS);
4289 block = (block & ~DOWAIT_JOBSTATUS);
4292 TRACE(("dowait(0x%x) called\n", block));
4294 /* It's wrong to call waitpid() outside of INT_OFF region:
4295 * signal can arrive just after syscall return and handler can
4296 * longjmp away, losing stop/exit notification processing.
4297 * Thus, for "jobs" builtin, and for waiting for a fg job,
4298 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
4300 * However, for "wait" builtin it is wrong to simply call waitpid()
4301 * in INT_OFF region: "wait" needs to wait for any running job
4302 * to change state, but should exit on any trap too.
4303 * In INT_OFF region, a signal just before syscall entry can set
4304 * pending_sig variables, but we can't check them, and we would
4305 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
4307 * Because of this, we run inside INT_OFF, but use a special routine
4308 * which combines waitpid() and sigsuspend().
4309 * This is the reason why we need to have a handler for SIGCHLD:
4310 * SIG_DFL handler does not wake sigsuspend().
4313 if (block == DOWAIT_BLOCK_OR_SIG) {
4314 pid = wait_block_or_sig(&status);
4317 if (block == DOWAIT_NONBLOCK)
4318 wait_flags = WNOHANG;
4319 /* if job control is active, accept stopped processes too */
4321 wait_flags |= WUNTRACED;
4322 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4323 pid = waitpid(-1, &status, wait_flags);
4325 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4326 pid, status, errno, strerror(errno)));
4331 for (jp = curjob; jp; jp = jp->prev_job) {
4333 struct procstat *ps;
4334 struct procstat *psend;
4335 if (jp->state == JOBDONE)
4339 psend = ps + jp->nprocs;
4341 if (ps->ps_pid == pid) {
4342 TRACE(("Job %d: changing status of proc %d "
4343 "from 0x%x to 0x%x\n",
4344 jobno(jp), pid, ps->ps_status, status));
4345 ps->ps_status = status;
4348 if (ps->ps_status == -1)
4349 jobstate = JOBRUNNING;
4351 if (jobstate == JOBRUNNING)
4353 if (WIFSTOPPED(ps->ps_status)) {
4354 jp->stopstatus = ps->ps_status;
4355 jobstate = JOBSTOPPED;
4358 } while (++ps < psend);
4362 /* Found the job where one of its processes changed its state.
4363 * Is there at least one live and running process in this job? */
4364 if (jobstate != JOBRUNNING) {
4365 /* No. All live processes in the job are stopped
4366 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4368 thisjob->changed = 1;
4369 if (thisjob->state != jobstate) {
4370 TRACE(("Job %d: changing state from %d to %d\n",
4371 jobno(thisjob), thisjob->state, jobstate));
4372 thisjob->state = jobstate;
4374 if (jobstate == JOBSTOPPED)
4375 set_curjob(thisjob, CUR_STOPPED);
4381 /* The process wasn't found in job list */
4383 if (!WIFSTOPPED(status))
4390 if (want_jobexitstatus) {
4392 if (thisjob && thisjob->state == JOBDONE)
4393 pid = thisjob->ps[thisjob->nprocs - 1].ps_status;
4396 if (thisjob && thisjob == job) {
4400 len = sprint_status48(s, status, 1);
4412 showjob(struct job *jp, int mode)
4414 struct procstat *ps;
4415 struct procstat *psend;
4418 char s[16 + 16 + 48];
4419 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4423 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4424 /* just output process (group) id of pipeline */
4425 fprintf(out, "%d\n", ps->ps_pid);
4429 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4434 else if (curjob && jp == curjob->prev_job)
4437 if (mode & SHOW_PIDS)
4438 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4440 psend = ps + jp->nprocs;
4442 if (jp->state == JOBRUNNING) {
4443 strcpy(s + col, "Running");
4444 col += sizeof("Running") - 1;
4446 int status = psend[-1].ps_status;
4447 if (jp->state == JOBSTOPPED)
4448 status = jp->stopstatus;
4449 col += sprint_status48(s + col, status, 0);
4451 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4453 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4454 * or prints several "PID | <cmdN>" lines,
4455 * depending on SHOW_PIDS bit.
4456 * We do not print status of individual processes
4457 * between PID and <cmdN>. bash does it, but not very well:
4458 * first line shows overall job status, not process status,
4459 * making it impossible to know 1st process status.
4463 /* for each process */
4466 if (mode & SHOW_PIDS)
4467 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4469 fprintf(out, "%s%*c%s%s",
4471 33 - col >= 0 ? 33 - col : 0, ' ',
4472 ps == jp->ps ? "" : "| ",
4475 } while (++ps != psend);
4476 newline_and_flush(out);
4480 if (jp->state == JOBDONE) {
4481 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4487 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4488 * statuses have changed since the last call to showjobs.
4495 TRACE(("showjobs(0x%x) called\n", mode));
4497 /* Handle all finished jobs */
4498 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4501 for (jp = curjob; jp; jp = jp->prev_job) {
4502 if (!(mode & SHOW_CHANGED) || jp->changed) {
4508 static int FAST_FUNC
4509 jobscmd(int argc UNUSED_PARAM, char **argv)
4514 while ((m = nextopt("lp")) != '\0') {
4518 mode |= SHOW_ONLY_PGID;
4524 showjob(getjob(*argv, 0), mode);
4534 /* Called only on finished or stopped jobs (no members are running) */
4536 getstatus(struct job *job)
4540 struct procstat *ps;
4542 /* Fetch last member's status */
4543 ps = job->ps + job->nprocs - 1;
4544 status = ps->ps_status;
4546 /* "set -o pipefail" mode: use last _nonzero_ status */
4547 while (status == 0 && --ps >= job->ps)
4548 status = ps->ps_status;
4551 retval = WEXITSTATUS(status);
4552 if (!WIFEXITED(status)) {
4554 retval = WSTOPSIG(status);
4555 if (!WIFSTOPPED(status))
4558 /* XXX: limits number of signals */
4559 retval = WTERMSIG(status);
4561 if (retval == SIGINT)
4567 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4568 jobno(job), job->nprocs, status, retval));
4572 static int FAST_FUNC
4573 waitcmd(int argc UNUSED_PARAM, char **argv)
4580 char one = nextopt("n");
4588 /* wait for all jobs / one job if -n */
4593 /* exitcode of "wait -n" with nothing to wait for is 127, not 0 */
4597 if (!jp) /* no running procs */
4599 if (jp->state == JOBRUNNING)
4605 * "When bash is waiting for an asynchronous command via
4606 * the wait builtin, the reception of a signal for which a trap
4607 * has been set will cause the wait builtin to return immediately
4608 * with an exit status greater than 128, immediately after which
4609 * the trap is executed."
4612 status = dowait(DOWAIT_BLOCK_OR_SIG | DOWAIT_JOBSTATUS, NULL);
4614 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4616 /* if child sends us a signal *and immediately exits*,
4617 * dowait() returns pid > 0. Check this case,
4618 * not "if (dowait() < 0)"!
4624 /* wait -n waits for one _job_, not one _process_.
4625 * date; sleep 3 & sleep 2 | sleep 1 & wait -n; date
4626 * should wait for 2 seconds. Not 1 or 3.
4628 if (status != -1 && !WIFSTOPPED(status)) {
4629 retval = WEXITSTATUS(status);
4630 if (WIFSIGNALED(status))
4631 retval = WTERMSIG(status) + 128;
4641 if (**argv != '%') {
4642 pid_t pid = number(*argv);
4647 if (job->ps[job->nprocs - 1].ps_pid == pid)
4649 job = job->prev_job;
4652 job = getjob(*argv, 0);
4654 /* loop until process terminated or stopped */
4655 while (job->state == JOBRUNNING) {
4656 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4661 retval = getstatus(job);
4668 retval = 128 + pending_sig;
4677 struct job *jp, *jq;
4679 len = njobs * sizeof(*jp);
4681 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4683 offset = (char *)jp - (char *)jq;
4685 /* Relocate pointers */
4688 jq = (struct job *)((char *)jq + l);
4692 #define joff(p) ((struct job *)((char *)(p) + l))
4693 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4694 if (joff(jp)->ps == &jq->ps0)
4695 jmove(joff(jp)->ps);
4696 if (joff(jp)->prev_job)
4697 jmove(joff(jp)->prev_job);
4707 jp = (struct job *)((char *)jp + len);
4711 } while (--jq >= jp);
4716 * Return a new job structure.
4717 * Called with interrupts off.
4720 makejob(/*union node *node,*/ int nprocs)
4725 for (i = njobs, jp = jobtab; ; jp++) {
4732 if (jp->state != JOBDONE || !jp->waited)
4741 memset(jp, 0, sizeof(*jp));
4743 /* jp->jobctl is a bitfield.
4744 * "jp->jobctl |= doing_jobctl" likely to give awful code */
4748 jp->prev_job = curjob;
4753 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4755 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4762 * Return a string identifying a command (to be printed by the
4765 static char *cmdnextc;
4768 cmdputs(const char *s)
4770 static const char vstype[VSTYPE + 1][3] = {
4771 "", "}", "-", "+", "?", "=",
4772 "%", "%%", "#", "##"
4773 IF_BASH_SUBSTR(, ":")
4774 IF_BASH_PATTERN_SUBST(, "/", "//")
4777 const char *p, *str;
4781 unsigned char subtype = 0;
4785 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4787 while ((c = *p++) != '\0') {
4795 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() + startloc) && 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);
7512 if (subtype != VSNORMAL) { /* skip to end of alternative */
7515 unsigned char c = *p++;
7518 else if (c == CTLBACKQ) {
7520 argbackq = argbackq->next;
7521 } else if (c == CTLVAR) {
7522 if ((*p++ & VSTYPE) != VSNORMAL)
7524 } else if (c == CTLENDVAR) {
7534 * Add a file name to the list.
7537 addfname(const char *name)
7541 sp = stzalloc(sizeof(*sp));
7542 sp->text = sstrdup(name);
7544 exparg.lastp = &sp->next;
7547 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7549 hasmeta(const char *p)
7551 static const char chars[] ALIGN1 = {
7552 '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
7556 p = strpbrk(p, chars);
7559 switch ((unsigned char)*p) {
7563 if ((unsigned char)*p == CTLQUOTEMARK)
7565 if ((unsigned char)*p == CTLESC)
7567 if (*p == '\0') /* huh? */
7578 if (!strchr(p + 1, ']')) {
7579 /* It's not a properly closed [] pattern,
7580 * but other metas may follow. Continue checking.
7581 * my[file* _is_ globbed by bash
7582 * and matches filenames like "my[file1".
7598 /* If we want to use glob() from libc... */
7599 #if !ENABLE_ASH_INTERNAL_GLOB
7601 /* Add the result of glob() to the list */
7603 addglob(const glob_t *pglob)
7605 char **p = pglob->gl_pathv;
7612 expandmeta(struct strlist *str /*, int flag*/)
7614 /* TODO - EXP_REDIR */
7624 if (!hasmeta(str->text))
7628 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7629 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7630 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7632 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7633 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7634 // Which means you need to unescape the string, right? Not so fast:
7635 // if there _is_ a file named "file\?" (with backslash), it is returned
7636 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7637 // You DON'T KNOW by looking at the result whether you need to unescape it.
7639 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7640 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7641 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7642 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7643 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7644 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7645 i = glob(p, 0, NULL, &pglob);
7646 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7651 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7652 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7653 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7665 *exparg.lastp = str;
7666 rmescapes(str->text, 0, NULL);
7667 exparg.lastp = &str->next;
7669 default: /* GLOB_NOSPACE */
7672 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7679 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7682 * Do metacharacter (i.e. *, ?, [...]) expansion.
7684 typedef struct exp_t {
7689 expmeta(exp_t *exp, char *name, unsigned name_len, unsigned expdir_len)
7691 #define expdir exp->dir
7692 #define expdir_max exp->dir_max
7693 char *enddir = expdir + expdir_len;
7708 for (p = name; esc = 0, *p; p += esc + 1) {
7709 if (*p == '*' || *p == '?')
7711 else if (*p == '[') {
7718 if (*q == '/' || *q == '\0')
7726 if (*p == '\\' && p[1])
7728 if (p[esc] == '/') {
7731 start = p + esc + 1;
7735 if (metaflag == 0) { /* we've reached the end of the file name */
7740 if (*p == '\\' && p[1])
7744 if (lstat(expdir, &statb) == 0)
7752 if (*p == '\\' && p[1])
7755 } while (p < start);
7759 expdir_len = enddir - cp;
7765 if (*endname == 0) {
7772 name_len -= endname - name;
7779 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7780 if (dp->d_name[0] == '.' && !matchdot)
7782 if (pmatch(start, dp->d_name)) {
7784 strcpy(enddir, dp->d_name);
7790 p = stpcpy(enddir, dp->d_name);
7793 offset = p - expdir + 1;
7794 len = offset + name_len + NAME_MAX;
7795 if (len > expdir_max) {
7797 expdir = ckrealloc(expdir, len);
7801 expmeta(exp, endname, name_len, offset);
7802 enddir = expdir + expdir_len;
7808 endname[-esc - 1] = esc ? '\\' : '/';
7813 static struct strlist *
7814 msort(struct strlist *list, int len)
7816 struct strlist *p, *q = NULL;
7817 struct strlist **lpp;
7825 for (n = half; --n >= 0;) {
7829 q->next = NULL; /* terminate first half of list */
7830 q = msort(list, half); /* sort first half of list */
7831 p = msort(p, len - half); /* sort second half */
7834 #if ENABLE_LOCALE_SUPPORT
7835 if (strcoll(p->text, q->text) < 0)
7837 if (strcmp(p->text, q->text) < 0)
7861 * Sort the results of file name expansion. It calculates the number of
7862 * strings to sort and then calls msort (short for merge sort) to do the
7865 static struct strlist *
7866 expsort(struct strlist *str)
7872 for (sp = str; sp; sp = sp->next)
7874 return msort(str, len);
7878 expandmeta(struct strlist *str /*, int flag*/)
7880 /* TODO - EXP_REDIR */
7884 struct strlist **savelastp;
7891 if (!hasmeta(str->text))
7893 savelastp = exparg.lastp;
7896 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7898 exp.dir_max = len + PATH_MAX;
7899 exp.dir = ckmalloc(exp.dir_max);
7901 expmeta(&exp, p, len, 0);
7906 if (exparg.lastp == savelastp) {
7911 *exparg.lastp = str;
7912 rmescapes(str->text, 0, NULL);
7913 exparg.lastp = &str->next;
7915 *exparg.lastp = NULL;
7916 *savelastp = sp = expsort(*savelastp);
7917 while (sp->next != NULL)
7919 exparg.lastp = &sp->next;
7924 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7927 * Perform variable substitution and command substitution on an argument,
7928 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7929 * perform splitting and file name expansion. When arglist is NULL, perform
7930 * here document expansion.
7933 expandarg(union node *arg, struct arglist *arglist, int flag)
7938 argbackq = arg->narg.backquote;
7939 STARTSTACKSTR(expdest);
7940 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7941 argstr(arg->narg.text, flag);
7942 p = _STPUTC('\0', expdest);
7944 if (arglist == NULL) {
7945 /* here document expanded */
7948 p = grabstackstr(p);
7949 TRACE(("expandarg: p:'%s'\n", p));
7950 exparg.lastp = &exparg.list;
7954 if (flag & EXP_FULL) {
7955 ifsbreakup(p, &exparg);
7956 *exparg.lastp = NULL;
7957 exparg.lastp = &exparg.list;
7958 expandmeta(exparg.list /*, flag*/);
7960 sp = stzalloc(sizeof(*sp));
7963 exparg.lastp = &sp->next;
7965 *exparg.lastp = NULL;
7967 *arglist->lastp = exparg.list;
7968 arglist->lastp = exparg.lastp;
7976 * Expand shell variables and backquotes inside a here document.
7979 expandhere(union node *arg, int fd)
7981 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7982 full_write(fd, stackblock(), expdest - (char *)stackblock());
7986 * Returns true if the pattern matches the string.
7989 patmatch(char *pattern, const char *string)
7991 char *p = preglob(pattern, 0);
7992 int r = pmatch(p, string);
7993 //bb_error_msg("!fnmatch(pattern:'%s',str:'%s',0):%d", p, string, r);
7998 * See if a pattern matches in a case statement.
8001 casematch(union node *pattern, char *val)
8003 struct stackmark smark;
8006 setstackmark(&smark);
8007 argbackq = pattern->narg.backquote;
8008 STARTSTACKSTR(expdest);
8009 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
8010 STACKSTRNUL(expdest);
8012 result = patmatch(stackblock(), val);
8013 popstackmark(&smark);
8018 /* ============ find_command */
8022 int (*builtin)(int, char **) FAST_FUNC;
8023 /* unsigned flags; */
8025 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
8026 /* "regular" builtins always take precedence over commands,
8027 * regardless of PATH=....%builtin... position */
8028 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
8029 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
8032 smallint cmdtype; /* CMDxxx */
8035 /* index >= 0 for commands without path (slashes) */
8036 /* (TODO: what exactly does the value mean? PATH position?) */
8037 /* index == -1 for commands with slashes */
8038 /* index == (-2 - applet_no) for NOFORK applets */
8039 const struct builtincmd *cmd;
8040 struct funcnode *func;
8043 /* values of cmdtype */
8044 #define CMDUNKNOWN -1 /* no entry in table for command */
8045 #define CMDNORMAL 0 /* command is an executable program */
8046 #define CMDFUNCTION 1 /* command is a shell function */
8047 #define CMDBUILTIN 2 /* command is a shell builtin */
8049 /* action to find_command() */
8050 #define DO_ERR 0x01 /* prints errors */
8051 #define DO_ABS 0x02 /* checks absolute paths */
8052 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
8053 #define DO_ALTPATH 0x08 /* using alternate path */
8054 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
8056 static void find_command(char *, struct cmdentry *, int, const char *);
8059 /* ============ Hashing commands */
8062 * When commands are first encountered, they are entered in a hash table.
8063 * This ensures that a full path search will not have to be done for them
8064 * on each invocation.
8066 * We should investigate converting to a linear search, even though that
8067 * would make the command name "hash" a misnomer.
8071 struct tblentry *next; /* next entry in hash chain */
8072 union param param; /* definition of builtin function */
8073 smallint cmdtype; /* CMDxxx */
8074 char rehash; /* if set, cd done since entry created */
8075 char cmdname[1]; /* name of command */
8078 static struct tblentry **cmdtable;
8079 #define INIT_G_cmdtable() do { \
8080 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
8083 static int builtinloc = -1; /* index in path of %builtin, or -1 */
8087 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
8089 #if ENABLE_FEATURE_SH_STANDALONE
8090 if (applet_no >= 0) {
8091 if (APPLET_IS_NOEXEC(applet_no)) {
8095 popredir(/*drop:*/ 1);
8096 run_noexec_applet_and_exit(applet_no, cmd, argv);
8098 /* re-exec ourselves with the new arguments */
8099 execve(bb_busybox_exec_path, argv, envp);
8100 /* If they called chroot or otherwise made the binary no longer
8101 * executable, fall through */
8108 execve(cmd, argv, envp);
8109 } while (errno == EINTR);
8111 execve(cmd, argv, envp);
8114 if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
8115 /* Run "cmd" as a shell script:
8116 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
8117 * "If the execve() function fails with ENOEXEC, the shell
8118 * shall execute a command equivalent to having a shell invoked
8119 * with the command name as its first operand,
8120 * with any remaining arguments passed to the new shell"
8122 * That is, do not use $SHELL, user's shell, or /bin/sh;
8123 * just call ourselves.
8125 * Note that bash reads ~80 chars of the file, and if it sees
8126 * a zero byte before it sees newline, it doesn't try to
8127 * interpret it, but fails with "cannot execute binary file"
8128 * message and exit code 126. For one, this prevents attempts
8129 * to interpret foreign ELF binaries as shell scripts.
8131 argv[0] = (char*) cmd;
8132 cmd = bb_busybox_exec_path;
8133 /* NB: this is only possible because all callers of shellexec()
8134 * ensure that the argv[-1] slot exists!
8137 argv[0] = (char*) "ash";
8143 * Exec a program. Never returns. If you change this routine, you may
8144 * have to change the find_command routine as well.
8145 * argv[-1] must exist and be writable! See tryexec() for why.
8147 static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
8148 static void shellexec(char *prog, char **argv, const char *path, int idx)
8154 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
8156 envp = listvars(VEXPORT, VUNSET, /*strlist:*/ NULL, /*end:*/ NULL);
8157 if (strchr(prog, '/') != NULL
8158 #if ENABLE_FEATURE_SH_STANDALONE
8159 || (applet_no = find_applet_by_name(prog)) >= 0
8162 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
8163 if (applet_no >= 0) {
8164 /* We tried execing ourself, but it didn't work.
8165 * Maybe /proc/self/exe doesn't exist?
8174 while (padvance(&path, argv[0]) >= 0) {
8175 cmdname = stackblock();
8176 if (--idx < 0 && pathopt == NULL) {
8177 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
8178 if (errno != ENOENT && errno != ENOTDIR)
8184 /* Map to POSIX errors */
8196 exitstatus = exerrno;
8197 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
8198 prog, e, suppress_int));
8199 ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
8204 printentry(struct tblentry *cmdp)
8210 idx = cmdp->param.index;
8213 padvance(&path, cmdp->cmdname);
8214 } while (--idx >= 0);
8215 name = stackblock();
8216 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
8220 * Clear out command entries. The argument specifies the first entry in
8221 * PATH which has changed.
8224 clearcmdentry(int firstchange)
8226 struct tblentry **tblp;
8227 struct tblentry **pp;
8228 struct tblentry *cmdp;
8231 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
8233 while ((cmdp = *pp) != NULL) {
8234 if ((cmdp->cmdtype == CMDNORMAL &&
8235 cmdp->param.index >= firstchange)
8236 || (cmdp->cmdtype == CMDBUILTIN &&
8237 builtinloc >= firstchange)
8250 * Locate a command in the command hash table. If "add" is nonzero,
8251 * add the command to the table if it is not already present. The
8252 * variable "lastcmdentry" is set to point to the address of the link
8253 * pointing to the entry, so that delete_cmd_entry can delete the
8256 * Interrupts must be off if called with add != 0.
8258 static struct tblentry **lastcmdentry;
8260 static struct tblentry *
8261 cmdlookup(const char *name, int add)
8263 unsigned int hashval;
8265 struct tblentry *cmdp;
8266 struct tblentry **pp;
8269 hashval = (unsigned char)*p << 4;
8271 hashval += (unsigned char)*p++;
8273 pp = &cmdtable[hashval % CMDTABLESIZE];
8274 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8275 if (strcmp(cmdp->cmdname, name) == 0)
8279 if (add && cmdp == NULL) {
8280 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
8282 /* + 1 - already done because
8283 * tblentry::cmdname is char[1] */);
8284 /*cmdp->next = NULL; - ckzalloc did it */
8285 cmdp->cmdtype = CMDUNKNOWN;
8286 strcpy(cmdp->cmdname, name);
8293 * Delete the command entry returned on the last lookup.
8296 delete_cmd_entry(void)
8298 struct tblentry *cmdp;
8301 cmdp = *lastcmdentry;
8302 *lastcmdentry = cmdp->next;
8303 if (cmdp->cmdtype == CMDFUNCTION)
8304 freefunc(cmdp->param.func);
8310 * Add a new command entry, replacing any existing command entry for
8311 * the same name - except special builtins.
8314 addcmdentry(char *name, struct cmdentry *entry)
8316 struct tblentry *cmdp;
8318 cmdp = cmdlookup(name, 1);
8319 if (cmdp->cmdtype == CMDFUNCTION) {
8320 freefunc(cmdp->param.func);
8322 cmdp->cmdtype = entry->cmdtype;
8323 cmdp->param = entry->u;
8327 static int FAST_FUNC
8328 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8330 struct tblentry **pp;
8331 struct tblentry *cmdp;
8333 struct cmdentry entry;
8336 if (nextopt("r") != '\0') {
8341 if (*argptr == NULL) {
8342 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8343 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8344 if (cmdp->cmdtype == CMDNORMAL)
8352 while ((name = *argptr) != NULL) {
8353 cmdp = cmdlookup(name, 0);
8355 && (cmdp->cmdtype == CMDNORMAL
8356 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
8360 find_command(name, &entry, DO_ERR, pathval());
8361 if (entry.cmdtype == CMDUNKNOWN)
8369 * Called when a cd is done. Marks all commands so the next time they
8370 * are executed they will be rehashed.
8375 struct tblentry **pp;
8376 struct tblentry *cmdp;
8378 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8379 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8380 if (cmdp->cmdtype == CMDNORMAL
8381 || (cmdp->cmdtype == CMDBUILTIN
8382 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
8392 * Fix command hash table when PATH changed.
8393 * Called before PATH is changed. The argument is the new value of PATH;
8394 * pathval() still returns the old value at this point.
8395 * Called with interrupts off.
8397 static void FAST_FUNC
8398 changepath(const char *new)
8406 firstchange = 9999; /* assume no change */
8412 if ((*old == '\0' && *new == ':')
8413 || (*old == ':' && *new == '\0')
8417 old = new; /* ignore subsequent differences */
8421 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
8428 if (builtinloc < 0 && idx_bltin >= 0)
8429 builtinloc = idx_bltin; /* zap builtins */
8430 if (builtinloc >= 0 && idx_bltin < 0)
8432 clearcmdentry(firstchange);
8433 builtinloc = idx_bltin;
8469 typedef smallint token_id_t;
8471 /* Nth bit indicates if token marks the end of a list */
8474 /* 0 */ | (1u << TEOF)
8475 /* 1 */ | (0u << TNL)
8476 /* 2 */ | (0u << TREDIR)
8477 /* 3 */ | (0u << TWORD)
8478 /* 4 */ | (0u << TSEMI)
8479 /* 5 */ | (0u << TBACKGND)
8480 /* 6 */ | (0u << TAND)
8481 /* 7 */ | (0u << TOR)
8482 /* 8 */ | (0u << TPIPE)
8483 /* 9 */ | (0u << TLP)
8484 /* 10 */ | (1u << TRP)
8485 /* 11 */ | (1u << TENDCASE)
8486 /* 12 */ | (1u << TENDBQUOTE)
8487 /* 13 */ | (0u << TNOT)
8488 /* 14 */ | (0u << TCASE)
8489 /* 15 */ | (1u << TDO)
8490 /* 16 */ | (1u << TDONE)
8491 /* 17 */ | (1u << TELIF)
8492 /* 18 */ | (1u << TELSE)
8493 /* 19 */ | (1u << TESAC)
8494 /* 20 */ | (1u << TFI)
8495 /* 21 */ | (0u << TFOR)
8497 /* 22 */ | (0u << TFUNCTION)
8499 /* 23 */ | (0u << TIF)
8500 /* 24 */ | (0u << TIN)
8501 /* 25 */ | (1u << TTHEN)
8502 /* 26 */ | (0u << TUNTIL)
8503 /* 27 */ | (0u << TWHILE)
8504 /* 28 */ | (0u << TBEGIN)
8505 /* 29 */ | (1u << TEND)
8506 , /* thus far 29 bits used */
8509 static const char *const tokname_array[] = {
8523 #define KWDOFFSET 13
8524 /* the following are keywords */
8546 /* Wrapper around strcmp for qsort/bsearch/... */
8548 pstrcmp(const void *a, const void *b)
8550 return strcmp((char*)a, *(char**)b);
8553 static const char *const *
8554 findkwd(const char *s)
8556 return bsearch(s, tokname_array + KWDOFFSET,
8557 ARRAY_SIZE(tokname_array) - KWDOFFSET,
8558 sizeof(tokname_array[0]), pstrcmp);
8562 * Locate and print what a word is...
8565 describe_command(char *command, const char *path, int describe_command_verbose)
8567 struct cmdentry entry;
8568 #if ENABLE_ASH_ALIAS
8569 const struct alias *ap;
8572 path = path ? path : pathval();
8574 if (describe_command_verbose) {
8578 /* First look at the keywords */
8579 if (findkwd(command)) {
8580 out1str(describe_command_verbose ? " is a shell keyword" : command);
8584 #if ENABLE_ASH_ALIAS
8585 /* Then look at the aliases */
8586 ap = lookupalias(command, 0);
8588 if (!describe_command_verbose) {
8593 out1fmt(" is an alias for %s", ap->val);
8598 find_command(command, &entry, DO_ABS, path);
8600 switch (entry.cmdtype) {
8602 int j = entry.u.index;
8608 padvance(&path, command);
8612 if (describe_command_verbose) {
8613 out1fmt(" is %s", p);
8621 if (describe_command_verbose) {
8622 /*out1str(" is a shell function");*/
8623 out1str(" is a function"); /* bash says this */
8630 if (describe_command_verbose) {
8631 out1fmt(" is a %sshell builtin",
8632 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8633 "special " : nullstr
8641 if (describe_command_verbose) {
8642 out1str(": not found\n");
8651 static int FAST_FUNC
8652 typecmd(int argc UNUSED_PARAM, char **argv)
8658 /* type -p ... ? (we don't bother checking for 'p') */
8659 if (argv[1] && argv[1][0] == '-') {
8664 err |= describe_command(argv[i++], NULL, verbose);
8669 #if ENABLE_ASH_CMDCMD
8670 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8672 parse_command_args(char **argv, const char **path)
8685 if (c == '-' && !*cp) {
8693 *path = bb_default_path;
8696 /* run 'typecmd' for other options */
8705 static int FAST_FUNC
8706 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8714 const char *path = NULL;
8716 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8717 * never reaches this function.
8720 while ((c = nextopt("pvV")) != '\0')
8722 verify |= VERIFY_VERBOSE;
8724 /*verify |= VERIFY_BRIEF*/;
8730 path = bb_default_path;
8732 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8734 if (/*verify && */ cmd)
8735 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8742 /*static int funcblocksize; // size of structures in function */
8743 /*static int funcstringsize; // size of strings in node */
8744 static void *funcblock; /* block to allocate function from */
8745 static char *funcstring_end; /* end of block to allocate strings from */
8747 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8748 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8749 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8750 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8751 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8752 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8753 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8754 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8755 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8756 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8757 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8758 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8759 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8760 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8761 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8762 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8763 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8764 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8765 #if BASH_REDIR_OUTPUT
8766 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8768 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8769 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8770 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8771 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8772 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8773 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8774 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8775 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8776 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8779 static int calcsize(int funcblocksize, union node *n);
8782 sizenodelist(int funcblocksize, struct nodelist *lp)
8785 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8786 funcblocksize = calcsize(funcblocksize, lp->n);
8789 return funcblocksize;
8793 calcsize(int funcblocksize, union node *n)
8796 return funcblocksize;
8797 funcblocksize += nodesize[n->type];
8800 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8801 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8802 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8805 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8810 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8811 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8818 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8819 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8822 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8823 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8824 funcblocksize = calcsize(funcblocksize, n->nif.test);
8827 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8828 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8829 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8832 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8833 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8836 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8837 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8838 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8841 funcblocksize = calcsize(funcblocksize, n->ndefun.body);
8842 funcblocksize += SHELL_ALIGN(strlen(n->ndefun.text) + 1);
8845 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8846 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8847 funcblocksize = calcsize(funcblocksize, n->narg.next);
8850 #if BASH_REDIR_OUTPUT
8857 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8858 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8862 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8863 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8867 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8868 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8871 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8874 return funcblocksize;
8878 nodeckstrdup(char *s)
8880 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8881 return strcpy(funcstring_end, s);
8884 static union node *copynode(union node *);
8886 static struct nodelist *
8887 copynodelist(struct nodelist *lp)
8889 struct nodelist *start;
8890 struct nodelist **lpp;
8895 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8896 (*lpp)->n = copynode(lp->n);
8898 lpp = &(*lpp)->next;
8905 copynode(union node *n)
8912 funcblock = (char *) funcblock + nodesize[n->type];
8916 new->ncmd.redirect = copynode(n->ncmd.redirect);
8917 new->ncmd.args = copynode(n->ncmd.args);
8918 new->ncmd.assign = copynode(n->ncmd.assign);
8919 new->ncmd.linno = n->ncmd.linno;
8922 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8923 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8928 new->nredir.redirect = copynode(n->nredir.redirect);
8929 new->nredir.n = copynode(n->nredir.n);
8930 new->nredir.linno = n->nredir.linno;
8937 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8938 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8941 new->nif.elsepart = copynode(n->nif.elsepart);
8942 new->nif.ifpart = copynode(n->nif.ifpart);
8943 new->nif.test = copynode(n->nif.test);
8946 new->nfor.var = nodeckstrdup(n->nfor.var);
8947 new->nfor.body = copynode(n->nfor.body);
8948 new->nfor.args = copynode(n->nfor.args);
8949 new->nfor.linno = n->nfor.linno;
8952 new->ncase.cases = copynode(n->ncase.cases);
8953 new->ncase.expr = copynode(n->ncase.expr);
8954 new->ncase.linno = n->ncase.linno;
8957 new->nclist.body = copynode(n->nclist.body);
8958 new->nclist.pattern = copynode(n->nclist.pattern);
8959 new->nclist.next = copynode(n->nclist.next);
8962 new->ndefun.body = copynode(n->ndefun.body);
8963 new->ndefun.text = nodeckstrdup(n->ndefun.text);
8964 new->ndefun.linno = n->ndefun.linno;
8967 new->narg.backquote = copynodelist(n->narg.backquote);
8968 new->narg.text = nodeckstrdup(n->narg.text);
8969 new->narg.next = copynode(n->narg.next);
8972 #if BASH_REDIR_OUTPUT
8979 new->nfile.fname = copynode(n->nfile.fname);
8980 new->nfile.fd = n->nfile.fd;
8981 new->nfile.next = copynode(n->nfile.next);
8985 new->ndup.vname = copynode(n->ndup.vname);
8986 new->ndup.dupfd = n->ndup.dupfd;
8987 new->ndup.fd = n->ndup.fd;
8988 new->ndup.next = copynode(n->ndup.next);
8992 new->nhere.doc = copynode(n->nhere.doc);
8993 new->nhere.fd = n->nhere.fd;
8994 new->nhere.next = copynode(n->nhere.next);
8997 new->nnot.com = copynode(n->nnot.com);
9000 new->type = n->type;
9005 * Make a copy of a parse tree.
9007 static struct funcnode *
9008 copyfunc(union node *n)
9013 /*funcstringsize = 0;*/
9014 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
9015 f = ckzalloc(blocksize /* + funcstringsize */);
9016 funcblock = (char *) f + offsetof(struct funcnode, n);
9017 funcstring_end = (char *) f + blocksize;
9019 /* f->count = 0; - ckzalloc did it */
9024 * Define a shell function.
9027 defun(union node *func)
9029 struct cmdentry entry;
9032 entry.cmdtype = CMDFUNCTION;
9033 entry.u.func = copyfunc(func);
9034 addcmdentry(func->ndefun.text, &entry);
9038 /* Reasons for skipping commands (see comment on breakcmd routine) */
9039 #define SKIPBREAK (1 << 0)
9040 #define SKIPCONT (1 << 1)
9041 #define SKIPFUNC (1 << 2)
9042 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
9043 static int skipcount; /* number of levels to skip */
9044 static int loopnest; /* current loop nesting level */
9045 static int funcline; /* starting line number of current function, or 0 if not in a function */
9047 /* Forward decl way out to parsing code - dotrap needs it */
9048 static int evalstring(char *s, int flags);
9050 /* Called to execute a trap.
9051 * Single callsite - at the end of evaltree().
9052 * If we return non-zero, evaltree raises EXEXIT exception.
9054 * Perhaps we should avoid entering new trap handlers
9055 * while we are executing a trap handler. [is it a TODO?]
9062 int status, last_status;
9067 status = savestatus;
9068 last_status = status;
9070 status = exitstatus;
9071 savestatus = status;
9076 TRACE(("dotrap entered\n"));
9077 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
9089 /* non-trapped SIGINT is handled separately by raise_interrupt,
9090 * don't upset it by resetting gotsig[SIGINT-1] */
9091 if (sig == SIGINT && !p)
9094 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
9099 exitstatus = status;
9102 savestatus = last_status;
9103 TRACE(("dotrap returns\n"));
9106 /* forward declarations - evaluation is fairly recursive business... */
9107 static int evalloop(union node *, int);
9108 static int evalfor(union node *, int);
9109 static int evalcase(union node *, int);
9110 static int evalsubshell(union node *, int);
9111 static void expredir(union node *);
9112 static int evalpipe(union node *, int);
9113 static int evalcommand(union node *, int);
9114 static int evalbltin(const struct builtincmd *, int, char **, int);
9115 static void prehash(union node *);
9118 * Evaluate a parse tree. The value is left in the global variable
9122 evaltree(union node *n, int flags)
9125 int (*evalfn)(union node *, int);
9126 struct stackmark smark;
9129 setstackmark(&smark);
9132 TRACE(("evaltree(NULL) called\n"));
9135 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
9142 out1fmt("Node type = %d\n", n->type);
9147 status = !evaltree(n->nnot.com, EV_TESTED);
9150 errlinno = lineno = n->nredir.linno;
9152 lineno -= funcline - 1;
9153 expredir(n->nredir.redirect);
9154 pushredir(n->nredir.redirect);
9155 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
9157 status = evaltree(n->nredir.n, flags & EV_TESTED);
9159 if (n->nredir.redirect)
9160 popredir(/*drop:*/ 0);
9163 evalfn = evalcommand;
9165 if (eflag && !(flags & EV_TESTED))
9177 evalfn = evalsubshell;
9190 #error NAND + 1 != NOR
9192 #if NOR + 1 != NSEMI
9193 #error NOR + 1 != NSEMI
9195 unsigned is_or = n->type - NAND;
9198 (flags | ((is_or >> 1) - 1)) & EV_TESTED
9200 if ((!status) == is_or || evalskip)
9206 status = evalfn(n, flags);
9210 status = evaltree(n->nif.test, EV_TESTED);
9217 if (n->nif.elsepart) {
9218 n = n->nif.elsepart;
9225 /* Not necessary. To test it:
9226 * "false; f() { qwerty; }; echo $?" should print 0.
9230 exitstatus = status;
9234 /* Order of checks below is important:
9235 * signal handlers trigger before exit caused by "set -e".
9239 if (checkexit & status)
9240 raise_exception(EXEXIT);
9241 if (flags & EV_EXIT)
9242 raise_exception(EXEXIT);
9244 popstackmark(&smark);
9245 TRACE(("leaving evaltree (no interrupts)\n"));
9252 int skip = evalskip;
9259 if (--skipcount <= 0) {
9270 evalloop(union node *n, int flags)
9281 i = evaltree(n->nbinary.ch1, EV_TESTED);
9283 if (skip == SKIPFUNC)
9287 if (n->type != NWHILE)
9291 status = evaltree(n->nbinary.ch2, flags);
9293 } while (!(skip & ~SKIPCONT));
9300 evalfor(union node *n, int flags)
9302 struct arglist arglist;
9307 errlinno = lineno = n->ncase.linno;
9309 lineno -= funcline - 1;
9311 arglist.list = NULL;
9312 arglist.lastp = &arglist.list;
9313 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
9314 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9316 *arglist.lastp = NULL;
9320 for (sp = arglist.list; sp; sp = sp->next) {
9321 setvar0(n->nfor.var, sp->text);
9322 status = evaltree(n->nfor.body, flags);
9323 if (skiploop() & ~SKIPCONT)
9332 evalcase(union node *n, int flags)
9336 struct arglist arglist;
9339 errlinno = lineno = n->ncase.linno;
9341 lineno -= funcline - 1;
9343 arglist.list = NULL;
9344 arglist.lastp = &arglist.list;
9345 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
9346 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
9347 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
9348 if (casematch(patp, arglist.list->text)) {
9349 /* Ensure body is non-empty as otherwise
9350 * EV_EXIT may prevent us from setting the
9353 if (evalskip == 0 && cp->nclist.body) {
9354 status = evaltree(cp->nclist.body, flags);
9365 * Kick off a subshell to evaluate a tree.
9368 evalsubshell(union node *n, int flags)
9371 int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
9374 errlinno = lineno = n->nredir.linno;
9376 lineno -= funcline - 1;
9378 expredir(n->nredir.redirect);
9379 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
9382 if (backgnd == FORK_FG)
9384 jp = makejob(/*n,*/ 1);
9385 if (forkshell(jp, n, backgnd) == 0) {
9390 flags &= ~EV_TESTED;
9392 redirect(n->nredir.redirect, 0);
9393 evaltreenr(n->nredir.n, flags);
9398 if (backgnd == FORK_FG)
9399 status = waitforjob(jp);
9405 * Compute the names of the files in a redirection list.
9407 static void fixredir(union node *, const char *, int);
9409 expredir(union node *n)
9413 for (redir = n; redir; redir = redir->nfile.next) {
9417 fn.lastp = &fn.list;
9418 switch (redir->type) {
9422 #if BASH_REDIR_OUTPUT
9427 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
9428 TRACE(("expredir expanded to '%s'\n", fn.list->text));
9429 #if BASH_REDIR_OUTPUT
9433 // By the design of stack allocator, the loop of this kind:
9434 // while true; do while true; do break; done </dev/null; done
9435 // will look like a memory leak: ash plans to free expfname's
9436 // of "/dev/null" as soon as it finishes running the loop
9437 // (in this case, never).
9438 // This "fix" is wrong:
9439 if (redir->nfile.expfname)
9440 stunalloc(redir->nfile.expfname);
9441 // It results in corrupted state of stacked allocations.
9443 redir->nfile.expfname = fn.list->text;
9446 case NTOFD: /* >& */
9447 if (redir->ndup.vname) {
9448 expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR);
9449 if (fn.list == NULL)
9450 ash_msg_and_raise_error("redir error");
9451 #if BASH_REDIR_OUTPUT
9452 if (!isdigit_str9(fn.list->text)) {
9453 /* >&file, not >&fd */
9454 if (redir->nfile.fd != 1) /* 123>&file - BAD */
9455 ash_msg_and_raise_error("redir error");
9457 goto store_expfname;
9460 fixredir(redir, fn.list->text, 1);
9468 * Evaluate a pipeline. All the processes in the pipeline are children
9469 * of the process creating the pipeline. (This differs from some versions
9470 * of the shell, which make the last process in a pipeline the parent
9474 evalpipe(union node *n, int flags)
9477 struct nodelist *lp;
9483 TRACE(("evalpipe(0x%lx) called\n", (long)n));
9485 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
9489 if (n->npipe.pipe_backgnd == 0)
9491 jp = makejob(/*n,*/ pipelen);
9493 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
9497 if (pipe(pip) < 0) {
9499 ash_msg_and_raise_perror("can't create pipe");
9502 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
9516 evaltreenr(lp->n, flags);
9523 /* Don't want to trigger debugging */
9527 if (n->npipe.pipe_backgnd == 0) {
9528 status = waitforjob(jp);
9529 TRACE(("evalpipe: job done exit status %d\n", status));
9536 /* setinteractive needs this forward reference */
9537 #if EDITING_HAS_get_exe_name
9538 static const char *get_builtin_name(int i) FAST_FUNC;
9542 * Controls whether the shell is interactive or not.
9545 setinteractive(int on)
9547 static smallint is_interactive;
9549 if (++on == is_interactive)
9551 is_interactive = on;
9555 if (is_interactive > 1) {
9556 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9557 /* Looks like they want an interactive shell */
9558 static smallint did_banner;
9561 /* note: ash and hush share this string */
9562 out1fmt("\n\n%s %s\n"
9563 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
9566 "built-in shell (ash)"
9571 #if ENABLE_FEATURE_EDITING
9572 if (!line_input_state) {
9573 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
9574 # if EDITING_HAS_get_exe_name
9575 line_input_state->get_exe_name = get_builtin_name;
9588 setinteractive(iflag);
9590 #if ENABLE_FEATURE_EDITING_VI
9591 if (line_input_state) {
9593 line_input_state->flags |= VI_MODE;
9595 line_input_state->flags &= ~VI_MODE;
9598 viflag = 0; /* forcibly keep the option off */
9602 struct localvar_list {
9603 struct localvar_list *next;
9604 struct localvar *lv;
9607 static struct localvar_list *localvar_stack;
9610 * Called after a function returns.
9611 * Interrupts must be off.
9614 poplocalvars(int keep)
9616 struct localvar_list *ll;
9617 struct localvar *lvp, *next;
9621 ll = localvar_stack;
9622 localvar_stack = ll->next;
9627 while ((lvp = next) != NULL) {
9630 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9632 int bits = VSTRFIXED;
9634 if (lvp->flags != VUNSET) {
9635 if (vp->var_text == lvp->text)
9637 else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
9638 free((char*)lvp->text);
9642 vp->flags |= (lvp->flags & bits);
9645 (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
9646 unsetvar(vp->var_text);
9647 } else if (vp == NULL) { /* $- saved */
9648 memcpy(optlist, lvp->text, sizeof(optlist));
9649 free((char*)lvp->text);
9651 } else if (lvp->flags == VUNSET) {
9652 vp->flags &= ~(VSTRFIXED|VREADONLY);
9653 unsetvar(vp->var_text);
9656 vp->var_func(var_end(lvp->text));
9657 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9658 free((char*)vp->var_text);
9659 vp->flags = lvp->flags;
9660 vp->var_text = lvp->text;
9668 * Create a new localvar environment.
9670 static struct localvar_list *
9673 struct localvar_list *ll;
9676 ll = ckzalloc(sizeof(*ll));
9677 /*ll->lv = NULL; - zalloc did it */
9678 ll->next = localvar_stack;
9679 localvar_stack = ll;
9686 unwindlocalvars(struct localvar_list *stop)
9688 while (localvar_stack != stop)
9693 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9695 volatile struct shparam saveparam;
9696 struct jmploc *volatile savehandler;
9697 struct jmploc jmploc;
9701 saveparam = shellparam;
9702 savefuncline = funcline;
9703 savehandler = exception_handler;
9704 e = setjmp(jmploc.loc);
9709 exception_handler = &jmploc;
9710 shellparam.malloced = 0;
9712 funcline = func->n.ndefun.linno;
9714 shellparam.nparam = argc - 1;
9715 shellparam.p = argv + 1;
9716 #if ENABLE_ASH_GETOPTS
9717 shellparam.optind = 1;
9718 shellparam.optoff = -1;
9720 evaltree(func->n.ndefun.body, flags & EV_TESTED);
9723 funcline = savefuncline;
9725 freeparam(&shellparam);
9726 shellparam = saveparam;
9727 exception_handler = savehandler;
9729 evalskip &= ~SKIPFUNC;
9734 * Make a variable a local variable. When a variable is made local, it's
9735 * value and flags are saved in a localvar structure. The saved values
9736 * will be restored when the shell function returns. We handle the name
9737 * "-" as a special case: it makes changes to "set +-options" local
9738 * (options will be restored on return from the function).
9743 struct localvar *lvp;
9746 char *eq = strchr(name, '=');
9749 /* Cater for duplicate "local". Examples:
9750 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9751 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9753 lvp = localvar_stack->lv;
9755 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9759 * it's a duplicate "local VAR" declaration, do nothing
9766 lvp = ckzalloc(sizeof(*lvp));
9767 if (LONE_DASH(name)) {
9769 p = ckmalloc(sizeof(optlist));
9770 lvp->text = memcpy(p, optlist, sizeof(optlist));
9773 vpp = hashvar(name);
9774 vp = *findvar(vpp, name);
9776 /* variable did not exist yet */
9778 vp = setvareq(name, VSTRFIXED);
9780 vp = setvar(name, NULL, VSTRFIXED);
9781 lvp->flags = VUNSET;
9783 lvp->text = vp->var_text;
9784 lvp->flags = vp->flags;
9785 /* make sure neither "struct var" nor string gets freed
9786 * during (un)setting:
9788 vp->flags |= VSTRFIXED|VTEXTFIXED;
9792 /* "local VAR" unsets VAR: */
9793 setvar0(name, NULL);
9797 lvp->next = localvar_stack->lv;
9798 localvar_stack->lv = lvp;
9804 * The "local" command.
9806 static int FAST_FUNC
9807 localcmd(int argc UNUSED_PARAM, char **argv)
9811 if (!localvar_stack)
9812 ash_msg_and_raise_error("not in a function");
9815 while ((name = *argv++) != NULL) {
9821 static int FAST_FUNC
9822 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9827 static int FAST_FUNC
9828 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9833 static int FAST_FUNC
9834 execcmd(int argc UNUSED_PARAM, char **argv)
9837 while (nextopt("a:") != '\0')
9838 /* nextopt() sets optionarg to "-a ARGV0" */;
9844 iflag = 0; /* exit on error */
9847 /* We should set up signals for "exec CMD"
9848 * the same way as for "CMD" without "exec".
9849 * But optschanged->setinteractive->setsignal
9850 * still thought we are a root shell. Therefore, for example,
9851 * SIGQUIT is still set to IGN. Fix it:
9855 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9856 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9857 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9861 argv[0] = optionarg;
9862 shellexec(prog, argv, pathval(), 0);
9869 * The return command.
9871 static int FAST_FUNC
9872 returncmd(int argc UNUSED_PARAM, char **argv)
9875 * If called outside a function, do what ksh does;
9876 * skip the rest of the file.
9878 evalskip = SKIPFUNC;
9879 return argv[1] ? number(argv[1]) : exitstatus;
9882 /* Forward declarations for builtintab[] */
9883 static int breakcmd(int, char **) FAST_FUNC;
9884 static int dotcmd(int, char **) FAST_FUNC;
9885 static int evalcmd(int, char **, int) FAST_FUNC;
9886 static int exitcmd(int, char **) FAST_FUNC;
9887 static int exportcmd(int, char **) FAST_FUNC;
9888 #if ENABLE_ASH_GETOPTS
9889 static int getoptscmd(int, char **) FAST_FUNC;
9892 static int helpcmd(int, char **) FAST_FUNC;
9895 static int historycmd(int, char **) FAST_FUNC;
9897 #if ENABLE_FEATURE_SH_MATH
9898 static int letcmd(int, char **) FAST_FUNC;
9900 static int readcmd(int, char **) FAST_FUNC;
9901 static int setcmd(int, char **) FAST_FUNC;
9902 static int shiftcmd(int, char **) FAST_FUNC;
9903 static int timescmd(int, char **) FAST_FUNC;
9904 static int trapcmd(int, char **) FAST_FUNC;
9905 static int umaskcmd(int, char **) FAST_FUNC;
9906 static int unsetcmd(int, char **) FAST_FUNC;
9907 static int ulimitcmd(int, char **) FAST_FUNC;
9909 #define BUILTIN_NOSPEC "0"
9910 #define BUILTIN_SPECIAL "1"
9911 #define BUILTIN_REGULAR "2"
9912 #define BUILTIN_SPEC_REG "3"
9913 #define BUILTIN_ASSIGN "4"
9914 #define BUILTIN_SPEC_ASSG "5"
9915 #define BUILTIN_REG_ASSG "6"
9916 #define BUILTIN_SPEC_REG_ASSG "7"
9918 /* Stubs for calling non-FAST_FUNC's */
9920 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9922 #if ENABLE_ASH_PRINTF
9923 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9925 #if ENABLE_ASH_TEST || BASH_TEST2
9926 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9929 /* Keep these in proper order since it is searched via bsearch() */
9930 static const struct builtincmd builtintab[] = {
9931 { BUILTIN_SPEC_REG "." , dotcmd },
9932 { BUILTIN_SPEC_REG ":" , truecmd },
9934 { BUILTIN_REGULAR "[" , testcmd },
9937 { BUILTIN_REGULAR "[[" , testcmd },
9939 #if ENABLE_ASH_ALIAS
9940 { BUILTIN_REG_ASSG "alias" , aliascmd },
9943 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9945 { BUILTIN_SPEC_REG "break" , breakcmd },
9946 { BUILTIN_REGULAR "cd" , cdcmd },
9947 { BUILTIN_NOSPEC "chdir" , cdcmd },
9948 #if ENABLE_ASH_CMDCMD
9949 { BUILTIN_REGULAR "command" , commandcmd },
9951 { BUILTIN_SPEC_REG "continue", breakcmd },
9953 { BUILTIN_REGULAR "echo" , echocmd },
9955 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9956 { BUILTIN_SPEC_REG "exec" , execcmd },
9957 { BUILTIN_SPEC_REG "exit" , exitcmd },
9958 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9959 { BUILTIN_REGULAR "false" , falsecmd },
9961 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9963 #if ENABLE_ASH_GETOPTS
9964 { BUILTIN_REGULAR "getopts" , getoptscmd },
9966 { BUILTIN_REGULAR "hash" , hashcmd },
9968 { BUILTIN_NOSPEC "help" , helpcmd },
9971 { BUILTIN_NOSPEC "history" , historycmd },
9974 { BUILTIN_REGULAR "jobs" , jobscmd },
9975 { BUILTIN_REGULAR "kill" , killcmd },
9977 #if ENABLE_FEATURE_SH_MATH
9978 { BUILTIN_NOSPEC "let" , letcmd },
9980 { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
9981 #if ENABLE_ASH_PRINTF
9982 { BUILTIN_REGULAR "printf" , printfcmd },
9984 { BUILTIN_REGULAR "pwd" , pwdcmd },
9985 { BUILTIN_REGULAR "read" , readcmd },
9986 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9987 { BUILTIN_SPEC_REG "return" , returncmd },
9988 { BUILTIN_SPEC_REG "set" , setcmd },
9989 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9991 { BUILTIN_SPEC_REG "source" , dotcmd },
9994 { BUILTIN_REGULAR "test" , testcmd },
9996 { BUILTIN_SPEC_REG "times" , timescmd },
9997 { BUILTIN_SPEC_REG "trap" , trapcmd },
9998 { BUILTIN_REGULAR "true" , truecmd },
9999 { BUILTIN_REGULAR "type" , typecmd },
10000 { BUILTIN_REGULAR "ulimit" , ulimitcmd },
10001 { BUILTIN_REGULAR "umask" , umaskcmd },
10002 #if ENABLE_ASH_ALIAS
10003 { BUILTIN_REGULAR "unalias" , unaliascmd },
10005 { BUILTIN_SPEC_REG "unset" , unsetcmd },
10006 { BUILTIN_REGULAR "wait" , waitcmd },
10009 /* Should match the above table! */
10010 #define COMMANDCMD (builtintab + \
10012 /* [ */ 1 * ENABLE_ASH_TEST + \
10013 /* [[ */ 1 * BASH_TEST2 + \
10014 /* alias */ 1 * ENABLE_ASH_ALIAS + \
10015 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
10016 /* break cd cddir */ 3)
10017 #define EVALCMD (COMMANDCMD + \
10018 /* command */ 1 * ENABLE_ASH_CMDCMD + \
10019 /* continue */ 1 + \
10020 /* echo */ 1 * ENABLE_ASH_ECHO + \
10022 #define EXECCMD (EVALCMD + \
10026 * Search the table of builtin commands.
10029 pstrcmp1(const void *a, const void *b)
10031 return strcmp((char*)a, *(char**)b + 1);
10033 static struct builtincmd *
10034 find_builtin(const char *name)
10036 struct builtincmd *bp;
10039 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
10045 #if EDITING_HAS_get_exe_name
10046 static const char * FAST_FUNC
10047 get_builtin_name(int i)
10049 return /*i >= 0 &&*/ i < ARRAY_SIZE(builtintab) ? builtintab[i].name + 1 : NULL;
10054 * Execute a simple command.
10056 static void unwindfiles(struct parsefile *stop);
10058 isassignment(const char *p)
10060 const char *q = endofname(p);
10065 static int FAST_FUNC
10066 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10068 /* Preserve exitstatus of a previous possible redirection
10069 * as POSIX mandates */
10070 return back_exitstatus;
10073 evalcommand(union node *cmd, int flags)
10075 static const struct builtincmd null_bltin = {
10076 "\0\0", bltincmd /* why three NULs? */
10078 struct localvar_list *localvar_stop;
10079 struct parsefile *file_stop;
10080 struct redirtab *redir_stop;
10082 struct arglist arglist;
10083 struct arglist varlist;
10086 const struct strlist *sp;
10087 struct cmdentry cmdentry;
10094 smallint cmd_is_exec;
10096 errlinno = lineno = cmd->ncmd.linno;
10098 lineno -= funcline - 1;
10100 /* First expand the arguments. */
10101 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
10102 localvar_stop = pushlocalvars();
10103 file_stop = g_parsefile;
10104 back_exitstatus = 0;
10106 cmdentry.cmdtype = CMDBUILTIN;
10107 cmdentry.u.cmd = &null_bltin;
10108 varlist.lastp = &varlist.list;
10109 *varlist.lastp = NULL;
10110 arglist.lastp = &arglist.list;
10111 *arglist.lastp = NULL;
10114 if (cmd->ncmd.args) {
10115 struct builtincmd *bcmd;
10116 smallint pseudovarflag;
10118 bcmd = find_builtin(cmd->ncmd.args->narg.text);
10119 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
10121 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
10122 struct strlist **spp;
10124 spp = arglist.lastp;
10125 if (pseudovarflag && isassignment(argp->narg.text))
10126 expandarg(argp, &arglist, EXP_VARTILDE);
10128 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
10130 for (sp = *spp; sp; sp = sp->next)
10135 /* Reserve one extra spot at the front for shellexec. */
10136 nargv = stalloc(sizeof(char *) * (argc + 2));
10138 for (sp = arglist.list; sp; sp = sp->next) {
10139 TRACE(("evalcommand arg: %s\n", sp->text));
10140 *nargv++ = sp->text;
10145 if (iflag && funcline == 0 && argc > 0)
10146 lastarg = nargv[-1];
10148 expredir(cmd->ncmd.redirect);
10149 redir_stop = pushredir(cmd->ncmd.redirect);
10151 if (BASH_XTRACEFD && xflag) {
10152 /* NB: bash closes fd == $BASH_XTRACEFD when it is changed.
10153 * we do not emulate this. We only use its value.
10155 const char *xtracefd = lookupvar("BASH_XTRACEFD");
10156 if (xtracefd && is_number(xtracefd))
10157 preverrout_fd = atoi(xtracefd);
10160 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
10162 path = vpath.var_text;
10163 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
10164 struct strlist **spp;
10167 spp = varlist.lastp;
10168 expandarg(argp, &varlist, EXP_VARTILDE);
10170 mklocal((*spp)->text);
10173 * Modify the command lookup path, if a PATH= assignment
10177 if (varcmp(p, path) == 0)
10181 /* Print the command if xflag is set. */
10183 const char *pfx = "";
10185 fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
10189 char *varval = sp->text;
10190 char *eq = strchrnul(varval, '=');
10193 fdprintf(preverrout_fd, "%s%.*s%s",
10195 (int)(eq - varval), varval,
10196 maybe_single_quote(eq)
10204 fdprintf(preverrout_fd, "%s%s",
10206 /* always quote if matches reserved word: */
10208 ? single_quote(sp->text)
10209 : maybe_single_quote(sp->text)
10214 safe_write(preverrout_fd, "\n", 1);
10220 /* Now locate the command. */
10222 int cmd_flag = DO_ERR;
10223 #if ENABLE_ASH_CMDCMD
10224 const char *oldpath = path + 5;
10228 find_command(argv[0], &cmdentry, cmd_flag, path);
10229 if (cmdentry.cmdtype == CMDUNKNOWN) {
10230 flush_stdout_stderr();
10235 /* implement bltin and command here */
10236 if (cmdentry.cmdtype != CMDBUILTIN)
10239 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
10240 if (cmdentry.u.cmd == EXECCMD)
10242 #if ENABLE_ASH_CMDCMD
10243 if (cmdentry.u.cmd == COMMANDCMD) {
10245 nargv = parse_command_args(argv, &path);
10248 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
10249 * nargv => "PROG". path is updated if -p.
10251 argc -= nargv - argv;
10253 cmd_flag |= DO_NOFUNC;
10262 exitstatus = status;
10264 /* We have a redirection error. */
10266 raise_exception(EXERROR);
10271 /* Execute the command. */
10272 switch (cmdentry.cmdtype) {
10275 #if ENABLE_FEATURE_SH_STANDALONE \
10276 && ENABLE_FEATURE_SH_NOFORK \
10278 /* (1) BUG: if variables are set, we need to fork, or save/restore them
10279 * around run_nofork_applet() call.
10280 * (2) Should this check also be done in forkshell()?
10281 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
10283 /* find_command() encodes applet_no as (-2 - applet_no) */
10284 int applet_no = (- cmdentry.u.index - 2);
10285 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
10289 sv_environ = environ;
10290 environ = listvars(VEXPORT, VUNSET, varlist.list, /*end:*/ NULL);
10292 * Run <applet>_main().
10293 * Signals (^C) can't interrupt here.
10294 * Otherwise we can mangle stdio or malloc internal state.
10295 * This makes applets which can run for a long time
10296 * and/or wait for user input ineligible for NOFORK:
10297 * for example, "yes" or "rm" (rm -i waits for input).
10299 status = run_nofork_applet(applet_no, argv);
10300 environ = sv_environ;
10302 * Try enabling NOFORK for "yes" applet.
10303 * ^C _will_ stop it (write returns EINTR),
10304 * but this causes stdout FILE to be stuck
10305 * and needing clearerr(). What if other applets
10306 * also can get EINTRs? Do we need to switch
10307 * our signals to SA_RESTART?
10309 /*clearerr(stdout);*/
10314 /* Can we avoid forking? For example, very last command
10315 * in a script or a subshell does not need forking,
10316 * we can just exec it.
10318 if (!(flags & EV_EXIT) || may_have_traps) {
10319 /* No, forking off a child is necessary */
10322 jp = makejob(/*cmd,*/ 1);
10323 if (forkshell(jp, cmd, FORK_FG) != 0) {
10325 status = waitforjob(jp);
10327 TRACE(("forked child exited with %d\n", status));
10332 /* fall through to exec'ing external program */
10334 listsetvar(varlist.list, VEXPORT|VSTACK);
10335 shellexec(argv[0], argv, path, cmdentry.u.index);
10339 if (spclbltin > 0 || argc == 0) {
10341 if (cmd_is_exec && argc > 1)
10342 listsetvar(varlist.list, VEXPORT);
10345 /* Tight loop with builtins only:
10346 * "while kill -0 $child; do true; done"
10347 * will never exit even if $child died, unless we do this
10348 * to reap the zombie and make kill detect that it's gone: */
10349 dowait(DOWAIT_NONBLOCK, NULL);
10351 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
10352 if (exception_type == EXERROR && spclbltin <= 0) {
10357 longjmp(exception_handler->loc, 1);
10362 /* See above for the rationale */
10363 dowait(DOWAIT_NONBLOCK, NULL);
10364 if (evalfun(cmdentry.u.func, argc, argv, flags))
10367 status = exitstatus;
10372 if (cmd->ncmd.redirect)
10373 popredir(/*drop:*/ cmd_is_exec);
10374 unwindredir(redir_stop);
10375 unwindfiles(file_stop);
10376 unwindlocalvars(localvar_stop);
10378 /* dsl: I think this is intended to be used to support
10379 * '_' in 'vi' command mode during line editing...
10380 * However I implemented that within libedit itself.
10382 setvar0("_", lastarg);
10389 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
10391 char *volatile savecmdname;
10392 struct jmploc *volatile savehandler;
10393 struct jmploc jmploc;
10397 savecmdname = commandname;
10398 savehandler = exception_handler;
10399 i = setjmp(jmploc.loc);
10402 exception_handler = &jmploc;
10403 commandname = argv[0];
10405 optptr = NULL; /* initialize nextopt */
10406 if (cmd == EVALCMD)
10407 status = evalcmd(argc, argv, flags);
10409 status = (*cmd->builtin)(argc, argv);
10410 flush_stdout_stderr();
10411 status |= ferror(stdout);
10412 exitstatus = status;
10415 commandname = savecmdname;
10416 exception_handler = savehandler;
10422 goodname(const char *p)
10424 return endofname(p)[0] == '\0';
10429 * Search for a command. This is called before we fork so that the
10430 * location of the command will be available in the parent as well as
10431 * the child. The check for "goodname" is an overly conservative
10432 * check that the name will not be subject to expansion.
10435 prehash(union node *n)
10437 struct cmdentry entry;
10439 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
10440 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
10444 /* ============ Builtin commands
10446 * Builtin commands whose functions are closely tied to evaluation
10447 * are implemented here.
10451 * Handle break and continue commands. Break, continue, and return are
10452 * all handled by setting the evalskip flag. The evaluation routines
10453 * above all check this flag, and if it is set they start skipping
10454 * commands rather than executing them. The variable skipcount is
10455 * the number of loops to break/continue, or the number of function
10456 * levels to return. (The latter is always 1.) It should probably
10457 * be an error to break out of more loops than exist, but it isn't
10458 * in the standard shell so we don't make it one here.
10460 static int FAST_FUNC
10461 breakcmd(int argc UNUSED_PARAM, char **argv)
10463 int n = argv[1] ? number(argv[1]) : 1;
10466 ash_msg_and_raise_error(msg_illnum, argv[1]);
10470 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
10478 * This implements the input routines used by the parser.
10482 INPUT_PUSH_FILE = 1,
10483 INPUT_NOFILE_OK = 2,
10486 static smallint checkkwd;
10487 /* values of checkkwd variable */
10488 #define CHKALIAS 0x1
10491 #define CHKEOFMARK 0x8
10494 * Push a string back onto the input at this current parsefile level.
10495 * We handle aliases this way.
10497 #if !ENABLE_ASH_ALIAS
10498 #define pushstring(s, ap) pushstring(s)
10501 pushstring(char *s, struct alias *ap)
10503 struct strpush *sp;
10508 if (g_parsefile->strpush) {
10509 sp = ckzalloc(sizeof(*sp));
10510 sp->prev = g_parsefile->strpush;
10512 sp = &(g_parsefile->basestrpush);
10514 g_parsefile->strpush = sp;
10515 sp->prev_string = g_parsefile->next_to_pgetc;
10516 sp->prev_left_in_line = g_parsefile->left_in_line;
10517 sp->unget = g_parsefile->unget;
10518 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
10519 #if ENABLE_ASH_ALIAS
10522 ap->flag |= ALIASINUSE;
10526 g_parsefile->next_to_pgetc = s;
10527 g_parsefile->left_in_line = len;
10528 g_parsefile->unget = 0;
10535 struct strpush *sp = g_parsefile->strpush;
10538 #if ENABLE_ASH_ALIAS
10540 if (g_parsefile->next_to_pgetc[-1] == ' '
10541 || g_parsefile->next_to_pgetc[-1] == '\t'
10543 checkkwd |= CHKALIAS;
10545 if (sp->string != sp->ap->val) {
10548 sp->ap->flag &= ~ALIASINUSE;
10549 if (sp->ap->flag & ALIASDEAD) {
10550 unalias(sp->ap->name);
10554 g_parsefile->next_to_pgetc = sp->prev_string;
10555 g_parsefile->left_in_line = sp->prev_left_in_line;
10556 g_parsefile->unget = sp->unget;
10557 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
10558 g_parsefile->strpush = sp->prev;
10559 if (sp != &(g_parsefile->basestrpush))
10568 char *buf = g_parsefile->buf;
10570 g_parsefile->next_to_pgetc = buf;
10571 #if ENABLE_FEATURE_EDITING
10573 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
10574 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10576 # if ENABLE_ASH_IDLE_TIMEOUT
10578 const char *tmout_var = lookupvar("TMOUT");
10580 timeout = atoi(tmout_var) * 1000;
10584 line_input_state->timeout = timeout;
10586 # if ENABLE_FEATURE_TAB_COMPLETION
10587 line_input_state->path_lookup = pathval();
10589 reinit_unicode_for_ash();
10590 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ);
10592 /* ^C pressed, "convert" to SIGINT */
10593 write(STDOUT_FILENO, "^C", 2);
10594 if (trap[SIGINT]) {
10600 exitstatus = 128 + SIGINT;
10606 /* Ctrl+D pressed */
10609 # if ENABLE_ASH_IDLE_TIMEOUT
10610 else if (errno == EAGAIN && timeout > 0) {
10611 puts("\007timed out waiting for input: auto-logout");
10618 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10621 #if 0 /* disabled: nonblock_immune_read() handles this problem */
10623 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
10624 int flags = fcntl(0, F_GETFL);
10625 if (flags >= 0 && (flags & O_NONBLOCK)) {
10626 flags &= ~O_NONBLOCK;
10627 if (fcntl(0, F_SETFL, flags) >= 0) {
10628 out2str("sh: turning off NDELAY mode\n");
10639 * Refill the input buffer and return the next input character:
10641 * 1) If a string was pushed back on the input, pop it;
10642 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
10643 * or we are reading from a string so we can't refill the buffer,
10645 * 3) If there is more stuff in this buffer, use it else call read to fill it.
10646 * 4) Process input up to the next newline, deleting nul characters.
10648 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
10649 #define pgetc_debug(...) ((void)0)
10650 static int pgetc(void);
10657 if (g_parsefile->strpush) {
10658 #if ENABLE_ASH_ALIAS
10659 if (g_parsefile->left_in_line == -1
10660 && g_parsefile->strpush->ap
10661 && g_parsefile->next_to_pgetc[-1] != ' '
10662 && g_parsefile->next_to_pgetc[-1] != '\t'
10664 pgetc_debug("preadbuffer PEOA");
10671 /* on both branches above g_parsefile->left_in_line < 0.
10672 * "pgetc" needs refilling.
10675 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
10676 * pungetc() may increment it a few times.
10677 * Assuming it won't increment it to less than -90.
10679 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
10680 pgetc_debug("preadbuffer PEOF1");
10681 /* even in failure keep left_in_line and next_to_pgetc
10682 * in lock step, for correct multi-layer pungetc.
10683 * left_in_line was decremented before preadbuffer(),
10684 * must inc next_to_pgetc: */
10685 g_parsefile->next_to_pgetc++;
10689 more = g_parsefile->left_in_buffer;
10691 flush_stdout_stderr();
10695 /* don't try reading again */
10696 g_parsefile->left_in_line = -99;
10697 pgetc_debug("preadbuffer PEOF2");
10698 g_parsefile->next_to_pgetc++;
10703 /* Find out where's the end of line.
10704 * Set g_parsefile->left_in_line
10705 * and g_parsefile->left_in_buffer acordingly.
10706 * NUL chars are deleted.
10708 q = g_parsefile->next_to_pgetc;
10716 memmove(q, q + 1, more);
10720 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10726 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10727 if (g_parsefile->left_in_line < 0)
10732 g_parsefile->left_in_buffer = more;
10737 out2str(g_parsefile->next_to_pgetc);
10741 pgetc_debug("preadbuffer at %d:%p'%s'",
10742 g_parsefile->left_in_line,
10743 g_parsefile->next_to_pgetc,
10744 g_parsefile->next_to_pgetc);
10745 return (unsigned char)*g_parsefile->next_to_pgetc++;
10751 g_parsefile->linno++;
10752 setprompt_if(doprompt, 2);
10757 g_parsefile->linno++;
10758 needprompt = doprompt;
10766 pgetc_debug("pgetc at %d:%p'%s'",
10767 g_parsefile->left_in_line,
10768 g_parsefile->next_to_pgetc,
10769 g_parsefile->next_to_pgetc);
10770 if (g_parsefile->unget)
10771 return g_parsefile->lastc[--g_parsefile->unget];
10773 if (--g_parsefile->left_in_line >= 0)
10774 c = (unsigned char)*g_parsefile->next_to_pgetc++;
10778 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10779 g_parsefile->lastc[0] = c;
10784 #if ENABLE_ASH_ALIAS
10786 pgetc_without_PEOA(void)
10790 pgetc_debug("pgetc at %d:%p'%s'",
10791 g_parsefile->left_in_line,
10792 g_parsefile->next_to_pgetc,
10793 g_parsefile->next_to_pgetc);
10795 } while (c == PEOA);
10799 # define pgetc_without_PEOA() pgetc()
10803 * Undo a call to pgetc. Only two characters may be pushed back.
10804 * PEOF may be pushed back.
10809 g_parsefile->unget++;
10812 /* This one eats backslash+newline */
10818 while ((c = pgetc()) == '\\') {
10819 if (pgetc() != '\n') {
10832 uint8_t innerdq :1;
10833 uint8_t varpushed :1;
10834 uint8_t dblquote :1;
10835 int varnest; /* levels of variables expansion */
10836 int dqvarnest; /* levels of variables expansion within double quotes */
10837 int parenlevel; /* levels of parens in arithmetic */
10838 struct synstack *prev;
10839 struct synstack *next;
10843 pgetc_top(struct synstack *stack)
10845 return stack->syntax == SQSYNTAX ? pgetc() : pgetc_eatbnl();
10849 synstack_push(struct synstack **stack, struct synstack *next, int syntax)
10851 memset(next, 0, sizeof(*next));
10852 next->syntax = syntax;
10853 next->next = *stack;
10854 (*stack)->prev = next;
10858 static ALWAYS_INLINE void
10859 synstack_pop(struct synstack **stack)
10861 *stack = (*stack)->next;
10865 * To handle the "." command, a stack of input files is used. Pushfile
10866 * adds a new entry to the stack and popfile restores the previous level.
10871 struct parsefile *pf;
10873 pf = ckzalloc(sizeof(*pf));
10874 pf->prev = g_parsefile;
10876 /*pf->strpush = NULL; - ckzalloc did it */
10877 /*pf->basestrpush.prev = NULL;*/
10885 struct parsefile *pf = g_parsefile;
10891 if (pf->pf_fd >= 0)
10894 while (pf->strpush)
10896 g_parsefile = pf->prev;
10902 unwindfiles(struct parsefile *stop)
10904 while (g_parsefile != stop)
10909 * Return to top level.
10914 unwindfiles(&basepf);
10918 * Close the file(s) that the shell is reading commands from. Called
10919 * after a fork is done.
10925 if (g_parsefile->pf_fd > 0) {
10926 close(g_parsefile->pf_fd);
10927 g_parsefile->pf_fd = 0;
10932 * Like setinputfile, but takes an open file descriptor. Call this with
10936 setinputfd(int fd, int push)
10940 g_parsefile->buf = NULL;
10942 g_parsefile->pf_fd = fd;
10943 if (g_parsefile->buf == NULL)
10944 g_parsefile->buf = ckmalloc(IBUFSIZ);
10945 g_parsefile->left_in_buffer = 0;
10946 g_parsefile->left_in_line = 0;
10947 g_parsefile->linno = 1;
10951 * Set the input to take input from a file. If push is set, push the
10952 * old input onto the stack first.
10955 setinputfile(const char *fname, int flags)
10960 fd = open(fname, O_RDONLY | O_CLOEXEC);
10962 if (flags & INPUT_NOFILE_OK)
10965 ash_msg_and_raise_perror("can't open '%s'", fname);
10969 else if (O_CLOEXEC == 0) /* old libc */
10970 close_on_exec_on(fd);
10972 setinputfd(fd, flags & INPUT_PUSH_FILE);
10979 * Like setinputfile, but takes input from a string.
10982 setinputstring(char *string)
10986 g_parsefile->next_to_pgetc = string;
10987 g_parsefile->left_in_line = strlen(string);
10988 g_parsefile->buf = NULL;
10989 g_parsefile->linno = 1;
10995 * Routines to check for mail.
10998 #if ENABLE_ASH_MAIL
11000 /* Hash of mtimes of mailboxes */
11001 static unsigned mailtime_hash;
11002 /* Set if MAIL or MAILPATH is changed. */
11003 static smallint mail_var_path_changed;
11006 * Print appropriate message(s) if mail has arrived.
11007 * If mail_var_path_changed is set,
11008 * then the value of MAIL has mail_var_path_changed,
11009 * so we just update the values.
11018 struct stackmark smark;
11021 setstackmark(&smark);
11022 mpath = mpathset() ? mpathval() : mailval();
11027 len = padvance(&mpath, nullstr);
11034 for (q = p; *q; q++)
11040 q[-1] = '\0'; /* delete trailing '/' */
11041 if (stat(p, &statb) < 0) {
11044 /* Very simplistic "hash": just a sum of all mtimes */
11045 new_hash += (unsigned)statb.st_mtime;
11047 if (!mail_var_path_changed && mailtime_hash != new_hash) {
11048 if (mailtime_hash != 0)
11049 out2str("you have mail\n");
11050 mailtime_hash = new_hash;
11052 mail_var_path_changed = 0;
11053 popstackmark(&smark);
11056 static void FAST_FUNC
11057 changemail(const char *val UNUSED_PARAM)
11059 mail_var_path_changed = 1;
11062 #endif /* ASH_MAIL */
11065 /* ============ ??? */
11068 * Set the shell parameters.
11071 setparam(char **argv)
11077 for (nparam = 0; argv[nparam]; nparam++)
11079 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
11081 *ap++ = ckstrdup(*argv++);
11084 freeparam(&shellparam);
11085 shellparam.malloced = 1;
11086 shellparam.nparam = nparam;
11087 shellparam.p = newparam;
11088 #if ENABLE_ASH_GETOPTS
11089 shellparam.optind = 1;
11090 shellparam.optoff = -1;
11095 * Process shell options. The global variable argptr contains a pointer
11096 * to the argument list; we advance it past the options.
11098 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
11099 * For a non-interactive shell, an error condition encountered
11100 * by a special built-in ... shall cause the shell to write a diagnostic message
11101 * to standard error and exit as shown in the following table:
11102 * Error Special Built-In
11104 * Utility syntax error (option or operand error) Shall exit
11106 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
11107 * we see that bash does not do that (set "finishes" with error code 1 instead,
11108 * and shell continues), and people rely on this behavior!
11110 * set -o barfoo 2>/dev/null
11113 * Oh well. Let's mimic that.
11116 plus_minus_o(char *name, int val)
11121 for (i = 0; i < NOPTS; i++) {
11122 if (strcmp(name, optnames(i)) == 0) {
11127 ash_msg("illegal option %co %s", val ? '-' : '+', name);
11130 for (i = 0; i < NOPTS; i++) {
11131 if (optnames(i)[0] == '\0')
11134 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
11136 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
11142 setoption(int flag, int val)
11146 for (i = 0; i < NOPTS; i++) {
11147 if (optletters(i) == flag && optnames(i)[0] != '\0') {
11152 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
11155 /* If login_sh is not NULL, we are called to parse command line opts,
11159 options(int *login_sh)
11167 while ((p = *argptr) != NULL) {
11169 if (c != '-' && c != '+')
11172 val = 0; /* val = 0 if c == '+' */
11175 if (p[0] == '\0' || LONE_DASH(p)) {
11177 /* "-" means turn off -x and -v */
11180 /* "--" means reset params */
11181 else if (*argptr == NULL)
11184 break; /* "-" or "--" terminates options */
11187 /* first char was + or - */
11188 while ((c = *p++) != '\0') {
11190 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
11192 minusc = p; /* command is after shell args */
11196 if (c == 's') { /* -s, +s */
11200 if (c == 'i') { /* -i, +i */
11205 *login_sh = 1; /* -l or +l == --login */
11208 /* bash does not accept +-login, we also won't */
11209 if (val && (c == '-')) { /* long options */
11210 if (strcmp(p, "login") == 0) {
11217 if (plus_minus_o(*argptr, val)) {
11218 /* it already printed err message */
11219 return 1; /* error */
11232 * The shift builtin command.
11234 static int FAST_FUNC
11235 shiftcmd(int argc UNUSED_PARAM, char **argv)
11242 n = number(argv[1]);
11243 if (n > shellparam.nparam)
11246 shellparam.nparam -= n;
11247 for (ap1 = shellparam.p; --n >= 0; ap1++) {
11248 if (shellparam.malloced)
11251 ap2 = shellparam.p;
11252 while ((*ap2++ = *ap1++) != NULL)
11254 #if ENABLE_ASH_GETOPTS
11255 shellparam.optind = 1;
11256 shellparam.optoff = -1;
11263 * POSIX requires that 'set' (but not export or readonly) output the
11264 * variables in lexicographic order - by the locale's collating order (sigh).
11265 * Maybe we could keep them in an ordered balanced binary tree
11266 * instead of hashed lists.
11267 * For now just roll 'em through qsort for printing...
11270 showvars(const char *sep_prefix, int on, int off)
11273 char **ep, **epend;
11275 ep = listvars(on, off, /*strlist:*/ NULL, &epend);
11276 qsort(ep, epend - ep, sizeof(char *), vpcmp);
11278 sep = *sep_prefix ? " " : sep_prefix;
11280 for (; ep < epend; ep++) {
11284 p = endofname(*ep);
11285 /* Used to have simple "p = strchrnul(*ep, '=')" here instead, but this
11286 * makes "export -p" to have output not suitable for "eval":
11288 * os.environ["test-test"]="test"
11289 * if os.fork() == 0:
11290 * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
11291 * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ])
11295 q = single_quote(++p);
11296 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
11302 * The set command builtin.
11304 static int FAST_FUNC
11305 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
11310 return showvars(nullstr, 0, VUNSET);
11313 retval = options(/*login_sh:*/ NULL);
11314 if (retval == 0) { /* if no parse error... */
11316 if (*argptr != NULL) {
11324 #if ENABLE_ASH_RANDOM_SUPPORT
11325 static void FAST_FUNC
11326 change_random(const char *value)
11330 if (value == NULL) {
11331 /* "get", generate */
11332 t = next_random(&random_gen);
11333 /* set without recursion */
11334 setvar(vrandom.var_text, utoa(t), VNOFUNC);
11335 vrandom.flags &= ~VNOFUNC;
11338 t = strtoul(value, NULL, 10);
11339 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
11344 #if BASH_EPOCH_VARS
11345 static void FAST_FUNC
11346 change_epoch(struct var *vepoch, const char *fmt)
11349 char buffer[sizeof("%lu.nnnnnn") + sizeof(long)*3];
11351 gettimeofday(&tv, NULL);
11352 sprintf(buffer, fmt, (unsigned long)tv.tv_sec, (unsigned)tv.tv_usec);
11353 setvar(vepoch->var_text, buffer, VNOFUNC);
11354 vepoch->flags &= ~VNOFUNC;
11357 static void FAST_FUNC
11358 change_seconds(const char *value UNUSED_PARAM)
11360 change_epoch(&vepochs, "%lu");
11363 static void FAST_FUNC
11364 change_realtime(const char *value UNUSED_PARAM)
11366 change_epoch(&vepochr, "%lu.%06u");
11370 #if ENABLE_ASH_GETOPTS
11372 getopts(char *optstr, char *optvar, char **optfirst)
11379 int ind = shellparam.optind;
11380 int off = shellparam.optoff;
11384 shellparam.optind = -1;
11385 optnext = optfirst + ind - 1;
11387 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
11390 p = optnext[-1] + off;
11391 if (p == NULL || *p == '\0') {
11392 /* Current word is done, advance */
11394 if (p == NULL || *p != '-' || *++p == '\0') {
11396 unsetvar("OPTARG");
11402 if (LONE_DASH(p)) /* check for "--" */
11407 for (q = optstr; *q != c;) {
11409 /* OPTERR is a bashism */
11410 const char *cp = lookupvar("OPTERR");
11411 if ((cp && LONE_CHAR(cp, '0'))
11412 || (optstr[0] == ':')
11415 /*sbuf[1] = '\0'; - already is */
11416 setvar0("OPTARG", sbuf);
11418 fprintf(stderr, "Illegal option -%c\n", c);
11419 unsetvar("OPTARG");
11429 if (*p == '\0' && (p = *optnext) == NULL) {
11430 /* OPTERR is a bashism */
11431 const char *cp = lookupvar("OPTERR");
11432 if ((cp && LONE_CHAR(cp, '0'))
11433 || (optstr[0] == ':')
11436 /*sbuf[1] = '\0'; - already is */
11437 setvar0("OPTARG", sbuf);
11440 fprintf(stderr, "No arg for -%c option\n", c);
11441 unsetvar("OPTARG");
11449 setvar0("OPTARG", p);
11452 setvar0("OPTARG", nullstr);
11454 ind = optnext - optfirst + 1;
11455 setvar("OPTIND", itoa(ind), VNOFUNC);
11457 /*sbuf[1] = '\0'; - already is */
11458 setvar0(optvar, sbuf);
11460 shellparam.optoff = p ? p - *(optnext - 1) : -1;
11461 shellparam.optind = ind;
11467 * The getopts builtin. Shellparam.optnext points to the next argument
11468 * to be processed. Shellparam.optptr points to the next character to
11469 * be processed in the current argument. If shellparam.optnext is NULL,
11470 * then it's the first time getopts has been called.
11472 static int FAST_FUNC
11473 getoptscmd(int argc, char **argv)
11478 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
11480 optbase = shellparam.p;
11481 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
11482 shellparam.optind = 1;
11483 shellparam.optoff = -1;
11486 optbase = &argv[3];
11487 if ((unsigned)shellparam.optind > argc - 2) {
11488 shellparam.optind = 1;
11489 shellparam.optoff = -1;
11493 return getopts(argv[1], argv[2], optbase);
11495 #endif /* ASH_GETOPTS */
11498 /* ============ Shell parser */
11501 struct heredoc *next; /* next here document in list */
11502 union node *here; /* redirection node */
11503 char *eofmark; /* string indicating end of input */
11504 smallint striptabs; /* if set, strip leading tabs */
11507 static smallint tokpushback; /* last token pushed back */
11508 static smallint quoteflag; /* set if (part of) last token was quoted */
11509 static token_id_t lasttoken; /* last token read (integer id Txxx) */
11510 static struct heredoc *heredoclist; /* list of here documents to read */
11511 static char *wordtext; /* text of last word returned by readtoken */
11512 static struct nodelist *backquotelist;
11513 static union node *redirnode;
11514 static struct heredoc *heredoc;
11516 static const char *
11517 tokname(char *buf, int tok)
11520 return tokname_array[tok];
11521 sprintf(buf, "\"%s\"", tokname_array[tok]);
11525 /* raise_error_unexpected_syntax:
11526 * Called when an unexpected token is read during the parse. The argument
11527 * is the token that is expected, or -1 if more than one type of token can
11528 * occur at this point.
11530 static void raise_error_unexpected_syntax(int) NORETURN;
11532 raise_error_unexpected_syntax(int token)
11538 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
11540 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
11541 raise_error_syntax(msg);
11545 /* parsing is heavily cross-recursive, need these forward decls */
11546 static union node *andor(void);
11547 static union node *pipeline(void);
11548 static union node *parse_command(void);
11549 static void parseheredoc(void);
11550 static int peektoken(void);
11551 static int readtoken(void);
11553 static union node *
11556 union node *n1, *n2, *n3;
11561 switch (peektoken()) {
11569 if (!n1 && (nlflag & 1))
11575 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11576 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
11582 if (tok == TBACKGND) {
11583 if (n2->type == NPIPE) {
11584 n2->npipe.pipe_backgnd = 1;
11586 if (n2->type != NREDIR) {
11587 n3 = stzalloc(sizeof(struct nredir));
11589 /*n3->nredir.redirect = NULL; - stzalloc did it */
11592 n2->type = NBACKGND;
11598 n3 = stzalloc(sizeof(struct nbinary));
11600 n3->nbinary.ch1 = n1;
11601 n3->nbinary.ch2 = n2;
11614 raise_error_unexpected_syntax(-1);
11621 static union node *
11624 union node *n1, *n2, *n3;
11632 } else if (t == TOR) {
11638 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11640 n3 = stzalloc(sizeof(struct nbinary));
11642 n3->nbinary.ch1 = n1;
11643 n3->nbinary.ch2 = n2;
11648 static union node *
11651 union node *n1, *n2, *pipenode;
11652 struct nodelist *lp, *prev;
11656 TRACE(("pipeline: entered\n"));
11657 if (readtoken() == TNOT) {
11659 checkkwd = CHKKWD | CHKALIAS;
11662 n1 = parse_command();
11663 if (readtoken() == TPIPE) {
11664 pipenode = stzalloc(sizeof(struct npipe));
11665 pipenode->type = NPIPE;
11666 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
11667 lp = stzalloc(sizeof(struct nodelist));
11668 pipenode->npipe.cmdlist = lp;
11672 lp = stzalloc(sizeof(struct nodelist));
11673 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11674 lp->n = parse_command();
11676 } while (readtoken() == TPIPE);
11682 n2 = stzalloc(sizeof(struct nnot));
11690 static union node *
11695 n = stzalloc(sizeof(struct narg));
11697 /*n->narg.next = NULL; - stzalloc did it */
11698 n->narg.text = wordtext;
11699 n->narg.backquote = backquotelist;
11704 fixredir(union node *n, const char *text, int err)
11708 TRACE(("Fix redir %s %d\n", text, err));
11710 n->ndup.vname = NULL;
11712 fd = bb_strtou(text, NULL, 10);
11713 if (!errno && fd >= 0)
11714 n->ndup.dupfd = fd;
11715 else if (LONE_DASH(text))
11716 n->ndup.dupfd = -1;
11719 raise_error_syntax("bad fd number");
11720 n->ndup.vname = makename();
11727 union node *n = redirnode;
11729 if (n->type == NHERE)
11730 checkkwd = CHKEOFMARK;
11731 if (readtoken() != TWORD)
11732 raise_error_unexpected_syntax(-1);
11733 if (n->type == NHERE) {
11734 struct heredoc *here = heredoc;
11737 if (quoteflag == 0)
11739 TRACE(("Here document %d\n", n->type));
11740 rmescapes(wordtext, 0, NULL);
11741 here->eofmark = wordtext;
11743 if (heredoclist == NULL)
11744 heredoclist = here;
11746 for (p = heredoclist; p->next; p = p->next)
11750 } else if (n->type == NTOFD || n->type == NFROMFD) {
11751 fixredir(n, wordtext, 0);
11753 n->nfile.fname = makename();
11757 static union node *
11760 union node *args, **app;
11761 union node *n = NULL;
11762 union node *vars, **vpp;
11763 union node **rpp, *redir;
11767 smallint double_brackets_flag = 0;
11769 IF_BASH_FUNCTION(smallint function_flag = 0;)
11778 savecheckkwd = CHKALIAS;
11779 savelinno = g_parsefile->linno;
11782 checkkwd = savecheckkwd;
11787 if (peektoken() != TWORD)
11788 raise_error_unexpected_syntax(TWORD);
11793 case TAND: /* "&&" */
11794 case TOR: /* "||" */
11795 if (!double_brackets_flag) {
11799 wordtext = (char *) (t == TAND ? "-a" : "-o");
11802 n = stzalloc(sizeof(struct narg));
11804 /*n->narg.next = NULL; - stzalloc did it */
11805 n->narg.text = wordtext;
11807 if (strcmp("[[", wordtext) == 0)
11808 double_brackets_flag = 1;
11809 else if (strcmp("]]", wordtext) == 0)
11810 double_brackets_flag = 0;
11812 n->narg.backquote = backquotelist;
11813 if (savecheckkwd && isassignment(wordtext)) {
11815 vpp = &n->narg.next;
11818 app = &n->narg.next;
11822 if (function_flag) {
11823 checkkwd = CHKNL | CHKKWD;
11824 switch (peektoken()) {
11837 if (strcmp("[[", wordtext) == 0)
11842 raise_error_unexpected_syntax(-1);
11848 *rpp = n = redirnode;
11849 rpp = &n->nfile.next;
11850 parsefname(); /* read name of redirection file */
11853 IF_BASH_FUNCTION(do_func:)
11854 if (args && app == &args->narg.next
11857 struct builtincmd *bcmd;
11860 /* We have a function */
11861 if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
11862 raise_error_unexpected_syntax(TRP);
11863 name = n->narg.text;
11864 if (!goodname(name)
11865 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11867 raise_error_syntax("bad function name");
11870 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11871 n->ndefun.text = n->narg.text;
11872 n->ndefun.linno = g_parsefile->linno;
11873 n->ndefun.body = parse_command();
11876 IF_BASH_FUNCTION(function_flag = 0;)
11887 n = stzalloc(sizeof(struct ncmd));
11890 n->ncmd.linno = savelinno;
11891 n->ncmd.args = args;
11892 n->ncmd.assign = vars;
11893 n->ncmd.redirect = redir;
11897 static union node *
11898 parse_command(void)
11900 union node *n1, *n2;
11901 union node *ap, **app;
11902 union node *cp, **cpp;
11903 union node *redir, **rpp;
11911 savelinno = g_parsefile->linno;
11913 switch (readtoken()) {
11915 raise_error_unexpected_syntax(-1);
11918 n1 = stzalloc(sizeof(struct nif));
11920 n1->nif.test = list(0);
11921 if (readtoken() != TTHEN)
11922 raise_error_unexpected_syntax(TTHEN);
11923 n1->nif.ifpart = list(0);
11925 while (readtoken() == TELIF) {
11926 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11927 n2 = n2->nif.elsepart;
11929 n2->nif.test = list(0);
11930 if (readtoken() != TTHEN)
11931 raise_error_unexpected_syntax(TTHEN);
11932 n2->nif.ifpart = list(0);
11934 if (lasttoken == TELSE)
11935 n2->nif.elsepart = list(0);
11937 n2->nif.elsepart = NULL;
11945 n1 = stzalloc(sizeof(struct nbinary));
11946 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11947 n1->nbinary.ch1 = list(0);
11950 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11951 got == TWORD ? wordtext : ""));
11952 raise_error_unexpected_syntax(TDO);
11954 n1->nbinary.ch2 = list(0);
11959 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11960 raise_error_syntax("bad for loop variable");
11961 n1 = stzalloc(sizeof(struct nfor));
11963 n1->nfor.linno = savelinno;
11964 n1->nfor.var = wordtext;
11965 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11966 if (readtoken() == TIN) {
11968 while (readtoken() == TWORD) {
11969 n2 = stzalloc(sizeof(struct narg));
11971 /*n2->narg.next = NULL; - stzalloc did it */
11972 n2->narg.text = wordtext;
11973 n2->narg.backquote = backquotelist;
11975 app = &n2->narg.next;
11978 n1->nfor.args = ap;
11979 if (lasttoken != TNL && lasttoken != TSEMI)
11980 raise_error_unexpected_syntax(-1);
11982 n2 = stzalloc(sizeof(struct narg));
11984 /*n2->narg.next = NULL; - stzalloc did it */
11985 n2->narg.text = (char *)dolatstr;
11986 /*n2->narg.backquote = NULL;*/
11987 n1->nfor.args = n2;
11989 * Newline or semicolon here is optional (but note
11990 * that the original Bourne shell only allowed NL).
11992 if (lasttoken != TSEMI)
11995 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11996 if (readtoken() != TDO)
11997 raise_error_unexpected_syntax(TDO);
11998 n1->nfor.body = list(0);
12002 n1 = stzalloc(sizeof(struct ncase));
12004 n1->ncase.linno = savelinno;
12005 if (readtoken() != TWORD)
12006 raise_error_unexpected_syntax(TWORD);
12007 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
12009 /*n2->narg.next = NULL; - stzalloc did it */
12010 n2->narg.text = wordtext;
12011 n2->narg.backquote = backquotelist;
12012 checkkwd = CHKNL | CHKKWD | CHKALIAS;
12013 if (readtoken() != TIN)
12014 raise_error_unexpected_syntax(TIN);
12015 cpp = &n1->ncase.cases;
12017 checkkwd = CHKNL | CHKKWD;
12019 while (t != TESAC) {
12020 if (lasttoken == TLP)
12022 *cpp = cp = stzalloc(sizeof(struct nclist));
12024 app = &cp->nclist.pattern;
12026 *app = ap = stzalloc(sizeof(struct narg));
12028 /*ap->narg.next = NULL; - stzalloc did it */
12029 ap->narg.text = wordtext;
12030 ap->narg.backquote = backquotelist;
12031 if (readtoken() != TPIPE)
12033 app = &ap->narg.next;
12036 //ap->narg.next = NULL;
12037 if (lasttoken != TRP)
12038 raise_error_unexpected_syntax(TRP);
12039 cp->nclist.body = list(2);
12041 cpp = &cp->nclist.next;
12043 checkkwd = CHKNL | CHKKWD;
12047 raise_error_unexpected_syntax(TENDCASE);
12054 n1 = stzalloc(sizeof(struct nredir));
12055 n1->type = NSUBSHELL;
12056 n1->nredir.linno = savelinno;
12057 n1->nredir.n = list(0);
12058 /*n1->nredir.redirect = NULL; - stzalloc did it */
12065 IF_BASH_FUNCTION(case TFUNCTION:)
12069 return simplecmd();
12072 if (readtoken() != t)
12073 raise_error_unexpected_syntax(t);
12076 /* Now check for redirection which may follow command */
12077 checkkwd = CHKKWD | CHKALIAS;
12079 while (readtoken() == TREDIR) {
12080 *rpp = n2 = redirnode;
12081 rpp = &n2->nfile.next;
12087 if (n1->type != NSUBSHELL) {
12088 n2 = stzalloc(sizeof(struct nredir));
12090 n2->nredir.linno = savelinno;
12094 n1->nredir.redirect = redir;
12099 #if BASH_DOLLAR_SQUOTE
12101 decode_dollar_squote(void)
12103 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
12109 p = strchr(C_escapes, c);
12114 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
12118 } while ((unsigned char)(c - '0') <= 7 && --cnt);
12120 } else if (c == 'x') { /* \xHH */
12124 } while (isxdigit(c) && --cnt);
12126 if (cnt == 3) { /* \x but next char is "bad" */
12130 } else { /* simple seq like \\ or \t */
12135 c = bb_process_escape_sequence((void*)&p);
12136 } else { /* unrecognized "\z": print both chars unless ' or " */
12137 if (c != '\'' && c != '"') {
12139 c |= 0x100; /* "please encode \, then me" */
12146 /* Used by expandstr to get here-doc like behaviour. */
12147 #define FAKEEOFMARK ((char*)(uintptr_t)1)
12149 static ALWAYS_INLINE int
12150 realeofmark(const char *eofmark)
12152 return eofmark && eofmark != FAKEEOFMARK;
12156 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
12157 * is not NULL, read a here document. In the latter case, eofmark is the
12158 * word which marks the end of the document and striptabs is true if
12159 * leading tabs should be stripped from the document. The argument c
12160 * is the first character of the input token or document.
12162 * Because C does not have internal subroutines, I have simulated them
12163 * using goto's to implement the subroutine linkage. The following macros
12164 * will run code that appears at the end of readtoken1.
12166 #define CHECKEND() {goto checkend; checkend_return:;}
12167 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
12168 #define PARSESUB() {goto parsesub; parsesub_return:;}
12169 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
12170 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
12171 #define PARSEARITH() {goto parsearith; parsearith_return:;}
12173 readtoken1(int c, int syntax, char *eofmark, int striptabs)
12175 /* NB: syntax parameter fits into smallint */
12176 /* c parameter is an unsigned char or PEOF or PEOA */
12179 struct nodelist *bqlist;
12182 smallint pssyntax; /* we are expanding a prompt string */
12183 IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
12185 struct synstack synbase = { };
12186 struct synstack *synstack = &synbase;
12188 #if ENABLE_ASH_EXPAND_PRMT
12189 pssyntax = (syntax == PSSYNTAX);
12193 pssyntax = 0; /* constant */
12195 synstack->syntax = syntax;
12197 if (syntax == DQSYNTAX)
12198 synstack->dblquote = 1;
12202 STARTSTACKSTR(out);
12204 /* For each line, until end of word */
12205 CHECKEND(); /* set c to PEOF if at end of here document */
12206 for (;;) { /* until end of line or end of word */
12207 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
12208 switch (SIT(c, synstack->syntax)) {
12209 case CNL: /* '\n' */
12210 if (synstack->syntax == BASESYNTAX
12211 && !synstack->varnest
12213 goto endword; /* exit outer loop */
12217 c = pgetc_top(synstack);
12218 goto loop; /* continue outer loop */
12223 #if BASH_DOLLAR_SQUOTE
12224 if (c == '\\' && bash_dollar_squote) {
12225 c = decode_dollar_squote();
12227 /* skip $'\000', $'\x00' (like bash) */
12231 /* Unknown escape. Encode as '\z' */
12232 c = (unsigned char)c;
12233 if (eofmark == NULL || synstack->dblquote)
12234 USTPUTC(CTLESC, out);
12235 USTPUTC('\\', out);
12239 if (!eofmark || synstack->dblquote || synstack->varnest)
12240 USTPUTC(CTLESC, out);
12243 case CBACK: /* backslash */
12244 c = pgetc_without_PEOA();
12246 USTPUTC(CTLESC, out);
12247 USTPUTC('\\', out);
12250 if (pssyntax && c == '$') {
12251 USTPUTC(CTLESC, out);
12252 USTPUTC('\\', out);
12254 /* Backslash is retained if we are in "str"
12255 * and next char isn't dquote-special.
12257 if (synstack->dblquote
12261 && (c != '"' || (eofmark != NULL && !synstack->varnest))
12262 && (c != '}' || !synstack->varnest)
12264 USTPUTC(CTLESC, out); /* protect '\' from glob */
12265 USTPUTC('\\', out);
12267 USTPUTC(CTLESC, out);
12273 synstack->syntax = SQSYNTAX;
12275 if (eofmark == NULL) {
12276 USTPUTC(CTLQUOTEMARK, out);
12280 synstack->syntax = DQSYNTAX;
12281 synstack->dblquote = 1;
12283 if (synstack->varnest)
12284 synstack->innerdq ^= 1;
12287 IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
12288 if (eofmark != NULL && synstack->varnest == 0) {
12293 if (synstack->dqvarnest == 0) {
12294 synstack->syntax = BASESYNTAX;
12295 synstack->dblquote = 0;
12304 case CVAR: /* '$' */
12305 PARSESUB(); /* parse substitution */
12307 case CENDVAR: /* '}' */
12308 if (!synstack->innerdq && synstack->varnest > 0) {
12309 if (!--synstack->varnest && synstack->varpushed)
12310 synstack_pop(&synstack);
12311 else if (synstack->dqvarnest > 0)
12312 synstack->dqvarnest--;
12317 #if ENABLE_FEATURE_SH_MATH
12318 case CLP: /* '(' in arithmetic */
12319 synstack->parenlevel++;
12322 case CRP: /* ')' in arithmetic */
12323 if (synstack->parenlevel > 0) {
12324 synstack->parenlevel--;
12326 if (pgetc_eatbnl() == ')') {
12328 synstack_pop(&synstack);
12331 * unbalanced parens
12332 * (don't 2nd guess - no error)
12340 case CBQUOTE: /* '`' */
12341 if (checkkwd & CHKEOFMARK) {
12350 goto endword; /* exit outer loop */
12354 if (synstack->varnest == 0) {
12355 #if BASH_REDIR_OUTPUT
12357 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
12358 if (pgetc() == '>')
12359 c = 0x100 + '>'; /* flag &> */
12363 goto endword; /* exit outer loop */
12365 IF_ASH_ALIAS(if (c != PEOA))
12368 c = pgetc_top(synstack);
12372 #if ENABLE_FEATURE_SH_MATH
12373 if (synstack->syntax == ARISYNTAX)
12374 raise_error_syntax("missing '))'");
12376 if (synstack->syntax != BASESYNTAX && eofmark == NULL)
12377 raise_error_syntax("unterminated quoted string");
12378 if (synstack->varnest != 0) {
12380 raise_error_syntax("missing '}'");
12382 USTPUTC('\0', out);
12383 len = out - (char *)stackblock();
12384 out = stackblock();
12385 if (eofmark == NULL) {
12386 if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
12389 if (isdigit_str9(out)) {
12390 PARSEREDIR(); /* passed as params: out, c */
12391 lasttoken = TREDIR;
12394 /* else: non-number X seen, interpret it
12395 * as "NNNX>file" = "NNNX >file" */
12399 quoteflag = quotef;
12400 backquotelist = bqlist;
12401 grabstackblock(len);
12405 /* end of readtoken routine */
12408 * Check to see whether we are at the end of the here document. When this
12409 * is called, c is set to the first character of the next input line. If
12410 * we are at the end of the here document, this routine sets the c to PEOF.
12413 if (realeofmark(eofmark)) {
12417 #if ENABLE_ASH_ALIAS
12419 c = pgetc_without_PEOA();
12422 while (c == '\t') {
12423 c = pgetc_without_PEOA();
12427 markloc = out - (char *)stackblock();
12428 for (p = eofmark; STPUTC(c, out), *p; p++) {
12431 /* FIXME: fails for backslash-newlined terminator:
12436 * (see heredoc_bkslash_newline2.tests)
12438 c = pgetc_without_PEOA();
12441 if (c == '\n' || c == PEOF) {
12443 g_parsefile->linno++;
12444 needprompt = doprompt;
12449 p = (char *)stackblock() + markloc + 1;
12450 len_here = out - p;
12453 len_here -= (c >= PEOF);
12459 str = alloca(len_here + 1);
12460 *(char *)mempcpy(str, p, len_here) = '\0';
12462 pushstring(str, NULL);
12467 STADJUST((char *)stackblock() + markloc - out, out);
12469 goto checkend_return;
12473 * Parse a redirection operator. The variable "out" points to a string
12474 * specifying the fd to be redirected. The variable "c" contains the
12475 * first character of the redirection operator.
12478 /* out is already checked to be a valid number or "" */
12479 int fd = (*out == '\0' ? -1 : atoi(out));
12482 np = stzalloc(sizeof(struct nfile));
12485 c = pgetc_eatbnl();
12487 np->type = NAPPEND;
12489 np->type = NCLOBBER;
12492 /* it also can be NTO2 (>&file), but we can't figure it out yet */
12498 #if BASH_REDIR_OUTPUT
12499 else if (c == 0x100 + '>') { /* this flags &> redirection */
12501 pgetc(); /* this is '>', no need to check */
12505 else { /* c == '<' */
12506 /*np->nfile.fd = 0; - stzalloc did it */
12507 c = pgetc_eatbnl();
12510 if (sizeof(struct nfile) != sizeof(struct nhere)) {
12511 np = stzalloc(sizeof(struct nhere));
12512 /*np->nfile.fd = 0; - stzalloc did it */
12515 heredoc = stzalloc(sizeof(struct heredoc));
12516 heredoc->here = np;
12517 c = pgetc_eatbnl();
12519 heredoc->striptabs = 1;
12521 /*heredoc->striptabs = 0; - stzalloc did it */
12527 np->type = NFROMFD;
12531 np->type = NFROMTO;
12543 goto parseredir_return;
12547 * Parse a substitution. At this point, we have read the dollar sign
12548 * and nothing else.
12551 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
12552 * (assuming ascii char codes, as the original implementation did) */
12553 #define is_special(c) \
12554 (((unsigned)(c) - 33 < 32) \
12555 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
12557 unsigned char subtype;
12560 c = pgetc_eatbnl();
12561 if ((checkkwd & CHKEOFMARK)
12562 || c > 255 /* PEOA or PEOF */
12563 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
12565 #if BASH_DOLLAR_SQUOTE
12566 if (synstack->syntax != DQSYNTAX && c == '\'')
12567 bash_dollar_squote = 1;
12572 } else if (c == '(') {
12573 /* $(command) or $((arith)) */
12574 if (pgetc_eatbnl() == '(') {
12575 #if ENABLE_FEATURE_SH_MATH
12578 raise_error_syntax("support for $((arith)) is disabled");
12585 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
12586 smalluint newsyn = synstack->syntax;
12588 USTPUTC(CTLVAR, out);
12589 typeloc = out - (char *)stackblock();
12591 subtype = VSNORMAL;
12593 c = pgetc_eatbnl();
12598 /* $[{[#]]NAME[}] */
12601 c = pgetc_eatbnl();
12602 } while (is_in_name(c));
12603 } else if (isdigit(c)) {
12604 /* $[{[#]]NUM[}] */
12607 c = pgetc_eatbnl();
12608 } while (!subtype && isdigit(c));
12609 } else if (c != '}') {
12610 /* $[{[#]]<specialchar>[}] */
12613 c = pgetc_eatbnl();
12614 if (!subtype && cc == '#') {
12615 subtype = VSLENGTH;
12616 if (c == '_' || isalnum(c))
12619 c = pgetc_eatbnl();
12620 if (cc == '}' || c != '}') {
12628 if (!is_special(cc)) {
12629 if (subtype == VSLENGTH)
12638 if (c != '}' && subtype == VSLENGTH) {
12639 /* ${#VAR didn't end with } */
12643 if (subtype == 0) {
12644 static const char types[] ALIGN1 = "}-+?=";
12645 /* ${VAR...} but not $VAR or ${#VAR} */
12646 /* c == first char after VAR */
12651 c = pgetc_eatbnl();
12653 /* This check is only needed to not misinterpret
12654 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
12657 if (!strchr(types, c)) {
12658 subtype = VSSUBSTR;
12660 break; /* "goto badsub" is bigger (!) */
12666 const char *p = strchr(types, c);
12669 subtype |= p - types + VSNORMAL;
12674 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
12675 c = pgetc_eatbnl();
12681 newsyn = BASESYNTAX;
12683 #if BASH_PATTERN_SUBST
12685 /* ${v/[/]pattern/repl} */
12686 //TODO: encode pattern and repl separately.
12687 // Currently cases like: v=1;echo ${v/$((1/1))/ONE}
12688 // are broken (should print "ONE")
12689 subtype = VSREPLACE;
12690 newsyn = BASESYNTAX;
12691 c = pgetc_eatbnl();
12694 subtype++; /* VSREPLACEALL */
12703 if (newsyn == ARISYNTAX)
12706 if ((newsyn != synstack->syntax || synstack->innerdq)
12707 && subtype != VSNORMAL
12709 synstack_push(&synstack,
12710 synstack->prev ?: alloca(sizeof(*synstack)),
12713 synstack->varpushed = 1;
12714 synstack->dblquote = newsyn != BASESYNTAX;
12717 ((unsigned char *)stackblock())[typeloc] = subtype;
12718 if (subtype != VSNORMAL) {
12719 synstack->varnest++;
12720 if (synstack->dblquote)
12721 synstack->dqvarnest++;
12725 goto parsesub_return;
12729 * Called to parse command substitutions. Newstyle is set if the command
12730 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
12731 * list of commands (passed by reference), and savelen is the number of
12732 * characters on the top of the stack which must be preserved.
12735 struct nodelist **nlpp;
12739 struct heredoc *saveheredoclist;
12740 smallint saveprompt = 0;
12743 savelen = out - (char *)stackblock();
12746 * FIXME: this can allocate very large block on stack and SEGV.
12748 * echo "..<100kbytes>..`true` $(true) `true` ..."
12749 * allocates 100kb for every command subst. With about
12750 * a hundred command substitutions stack overflows.
12751 * With larger prepended string, SEGV happens sooner.
12753 str = alloca(savelen);
12754 memcpy(str, stackblock(), savelen);
12758 /* We must read until the closing backquote, giving special
12759 * treatment to some slashes, and then push the string and
12760 * reread it as input, interpreting it normally.
12766 STARTSTACKSTR(pout);
12770 setprompt_if(needprompt, 2);
12771 pc = pgetc_eatbnl();
12777 pc = pgetc(); /* or pgetc_eatbnl()? why (example)? */
12778 if (pc != '\\' && pc != '`' && pc != '$'
12779 && (!synstack->dblquote || pc != '"')
12781 STPUTC('\\', pout);
12783 if (pc <= 255 /* not PEOA or PEOF */) {
12789 IF_ASH_ALIAS(case PEOA:)
12790 raise_error_syntax("EOF in backquote substitution");
12802 STPUTC('\0', pout);
12803 psavelen = pout - (char *)stackblock();
12804 if (psavelen > 0) {
12805 pstr = grabstackstr(pout);
12806 setinputstring(pstr);
12811 nlpp = &(*nlpp)->next;
12812 *nlpp = stzalloc(sizeof(**nlpp));
12813 /* (*nlpp)->next = NULL; - stzalloc did it */
12815 saveheredoclist = heredoclist;
12816 heredoclist = NULL;
12819 saveprompt = doprompt;
12826 doprompt = saveprompt;
12828 if (readtoken() != TRP)
12829 raise_error_unexpected_syntax(TRP);
12830 setinputstring(nullstr);
12834 heredoclist = saveheredoclist;
12837 /* Start reading from old file again. */
12839 /* Ignore any pushed back tokens left from the backquote parsing. */
12842 out = growstackto(savelen + 1);
12844 memcpy(out, str, savelen);
12845 STADJUST(savelen, out);
12847 USTPUTC(CTLBACKQ, out);
12849 goto parsebackq_oldreturn;
12850 goto parsebackq_newreturn;
12853 #if ENABLE_FEATURE_SH_MATH
12855 * Parse an arithmetic expansion (indicate start of one and set state)
12859 synstack_push(&synstack,
12860 synstack->prev ?: alloca(sizeof(*synstack)),
12862 synstack->dblquote = 1;
12863 USTPUTC(CTLARI, out);
12864 goto parsearith_return;
12867 } /* end of readtoken */
12870 * Read the next input token.
12871 * If the token is a word, we set backquotelist to the list of cmds in
12872 * backquotes. We set quoteflag to true if any part of the word was
12874 * If the token is TREDIR, then we set redirnode to a structure containing
12877 * [Change comment: here documents and internal procedures]
12878 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12879 * word parsing code into a separate routine. In this case, readtoken
12880 * doesn't need to have any internal procedures, but parseword does.
12881 * We could also make parseoperator in essence the main routine, and
12882 * have parseword (readtoken1?) handle both words and redirection.]
12884 #define NEW_xxreadtoken
12885 #ifdef NEW_xxreadtoken
12886 /* singles must be first! */
12887 static const char xxreadtoken_chars[7] ALIGN1 = {
12888 '\n', '(', ')', /* singles */
12889 '&', '|', ';', /* doubles */
12893 #define xxreadtoken_singles 3
12894 #define xxreadtoken_doubles 3
12896 static const char xxreadtoken_tokens[] ALIGN1 = {
12897 TNL, TLP, TRP, /* only single occurrence allowed */
12898 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12899 TEOF, /* corresponds to trailing nul */
12900 TAND, TOR, TENDCASE /* if double occurrence */
12912 setprompt_if(needprompt, 2);
12913 for (;;) { /* until token or start of word found */
12914 c = pgetc_eatbnl();
12915 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12919 while ((c = pgetc()) != '\n' && c != PEOF)
12922 } else if (c == '\\') {
12923 break; /* return readtoken1(...) */
12927 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12933 p = strchr(xxreadtoken_chars, c);
12935 break; /* return readtoken1(...) */
12937 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12938 int cc = pgetc_eatbnl();
12939 if (cc == c) { /* double occurrence? */
12940 p += xxreadtoken_doubles + 1;
12943 #if BASH_REDIR_OUTPUT
12944 if (c == '&' && cc == '>') /* &> */
12945 break; /* return readtoken1(...) */
12950 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12955 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12957 #else /* old xxreadtoken */
12958 #define RETURN(token) return lasttoken = token
12968 setprompt_if(needprompt, 2);
12969 for (;;) { /* until token or start of word found */
12970 c = pgetc_eatbnl();
12972 case ' ': case '\t':
12973 IF_ASH_ALIAS(case PEOA:)
12976 while ((c = pgetc()) != '\n' && c != PEOF)
12986 if (pgetc_eatbnl() == '&')
12991 if (pgetc_eatbnl() == '|')
12996 if (pgetc_eatbnl() == ';')
13007 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
13010 #endif /* old xxreadtoken */
13016 int kwd = checkkwd;
13018 smallint alreadyseen = tokpushback;
13021 #if ENABLE_ASH_ALIAS
13037 if (t != TWORD || quoteflag) {
13042 * check for keywords
13044 if (kwd & CHKKWD) {
13045 const char *const *pp;
13047 pp = findkwd(wordtext);
13049 lasttoken = t = pp - tokname_array;
13050 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
13055 if (checkkwd & CHKALIAS) {
13056 #if ENABLE_ASH_ALIAS
13058 ap = lookupalias(wordtext, 1);
13061 pushstring(ap->val, ap);
13071 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
13073 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
13089 * Read and parse a command. Returns NODE_EOF on end of file.
13090 * (NULL is a valid parse tree indicating a blank line.)
13092 static union node *
13093 parsecmd(int interact)
13098 doprompt = interact;
13099 setprompt_if(doprompt, doprompt);
13105 * Input any here documents.
13110 struct heredoc *here;
13113 here = heredoclist;
13114 heredoclist = NULL;
13118 setprompt_if(needprompt, 2);
13119 if (here->here->type == NHERE)
13120 readtoken1(pgetc(), SQSYNTAX, here->eofmark, here->striptabs);
13122 readtoken1(pgetc_eatbnl(), DQSYNTAX, here->eofmark, here->striptabs);
13123 n = stzalloc(sizeof(struct narg));
13124 n->narg.type = NARG;
13125 /*n->narg.next = NULL; - stzalloc did it */
13126 n->narg.text = wordtext;
13127 n->narg.backquote = backquotelist;
13128 here->here->nhere.doc = n;
13134 static const char *
13135 expandstr(const char *ps, int syntax_type)
13139 struct parsefile *file_stop = g_parsefile;
13140 volatile int saveint;
13141 struct jmploc *volatile savehandler = exception_handler;
13142 struct jmploc jmploc;
13143 const char *volatile result;
13146 /* XXX Fix (char *) cast. */
13147 setinputstring((char *)ps);
13149 saveprompt = doprompt;
13154 err = setjmp(jmploc.loc);
13158 /* readtoken1() might die horribly.
13159 * Try a prompt with syntactically wrong command:
13160 * PS1='$(date "+%H:%M:%S) > '
13162 exception_handler = &jmploc;
13163 readtoken1(pgetc(), syntax_type, FAKEEOFMARK, 0);
13165 n.narg.type = NARG;
13166 n.narg.next = NULL;
13167 n.narg.text = wordtext;
13168 n.narg.backquote = backquotelist;
13170 /* expandarg() might fail too:
13173 expandarg(&n, NULL, EXP_QUOTED);
13174 result = stackblock();
13177 exception_handler = savehandler;
13178 if (err && exception_type != EXERROR)
13179 longjmp(exception_handler->loc, 1);
13180 RESTORE_INT(saveint);
13182 doprompt = saveprompt;
13183 /* Try: PS1='`xxx(`' */
13184 unwindfiles(file_stop);
13192 return tokpushback && lasttoken == TEOF;
13196 * Execute a command or commands contained in a string.
13199 evalstring(char *s, int flags)
13201 struct jmploc *volatile savehandler;
13202 struct jmploc jmploc;
13206 struct stackmark smark;
13211 setstackmark(&smark);
13214 /* On exception inside execution loop, we must popfile().
13215 * Try interactively:
13217 * command eval "a=b" # throws "is read only" error
13218 * "command BLTIN" is not supposed to abort (even in non-interactive use).
13219 * But if we skip popfile(), we hit EOF in eval's string, and exit.
13221 savehandler = exception_handler;
13222 ex = setjmp(jmploc.loc);
13225 exception_handler = &jmploc;
13227 while ((n = parsecmd(0)) != NODE_EOF) {
13230 i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
13233 popstackmark(&smark);
13238 popstackmark(&smark);
13242 exception_handler = savehandler;
13244 longjmp(exception_handler->loc, ex);
13250 * The eval command.
13252 static int FAST_FUNC
13253 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
13262 STARTSTACKSTR(concat);
13264 concat = stack_putstr(p, concat);
13268 STPUTC(' ', concat);
13270 STPUTC('\0', concat);
13271 p = grabstackstr(concat);
13273 return evalstring(p, flags & EV_TESTED);
13279 * Read and execute commands.
13280 * "Top" is nonzero for the top level command loop;
13281 * it turns on prompting if the shell is interactive.
13287 struct stackmark smark;
13292 TRACE(("cmdloop(%d) called\n", top));
13296 setstackmark(&smark);
13299 showjobs(SHOW_CHANGED|SHOW_STDERR);
13302 if (iflag && top) {
13306 n = parsecmd(inter);
13308 if (DEBUG > 2 && debug && (n != NODE_EOF))
13311 if (n == NODE_EOF) {
13312 if (!top || numeof >= 50)
13314 if (!stoppedjobs()) {
13317 newline_and_flush(stderr);
13321 out2str("\nUse \"exit\" to leave shell.\n");
13324 } else if (nflag == 0) {
13327 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
13330 i = evaltree(n, 0);
13334 popstackmark(&smark);
13338 evalskip &= ~SKIPFUNC;
13346 * Take commands from a file. To be compatible we should do a path
13347 * search for the file, which is necessary to find sub-commands.
13350 find_dot_file(char *basename)
13353 const char *path = pathval();
13357 /* don't try this for absolute or relative paths */
13358 if (strchr(basename, '/'))
13361 while ((len = padvance(&path, basename)) >= 0) {
13362 fullname = stackblock();
13363 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
13364 /* This will be freed by the caller. */
13365 return stalloc(len);
13368 /* not found in PATH */
13370 #if ENABLE_ASH_BASH_SOURCE_CURDIR
13373 ash_msg_and_raise_error("%s: not found", basename);
13378 static int FAST_FUNC
13379 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
13381 /* "false; . empty_file; echo $?" should print 0, not 1: */
13385 char *args_need_save;
13386 volatile struct shparam saveparam;
13389 // struct strlist *sp;
13390 // for (sp = cmdenviron; sp; sp = sp->next)
13391 // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
13393 nextopt(nullstr); /* handle possible "--" */
13397 /* bash says: "bash: .: filename argument required" */
13398 return 2; /* bash compat */
13401 /* This aborts if file isn't found, which is POSIXly correct.
13402 * bash returns exitcode 1 instead.
13404 fullname = find_dot_file(argv[0]);
13406 args_need_save = argv[0];
13407 if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
13409 saveparam = shellparam;
13410 shellparam.malloced = 0;
13414 shellparam.nparam = argc;
13415 shellparam.p = argv;
13418 /* This aborts if file can't be opened, which is POSIXly correct.
13419 * bash returns exitcode 1 instead.
13421 setinputfile(fullname, INPUT_PUSH_FILE);
13422 commandname = fullname;
13423 status = cmdloop(0);
13426 if (args_need_save) {
13427 freeparam(&shellparam);
13428 shellparam = saveparam;
13434 static int FAST_FUNC
13435 exitcmd(int argc UNUSED_PARAM, char **argv)
13441 savestatus = number(argv[1]);
13443 raise_exception(EXEXIT);
13448 * Read a file containing shell functions.
13451 readcmdfile(char *name)
13453 setinputfile(name, INPUT_PUSH_FILE);
13459 /* ============ find_command inplementation */
13462 * Resolve a command name. If you change this routine, you may have to
13463 * change the shellexec routine as well.
13466 find_command(char *name, struct cmdentry *entry, int act, const char *path)
13468 struct tblentry *cmdp;
13475 struct builtincmd *bcmd;
13478 /* If name contains a slash, don't use PATH or hash table */
13479 if (strchr(name, '/') != NULL) {
13480 entry->u.index = -1;
13481 if (act & DO_ABS) {
13482 while (stat(name, &statb) < 0) {
13484 if (errno == EINTR)
13487 entry->cmdtype = CMDUNKNOWN;
13491 entry->cmdtype = CMDNORMAL;
13495 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
13497 updatetbl = (path == pathval());
13500 if (strstr(path, "%builtin") != NULL)
13501 act |= DO_ALTBLTIN;
13504 /* If name is in the table, check answer will be ok */
13505 cmdp = cmdlookup(name, 0);
13506 if (cmdp != NULL) {
13509 switch (cmdp->cmdtype) {
13527 } else if (cmdp->rehash == 0)
13528 /* if not invalidated by cd, we're done */
13532 /* If %builtin not in path, check for builtin next */
13533 bcmd = find_builtin(name);
13535 if (IS_BUILTIN_REGULAR(bcmd))
13536 goto builtin_success;
13537 if (act & DO_ALTPATH) {
13538 if (!(act & DO_ALTBLTIN))
13539 goto builtin_success;
13540 } else if (builtinloc <= 0) {
13541 goto builtin_success;
13545 #if ENABLE_FEATURE_SH_STANDALONE
13547 int applet_no = find_applet_by_name(name);
13548 if (applet_no >= 0) {
13549 entry->cmdtype = CMDNORMAL;
13550 entry->u.index = -2 - applet_no;
13556 /* We have to search path. */
13557 prev = -1; /* where to start */
13558 if (cmdp && cmdp->rehash) { /* doing a rehash */
13559 if (cmdp->cmdtype == CMDBUILTIN)
13562 prev = cmdp->param.index;
13568 while ((len = padvance(&path, name)) >= 0) {
13569 fullname = stackblock();
13572 if (prefix(pathopt, "builtin")) {
13574 goto builtin_success;
13577 if ((act & DO_NOFUNC)
13578 || !prefix(pathopt, "func")
13579 ) { /* ignore unimplemented options */
13583 /* if rehash, don't redo absolute path names */
13584 if (fullname[0] == '/' && idx <= prev) {
13587 TRACE(("searchexec \"%s\": no change\n", name));
13590 while (stat(fullname, &statb) < 0) {
13592 if (errno == EINTR)
13595 if (errno != ENOENT && errno != ENOTDIR)
13599 e = EACCES; /* if we fail, this will be the error */
13600 if (!S_ISREG(statb.st_mode))
13602 if (pathopt) { /* this is a %func directory */
13604 /* NB: stalloc will return space pointed by fullname
13605 * (because we don't have any intervening allocations
13606 * between stunalloc above and this stalloc) */
13607 readcmdfile(fullname);
13608 cmdp = cmdlookup(name, 0);
13609 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
13610 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
13611 stunalloc(fullname);
13614 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
13616 entry->cmdtype = CMDNORMAL;
13617 entry->u.index = idx;
13621 cmdp = cmdlookup(name, 1);
13622 cmdp->cmdtype = CMDNORMAL;
13623 cmdp->param.index = idx;
13628 /* We failed. If there was an entry for this command, delete it */
13629 if (cmdp && updatetbl)
13630 delete_cmd_entry();
13631 if (act & DO_ERR) {
13632 #if ENABLE_ASH_BASH_NOT_FOUND_HOOK
13633 struct tblentry *hookp = cmdlookup("command_not_found_handle", 0);
13634 if (hookp && hookp->cmdtype == CMDFUNCTION) {
13636 argv[0] = (char*) "command_not_found_handle";
13639 evalfun(hookp->param.func, 2, argv, 0);
13640 entry->cmdtype = CMDUNKNOWN;
13644 ash_msg("%s: %s", name, errmsg(e, "not found"));
13646 entry->cmdtype = CMDUNKNOWN;
13651 entry->cmdtype = CMDBUILTIN;
13652 entry->u.cmd = bcmd;
13656 cmdp = cmdlookup(name, 1);
13657 cmdp->cmdtype = CMDBUILTIN;
13658 cmdp->param.cmd = bcmd;
13662 entry->cmdtype = cmdp->cmdtype;
13663 entry->u = cmdp->param;
13668 * The trap builtin.
13670 static int FAST_FUNC
13671 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13675 int signo, exitcode;
13680 for (signo = 0; signo < NSIG; signo++) {
13681 char *tr = trap_ptr[signo];
13683 /* note: bash adds "SIG", but only if invoked
13684 * as "bash". If called as "sh", or if set -o posix,
13685 * then it prints short signal names.
13686 * We are printing short names: */
13687 out1fmt("trap -- %s %s\n",
13689 get_signame(signo));
13690 /* trap_ptr != trap only if we are in special-cased `trap` code.
13691 * In this case, we will exit very soon, no need to free(). */
13692 /* if (trap_ptr != trap && tp[0]) */
13697 if (trap_ptr != trap) {
13705 /* Why the second check?
13706 * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
13707 * In this case, NUM is signal no, not an action.
13710 if (ap[1] && !is_number(ap[0]))
13715 signo = get_signum(*ap);
13717 /* Mimic bash message exactly */
13718 ash_msg("%s: invalid signal specification", *ap);
13724 if (LONE_DASH(action))
13727 if (action[0]) /* not NULL and not "" and not "-" */
13728 may_have_traps = 1;
13729 action = ckstrdup(action);
13733 trap[signo] = action;
13744 /* ============ Builtins */
13746 #if ENABLE_ASH_HELP
13747 static int FAST_FUNC
13748 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13754 "Built-in commands:\n"
13755 "------------------\n");
13756 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
13757 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
13758 builtintab[i].name + 1);
13764 # if ENABLE_FEATURE_SH_STANDALONE
13766 const char *a = applet_names;
13768 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
13773 while (*a++ != '\0')
13778 newline_and_flush(stdout);
13779 return EXIT_SUCCESS;
13784 static int FAST_FUNC
13785 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13787 if (line_input_state)
13788 show_history(line_input_state);
13789 return EXIT_SUCCESS;
13794 * The export and readonly commands.
13796 static int FAST_FUNC
13797 exportcmd(int argc UNUSED_PARAM, char **argv)
13807 /* "readonly" in bash accepts, but ignores -n.
13808 * We do the same: it saves a conditional in nextopt's param.
13811 while ((opt = nextopt("np")) != '\0') {
13813 flag_off = VEXPORT;
13816 if (argv[0][0] == 'r') {
13818 flag_off = 0; /* readonly ignores -n */
13820 flag_off = ~flag_off;
13822 /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
13828 p = strchr(name, '=');
13832 vp = *findvar(hashvar(name), name);
13834 vp->flags = ((vp->flags | flag) & flag_off);
13838 setvar(name, p, (flag & flag_off));
13839 } while ((name = *++aptr) != NULL);
13844 /* No arguments. Show the list of exported or readonly vars.
13847 showvars(argv[0], flag, 0);
13852 * Delete a function if it exists.
13855 unsetfunc(const char *name)
13857 struct tblentry *cmdp;
13859 cmdp = cmdlookup(name, 0);
13860 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
13861 delete_cmd_entry();
13865 * The unset builtin command. We unset the function before we unset the
13866 * variable to allow a function to be unset when there is a readonly variable
13867 * with the same name.
13869 static int FAST_FUNC
13870 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13876 while ((i = nextopt("vf")) != 0) {
13880 for (ap = argptr; *ap; ap++) {
13891 static const unsigned char timescmd_str[] ALIGN1 = {
13892 ' ', offsetof(struct tms, tms_utime),
13893 '\n', offsetof(struct tms, tms_stime),
13894 ' ', offsetof(struct tms, tms_cutime),
13895 '\n', offsetof(struct tms, tms_cstime),
13898 static int FAST_FUNC
13899 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13902 const unsigned char *p;
13905 clk_tck = bb_clk_tck();
13910 unsigned sec, frac;
13912 t = *(clock_t *)(((char *) &buf) + p[1]);
13914 frac = t % clk_tck;
13915 out1fmt("%um%u.%03us%c",
13916 sec / 60, sec % 60,
13917 (frac * 1000) / clk_tck,
13925 #if ENABLE_FEATURE_SH_MATH
13927 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13928 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13930 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13932 static int FAST_FUNC
13933 letcmd(int argc UNUSED_PARAM, char **argv)
13939 ash_msg_and_raise_error("expression expected");
13941 i = ash_arith(*argv);
13949 * The read builtin. Options:
13950 * -r Do not interpret '\' specially
13951 * -s Turn off echo (tty only)
13952 * -n NCHARS Read NCHARS max
13953 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13954 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13955 * -u FD Read from given FD instead of fd 0
13956 * -d DELIM End on DELIM char, not newline
13957 * This uses unbuffered input, which may be avoidable in some cases.
13958 * TODO: bash also has:
13959 * -a ARRAY Read into array[0],[1],etc
13960 * -e Use line editing (tty only)
13962 static int FAST_FUNC
13963 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13965 struct builtin_read_params params;
13969 memset(¶ms, 0, sizeof(params));
13971 while ((i = nextopt("p:u:rt:n:sd:")) != '\0') {
13974 params.opt_p = optionarg;
13977 params.opt_n = optionarg;
13980 params.read_flags |= BUILTIN_READ_SILENT;
13983 params.opt_t = optionarg;
13986 params.read_flags |= BUILTIN_READ_RAW;
13989 params.opt_u = optionarg;
13993 params.opt_d = optionarg;
14001 params.argv = argptr;
14002 params.setvar = setvar0;
14003 params.ifs = bltinlookup("IFS"); /* can be NULL */
14005 /* "read -s" needs to save/restore termios, can't allow ^C
14006 * to jump out of it.
14010 r = shell_builtin_read(¶ms);
14013 if ((uintptr_t)r == 1 && errno == EINTR) {
14014 /* To get SIGCHLD: sleep 1 & read x; echo $x
14015 * Correct behavior is to not exit "read"
14017 if (pending_sig == 0)
14021 if ((uintptr_t)r > 1)
14022 ash_msg_and_raise_error(r);
14024 return (uintptr_t)r;
14027 static int FAST_FUNC
14028 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
14030 static const char permuser[3] ALIGN1 = "ogu";
14033 int symbolic_mode = 0;
14035 while (nextopt("S") != '\0') {
14044 if (*argptr == NULL) {
14045 if (symbolic_mode) {
14046 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
14053 *p++ = permuser[i];
14055 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
14056 if (!(mask & 0400)) *p++ = 'r';
14057 if (!(mask & 0200)) *p++ = 'w';
14058 if (!(mask & 0100)) *p++ = 'x';
14066 out1fmt("%04o\n", mask);
14069 char *modestr = *argptr;
14070 /* numeric umasks are taken as-is */
14071 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
14072 if (!isdigit(modestr[0]))
14074 mask = bb_parse_mode(modestr, mask);
14075 if ((unsigned)mask > 0777) {
14076 ash_msg_and_raise_error("illegal mode: %s", modestr);
14078 if (!isdigit(modestr[0]))
14085 static int FAST_FUNC
14086 ulimitcmd(int argc UNUSED_PARAM, char **argv)
14088 return shell_builtin_ulimit(argv);
14091 /* ============ main() and helpers */
14094 * Called to exit the shell.
14102 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
14103 if (line_input_state)
14104 save_history(line_input_state);
14106 savestatus = exitstatus;
14107 TRACE(("pid %d, exitshell(%d)\n", getpid(), savestatus));
14108 if (setjmp(loc.loc))
14110 exception_handler = &loc;
14116 /*free(p); - we'll exit soon */
14119 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
14120 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
14123 flush_stdout_stderr();
14128 /* Don't inline: conserve stack of caller from having our locals too */
14129 static NOINLINE void
14132 /* we will never free this */
14133 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
14136 sigmode[SIGCHLD - 1] = S_DFL; /* ensure we install handler even if it is SIG_IGNed */
14137 setsignal(SIGCHLD);
14139 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
14140 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
14142 signal(SIGHUP, SIG_DFL);
14149 for (envp = environ; envp && *envp; envp++) {
14151 * p = endofname(*envp);
14152 * if (p != *envp && *p == '=') {
14153 * here to weed out badly-named variables, but this breaks
14154 * scenarios where people do want them passed to children:
14156 * os.environ["test-test"]="test"
14157 * if os.fork() == 0:
14158 * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
14159 * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ]) # breaks this
14161 if (strchr(*envp, '=')) {
14162 setvareq(*envp, VEXPORT|VTEXTFIXED);
14166 setvareq((char*)defifsvar, VTEXTFIXED);
14167 setvareq((char*)defoptindvar, VTEXTFIXED);
14169 setvar0("PPID", utoa(getppid()));
14171 p = lookupvar("SHLVL");
14172 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
14174 #if BASH_HOSTNAME_VAR
14175 if (!lookupvar("HOSTNAME")) {
14176 struct utsname uts;
14178 setvar0("HOSTNAME", uts.nodename);
14181 p = lookupvar("PWD");
14183 struct stat st1, st2;
14184 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
14185 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
14195 //usage:#define ash_trivial_usage
14196 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
14197 //usage:#define ash_full_usage "\n\n"
14198 //usage: "Unix shell interpreter"
14201 * Process the shell command line arguments.
14204 procargs(char **argv)
14207 const char *xminusc;
14212 login_sh = xargv[0] && xargv[0][0] == '-';
14213 #if NUM_SCRIPTS > 0
14218 /* if (xargv[0]) - mmm, this is always true! */
14221 for (i = 0; i < NOPTS; i++)
14223 if (options(&login_sh)) {
14224 /* it already printed err message */
14225 raise_exception(EXERROR);
14229 if (*xargv == NULL) {
14231 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
14234 if (iflag == 2 /* no explicit -i given */
14235 && sflag == 1 /* -s given (or implied) */
14236 && !minusc /* bash compat: ash -sc 'echo $-' is not interactive (dash is) */
14237 && isatty(0) && isatty(1) /* we are on tty */
14243 for (i = 0; i < NOPTS; i++)
14244 if (optlist[i] == 2)
14249 /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
14254 } else if (!sflag) {
14255 setinputfile(*xargv, 0);
14258 commandname = arg0;
14261 shellparam.p = xargv;
14262 #if ENABLE_ASH_GETOPTS
14263 shellparam.optind = 1;
14264 shellparam.optoff = -1;
14266 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
14268 shellparam.nparam++;
14277 * Read /etc/profile, ~/.profile, $ENV.
14280 read_profile(const char *name)
14282 name = expandstr(name, DQSYNTAX);
14283 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
14290 * This routine is called when an error or an interrupt occurs in an
14291 * interactive shell and control is returned to the main command loop
14292 * but prior to exitshell.
14300 if (savestatus >= 0) {
14301 exitstatus = savestatus;
14305 /* from expand.c: */
14308 /* from redir.c: */
14313 * This routine is called when an error or an interrupt occurs in an
14314 * interactive shell and control is returned to the main command loop.
14315 * (In dash, this function is auto-generated by build machinery).
14320 /* from input.c: */
14321 g_parsefile->left_in_buffer = 0;
14322 g_parsefile->left_in_line = 0; /* clear input buffer */
14326 unwindlocalvars(NULL);
14330 static short profile_buf[16384];
14331 extern int etext();
14335 * Main routine. We initialize things, parse the arguments, execute
14336 * profiles if we're a login shell, and then call cmdloop to execute
14337 * commands. The setjmp call sets up the location to jump to when an
14338 * exception occurs. When an exception occurs the variable "state"
14339 * is used to figure out how far we had gotten.
14341 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
14342 #if NUM_SCRIPTS > 0
14343 int ash_main(int argc, char **argv)
14345 int ash_main(int argc UNUSED_PARAM, char **argv)
14347 /* note: 'argc' is used only if embedded scripts are enabled */
14349 volatile smallint state;
14350 struct jmploc jmploc;
14351 struct stackmark smark;
14354 /* Initialize global data */
14358 #if ENABLE_ASH_ALIAS
14364 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
14368 if (setjmp(jmploc.loc)) {
14374 e = exception_type;
14376 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
14383 newline_and_flush(stderr);
14386 popstackmark(&smark);
14387 FORCE_INT_ON; /* enable interrupts */
14396 exception_handler = &jmploc;
14397 rootpid = getpid();
14400 setstackmark(&smark);
14402 #if NUM_SCRIPTS > 0
14404 /* Non-NULL minusc tells procargs that an embedded script is being run */
14405 minusc = get_script_content(-argc - 1);
14407 login_sh = procargs(argv);
14409 TRACE(("Shell args: "));
14410 trace_puts_args(argv);
14417 read_profile("/etc/profile");
14420 hp = lookupvar("HOME");
14422 read_profile("$HOME/.profile");
14428 getuid() == geteuid() && getgid() == getegid() &&
14432 const char *shinit = lookupvar("ENV");
14433 if (shinit != NULL && *shinit != '\0')
14434 read_profile(shinit);
14436 popstackmark(&smark);
14440 /* evalstring pushes parsefile stack.
14441 * Ensure we don't falsely claim that 0 (stdin)
14442 * is one of stacked source fds.
14443 * Testcase: ash -c 'exec 1>&0' must not complain. */
14445 // if (!sflag) g_parsefile->pf_fd = -1;
14446 // ^^ not necessary since now we special-case fd 0
14447 // in save_fd_on_redirect()
14449 // dash: evalstring(minusc, sflag ? 0 : EV_EXIT);
14451 // ash -sc 'echo $-'
14452 // continue reading input from stdin after running 'echo'.
14453 // bash does not do this: it prints "hBcs" and exits.
14454 evalstring(minusc, EV_EXIT);
14457 if (sflag || minusc == NULL) {
14458 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
14460 const char *hp = lookupvar("HISTFILE");
14462 hp = lookupvar("HOME");
14465 hp = concat_path_file(hp, ".ash_history");
14466 setvar0("HISTFILE", hp);
14469 hp = lookupvar("HISTFILE");
14473 line_input_state->hist_file = hp;
14474 # if ENABLE_FEATURE_SH_HISTFILESIZE
14475 hp = lookupvar("HISTFILESIZE");
14476 line_input_state->max_history = size_from_HISTFILESIZE(hp);
14480 state4: /* XXX ??? - why isn't this before the "if" statement */
14488 extern void _mcleanup(void);
14492 TRACE(("End of main reached\n"));
14499 * Copyright (c) 1989, 1991, 1993, 1994
14500 * The Regents of the University of California. All rights reserved.
14502 * This code is derived from software contributed to Berkeley by
14503 * Kenneth Almquist.
14505 * Redistribution and use in source and binary forms, with or without
14506 * modification, are permitted provided that the following conditions
14508 * 1. Redistributions of source code must retain the above copyright
14509 * notice, this list of conditions and the following disclaimer.
14510 * 2. Redistributions in binary form must reproduce the above copyright
14511 * notice, this list of conditions and the following disclaimer in the
14512 * documentation and/or other materials provided with the distribution.
14513 * 3. Neither the name of the University nor the names of its contributors
14514 * may be used to endorse or promote products derived from this software
14515 * without specific prior written permission.
14517 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
14518 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
14519 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
14520 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
14521 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
14522 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
14523 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
14524 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
14525 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
14526 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF