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 rootpid; /* pid of main shell */
388 /* shell level: 0 for the main shell, 1 for its children, and so on */
390 #define rootshell (!shlvl)
393 char *minusc; /* argument to -c option */
395 char *curdir; // = nullstr; /* current working directory */
396 char *physdir; // = nullstr; /* physical working directory */
398 char *arg0; /* value of $0 */
400 struct jmploc *exception_handler;
402 volatile int suppress_int; /* counter */
403 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
404 volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
405 volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
406 smallint exception_type; /* kind of exception (0..5) */
408 #define EXINT 0 /* SIGINT received */
409 #define EXERROR 1 /* a generic error */
410 #define EXEXIT 4 /* exit the shell */
412 char nullstr[1]; /* zero length string */
415 #define eflag optlist[0]
416 #define fflag optlist[1]
417 #define Iflag optlist[2]
418 #define iflag optlist[3]
419 #define mflag optlist[4]
420 #define nflag optlist[5]
421 #define sflag optlist[6]
422 #define cflag optlist[7]
423 #define xflag optlist[8]
424 #define vflag optlist[9]
425 #define Cflag optlist[10]
426 #define aflag optlist[11]
427 #define bflag optlist[12]
428 #define uflag optlist[13]
429 #define viflag optlist[14]
431 # define pipefail optlist[15]
436 # define nolog optlist[15 + BASH_PIPEFAIL]
437 # define debug optlist[16 + BASH_PIPEFAIL]
440 /* trap handler commands */
442 * Sigmode records the current value of the signal handlers for the various
443 * modes. A value of zero means that the current handler is not known.
444 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
446 char sigmode[NSIG - 1];
447 #define S_DFL 1 /* default signal handling (SIG_DFL) */
448 #define S_CATCH 2 /* signal is caught */
449 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
450 #define S_HARD_IGN 4 /* signal is ignored permanently (it was SIG_IGN on entry to shell) */
452 /* indicates specified signal received */
453 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
454 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
456 char **trap_ptr; /* used only by "trap hack" */
458 /* Rarely referenced stuff */
459 #if ENABLE_ASH_RANDOM_SUPPORT
462 pid_t backgndpid; /* pid of last background process */
464 extern struct globals_misc *BB_GLOBAL_CONST ash_ptr_to_globals_misc;
465 #define G_misc (*ash_ptr_to_globals_misc)
466 #define exitstatus (G_misc.exitstatus )
467 #define back_exitstatus (G_misc.back_exitstatus )
468 #define job_warning (G_misc.job_warning)
469 #define rootpid (G_misc.rootpid )
470 #define shlvl (G_misc.shlvl )
471 #define errlinno (G_misc.errlinno )
472 #define minusc (G_misc.minusc )
473 #define curdir (G_misc.curdir )
474 #define physdir (G_misc.physdir )
475 #define arg0 (G_misc.arg0 )
476 #define exception_handler (G_misc.exception_handler)
477 #define exception_type (G_misc.exception_type )
478 #define suppress_int (G_misc.suppress_int )
479 #define pending_int (G_misc.pending_int )
480 #define got_sigchld (G_misc.got_sigchld )
481 #define pending_sig (G_misc.pending_sig )
482 #define nullstr (G_misc.nullstr )
483 #define optlist (G_misc.optlist )
484 #define sigmode (G_misc.sigmode )
485 #define gotsig (G_misc.gotsig )
486 #define may_have_traps (G_misc.may_have_traps )
487 #define trap (G_misc.trap )
488 #define trap_ptr (G_misc.trap_ptr )
489 #define random_gen (G_misc.random_gen )
490 #define backgndpid (G_misc.backgndpid )
491 #define INIT_G_misc() do { \
492 (*(struct globals_misc**)not_const_pp(&ash_ptr_to_globals_misc)) = xzalloc(sizeof(G_misc)); \
500 /* ============ DEBUG */
502 static void trace_printf(const char *fmt, ...);
503 static void trace_vprintf(const char *fmt, va_list va);
504 # define TRACE(param) trace_printf param
505 # define TRACEV(param) trace_vprintf param
506 # define close(fd) do { \
508 if (close(dfd) < 0) \
509 bb_error_msg("bug on %d: closing %d(0x%x)", \
510 __LINE__, dfd, dfd); \
513 # define TRACE(param)
514 # define TRACEV(param)
518 /* ============ Utility functions */
519 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
520 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
523 isdigit_str9(const char *str)
525 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
526 while (--maxlen && isdigit(*str))
528 return (*str == '\0');
532 var_end(const char *var)
541 /* ============ Interrupts / exceptions */
543 static void exitshell(void) NORETURN;
546 * These macros allow the user to suspend the handling of interrupt signals
547 * over a period of time. This is similar to SIGHOLD or to sigblock, but
548 * much more efficient and portable. (But hacking the kernel is so much
549 * more fun than worrying about efficiency and portability. :-))
552 # define INT_OFF do { \
553 TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
558 # define INT_OFF do { \
565 * Called to raise an exception. Since C doesn't include exceptions, we
566 * just do a longjmp to the exception handler. The type of exception is
567 * stored in the global variable "exception_type".
569 static void raise_exception(int) NORETURN;
571 raise_exception(int e)
574 if (exception_handler == NULL)
579 longjmp(exception_handler->loc, 1);
582 #define raise_exception(e) do { \
583 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
584 raise_exception(e); \
589 * Called when a SIGINT is received. (If the user specifies
590 * that SIGINT is to be trapped or ignored using the trap builtin, then
591 * this routine is not called.) Suppressint is nonzero when interrupts
592 * are held using the INT_OFF macro. (The test for iflag is just
593 * defensive programming.)
595 static void raise_interrupt(void) NORETURN;
597 raise_interrupt(void)
600 /* Signal is not automatically unmasked after it is raised,
601 * do it ourself - unmask all signals */
602 sigprocmask_allsigs(SIG_UNBLOCK);
603 /* pending_sig = 0; - now done in signal_handler() */
605 if (!(rootshell && iflag)) {
606 /* Kill ourself with SIGINT */
607 signal(SIGINT, SIG_DFL);
610 /* bash: ^C even on empty command line sets $? */
611 exitstatus = SIGINT + 128;
612 raise_exception(EXINT);
616 #define raise_interrupt() do { \
617 TRACE(("raising interrupt on line %d\n", __LINE__)); \
622 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
626 if (--suppress_int == 0 && pending_int) {
631 # define INT_ON do { \
632 TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
636 # define INT_ON int_on()
638 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
646 #define FORCE_INT_ON force_int_on()
648 #define SAVE_INT(v) ((v) = suppress_int)
650 #define RESTORE_INT(v) do { \
652 suppress_int = (v); \
653 if (suppress_int == 0 && pending_int) \
658 /* ============ Stdout/stderr output */
661 outstr(const char *p, FILE *file)
669 flush_stdout_stderr(void)
676 /* Was called outcslow(c,FILE*), but c was always '\n' */
678 newline_and_flush(FILE *dest)
686 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
688 out1fmt(const char *fmt, ...)
695 r = vprintf(fmt, ap);
701 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
703 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
710 ret = vsnprintf(outbuf, length, fmt, ap);
717 out1str(const char *p)
723 out2str(const char *p)
726 flush_stdout_stderr();
730 /* ============ Parser structures */
732 /* control characters in argument strings */
733 #define CTL_FIRST CTLESC
734 #define CTLESC ((unsigned char)'\201') /* escape next character */
735 #define CTLVAR ((unsigned char)'\202') /* variable defn */
736 #define CTLENDVAR ((unsigned char)'\203')
737 #define CTLBACKQ ((unsigned char)'\204')
738 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
739 #define CTLENDARI ((unsigned char)'\207')
740 #define CTLQUOTEMARK ((unsigned char)'\210')
741 #define CTL_LAST CTLQUOTEMARK
743 /* variable substitution byte (follows CTLVAR) */
744 #define VSTYPE 0x0f /* type of variable substitution */
745 #define VSNUL 0x10 /* colon--treat the empty string as unset */
747 /* values of VSTYPE field */
748 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
749 #define VSMINUS 0x2 /* ${var-text} */
750 #define VSPLUS 0x3 /* ${var+text} */
751 #define VSQUESTION 0x4 /* ${var?message} */
752 #define VSASSIGN 0x5 /* ${var=text} */
753 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
754 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
755 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
756 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
757 #define VSLENGTH 0xa /* ${#var} */
759 #define VSSUBSTR 0xc /* ${var:position:length} */
761 #if BASH_PATTERN_SUBST
762 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
763 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
766 static const char dolatstr[] ALIGN1 = {
767 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
769 #define DOLATSTRLEN 6
788 #if BASH_REDIR_OUTPUT
805 smallint type; /* Nxxxx */
809 union node *redirect;
814 smallint pipe_backgnd;
815 struct nodelist *cmdlist;
822 union node *redirect;
835 union node *elsepart;
871 struct nodelist *backquote;
874 /* nfile and ndup layout must match!
875 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
876 * that it is actually NTO2 (>&file), and change its type.
893 char *_unused_expfname;
912 struct nredir nredir;
913 struct nbinary nbinary;
917 struct nclist nclist;
918 struct ndefun ndefun;
927 * NODE_EOF is returned by parsecmd when it encounters an end of file.
928 * It must be distinct from NULL.
930 #define NODE_EOF ((union node *) -1L)
933 struct nodelist *next;
946 freefunc(struct funcnode *f)
948 if (f && --f->count < 0)
953 /* ============ Debugging output */
957 static FILE *tracefile;
960 trace_printf(const char *fmt, ...)
967 fprintf(tracefile, "%u ", (int) time(NULL));
969 fprintf(tracefile, "[%u] ", (int) getpid());
971 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
973 vfprintf(tracefile, fmt, va);
978 trace_vprintf(const char *fmt, va_list va)
982 vfprintf(tracefile, fmt, va);
983 fprintf(tracefile, "\n");
987 trace_puts(const char *s)
995 trace_puts_quoted(char *s)
1002 putc('"', tracefile);
1003 for (p = s; *p; p++) {
1004 switch ((unsigned char)*p) {
1005 case '\n': c = 'n'; goto backslash;
1006 case '\t': c = 't'; goto backslash;
1007 case '\r': c = 'r'; goto backslash;
1008 case '\"': c = '\"'; goto backslash;
1009 case '\\': c = '\\'; goto backslash;
1010 case CTLESC: c = 'e'; goto backslash;
1011 case CTLVAR: c = 'v'; goto backslash;
1012 case CTLBACKQ: c = 'q'; goto backslash;
1014 putc('\\', tracefile);
1018 if (*p >= ' ' && *p <= '~')
1019 putc(*p, tracefile);
1021 putc('\\', tracefile);
1022 putc((*p >> 6) & 03, tracefile);
1023 putc((*p >> 3) & 07, tracefile);
1024 putc(*p & 07, tracefile);
1029 putc('"', tracefile);
1033 trace_puts_args(char **ap)
1040 trace_puts_quoted(*ap);
1042 putc('\n', tracefile);
1045 putc(' ', tracefile);
1060 /* leave open because libedit might be using it */
1063 strcpy(s, "./trace");
1065 if (!freopen(s, "a", tracefile)) {
1066 fprintf(stderr, "Can't re-open %s\n", s);
1071 tracefile = fopen(s, "a");
1072 if (tracefile == NULL) {
1073 fprintf(stderr, "Can't open %s\n", s);
1079 flags = fcntl(fileno(tracefile), F_GETFL);
1081 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
1083 setlinebuf(tracefile);
1084 fputs("\nTracing started.\n", tracefile);
1088 indent(int amount, char *pfx, FILE *fp)
1092 for (i = 0; i < amount; i++) {
1093 if (pfx && i == amount - 1)
1099 /* little circular references here... */
1100 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
1103 sharg(union node *arg, FILE *fp)
1106 struct nodelist *bqlist;
1107 unsigned char subtype;
1109 if (arg->type != NARG) {
1110 out1fmt("<node type %d>\n", arg->type);
1113 bqlist = arg->narg.backquote;
1114 for (p = arg->narg.text; *p; p++) {
1115 switch ((unsigned char)*p) {
1124 if (subtype == VSLENGTH)
1132 if (subtype & VSNUL)
1135 switch (subtype & VSTYPE) {
1161 case VSTRIMRIGHTMAX:
1168 out1fmt("<subtype %d>", subtype);
1177 shtree(bqlist->n, -1, NULL, fp);
1188 shcmd(union node *cmd, FILE *fp)
1196 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1202 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1206 switch (np->nfile.type) {
1207 case NTO: s = ">>"+1; dftfd = 1; break;
1208 case NCLOBBER: s = ">|"; dftfd = 1; break;
1209 case NAPPEND: s = ">>"; dftfd = 1; break;
1210 #if BASH_REDIR_OUTPUT
1213 case NTOFD: s = ">&"; dftfd = 1; break;
1214 case NFROM: s = "<"; break;
1215 case NFROMFD: s = "<&"; break;
1216 case NFROMTO: s = "<>"; break;
1217 default: s = "*error*"; break;
1219 if (np->nfile.fd != dftfd)
1220 fprintf(fp, "%d", np->nfile.fd);
1222 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1223 fprintf(fp, "%d", np->ndup.dupfd);
1225 sharg(np->nfile.fname, fp);
1232 shtree(union node *n, int ind, char *pfx, FILE *fp)
1234 struct nodelist *lp;
1240 indent(ind, pfx, fp);
1242 if (n == NODE_EOF) {
1257 shtree(n->nbinary.ch1, ind, NULL, fp);
1260 shtree(n->nbinary.ch2, ind, NULL, fp);
1268 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1269 shtree(lp->n, 0, NULL, fp);
1273 if (n->npipe.pipe_backgnd)
1279 fprintf(fp, "<node type %d>", n->type);
1287 showtree(union node *n)
1289 trace_puts("showtree called\n");
1290 shtree(n, 1, NULL, stderr);
1296 /* ============ Parser data */
1299 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1302 struct strlist *next;
1309 struct strpush *prev; /* preceding string on stack */
1311 int prev_left_in_line;
1312 #if ENABLE_ASH_ALIAS
1313 struct alias *ap; /* if push was associated with an alias */
1315 char *string; /* remember the string since it may change */
1317 /* Remember last two characters for pungetc. */
1320 /* Number of outstanding calls to pungetc. */
1325 * The parsefile structure pointed to by the global variable parsefile
1326 * contains information about the current file being read.
1329 struct parsefile *prev; /* preceding file on stack */
1330 int linno; /* current line */
1331 int pf_fd; /* file descriptor (or -1 if string) */
1332 int left_in_line; /* number of chars left in this line */
1333 int left_in_buffer; /* number of chars left in this buffer past the line */
1334 char *next_to_pgetc; /* next char in buffer */
1335 char *buf; /* input buffer */
1336 struct strpush *strpush; /* for pushing strings at this level */
1337 struct strpush basestrpush; /* so pushing one is fast */
1339 /* Remember last two characters for pungetc. */
1342 /* Number of outstanding calls to pungetc. */
1346 static struct parsefile basepf; /* top level input file */
1347 static struct parsefile *g_parsefile = &basepf; /* current input file */
1348 static char *commandname; /* currently executing command */
1351 /* ============ Message printing */
1354 ash_vmsg(const char *msg, va_list ap)
1356 fprintf(stderr, "%s: ", arg0);
1358 if (strcmp(arg0, commandname))
1359 fprintf(stderr, "%s: ", commandname);
1360 if (!iflag || g_parsefile->pf_fd > 0)
1361 fprintf(stderr, "line %d: ", errlinno);
1363 vfprintf(stderr, msg, ap);
1364 newline_and_flush(stderr);
1368 * Exverror is called to raise the error exception. If the second argument
1369 * is not NULL then error prints an error message using printf style
1370 * formatting. It then raises the error exception.
1372 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1374 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1378 TRACE(("ash_vmsg_and_raise(%d):", cond));
1381 TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
1386 flush_stdout_stderr();
1387 raise_exception(cond);
1391 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1393 ash_msg_and_raise_error(const char *msg, ...)
1400 ash_vmsg_and_raise(EXERROR, msg, ap);
1406 * 'fmt' must be a string literal.
1408 #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": "STRERROR_FMT, ##__VA_ARGS__ STRERROR_ERRNO)
1410 static void raise_error_syntax(const char *) NORETURN;
1412 raise_error_syntax(const char *msg)
1414 errlinno = g_parsefile->linno;
1415 ash_msg_and_raise_error("syntax error: %s", msg);
1419 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1421 ash_msg_and_raise(int cond, const char *msg, ...)
1426 ash_vmsg_and_raise(cond, msg, ap);
1432 * error/warning routines for external builtins
1435 ash_msg(const char *fmt, ...)
1445 * Return a string describing an error. The returned string may be a
1446 * pointer to a static buffer that will be overwritten on the next call.
1447 * Action describes the operation that got the error.
1450 errmsg(int e, const char *em)
1452 if (e == ENOENT || e == ENOTDIR) {
1459 /* ============ Memory allocation */
1462 /* I consider these wrappers nearly useless:
1463 * ok, they return you to nearest exception handler, but
1464 * how much memory do you leak in the process, making
1465 * memory starvation worse?
1468 ckrealloc(void * p, size_t nbytes)
1470 p = realloc(p, nbytes);
1472 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1477 ckmalloc(size_t nbytes)
1479 return ckrealloc(NULL, nbytes);
1483 ckzalloc(size_t nbytes)
1485 return memset(ckmalloc(nbytes), 0, nbytes);
1489 ckstrdup(const char *s)
1491 char *p = strdup(s);
1493 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1497 /* Using bbox equivalents. They exit if out of memory */
1498 # define ckrealloc xrealloc
1499 # define ckmalloc xmalloc
1500 # define ckzalloc xzalloc
1501 # define ckstrdup xstrdup
1505 * It appears that grabstackstr() will barf with such alignments
1506 * because stalloc() will return a string allocated in a new stackblock.
1508 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1510 /* Most machines require the value returned from malloc to be aligned
1511 * in some way. The following macro will get this right
1512 * on many machines. */
1513 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1514 /* Minimum size of a block */
1515 MINSIZE = SHELL_ALIGN(504),
1518 struct stack_block {
1519 struct stack_block *prev;
1520 char space[MINSIZE];
1524 struct stack_block *stackp;
1530 struct globals_memstack {
1531 struct stack_block *g_stackp; // = &stackbase;
1532 char *g_stacknxt; // = stackbase.space;
1533 char *sstrend; // = stackbase.space + MINSIZE;
1534 size_t g_stacknleft; // = MINSIZE;
1535 struct stack_block stackbase;
1537 extern struct globals_memstack *BB_GLOBAL_CONST ash_ptr_to_globals_memstack;
1538 #define G_memstack (*ash_ptr_to_globals_memstack)
1539 #define g_stackp (G_memstack.g_stackp )
1540 #define g_stacknxt (G_memstack.g_stacknxt )
1541 #define sstrend (G_memstack.sstrend )
1542 #define g_stacknleft (G_memstack.g_stacknleft)
1543 #define stackbase (G_memstack.stackbase )
1544 #define INIT_G_memstack() do { \
1545 (*(struct globals_memstack**)not_const_pp(&ash_ptr_to_globals_memstack)) = xzalloc(sizeof(G_memstack)); \
1547 g_stackp = &stackbase; \
1548 g_stacknxt = stackbase.space; \
1549 g_stacknleft = MINSIZE; \
1550 sstrend = stackbase.space + MINSIZE; \
1554 #define stackblock() ((void *)g_stacknxt)
1555 #define stackblocksize() g_stacknleft
1558 * Parse trees for commands are allocated in lifo order, so we use a stack
1559 * to make this more efficient, and also to avoid all sorts of exception
1560 * handling code to handle interrupts in the middle of a parse.
1562 * The size 504 was chosen because the Ultrix malloc handles that size
1566 stalloc(size_t nbytes)
1571 aligned = SHELL_ALIGN(nbytes);
1572 if (aligned > g_stacknleft) {
1575 struct stack_block *sp;
1577 blocksize = aligned;
1578 if (blocksize < MINSIZE)
1579 blocksize = MINSIZE;
1580 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1581 if (len < blocksize)
1582 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1585 sp->prev = g_stackp;
1586 g_stacknxt = sp->space;
1587 g_stacknleft = blocksize;
1588 sstrend = g_stacknxt + blocksize;
1593 g_stacknxt += aligned;
1594 g_stacknleft -= aligned;
1599 stzalloc(size_t nbytes)
1601 return memset(stalloc(nbytes), 0, nbytes);
1608 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1609 write(STDERR_FILENO, "stunalloc\n", 10);
1613 g_stacknleft += g_stacknxt - (char *)p;
1618 * Like strdup but works with the ash stack.
1621 sstrdup(const char *p)
1623 size_t len = strlen(p) + 1;
1624 return memcpy(stalloc(len), p, len);
1627 static ALWAYS_INLINE void
1628 grabstackblock(size_t len)
1634 pushstackmark(struct stackmark *mark, size_t len)
1636 mark->stackp = g_stackp;
1637 mark->stacknxt = g_stacknxt;
1638 mark->stacknleft = g_stacknleft;
1639 grabstackblock(len);
1643 setstackmark(struct stackmark *mark)
1645 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1649 popstackmark(struct stackmark *mark)
1651 struct stack_block *sp;
1657 while (g_stackp != mark->stackp) {
1659 g_stackp = sp->prev;
1662 g_stacknxt = mark->stacknxt;
1663 g_stacknleft = mark->stacknleft;
1664 sstrend = mark->stacknxt + mark->stacknleft;
1669 * When the parser reads in a string, it wants to stick the string on the
1670 * stack and only adjust the stack pointer when it knows how big the
1671 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1672 * of space on top of the stack and stackblocklen returns the length of
1673 * this block. Growstackblock will grow this space by at least one byte,
1674 * possibly moving it (like realloc). Grabstackblock actually allocates the
1675 * part of the block that has been used.
1678 growstackblock(void)
1682 newlen = g_stacknleft * 2;
1683 if (newlen < g_stacknleft)
1684 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1688 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1689 struct stack_block *sp;
1690 struct stack_block *prevstackp;
1695 prevstackp = sp->prev;
1696 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1697 sp = ckrealloc(sp, grosslen);
1698 sp->prev = prevstackp;
1700 g_stacknxt = sp->space;
1701 g_stacknleft = newlen;
1702 sstrend = sp->space + newlen;
1705 char *oldspace = g_stacknxt;
1706 size_t oldlen = g_stacknleft;
1707 char *p = stalloc(newlen);
1709 /* free the space we just allocated */
1710 g_stacknxt = memcpy(p, oldspace, oldlen);
1711 g_stacknleft += newlen;
1716 * The following routines are somewhat easier to use than the above.
1717 * The user declares a variable of type STACKSTR, which may be declared
1718 * to be a register. The macro STARTSTACKSTR initializes things. Then
1719 * the user uses the macro STPUTC to add characters to the string. In
1720 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1721 * grown as necessary. When the user is done, she can just leave the
1722 * string there and refer to it using stackblock(). Or she can allocate
1723 * the space for it using grabstackstr(). If it is necessary to allow
1724 * someone else to use the stack temporarily and then continue to grow
1725 * the string, the user should use grabstack to allocate the space, and
1726 * then call ungrabstr(p) to return to the previous mode of operation.
1728 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1729 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1730 * is space for at least one character.
1735 size_t len = stackblocksize();
1737 return (char *)stackblock() + len;
1741 * Called from CHECKSTRSPACE.
1744 makestrspace(size_t newlen, char *p)
1746 size_t len = p - g_stacknxt;
1752 size = stackblocksize();
1754 if (nleft >= newlen)
1758 return (char *)stackblock() + len;
1762 stack_nputstr(const char *s, size_t n, char *p)
1764 p = makestrspace(n, p);
1765 p = (char *)mempcpy(p, s, n);
1770 stack_putstr(const char *s, char *p)
1772 return stack_nputstr(s, strlen(s), p);
1776 _STPUTC(int c, char *p)
1784 #define STARTSTACKSTR(p) ((p) = stackblock())
1785 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1786 #define CHECKSTRSPACE(n, p) do { \
1789 size_t m = sstrend - q; \
1791 (p) = makestrspace(l, q); \
1793 #define USTPUTC(c, p) (*(p)++ = (c))
1794 #define STACKSTRNUL(p) do { \
1795 if ((p) == sstrend) \
1796 (p) = growstackstr(); \
1799 #define STUNPUTC(p) (--(p))
1800 #define STTOPC(p) ((p)[-1])
1801 #define STADJUST(amount, p) ((p) += (amount))
1803 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1804 #define ungrabstackstr(s, p) stunalloc(s)
1805 #define stackstrend() ((void *)sstrend)
1808 /* ============ String helpers */
1811 * prefix -- see if pfx is a prefix of string.
1814 prefix(const char *string, const char *pfx)
1817 if (*pfx++ != *string++)
1820 return (char *) string;
1824 * Check for a valid number. This should be elsewhere.
1827 is_number(const char *p)
1832 } while (*++p != '\0');
1837 * Convert a string of digits to an integer, printing an error message on
1841 number(const char *s)
1844 ash_msg_and_raise_error(msg_illnum, s);
1849 * Produce a single quoted string suitable as input to the shell.
1850 * The return string is allocated on the stack.
1853 single_quote(const char *s)
1863 len = strchrnul(s, '\'') - s;
1865 q = p = makestrspace(len + 3, p);
1868 q = (char *)mempcpy(q, s, len);
1877 do len++; while (*++s == '\'');
1879 q = p = makestrspace(len + 3, p);
1882 q = (char *)mempcpy(q, s - len, len);
1890 return stackblock();
1894 * Produce a possibly single quoted string suitable as input to the shell.
1895 * If quoting was done, the return string is allocated on the stack,
1896 * otherwise a pointer to the original string is returned.
1899 maybe_single_quote(const char *s)
1904 /* Assuming ACSII */
1905 /* quote ctrl_chars space !"#$%&'()* */
1909 if (*p >= ';' && *p <= '?')
1918 /* quote {|}~ DEL and high bytes */
1921 /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
1922 /* TODO: maybe avoid quoting % */
1928 return single_quote(s);
1932 /* ============ nextopt */
1934 static char **argptr; /* argument list for builtin commands */
1935 static char *optionarg; /* set by nextopt (like getopt) */
1936 static char *optptr; /* used by nextopt */
1939 * XXX - should get rid of. Have all builtins use getopt(3).
1940 * The library getopt must have the BSD extension static variable
1941 * "optreset", otherwise it can't be used within the shell safely.
1943 * Standard option processing (a la getopt) for builtin routines.
1944 * The only argument that is passed to nextopt is the option string;
1945 * the other arguments are unnecessary. It returns the character,
1946 * or '\0' on end of input.
1949 nextopt(const char *optstring)
1956 if (p == NULL || *p == '\0') {
1957 /* We ate entire "-param", take next one */
1963 if (*++p == '\0') /* just "-" ? */
1966 if (LONE_DASH(p)) /* "--" ? */
1968 /* p => next "-param" */
1970 /* p => some option char in the middle of a "-param" */
1972 for (q = optstring; *q != c;) {
1974 ash_msg_and_raise_error("illegal option -%c", c);
1982 ash_msg_and_raise_error("no arg for -%c option", c);
1992 /* ============ Shell variables */
1995 int nparam; /* # of positional parameters (without $0) */
1996 #if ENABLE_ASH_GETOPTS
1997 int optind; /* next parameter to be processed by getopts */
1998 int optoff; /* used by getopts */
2000 unsigned char malloced; /* if parameter list dynamically allocated */
2001 char **p; /* parameter list */
2005 * Free the list of positional parameters.
2008 freeparam(volatile struct shparam *param)
2010 if (param->malloced) {
2012 ap = ap1 = param->p;
2019 #if ENABLE_ASH_GETOPTS
2020 static void FAST_FUNC getoptsreset(const char *value);
2024 struct var *next; /* next entry in hash list */
2025 int flags; /* flags are defined above */
2026 const char *var_text; /* name=value */
2027 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
2028 /* the variable gets set/unset */
2032 struct localvar *next; /* next local variable in list */
2033 struct var *vp; /* the variable that was made local */
2034 int flags; /* saved flags */
2035 const char *text; /* saved text */
2039 #define VEXPORT 0x01 /* variable is exported */
2040 #define VREADONLY 0x02 /* variable cannot be modified */
2041 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
2042 #define VTEXTFIXED 0x08 /* text is statically allocated */
2043 #define VSTACK 0x10 /* text is allocated on the stack */
2044 #define VUNSET 0x20 /* the variable is not set */
2045 #define VNOFUNC 0x40 /* don't call the callback function */
2046 #define VNOSET 0x80 /* do not set variable - just readonly test */
2047 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
2048 #if ENABLE_ASH_RANDOM_SUPPORT
2049 # define VDYNAMIC 0x200 /* dynamic variable */
2055 /* Need to be before varinit_data[] */
2056 #if ENABLE_LOCALE_SUPPORT
2057 static void FAST_FUNC
2058 change_lc_all(const char *value)
2060 if (value && *value != '\0')
2061 setlocale(LC_ALL, value);
2063 static void FAST_FUNC
2064 change_lc_ctype(const char *value)
2066 if (value && *value != '\0')
2067 setlocale(LC_CTYPE, value);
2071 static void chkmail(void);
2072 static void changemail(const char *var_value) FAST_FUNC;
2074 # define chkmail() ((void)0)
2076 static void changepath(const char *) FAST_FUNC;
2077 #if ENABLE_ASH_RANDOM_SUPPORT
2078 static void change_random(const char *) FAST_FUNC;
2081 static void change_seconds(const char *) FAST_FUNC;
2082 static void change_realtime(const char *) FAST_FUNC;
2085 static const struct {
2087 const char *var_text;
2088 void (*var_func)(const char *) FAST_FUNC;
2089 } varinit_data[] = {
2091 * Note: VEXPORT would not work correctly here for NOFORK applets:
2092 * some environment strings may be constant.
2094 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
2096 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
2097 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
2099 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
2100 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
2101 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
2102 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
2103 #if ENABLE_ASH_GETOPTS
2104 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
2106 { VSTRFIXED|VTEXTFIXED , NULL /* inited to linenovar */, NULL },
2107 #if ENABLE_ASH_RANDOM_SUPPORT
2108 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
2111 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "EPOCHSECONDS", change_seconds },
2112 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "EPOCHREALTIME", change_realtime },
2114 #if ENABLE_LOCALE_SUPPORT
2115 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
2116 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
2118 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
2119 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
2125 struct globals_var {
2126 struct shparam shellparam; /* $@ current positional parameters */
2127 struct redirtab *redirlist;
2128 int preverrout_fd; /* stderr fd: usually 2, unless redirect moved it */
2129 struct var *vartab[VTABSIZE];
2130 struct var varinit[ARRAY_SIZE(varinit_data)];
2132 char linenovar[sizeof("LINENO=") + sizeof(int)*3];
2134 extern struct globals_var *BB_GLOBAL_CONST ash_ptr_to_globals_var;
2135 #define G_var (*ash_ptr_to_globals_var)
2136 #define shellparam (G_var.shellparam )
2137 //#define redirlist (G_var.redirlist )
2138 #define preverrout_fd (G_var.preverrout_fd)
2139 #define vartab (G_var.vartab )
2140 #define varinit (G_var.varinit )
2141 #define lineno (G_var.lineno )
2142 #define linenovar (G_var.linenovar )
2143 #define vifs varinit[0]
2145 # define vmail varinit[1]
2146 # define vmpath varinit[2]
2148 #define VAR_OFFSET1 (ENABLE_ASH_MAIL*2)
2149 #define vpath varinit[VAR_OFFSET1 + 1]
2150 #define vps1 varinit[VAR_OFFSET1 + 2]
2151 #define vps2 varinit[VAR_OFFSET1 + 3]
2152 #define vps4 varinit[VAR_OFFSET1 + 4]
2153 #if ENABLE_ASH_GETOPTS
2154 # define voptind varinit[VAR_OFFSET1 + 5]
2156 #define VAR_OFFSET2 (VAR_OFFSET1 + ENABLE_ASH_GETOPTS)
2157 #define vlineno varinit[VAR_OFFSET2 + 5]
2158 #if ENABLE_ASH_RANDOM_SUPPORT
2159 # define vrandom varinit[VAR_OFFSET2 + 6]
2161 #define VAR_OFFSET3 (VAR_OFFSET2 + ENABLE_ASH_RANDOM_SUPPORT)
2163 # define vepochs varinit[VAR_OFFSET3 + 6]
2164 # define vepochr varinit[VAR_OFFSET3 + 7]
2166 #define INIT_G_var() do { \
2168 (*(struct globals_var**)not_const_pp(&ash_ptr_to_globals_var)) = xzalloc(sizeof(G_var)); \
2170 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
2171 varinit[i].flags = varinit_data[i].flags; \
2172 varinit[i].var_text = varinit_data[i].var_text; \
2173 varinit[i].var_func = varinit_data[i].var_func; \
2175 strcpy(linenovar, "LINENO="); \
2176 vlineno.var_text = linenovar; \
2180 * The following macros access the values of the above variables.
2181 * They have to skip over the name. They return the null string
2182 * for unset variables.
2184 #define ifsval() (vifs.var_text + 4)
2185 #define ifsset() ((vifs.flags & VUNSET) == 0)
2187 # define mailval() (vmail.var_text + 5)
2188 # define mpathval() (vmpath.var_text + 9)
2189 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2191 #define pathval() (vpath.var_text + 5)
2192 #define ps1val() (vps1.var_text + 4)
2193 #define ps2val() (vps2.var_text + 4)
2194 #define ps4val() (vps4.var_text + 4)
2195 #if ENABLE_ASH_GETOPTS
2196 # define optindval() (voptind.var_text + 7)
2199 #if ENABLE_ASH_GETOPTS
2200 static void FAST_FUNC
2201 getoptsreset(const char *value)
2203 shellparam.optind = 1;
2204 if (is_number(value))
2205 shellparam.optind = number(value) ?: 1;
2206 shellparam.optoff = -1;
2211 * Compares two strings up to the first = or '\0'. The first
2212 * string must be terminated by '='; the second may be terminated by
2213 * either '=' or '\0'.
2216 varcmp(const char *p, const char *q)
2220 while ((c = *p) == (d = *q)) {
2221 if (c == '\0' || c == '=')
2235 * Find the appropriate entry in the hash table from the name.
2237 static struct var **
2238 hashvar(const char *p)
2242 hashval = ((unsigned char) *p) << 4;
2243 while (*p && *p != '=')
2244 hashval += (unsigned char) *p++;
2245 return &vartab[hashval % VTABSIZE];
2249 vpcmp(const void *a, const void *b)
2251 return varcmp(*(const char **)a, *(const char **)b);
2255 * This routine initializes the builtin variables.
2265 * PS1 depends on uid
2267 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2268 vps1.var_text = "PS1=\\w \\$ ";
2271 vps1.var_text = "PS1=# ";
2274 end = vp + ARRAY_SIZE(varinit);
2276 vpp = hashvar(vp->var_text);
2279 } while (++vp < end);
2282 static struct var **
2283 findvar(struct var **vpp, const char *name)
2285 for (; *vpp; vpp = &(*vpp)->next) {
2286 if (varcmp((*vpp)->var_text, name) == 0) {
2294 * Find the value of a variable. Returns NULL if not set.
2296 static const char* FAST_FUNC
2297 lookupvar(const char *name)
2301 v = *findvar(hashvar(name), name);
2303 #if ENABLE_ASH_RANDOM_SUPPORT || BASH_EPOCH_VARS
2305 * Dynamic variables are implemented roughly the same way they are
2306 * in bash. Namely, they're "special" so long as they aren't unset.
2307 * As soon as they're unset, they're no longer dynamic, and dynamic
2308 * lookup will no longer happen at that point. -- PFM.
2310 if (v->flags & VDYNAMIC)
2313 if (!(v->flags & VUNSET)) {
2314 if (v == &vlineno && v->var_text == linenovar) {
2315 fmtstr(linenovar+7, sizeof(linenovar)-7, "%d", lineno);
2317 return var_end(v->var_text);
2323 #if ENABLE_UNICODE_SUPPORT
2325 reinit_unicode_for_ash(void)
2327 /* Unicode support should be activated even if LANG is set
2328 * _during_ shell execution, not only if it was set when
2329 * shell was started. Therefore, re-check LANG every time:
2331 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2332 || ENABLE_UNICODE_USING_LOCALE
2334 const char *s = lookupvar("LC_ALL");
2335 if (!s) s = lookupvar("LC_CTYPE");
2336 if (!s) s = lookupvar("LANG");
2341 # define reinit_unicode_for_ash() ((void)0)
2345 * Search the environment of a builtin command.
2347 static ALWAYS_INLINE const char *
2348 bltinlookup(const char *name)
2350 return lookupvar(name);
2354 * Same as setvar except that the variable and value are passed in
2355 * the first argument as name=value. Since the first argument will
2356 * be actually stored in the table, it should not be a string that
2358 * Called with interrupts off.
2361 setvareq(char *s, int flags)
2363 struct var *vp, **vpp;
2366 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2367 vpp = findvar(vpp, s);
2370 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2373 if (flags & VNOSAVE)
2377 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2383 if (vp->var_func && !(flags & VNOFUNC))
2384 vp->var_func(var_end(s));
2386 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2387 free((char*)vp->var_text);
2389 if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
2393 if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
2398 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2399 #if ENABLE_ASH_RANDOM_SUPPORT || BASH_EPOCH_VARS
2404 /* variable s is not found */
2407 if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
2409 vp = ckzalloc(sizeof(*vp));
2411 /*vp->func = NULL; - ckzalloc did it */
2414 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2424 * Set the value of a variable. The flags argument is ored with the
2425 * flags of the variable. If val is NULL, the variable is unset.
2428 setvar(const char *name, const char *val, int flags)
2437 q = endofname(name);
2438 p = strchrnul(q, '=');
2440 if (!namelen || p != q)
2441 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2446 vallen = strlen(val);
2450 nameeq = ckzalloc(namelen + vallen + 2);
2451 p = mempcpy(nameeq, name, namelen);
2454 memcpy(p, val, vallen);
2456 vp = setvareq(nameeq, flags | VNOSAVE);
2462 static void FAST_FUNC
2463 setvar0(const char *name, const char *val)
2465 setvar(name, val, 0);
2469 * Unset the specified variable.
2472 unsetvar(const char *s)
2478 * Process a linked list of variable assignments.
2481 listsetvar(struct strlist *list_set_var, int flags)
2483 struct strlist *lp = list_set_var;
2489 setvareq(lp->text, flags);
2496 * Generate a list of variables satisfying the given conditions.
2498 #if !ENABLE_FEATURE_SH_NOFORK
2499 # define listvars(on, off, lp, end) listvars(on, off, end)
2502 listvars(int on, int off, struct strlist *lp, char ***end)
2513 for (vp = *vpp; vp; vp = vp->next) {
2514 if ((vp->flags & mask) == on) {
2515 #if ENABLE_FEATURE_SH_NOFORK
2516 /* If variable with the same name is both
2517 * exported and temporarily set for a command:
2520 * then "ZVAR=6" will be both in vartab and
2521 * lp lists. Do not pass it twice to printenv.
2523 struct strlist *lp1 = lp;
2525 if (strcmp(lp1->text, vp->var_text) == 0)
2530 if (ep == stackstrend())
2531 ep = growstackstr();
2532 *ep++ = (char*)vp->var_text;
2533 #if ENABLE_FEATURE_SH_NOFORK
2538 } while (++vpp < vartab + VTABSIZE);
2540 #if ENABLE_FEATURE_SH_NOFORK
2542 if (ep == stackstrend())
2543 ep = growstackstr();
2549 if (ep == stackstrend())
2550 ep = growstackstr();
2554 return grabstackstr(ep);
2558 /* ============ Path search helper
2560 * The variable path (passed by reference) should be set to the start
2561 * of the path before the first call; path_advance will update
2562 * this value as it proceeds. Successive calls to path_advance will return
2563 * the possible path expansions in sequence. If an option (indicated by
2564 * a percent sign) appears in the path entry then the global variable
2565 * pathopt will be set to point to it; otherwise pathopt will be set to
2568 static const char *pathopt; /* set by path_advance */
2571 path_advance(const char **path, const char *name)
2581 for (p = start; *p && *p != ':' && *p != '%'; p++)
2583 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2584 while (stackblocksize() < len)
2588 q = mempcpy(q, start, p - start);
2595 while (*p && *p != ':')
2602 return stalloc(len);
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)
2847 dest = bltinlookup("HOME");
2848 else if (LONE_DASH(dest)) {
2849 dest = bltinlookup("OLDPWD");
2871 path = bltinlookup("CDPATH");
2874 p = path_advance(&path, dest);
2875 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2879 if (!docd(p, flags))
2890 ash_msg_and_raise_perror("can't cd to %s", dest);
2893 if (flags & CD_PRINT)
2894 out1fmt("%s\n", curdir);
2898 static int FAST_FUNC
2899 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2902 const char *dir = curdir;
2906 if (physdir == nullstr)
2910 out1fmt("%s\n", dir);
2915 /* ============ ... */
2918 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2920 /* Syntax classes */
2921 #define CWORD 0 /* character is nothing special */
2922 #define CNL 1 /* newline character */
2923 #define CBACK 2 /* a backslash character */
2924 #define CSQUOTE 3 /* single quote */
2925 #define CDQUOTE 4 /* double quote */
2926 #define CENDQUOTE 5 /* a terminating quote */
2927 #define CBQUOTE 6 /* backwards single quote */
2928 #define CVAR 7 /* a dollar sign */
2929 #define CENDVAR 8 /* a '}' character */
2930 #define CLP 9 /* a left paren in arithmetic */
2931 #define CRP 10 /* a right paren in arithmetic */
2932 #define CENDFILE 11 /* end of file */
2933 #define CCTL 12 /* like CWORD, except it must be escaped */
2934 #define CSPCL 13 /* these terminate a word */
2935 #define CIGN 14 /* character should be ignored */
2938 #if ENABLE_ASH_ALIAS
2942 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2944 #if ENABLE_FEATURE_SH_MATH
2945 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2947 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2949 static const uint16_t S_I_T[] ALIGN2 = {
2950 #if ENABLE_ASH_ALIAS
2951 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2953 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2954 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2955 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2956 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2957 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2958 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2959 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2960 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2961 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2962 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2963 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2964 #if !USE_SIT_FUNCTION
2965 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2966 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2967 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2971 /* Constants below must match table above */
2973 #if ENABLE_ASH_ALIAS
2974 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2976 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2977 CNL_CNL_CNL_CNL , /* 2 */
2978 CWORD_CCTL_CCTL_CWORD , /* 3 */
2979 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2980 CVAR_CVAR_CWORD_CVAR , /* 5 */
2981 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2982 CSPCL_CWORD_CWORD_CLP , /* 7 */
2983 CSPCL_CWORD_CWORD_CRP , /* 8 */
2984 CBACK_CBACK_CCTL_CBACK , /* 9 */
2985 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2986 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2987 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2988 CWORD_CWORD_CWORD_CWORD , /* 13 */
2989 CCTL_CCTL_CCTL_CCTL , /* 14 */
2992 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2993 * caller must ensure proper cast on it if c is *char_ptr!
2995 #if USE_SIT_FUNCTION
2998 SIT(int c, int syntax)
3000 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
3001 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
3003 * This causes '/' to be prepended with CTLESC in dquoted string,
3004 * making "./file"* treated incorrectly because we feed
3005 * ".\/file*" string to glob(), confusing it (see expandmeta func).
3006 * The "homegrown" glob implementation is okay with that,
3007 * but glibc one isn't. With '/' always treated as CWORD,
3010 # if ENABLE_ASH_ALIAS
3011 static const uint8_t syntax_index_table[] ALIGN1 = {
3012 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
3013 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
3014 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
3018 static const uint8_t syntax_index_table[] ALIGN1 = {
3019 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
3020 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
3021 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
3030 # if ENABLE_ASH_ALIAS
3036 /* Cast is purely for paranoia here,
3037 * just in case someone passed signed char to us */
3038 if ((unsigned char)c >= CTL_FIRST
3039 && (unsigned char)c <= CTL_LAST
3043 s = strchrnul(spec_symbls, c);
3046 indx = syntax_index_table[s - spec_symbls];
3048 return (S_I_T[indx] >> (syntax*4)) & 0xf;
3051 #else /* !USE_SIT_FUNCTION */
3053 static const uint8_t syntax_index_table[] ALIGN1 = {
3054 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
3055 /* 0 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 1 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 2 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 3 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 4 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 5 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 6 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 7 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 8 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
3065 /* 10 "\n" */ CNL_CNL_CNL_CNL,
3066 /* 11 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 12 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 13 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 14 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 15 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 16 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 17 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 18 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 19 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 20 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 21 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 22 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 23 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 24 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 25 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 26 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 27 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 28 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 29 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 30 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 31 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
3088 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
3089 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
3090 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
3091 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
3092 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
3093 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
3094 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
3095 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
3096 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
3097 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
3098 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
3099 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
3100 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
3101 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
3102 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
3103 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
3104 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
3105 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
3106 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
3107 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
3108 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
3109 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
3110 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
3111 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
3112 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
3113 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
3114 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
3115 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
3116 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
3117 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
3118 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
3119 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
3120 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
3121 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
3122 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
3123 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
3124 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
3125 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
3126 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
3127 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
3128 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
3129 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
3130 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
3131 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
3132 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
3133 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
3134 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
3135 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
3136 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
3137 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
3138 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
3139 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
3140 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
3141 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
3142 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
3143 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
3144 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
3145 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
3146 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
3147 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
3148 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
3149 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
3150 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
3151 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
3152 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
3153 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
3154 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
3155 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
3156 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
3157 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
3158 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
3159 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
3160 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
3161 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
3162 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
3163 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
3164 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
3165 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
3166 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
3167 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3168 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3169 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3170 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3171 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3172 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3173 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3174 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3175 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3176 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3177 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3178 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3179 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3180 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3181 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3182 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3183 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
3184 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
3185 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
3186 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
3187 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
3188 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
3189 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
3190 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3191 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3192 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3193 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3194 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3195 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3196 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3197 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3198 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3199 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3200 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3201 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3202 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3203 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3204 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3205 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3206 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3207 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3208 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3209 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3210 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3211 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3212 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3213 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3214 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3215 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3216 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3217 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3218 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3219 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3220 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3221 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3222 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3223 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3224 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3225 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3226 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3227 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3228 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3229 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3230 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3231 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3232 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3233 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3234 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3235 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3236 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3237 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3238 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3239 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3240 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3241 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3242 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3243 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3244 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3245 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3246 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3247 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3248 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3249 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3250 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3251 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3252 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3253 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3254 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3255 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3256 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3257 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3258 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3259 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3260 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3261 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3262 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3263 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3264 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3265 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3266 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3267 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3268 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3269 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3270 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3271 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3272 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3273 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3274 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3275 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3276 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3277 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3278 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3279 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3280 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3281 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3282 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3283 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3284 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3285 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3286 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3287 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3288 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3289 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3290 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3291 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3292 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3293 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3294 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3295 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3296 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3297 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3298 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3299 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3300 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3301 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3302 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3303 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3304 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3305 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3306 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3307 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3308 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3309 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3310 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3311 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3312 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3313 # if ENABLE_ASH_ALIAS
3314 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3319 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3320 #else /* debug version, caught one signed char bug */
3321 # define SIT(c, syntax) \
3323 if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
3324 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3325 if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
3326 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3327 ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
3331 #endif /* !USE_SIT_FUNCTION */
3334 /* ============ Alias handling */
3336 #if ENABLE_ASH_ALIAS
3338 #define ALIASINUSE 1
3349 static struct alias **atab; // [ATABSIZE];
3350 #define INIT_G_alias() do { \
3351 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3355 static struct alias **
3356 __lookupalias(const char *name)
3358 unsigned int hashval;
3365 ch = (unsigned char)*p;
3369 ch = (unsigned char)*++p;
3371 app = &atab[hashval % ATABSIZE];
3373 for (; *app; app = &(*app)->next) {
3374 if (strcmp(name, (*app)->name) == 0) {
3382 static struct alias *
3383 lookupalias(const char *name, int check)
3385 struct alias *ap = *__lookupalias(name);
3387 if (check && ap && (ap->flag & ALIASINUSE))
3392 static struct alias *
3393 freealias(struct alias *ap)
3397 if (ap->flag & ALIASINUSE) {
3398 ap->flag |= ALIASDEAD;
3410 setalias(const char *name, const char *val)
3412 struct alias *ap, **app;
3414 app = __lookupalias(name);
3418 if (!(ap->flag & ALIASINUSE)) {
3421 ap->val = ckstrdup(val);
3422 ap->flag &= ~ALIASDEAD;
3425 ap = ckzalloc(sizeof(struct alias));
3426 ap->name = ckstrdup(name);
3427 ap->val = ckstrdup(val);
3428 /*ap->flag = 0; - ckzalloc did it */
3429 /*ap->next = NULL;*/
3436 unalias(const char *name)
3440 app = __lookupalias(name);
3444 *app = freealias(*app);
3455 struct alias *ap, **app;
3459 for (i = 0; i < ATABSIZE; i++) {
3461 for (ap = *app; ap; ap = *app) {
3462 *app = freealias(*app);
3472 printalias(const struct alias *ap)
3474 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3478 * TODO - sort output
3480 static int FAST_FUNC
3481 aliascmd(int argc UNUSED_PARAM, char **argv)
3490 for (i = 0; i < ATABSIZE; i++) {
3491 for (ap = atab[i]; ap; ap = ap->next) {
3497 while ((n = *++argv) != NULL) {
3498 v = strchr(n+1, '=');
3499 if (v == NULL) { /* n+1: funny ksh stuff */
3500 ap = *__lookupalias(n);
3502 fprintf(stderr, "%s: %s not found\n", "alias", n);
3515 static int FAST_FUNC
3516 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3520 while (nextopt("a") != '\0') {
3524 for (i = 0; *argptr; argptr++) {
3525 if (unalias(*argptr)) {
3526 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3534 #endif /* ASH_ALIAS */
3537 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3540 #define FORK_NOJOB 2
3542 /* mode flags for showjob(s) */
3543 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3544 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3545 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3546 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3549 * A job structure contains information about a job. A job is either a
3550 * single process or a set of processes contained in a pipeline. In the
3551 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3555 pid_t ps_pid; /* process id */
3556 int ps_status; /* last process status from wait() */
3557 char *ps_cmd; /* text of command being run */
3561 struct procstat ps0; /* status of process */
3562 struct procstat *ps; /* status of processes when more than one */
3564 int stopstatus; /* status of a stopped job */
3566 unsigned nprocs; /* number of processes */
3568 #define JOBRUNNING 0 /* at least one proc running */
3569 #define JOBSTOPPED 1 /* all procs are stopped */
3570 #define JOBDONE 2 /* all procs are completed */
3574 sigint: 1, /* job was killed by SIGINT */
3575 jobctl: 1, /* job running under job control */
3577 waited: 1, /* true if this entry has been waited for */
3578 used: 1, /* true if this entry is in used */
3579 changed: 1; /* true if status has changed */
3580 struct job *prev_job; /* previous job */
3583 static struct job *makejob(/*union node *,*/ int);
3584 static int forkshell(struct job *, union node *, int);
3585 static int waitforjob(struct job *);
3588 enum { doing_jobctl = 0 };
3589 #define setjobctl(on) do {} while (0)
3591 static smallint doing_jobctl; //references:8
3592 static void setjobctl(int);
3599 ignoresig(int signo)
3601 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3602 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3603 /* No, need to do it */
3604 signal(signo, SIG_IGN);
3606 sigmode[signo - 1] = S_HARD_IGN;
3610 * Only one usage site - in setsignal()
3613 signal_handler(int signo)
3615 if (signo == SIGCHLD) {
3621 gotsig[signo - 1] = 1;
3622 pending_sig = signo;
3624 if (signo == SIGINT && !trap[SIGINT]) {
3625 if (!suppress_int) {
3627 raise_interrupt(); /* does not return */
3634 * Set the signal handler for the specified signal. The routine figures
3635 * out what it should be set to.
3638 setsignal(int signo)
3641 char cur_act, new_act;
3642 struct sigaction act;
3646 if (t != NULL) { /* trap for this sig is set */
3648 if (t[0] == '\0') /* trap is "": ignore this sig */
3652 if (rootshell && new_act == S_DFL) {
3655 if (iflag || minusc || sflag == 0)
3664 * "In all cases, bash ignores SIGQUIT. Non-builtin
3665 * commands run by bash have signal handlers
3666 * set to the values inherited by the shell
3667 * from its parent". */
3683 /* if !rootshell, we reset SIGQUIT to DFL,
3684 * whereas we have to restore it to what shell got on entry.
3685 * This is handled by the fact that if signal was IGNored on entry,
3686 * then cur_act is S_HARD_IGN and we never change its sigaction
3690 if (signo == SIGCHLD)
3693 t = &sigmode[signo - 1];
3696 /* current setting is not yet known */
3697 if (sigaction(signo, NULL, &act)) {
3698 /* pretend it worked; maybe we should give a warning,
3699 * but other shells don't. We don't alter sigmode,
3700 * so we retry every time.
3701 * btw, in Linux it never fails. --vda */
3704 if (act.sa_handler == SIG_IGN) {
3705 cur_act = S_HARD_IGN;
3707 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3709 cur_act = S_IGN; /* don't hard ignore these */
3712 if (act.sa_handler == SIG_DFL && new_act == S_DFL) {
3713 /* installing SIG_DFL over SIG_DFL is a no-op */
3714 /* saves one sigaction call in each "sh -c SCRIPT" invocation */
3719 if (cur_act == S_HARD_IGN || cur_act == new_act)
3724 act.sa_handler = SIG_DFL;
3727 act.sa_handler = signal_handler;
3730 act.sa_handler = SIG_IGN;
3733 /* flags and mask matter only if !DFL and !IGN, but we do it
3734 * for all cases for more deterministic behavior:
3736 act.sa_flags = 0; //TODO: why not SA_RESTART?
3737 sigfillset(&act.sa_mask);
3739 sigaction_set(signo, &act);
3742 /* mode flags for set_curjob */
3743 #define CUR_DELETE 2
3744 #define CUR_RUNNING 1
3745 #define CUR_STOPPED 0
3748 /* pgrp of shell on invocation */
3749 static int initialpgrp; //references:2
3750 static int ttyfd = -1; //5
3753 static struct job *jobtab; //5
3755 static unsigned njobs; //4
3757 static struct job *curjob; //lots
3758 /* number of presumed living untracked jobs */
3759 static int jobless; //4
3762 /* Bash has a feature: it restores termios after a successful wait for
3763 * a foreground job which had at least one stopped or sigkilled member.
3764 * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
3765 * properly restoring tty state. Should we do this too?
3766 * A reproducer: ^Z an interactive python:
3769 * Python 2.7.12 (...)
3771 * { python leaves tty in -icanon -echo state. We do survive that... }
3772 * [1]+ Stopped python
3773 * { ...however, next program (python #2) does not survive it well: }
3775 * Python 2.7.12 (...)
3776 * >>> Traceback (most recent call last):
3777 * { above, I typed "qwerty<CR>", but -echo state is still in effect }
3778 * File "<stdin>", line 1, in <module>
3779 * NameError: name 'qwerty' is not defined
3781 * The implementation below is modeled on bash code and seems to work.
3782 * However, I'm not sure we should do this. For one: what if I'd fg
3783 * the stopped python instead? It'll be confused by "restored" tty state.
3785 static struct termios shell_tty_info;
3789 if (rootshell && ttyfd >= 0)
3790 tcgetattr(ttyfd, &shell_tty_info);
3795 /* if (rootshell) - caller ensures this */
3797 tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
3800 job_signal_status(struct job *jp)
3804 struct procstat *ps = jp->ps;
3805 for (i = 0; i < jp->nprocs; i++) {
3806 status = ps[i].ps_status;
3807 if (WIFSIGNALED(status) || WIFSTOPPED(status))
3813 restore_tty_if_stopped_or_signaled(struct job *jp)
3815 //TODO: check what happens if we come from waitforjob() in expbackq()
3817 int s = job_signal_status(jp);
3818 if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
3823 # define get_tty_state() ((void)0)
3824 # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
3828 set_curjob(struct job *jp, unsigned mode)
3831 struct job **jpp, **curp;
3833 /* first remove from list */
3834 jpp = curp = &curjob;
3839 jpp = &jp1->prev_job;
3841 *jpp = jp1->prev_job;
3843 /* Then re-insert in correct position */
3851 /* job being deleted */
3854 /* newly created job or backgrounded job,
3855 * put after all stopped jobs.
3860 if (!jp1 || jp1->state != JOBSTOPPED)
3863 jpp = &jp1->prev_job;
3869 /* newly stopped job - becomes curjob */
3870 jp->prev_job = *jpp;
3878 jobno(const struct job *jp)
3880 return jp - jobtab + 1;
3885 * Convert a job name to a job structure.
3888 #define getjob(name, getctl) getjob(name)
3891 getjob(const char *name, int getctl)
3895 const char *err_msg = "%s: no such job";
3899 char *(*match)(const char *, const char *);
3914 if (c == '+' || c == '%') {
3916 err_msg = "No current job";
3922 err_msg = "No previous job";
3932 if (num > 0 && num <= njobs) {
3933 jp = jobtab + num - 1;
3948 if (match(jp->ps[0].ps_cmd, p)) {
3952 err_msg = "%s: ambiguous";
3962 err_msg = "job %s not created under job control";
3963 if (getctl && jp->jobctl == 0)
3968 ash_msg_and_raise_error(err_msg, name);
3972 * Mark a job structure as unused.
3975 freejob(struct job *jp)
3977 struct procstat *ps;
3981 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3982 if (ps->ps_cmd != nullstr)
3985 if (jp->ps != &jp->ps0)
3988 set_curjob(jp, CUR_DELETE);
3994 xtcsetpgrp(int fd, pid_t pgrp)
3996 if (tcsetpgrp(fd, pgrp))
3997 ash_msg_and_raise_perror("can't set tty process group");
4001 * Turn job control on and off.
4003 * Note: This code assumes that the third arg to ioctl is a character
4004 * pointer, which is true on Berkeley systems but not System V. Since
4005 * System V doesn't have job control yet, this isn't a problem now.
4007 * Called with interrupts off.
4015 if (on == doing_jobctl || rootshell == 0)
4019 ofd = fd = open(_PATH_TTY, O_RDWR);
4021 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
4022 * That sometimes helps to acquire controlling tty.
4023 * Obviously, a workaround for bugs when someone
4024 * failed to provide a controlling tty to bash! :) */
4030 /* fd is a tty at this point */
4031 fd = fcntl(fd, F_DUPFD_CLOEXEC, 10);
4032 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
4035 goto out; /* F_DUPFD failed */
4036 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
4037 close_on_exec_on(fd);
4038 while (1) { /* while we are in the background */
4039 pgrp = tcgetpgrp(fd);
4042 ash_msg("can't access tty; job control turned off");
4046 if (pgrp == getpgrp())
4057 xtcsetpgrp(fd, pgrp);
4059 /* turning job control off */
4062 /* was xtcsetpgrp, but this can make exiting ash
4063 * loop forever if pty is already deleted */
4064 tcsetpgrp(fd, pgrp);
4078 static int FAST_FUNC
4079 killcmd(int argc, char **argv)
4081 if (argv[1] && strcmp(argv[1], "-l") != 0) {
4084 if (argv[i][0] == '%') {
4086 * "kill %N" - job kill
4087 * Converting to pgrp / pid kill
4093 jp = getjob(argv[i], 0);
4095 * In jobs started under job control, we signal
4096 * entire process group by kill -PGRP_ID.
4097 * This happens, f.e., in interactive shell.
4099 * Otherwise, we signal each child via
4100 * kill PID1 PID2 PID3.
4102 * sh -c 'sleep 1|sleep 1 & kill %1'
4103 * sh -c 'true|sleep 2 & sleep 1; kill %1'
4104 * sh -c 'true|sleep 1 & sleep 2; kill %1'
4106 n = jp->nprocs; /* can't be 0 (I hope) */
4109 dst = alloca(n * sizeof(int)*4);
4111 for (j = 0; j < n; j++) {
4112 struct procstat *ps = &jp->ps[j];
4113 /* Skip non-running and not-stopped members
4114 * (i.e. dead members) of the job
4116 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
4119 * kill_main has matching code to expect
4120 * leading space. Needed to not confuse
4121 * negative pids with "kill -SIGNAL_NO" syntax
4123 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
4127 } while (argv[++i]);
4129 return kill_main(argc, argv);
4133 showpipe(struct job *jp /*, FILE *out*/)
4135 struct procstat *ps;
4136 struct procstat *psend;
4138 psend = jp->ps + jp->nprocs;
4139 for (ps = jp->ps + 1; ps < psend; ps++)
4140 printf(" | %s", ps->ps_cmd);
4141 newline_and_flush(stdout);
4142 flush_stdout_stderr();
4147 restartjob(struct job *jp, int mode)
4149 struct procstat *ps;
4155 if (jp->state == JOBDONE)
4157 jp->state = JOBRUNNING;
4158 pgid = jp->ps[0].ps_pid;
4159 if (mode == FORK_FG) {
4161 xtcsetpgrp(ttyfd, pgid);
4163 killpg(pgid, SIGCONT);
4167 if (WIFSTOPPED(ps->ps_status)) {
4173 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
4178 static int FAST_FUNC
4179 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
4185 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
4189 jp = getjob(*argv, 1);
4190 if (mode == FORK_BG) {
4191 set_curjob(jp, CUR_RUNNING);
4192 printf("[%d] ", jobno(jp));
4194 out1str(jp->ps[0].ps_cmd);
4195 showpipe(jp /*, stdout*/);
4196 retval = restartjob(jp, mode);
4197 } while (*argv && *++argv);
4203 sprint_status48(char *s, int status, int sigonly)
4209 if (!WIFEXITED(status)) {
4211 if (WIFSTOPPED(status))
4212 st = WSTOPSIG(status);
4215 st = WTERMSIG(status);
4217 if (st == SIGINT || st == SIGPIPE)
4220 if (WIFSTOPPED(status))
4225 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
4226 col = fmtstr(s, 32, strsignal(st));
4227 if (WCOREDUMP(status)) {
4228 strcpy(s + col, " (core dumped)");
4229 col += sizeof(" (core dumped)")-1;
4231 } else if (!sigonly) {
4232 st = WEXITSTATUS(status);
4233 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
4240 wait_block_or_sig(int *status)
4247 /* Poll all children for changes in their state */
4249 /* if job control is active, accept stopped processes too */
4250 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
4252 break; /* Error (e.g. EINTR, ECHILD) or pid */
4254 /* Children exist, but none are ready. Sleep until interesting signal */
4257 sigprocmask2(SIG_SETMASK, &mask); /* mask is updated */
4258 while (!got_sigchld && !pending_sig)
4260 sigprocmask(SIG_SETMASK, &mask, NULL);
4261 #else /* unsafe: a signal can set pending_sig after check, but before pause() */
4262 while (!got_sigchld && !pending_sig)
4266 /* If it was SIGCHLD, poll children again */
4267 } while (got_sigchld);
4272 #define DOWAIT_NONBLOCK 0
4273 #define DOWAIT_BLOCK 1
4274 #define DOWAIT_BLOCK_OR_SIG 2
4276 # define DOWAIT_JOBSTATUS 0x10 /* OR this to get job's exitstatus instead of pid */
4280 dowait(int block, struct job *job)
4285 struct job *thisjob;
4287 bool want_jobexitstatus = (block & DOWAIT_JOBSTATUS);
4288 block = (block & ~DOWAIT_JOBSTATUS);
4291 TRACE(("dowait(0x%x) called\n", block));
4293 /* It's wrong to call waitpid() outside of INT_OFF region:
4294 * signal can arrive just after syscall return and handler can
4295 * longjmp away, losing stop/exit notification processing.
4296 * Thus, for "jobs" builtin, and for waiting for a fg job,
4297 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
4299 * However, for "wait" builtin it is wrong to simply call waitpid()
4300 * in INT_OFF region: "wait" needs to wait for any running job
4301 * to change state, but should exit on any trap too.
4302 * In INT_OFF region, a signal just before syscall entry can set
4303 * pending_sig variables, but we can't check them, and we would
4304 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
4306 * Because of this, we run inside INT_OFF, but use a special routine
4307 * which combines waitpid() and sigsuspend().
4308 * This is the reason why we need to have a handler for SIGCHLD:
4309 * SIG_DFL handler does not wake sigsuspend().
4312 if (block == DOWAIT_BLOCK_OR_SIG) {
4313 pid = wait_block_or_sig(&status);
4316 if (block == DOWAIT_NONBLOCK)
4317 wait_flags = WNOHANG;
4318 /* if job control is active, accept stopped processes too */
4320 wait_flags |= WUNTRACED;
4321 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4322 pid = waitpid(-1, &status, wait_flags);
4324 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4325 pid, status, errno, strerror(errno)));
4330 for (jp = curjob; jp; jp = jp->prev_job) {
4332 struct procstat *ps;
4333 struct procstat *psend;
4334 if (jp->state == JOBDONE)
4338 psend = ps + jp->nprocs;
4340 if (ps->ps_pid == pid) {
4341 TRACE(("Job %d: changing status of proc %d "
4342 "from 0x%x to 0x%x\n",
4343 jobno(jp), pid, ps->ps_status, status));
4344 ps->ps_status = status;
4347 if (ps->ps_status == -1)
4348 jobstate = JOBRUNNING;
4350 if (jobstate == JOBRUNNING)
4352 if (WIFSTOPPED(ps->ps_status)) {
4353 jp->stopstatus = ps->ps_status;
4354 jobstate = JOBSTOPPED;
4357 } while (++ps < psend);
4361 /* Found the job where one of its processes changed its state.
4362 * Is there at least one live and running process in this job? */
4363 if (jobstate != JOBRUNNING) {
4364 /* No. All live processes in the job are stopped
4365 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4367 thisjob->changed = 1;
4368 if (thisjob->state != jobstate) {
4369 TRACE(("Job %d: changing state from %d to %d\n",
4370 jobno(thisjob), thisjob->state, jobstate));
4371 thisjob->state = jobstate;
4373 if (jobstate == JOBSTOPPED)
4374 set_curjob(thisjob, CUR_STOPPED);
4380 /* The process wasn't found in job list */
4382 if (!WIFSTOPPED(status))
4389 if (want_jobexitstatus) {
4391 if (thisjob && thisjob->state == JOBDONE)
4392 pid = thisjob->ps[thisjob->nprocs - 1].ps_status;
4395 if (thisjob && thisjob == job) {
4399 len = sprint_status48(s, status, 1);
4411 showjob(struct job *jp, int mode)
4413 struct procstat *ps;
4414 struct procstat *psend;
4417 char s[16 + 16 + 48];
4418 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4422 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4423 /* just output process (group) id of pipeline */
4424 fprintf(out, "%d\n", ps->ps_pid);
4428 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4433 else if (curjob && jp == curjob->prev_job)
4436 if (mode & SHOW_PIDS)
4437 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4439 psend = ps + jp->nprocs;
4441 if (jp->state == JOBRUNNING) {
4442 strcpy(s + col, "Running");
4443 col += sizeof("Running") - 1;
4445 int status = psend[-1].ps_status;
4446 if (jp->state == JOBSTOPPED)
4447 status = jp->stopstatus;
4448 col += sprint_status48(s + col, status, 0);
4450 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4452 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4453 * or prints several "PID | <cmdN>" lines,
4454 * depending on SHOW_PIDS bit.
4455 * We do not print status of individual processes
4456 * between PID and <cmdN>. bash does it, but not very well:
4457 * first line shows overall job status, not process status,
4458 * making it impossible to know 1st process status.
4462 /* for each process */
4465 if (mode & SHOW_PIDS)
4466 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4468 fprintf(out, "%s%*c%s%s",
4470 33 - col >= 0 ? 33 - col : 0, ' ',
4471 ps == jp->ps ? "" : "| ",
4474 } while (++ps != psend);
4475 newline_and_flush(out);
4479 if (jp->state == JOBDONE) {
4480 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4486 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4487 * statuses have changed since the last call to showjobs.
4494 TRACE(("showjobs(0x%x) called\n", mode));
4496 /* Handle all finished jobs */
4497 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4500 for (jp = curjob; jp; jp = jp->prev_job) {
4501 if (!(mode & SHOW_CHANGED) || jp->changed) {
4507 static int FAST_FUNC
4508 jobscmd(int argc UNUSED_PARAM, char **argv)
4513 while ((m = nextopt("lp")) != '\0') {
4517 mode |= SHOW_ONLY_PGID;
4523 showjob(getjob(*argv, 0), mode);
4533 /* Called only on finished or stopped jobs (no members are running) */
4535 getstatus(struct job *job)
4539 struct procstat *ps;
4541 /* Fetch last member's status */
4542 ps = job->ps + job->nprocs - 1;
4543 status = ps->ps_status;
4545 /* "set -o pipefail" mode: use last _nonzero_ status */
4546 while (status == 0 && --ps >= job->ps)
4547 status = ps->ps_status;
4550 retval = WEXITSTATUS(status);
4551 if (!WIFEXITED(status)) {
4553 retval = WSTOPSIG(status);
4554 if (!WIFSTOPPED(status))
4557 /* XXX: limits number of signals */
4558 retval = WTERMSIG(status);
4560 if (retval == SIGINT)
4566 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4567 jobno(job), job->nprocs, status, retval));
4571 static int FAST_FUNC
4572 waitcmd(int argc UNUSED_PARAM, char **argv)
4579 char one = nextopt("n");
4587 /* wait for all jobs / one job if -n */
4592 /* exitcode of "wait -n" with nothing to wait for is 127, not 0 */
4596 if (!jp) /* no running procs */
4598 if (jp->state == JOBRUNNING)
4604 * "When bash is waiting for an asynchronous command via
4605 * the wait builtin, the reception of a signal for which a trap
4606 * has been set will cause the wait builtin to return immediately
4607 * with an exit status greater than 128, immediately after which
4608 * the trap is executed."
4611 status = dowait(DOWAIT_BLOCK_OR_SIG | DOWAIT_JOBSTATUS, NULL);
4613 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4615 /* if child sends us a signal *and immediately exits*,
4616 * dowait() returns pid > 0. Check this case,
4617 * not "if (dowait() < 0)"!
4623 /* wait -n waits for one _job_, not one _process_.
4624 * date; sleep 3 & sleep 2 | sleep 1 & wait -n; date
4625 * should wait for 2 seconds. Not 1 or 3.
4627 if (status != -1 && !WIFSTOPPED(status)) {
4628 retval = WEXITSTATUS(status);
4629 if (WIFSIGNALED(status))
4630 retval = WTERMSIG(status) + 128;
4640 if (**argv != '%') {
4641 pid_t pid = number(*argv);
4646 if (job->ps[job->nprocs - 1].ps_pid == pid)
4648 job = job->prev_job;
4651 job = getjob(*argv, 0);
4653 /* loop until process terminated or stopped */
4654 while (job->state == JOBRUNNING) {
4655 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4660 retval = getstatus(job);
4667 retval = 128 + pending_sig;
4676 struct job *jp, *jq;
4678 len = njobs * sizeof(*jp);
4680 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4682 offset = (char *)jp - (char *)jq;
4684 /* Relocate pointers */
4687 jq = (struct job *)((char *)jq + l);
4691 #define joff(p) ((struct job *)((char *)(p) + l))
4692 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4693 if (joff(jp)->ps == &jq->ps0)
4694 jmove(joff(jp)->ps);
4695 if (joff(jp)->prev_job)
4696 jmove(joff(jp)->prev_job);
4706 jp = (struct job *)((char *)jp + len);
4710 } while (--jq >= jp);
4715 * Return a new job structure.
4716 * Called with interrupts off.
4719 makejob(/*union node *node,*/ int nprocs)
4724 for (i = njobs, jp = jobtab; ; jp++) {
4731 if (jp->state != JOBDONE || !jp->waited)
4740 memset(jp, 0, sizeof(*jp));
4742 /* jp->jobctl is a bitfield.
4743 * "jp->jobctl |= doing_jobctl" likely to give awful code */
4747 jp->prev_job = curjob;
4752 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4754 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4761 * Return a string identifying a command (to be printed by the
4764 static char *cmdnextc;
4767 cmdputs(const char *s)
4769 static const char vstype[VSTYPE + 1][3] = {
4770 "", "}", "-", "+", "?", "=",
4771 "%", "%%", "#", "##"
4772 IF_BASH_SUBSTR(, ":")
4773 IF_BASH_PATTERN_SUBST(, "/", "//")
4776 const char *p, *str;
4780 unsigned char subtype = 0;
4784 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4786 while ((c = *p++) != '\0') {
4794 if ((subtype & VSTYPE) == VSLENGTH)
4800 str = "\"}" + !(quoted & 1);
4807 #if ENABLE_FEATURE_SH_MATH
4822 if ((subtype & VSTYPE) != VSNORMAL)
4824 str = vstype[subtype & VSTYPE];
4825 if (subtype & VSNUL)
4834 /* These can only happen inside quotes */
4840 // [1]+ Done true ${\$} <<=== BUG: ${\$} is not a valid way to write $$ (${$} would be ok)
4851 while ((c = *str++) != '\0') {
4854 } /* while *p++ not NUL */
4857 USTPUTC('"', nextc);
4863 /* cmdtxt() and cmdlist() call each other */
4864 static void cmdtxt(union node *n);
4867 cmdlist(union node *np, int sep)
4869 for (; np; np = np->narg.next) {
4873 if (sep && np->narg.next)
4879 cmdtxt(union node *n)
4882 struct nodelist *lp;
4893 lp = n->npipe.cmdlist;
4911 cmdtxt(n->nbinary.ch1);
4927 cmdtxt(n->nif.test);
4929 if (n->nif.elsepart) {
4930 cmdtxt(n->nif.ifpart);
4932 n = n->nif.elsepart;
4950 cmdtxt(n->nbinary.ch1);
4960 cmdputs(n->nfor.var);
4962 cmdlist(n->nfor.args, 1);
4967 cmdputs(n->ndefun.text);
4971 cmdlist(n->ncmd.args, 1);
4972 cmdlist(n->ncmd.redirect, 0);
4985 cmdputs(n->ncase.expr->narg.text);
4987 for (np = n->ncase.cases; np; np = np->nclist.next) {
4988 cmdtxt(np->nclist.pattern);
4990 cmdtxt(np->nclist.body);
5004 #if BASH_REDIR_OUTPUT
5019 cmdputs(utoa(n->nfile.fd));
5021 if (n->type == NTOFD || n->type == NFROMFD) {
5022 if (n->ndup.dupfd >= 0)
5023 cmdputs(utoa(n->ndup.dupfd));
5034 commandtext(union node *n)
5038 STARTSTACKSTR(cmdnextc);
5040 name = stackblock();
5041 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
5042 return ckstrdup(name);
5047 * Fork off a subshell. If we are doing job control, give the subshell its
5048 * own process group. Jp is a job structure that the job is to be added to.
5049 * N is the command that will be evaluated by the child. Both jp and n may
5050 * be NULL. The mode parameter can be one of the following:
5051 * FORK_FG - Fork off a foreground process.
5052 * FORK_BG - Fork off a background process.
5053 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
5054 * process group even if job control is on.
5056 * When job control is turned off, background processes have their standard
5057 * input redirected to /dev/null (except for the second and later processes
5060 * Called with interrupts off.
5063 * Clear traps on a fork.
5071 for (tp = trap; tp < &trap[NSIG]; tp++) {
5072 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
5073 if (trap_ptr == trap)
5075 /* else: it "belongs" to trap_ptr vector, don't free */
5077 if ((tp - trap) != 0)
5078 setsignal(tp - trap);
5085 /* Lives far away from here, needed for forkchild */
5086 static void closescript(void);
5088 /* Called after fork(), in child */
5089 /* jp and n are NULL when called by openhere() for heredoc support */
5090 static NOINLINE void
5091 forkchild(struct job *jp, union node *n, int mode)
5095 TRACE(("Child shell %d\n", getpid()));
5099 /* man bash: "Non-builtin commands run by bash have signal handlers
5100 * set to the values inherited by the shell from its parent".
5101 * Do we do it correctly? */
5105 if (mode == FORK_NOJOB /* is it `xxx` ? */
5106 && n && n->type == NCMD /* is it single cmd? */
5107 /* && n->ncmd.args->type == NARG - always true? */
5108 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
5109 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
5110 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
5112 TRACE(("Trap hack\n"));
5113 /* Awful hack for `trap` or $(trap).
5115 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5116 * contains an example where "trap" is executed in a subshell:
5118 * save_traps=$(trap)
5120 * eval "$save_traps"
5122 * Standard does not say that "trap" in subshell shall print
5123 * parent shell's traps. It only says that its output
5124 * must have suitable form, but then, in the above example
5125 * (which is not supposed to be normative), it implies that.
5127 * bash (and probably other shell) does implement it
5128 * (traps are reset to defaults, but "trap" still shows them),
5129 * but as a result, "trap" logic is hopelessly messed up:
5132 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5133 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5134 * # true | trap <--- trap is in subshell - no output (ditto)
5135 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5136 * trap -- 'echo Ho' SIGWINCH
5137 * # echo `(trap)` <--- in subshell in subshell - output
5138 * trap -- 'echo Ho' SIGWINCH
5139 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5140 * trap -- 'echo Ho' SIGWINCH
5142 * The rules when to forget and when to not forget traps
5143 * get really complex and nonsensical.
5145 * Our solution: ONLY bare $(trap) or `trap` is special.
5147 /* Save trap handler strings for trap builtin to print */
5148 trap_ptr = xmemdup(trap, sizeof(trap));
5149 /* Fall through into clearing traps */
5153 /* do job control only in root shell */
5155 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
5158 if (jp->nprocs == 0)
5161 pgrp = jp->ps[0].ps_pid;
5162 /* this can fail because we are doing it in the parent also */
5164 if (mode == FORK_FG)
5165 xtcsetpgrp(ttyfd, pgrp);
5170 if (mode == FORK_BG) {
5171 /* man bash: "When job control is not in effect,
5172 * asynchronous commands ignore SIGINT and SIGQUIT" */
5175 if (jp->nprocs == 0) {
5177 if (open(bb_dev_null, O_RDONLY) != 0)
5178 ash_msg_and_raise_perror("can't open '%s'", bb_dev_null);
5182 if (iflag) { /* why if iflag only? */
5187 * "In all cases, bash ignores SIGQUIT. Non-builtin
5188 * commands run by bash have signal handlers
5189 * set to the values inherited by the shell
5191 * Take care of the second rule: */
5195 if (n && n->type == NCMD
5196 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
5198 TRACE(("Job hack\n"));
5199 /* "jobs": we do not want to clear job list for it,
5200 * instead we remove only _its_ own_ job from job list.
5201 * This makes "jobs .... | cat" more useful.
5207 for (jp = curjob; jp; jp = jp->prev_job)
5212 /* Called after fork(), in parent */
5214 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
5217 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
5219 TRACE(("In parent shell: child = %d\n", pid));
5221 /* jp is NULL when called by openhere() for heredoc support */
5222 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
5228 if (mode != FORK_NOJOB && jp->jobctl) {
5231 if (jp->nprocs == 0)
5234 pgrp = jp->ps[0].ps_pid;
5235 /* This can fail because we are doing it in the child also */
5239 if (mode == FORK_BG) {
5240 backgndpid = pid; /* set $! */
5241 set_curjob(jp, CUR_RUNNING);
5244 struct procstat *ps = &jp->ps[jp->nprocs++];
5247 ps->ps_cmd = nullstr;
5249 if (doing_jobctl && n)
5250 ps->ps_cmd = commandtext(n);
5255 /* jp and n are NULL when called by openhere() for heredoc support */
5257 forkshell(struct job *jp, union node *n, int mode)
5261 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
5264 TRACE(("Fork failed, errno=%d", errno));
5267 ash_msg_and_raise_perror("can't fork");
5270 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
5271 forkchild(jp, n, mode);
5273 forkparent(jp, n, mode, pid);
5279 * Wait for job to finish.
5281 * Under job control we have the problem that while a child process
5282 * is running interrupts generated by the user are sent to the child
5283 * but not to the shell. This means that an infinite loop started by
5284 * an interactive user may be hard to kill. With job control turned off,
5285 * an interactive user may place an interactive program inside a loop.
5286 * If the interactive program catches interrupts, the user doesn't want
5287 * these interrupts to also abort the loop. The approach we take here
5288 * is to have the shell ignore interrupt signals while waiting for a
5289 * foreground process to terminate, and then send itself an interrupt
5290 * signal if the child process was terminated by an interrupt signal.
5291 * Unfortunately, some programs want to do a bit of cleanup and then
5292 * exit on interrupt; unless these processes terminate themselves by
5293 * sending a signal to themselves (instead of calling exit) they will
5294 * confuse this approach.
5296 * Called with interrupts off.
5299 waitforjob(struct job *jp)
5303 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
5306 while (jp->state == JOBRUNNING) {
5307 /* In non-interactive shells, we _can_ get
5308 * a keyboard signal here and be EINTRed,
5309 * but we just loop back, waiting for command to complete.
5312 * "If bash is waiting for a command to complete and receives
5313 * a signal for which a trap has been set, the trap
5314 * will not be executed until the command completes."
5316 * Reality is that even if trap is not set, bash
5317 * will not act on the signal until command completes.
5318 * Try this. sleep5intoff.c:
5319 * #include <signal.h>
5320 * #include <unistd.h>
5323 * sigemptyset(&set);
5324 * sigaddset(&set, SIGINT);
5325 * sigaddset(&set, SIGQUIT);
5326 * sigprocmask(SIG_BLOCK, &set, NULL);
5330 * $ bash -c './sleep5intoff; echo hi'
5331 * ^C^C^C^C <--- pressing ^C once a second
5333 * $ bash -c './sleep5intoff; echo hi'
5334 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
5337 dowait(DOWAIT_BLOCK, jp);
5344 xtcsetpgrp(ttyfd, rootpid);
5345 restore_tty_if_stopped_or_signaled(jp);
5348 * This is truly gross.
5349 * If we're doing job control, then we did a TIOCSPGRP which
5350 * caused us (the shell) to no longer be in the controlling
5351 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
5352 * intuit from the subprocess exit status whether a SIGINT
5353 * occurred, and if so interrupt ourselves. Yuck. - mycroft
5355 if (jp->sigint) /* TODO: do the same with all signals */
5356 raise(SIGINT); /* ... by raise(jp->sig) instead? */
5358 if (jp->state == JOBDONE)
5365 * return 1 if there are stopped jobs, otherwise 0
5377 if (jp && jp->state == JOBSTOPPED) {
5378 out2str("You have stopped jobs.\n");
5388 * Code for dealing with input/output redirection.
5393 #define EMPTY -2 /* marks an unused slot in redirtab */
5394 #define CLOSED -1 /* marks a slot of previously-closed fd */
5397 * Handle here documents. Normally we fork off a process to write the
5398 * data to a pipe. If the document is short, we can stuff the data in
5399 * the pipe without forking.
5401 /* openhere needs this forward reference */
5402 static void expandhere(union node *arg, int fd);
5404 openhere(union node *redir)
5410 ash_msg_and_raise_perror("can't create pipe");
5411 if (redir->type == NHERE) {
5412 len = strlen(redir->nhere.doc->narg.text);
5413 if (len <= PIPE_BUF) {
5414 full_write(pip[1], redir->nhere.doc->narg.text, len);
5418 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5421 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5422 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5423 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5424 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5425 signal(SIGPIPE, SIG_DFL);
5426 if (redir->type == NHERE)
5427 full_write(pip[1], redir->nhere.doc->narg.text, len);
5429 expandhere(redir->nhere.doc, pip[1]);
5430 _exit(EXIT_SUCCESS);
5438 openredirect(union node *redir)
5444 switch (redir->nfile.type) {
5445 /* Can't happen, our single caller does this itself */
5451 return openhere(redir);
5454 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5455 * allocated space. Do it only when we know it is safe.
5457 fname = redir->nfile.expfname;
5459 switch (redir->nfile.type) {
5465 f = open(fname, O_RDONLY);
5470 f = open(fname, O_RDWR|O_CREAT, 0666);
5475 #if BASH_REDIR_OUTPUT
5478 /* Take care of noclobber mode. */
5480 if (stat(fname, &sb) < 0) {
5481 f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5484 } else if (!S_ISREG(sb.st_mode)) {
5485 f = open(fname, O_WRONLY, 0666);
5488 if (!fstat(f, &sb) && S_ISREG(sb.st_mode)) {
5501 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5506 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5514 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5516 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5520 * Copy a file descriptor to be >= 10. Throws exception on error.
5528 newfd = fcntl(from, F_DUPFD_CLOEXEC, 10);
5529 err = newfd < 0 ? errno : 0;
5532 ash_msg_and_raise_perror("%d", from);
5534 if (F_DUPFD_CLOEXEC == F_DUPFD)
5535 close_on_exec_on(newfd);
5541 dup2_or_raise(int from, int to)
5545 newfd = (from != to) ? dup2(from, to) : to;
5547 /* Happens when source fd is not open: try "echo >&99" */
5548 ash_msg_and_raise_perror("%d", from);
5553 dup_CLOEXEC(int fd, int avoid_fd)
5557 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
5559 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
5560 close_on_exec_on(newfd);
5561 } else { /* newfd < 0 */
5570 xdup_CLOEXEC_and_close(int fd, int avoid_fd)
5574 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
5580 /* fd was not open? */
5583 ash_msg_and_raise_perror("%d", newfd);
5585 if (F_DUPFD_CLOEXEC == F_DUPFD)
5586 close_on_exec_on(newfd);
5591 /* Struct def and variable are moved down to the first usage site */
5597 struct redirtab *next;
5599 struct squirrel two_fd[];
5601 #define redirlist (G_var.redirlist)
5604 add_squirrel_closed(struct redirtab *sq, int fd)
5611 for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
5612 /* If we collide with an already moved fd... */
5613 if (fd == sq->two_fd[i].orig_fd) {
5615 * "echo 3>FILE 3>&- 3>FILE"
5616 * "echo 3>&- 3>FILE"
5617 * No need for last redirect to insert
5618 * another "need to close 3" indicator.
5620 TRACE(("redirect_fd %d: already moved or closed\n", fd));
5624 TRACE(("redirect_fd %d: previous fd was closed\n", fd));
5625 sq->two_fd[i].orig_fd = fd;
5626 sq->two_fd[i].moved_to = CLOSED;
5630 save_fd_on_redirect(int fd, int avoid_fd, struct redirtab *sq)
5634 if (avoid_fd < 9) /* the important case here is that it can be -1 */
5639 /* Testcase: "ls -l /proc/$$/fd 10>&-" should work */
5640 ttyfd = xdup_CLOEXEC_and_close(ttyfd, avoid_fd);
5641 TRACE(("redirect_fd %d: matches ttyfd, moving it to %d\n", fd, ttyfd));
5642 return 1; /* "we closed fd" */
5645 /* Are we called from redirect(0)? E.g. redirect
5646 * in a forked child. No need to save fds,
5647 * we aren't going to use them anymore, ok to trash.
5652 /* If this one of script's fds? */
5654 struct parsefile *pf = g_parsefile;
5656 /* We skip fd == 0 case because of the following:
5657 * $ ash # running ash interactively
5659 * and in script.sh: "exec 9>&0".
5660 * Even though top-level pf_fd _is_ 0,
5661 * it's still ok to use it: "read" builtin uses it,
5662 * why should we cripple "exec" builtin?
5664 if (fd == pf->pf_fd) {
5665 pf->pf_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
5666 return 1; /* "we closed fd" */
5672 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
5674 /* First: do we collide with some already moved fds? */
5675 for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
5676 /* If we collide with an already moved fd... */
5677 if (fd == sq->two_fd[i].moved_to) {
5678 new_fd = dup_CLOEXEC(fd, avoid_fd);
5679 sq->two_fd[i].moved_to = new_fd;
5680 TRACE(("redirect_fd %d: already busy, moving to %d\n", fd, new_fd));
5681 if (new_fd < 0) /* what? */
5683 return 0; /* "we did not close fd" */
5685 if (fd == sq->two_fd[i].orig_fd) {
5686 /* Example: echo Hello >/dev/null 1>&2 */
5687 TRACE(("redirect_fd %d: already moved\n", fd));
5688 return 0; /* "we did not close fd" */
5692 /* If this fd is open, we move and remember it; if it's closed, new_fd = CLOSED (-1) */
5693 new_fd = dup_CLOEXEC(fd, avoid_fd);
5694 TRACE(("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, new_fd));
5698 /* new_fd = CLOSED; - already is -1 */
5700 sq->two_fd[i].moved_to = new_fd;
5701 sq->two_fd[i].orig_fd = fd;
5703 /* if we move stderr, let "set -x" code know */
5704 if (fd == preverrout_fd)
5705 preverrout_fd = new_fd;
5707 return 0; /* "we did not close fd" */
5711 internally_opened_fd(int fd, struct redirtab *sq)
5718 /* If this one of script's fds? */
5720 struct parsefile *pf = g_parsefile;
5722 if (fd == pf->pf_fd)
5728 if (sq) for (i = 0; i < sq->pair_count && sq->two_fd[i].orig_fd != EMPTY; i++) {
5729 if (fd == sq->two_fd[i].moved_to)
5736 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5737 * old file descriptors are stashed away so that the redirection can be
5738 * undone by calling popredir.
5740 /* flags passed to redirect */
5741 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5743 redirect(union node *redir, int flags)
5745 struct redirtab *sv;
5752 if (flags & REDIR_PUSH)
5760 fd = redir->nfile.fd;
5761 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5762 //bb_error_msg("doing %d > %d", fd, newfd);
5763 newfd = redir->ndup.dupfd;
5766 newfd = openredirect(redir); /* always >= 0 */
5768 /* open() gave us precisely the fd we wanted.
5769 * This means that this fd was not busy
5770 * (not opened to anywhere).
5771 * Remember to close it on restore:
5773 add_squirrel_closed(sv, fd);
5782 /* if "N>FILE": move newfd to fd */
5783 /* if "N>&M": dup newfd to fd */
5784 /* if "N>&-": close fd (newfd is -1) */
5786 IF_BASH_REDIR_OUTPUT(redirect_more:)
5788 closed = save_fd_on_redirect(fd, /*avoid:*/ newfd, sv);
5790 /* "N>&-" means "close me" */
5792 /* ^^^ optimization: saving may already
5793 * have closed it. If not... */
5797 /* if newfd is a script fd or saved fd, simulate EBADF */
5798 if (internally_opened_fd(newfd, sv)) {
5800 ash_msg_and_raise_perror("%d", newfd);
5802 dup2_or_raise(newfd, fd);
5803 if (close_fd >= 0) /* "N>FILE" or ">&FILE" or heredoc? */
5805 #if BASH_REDIR_OUTPUT
5806 if (redir->nfile.type == NTO2 && fd == 1) {
5807 /* ">&FILE". we already redirected to 1, now copy 1 to 2 */
5815 } while ((redir = redir->nfile.next) != NULL);
5818 //dash:#define REDIR_SAVEFD2 03 /* set preverrout */
5819 #define REDIR_SAVEFD2 0
5820 // dash has a bug: since REDIR_SAVEFD2=3 and REDIR_PUSH=1, this test
5821 // triggers for pure REDIR_PUSH too. Thus, this is done almost always,
5822 // not only for calls with flags containing REDIR_SAVEFD2.
5823 // We do this unconditionally (see save_fd_on_redirect()).
5824 //if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5825 // preverrout_fd = copied_fd2;
5829 redirectsafe(union node *redir, int flags)
5832 volatile int saveint;
5833 struct jmploc *volatile savehandler = exception_handler;
5834 struct jmploc jmploc;
5837 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5838 err = setjmp(jmploc.loc); /* was = setjmp(jmploc.loc) * 2; */
5840 exception_handler = &jmploc;
5841 redirect(redir, flags);
5843 exception_handler = savehandler;
5844 if (err && exception_type != EXERROR)
5845 longjmp(exception_handler->loc, 1);
5846 RESTORE_INT(saveint);
5850 static struct redirtab*
5851 pushredir(union node *redir)
5853 struct redirtab *sv;
5862 #if BASH_REDIR_OUTPUT
5863 if (redir->nfile.type == NTO2)
5866 redir = redir->nfile.next;
5869 sv = ckzalloc(sizeof(*sv) + i * sizeof(sv->two_fd[0]));
5872 sv->two_fd[i].orig_fd = sv->two_fd[i].moved_to = EMPTY;
5873 sv->next = redirlist;
5879 * Undo the effects of the last redirection.
5884 struct redirtab *rp;
5887 if (redirlist == NULL)
5891 for (i = 0; i < rp->pair_count; i++) {
5892 int fd = rp->two_fd[i].orig_fd;
5893 int copy = rp->two_fd[i].moved_to;
5894 if (copy == CLOSED) {
5899 if (copy != EMPTY) {
5902 dup2_or_raise(copy, fd);
5907 redirlist = rp->next;
5913 unwindredir(struct redirtab *stop)
5915 while (redirlist != stop)
5916 popredir(/*drop:*/ 0);
5920 /* ============ Routines to expand arguments to commands
5922 * We have to deal with backquotes, shell variables, and file metacharacters.
5925 #if ENABLE_FEATURE_SH_MATH
5927 ash_arith(const char *s)
5929 arith_state_t math_state;
5932 math_state.lookupvar = lookupvar;
5933 math_state.setvar = setvar0;
5934 //math_state.endofname = endofname;
5937 result = arith(&math_state, s);
5938 if (math_state.errmsg)
5939 ash_msg_and_raise_error(math_state.errmsg);
5946 # if ENABLE_FEATURE_SH_MATH
5947 static int substr_atoi(const char *s)
5949 arith_t t = ash_arith(s);
5950 if (sizeof(t) > sizeof(int)) {
5951 /* clamp very large or very large negative nums for ${v:N:M}:
5952 * else "${v:0:0x100000001}" would work as "${v:0:1}"
5962 # define substr_atoi(s) number(s)
5969 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5970 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5971 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5972 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5973 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5974 * POSIX says for this case:
5975 * Pathname expansion shall not be performed on the word by a
5976 * non-interactive shell; an interactive shell may perform it, but shall
5977 * do so only when the expansion would result in one word.
5978 * Currently, our code complies to the above rule by never globbing
5979 * redirection filenames.
5980 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5981 * (this means that on a typical Linux distro, bash almost always
5982 * performs globbing, and thus diverges from what we do).
5984 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5985 #define EXP_VARTILDE2 0x20 /* expand tildes after colons only */
5986 #define EXP_WORD 0x40 /* expand word in parameter expansion */
5987 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5991 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5992 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5993 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5994 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5996 /* Add CTLESC when necessary. */
5997 #define QUOTES_ESC (EXP_FULL | EXP_CASE)
5998 /* Do not skip NUL characters. */
5999 #define QUOTES_KEEPNUL EXP_TILDE
6002 * Structure specifying which parts of the string should be searched
6003 * for IFS characters.
6006 struct ifsregion *next; /* next region in list */
6007 int begoff; /* offset of start of region */
6008 int endoff; /* offset of end of region */
6009 int nulonly; /* search for nul bytes only */
6013 struct strlist *list;
6014 struct strlist **lastp;
6017 /* output of current string */
6018 static char *expdest;
6019 /* list of back quote expressions */
6020 static struct nodelist *argbackq;
6021 /* first struct in list of ifs regions */
6022 static struct ifsregion ifsfirst;
6023 /* last struct in list */
6024 static struct ifsregion *ifslastp;
6025 /* holds expanded arg list */
6026 static struct arglist exparg;
6030 * cvtnum() is used even if math support is off (to prepare $? values and such).
6037 /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
6038 len = sizeof(arith_t) * 3;
6039 /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
6040 if (sizeof(arith_t) < 4) len += 2;
6042 expdest = makestrspace(len, expdest);
6043 len = fmtstr(expdest, len, ARITH_FMT, num);
6044 STADJUST(len, expdest);
6049 * Break the argument string into pieces based upon IFS and add the
6050 * strings to the argument list. The regions of the string to be
6051 * searched for IFS characters have been stored by recordregion.
6054 ifsbreakup(char *string, struct arglist *arglist)
6056 struct ifsregion *ifsp;
6061 const char *ifs, *realifs;
6066 if (ifslastp != NULL) {
6069 realifs = ifsset() ? ifsval() : defifs;
6074 p = string + ifsp->begoff;
6076 nulonly = ifsp->nulonly;
6077 ifs = nulonly ? nullstr : realifs;
6079 while (p < string + ifsp->endoff) {
6081 if ((unsigned char)*p == CTLESC)
6083 if (!strchr(ifs, *p)) {
6087 if (!(afternul || nulonly))
6088 ifsspc = (strchr(defifs, *p) != NULL);
6089 /* Ignore IFS whitespace at start */
6090 if (q == start && ifsspc) {
6096 sp = stzalloc(sizeof(*sp));
6098 *arglist->lastp = sp;
6099 arglist->lastp = &sp->next;
6103 if (p >= string + ifsp->endoff) {
6107 if ((unsigned char)*p == CTLESC)
6109 if (strchr(ifs, *p) == NULL) {
6113 if (strchr(defifs, *p) == NULL) {
6128 } while (ifsp != NULL);
6137 sp = stzalloc(sizeof(*sp));
6139 *arglist->lastp = sp;
6140 arglist->lastp = &sp->next;
6146 struct ifsregion *p = ifsfirst.next;
6153 struct ifsregion *ifsp;
6158 ifsfirst.next = NULL;
6165 esclen(const char *start, const char *p)
6169 while (p > start && (unsigned char)*--p == CTLESC) {
6176 * Remove any CTLESC characters from a string.
6178 #if !BASH_PATTERN_SUBST
6179 #define rmescapes(str, flag, slash_position) \
6180 rmescapes(str, flag)
6183 rmescapes(char *str, int flag, int *slash_position)
6185 static const char qchars[] ALIGN1 = {
6186 IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
6189 unsigned protect_against_glob;
6192 p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash_position));
6198 if (flag & RMESCAPE_ALLOC) {
6199 size_t len = p - str;
6200 size_t fulllen = len + strlen(p) + 1;
6202 if (flag & RMESCAPE_GROW) {
6203 int strloc = str - (char *)stackblock();
6204 r = makestrspace(fulllen, expdest);
6205 /* p and str may be invalidated by makestrspace */
6206 str = (char *)stackblock() + strloc;
6208 } else if (flag & RMESCAPE_HEAP) {
6209 r = ckmalloc(fulllen);
6211 r = stalloc(fulllen);
6215 q = (char *)mempcpy(q, str, len);
6219 globbing = flag & RMESCAPE_GLOB;
6220 protect_against_glob = globbing;
6222 if ((unsigned char)*p == CTLQUOTEMARK) {
6223 // Note: protect_against_glob only affect whether
6224 // CTLESC,<ch> gets converted to <ch> or to \<ch>
6226 protect_against_glob = globbing;
6230 /* naked back slash */
6231 protect_against_glob = 0;
6234 if ((unsigned char)*p == CTLESC) {
6238 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
6240 if (protect_against_glob) {
6242 * We used to trust glob() and fnmatch() to eat
6243 * superfluous escapes (\z where z has no
6244 * special meaning anyway). But this causes
6245 * bugs such as string of one greek letter rho
6246 * (unicode-encoded as two bytes "cf,81")
6247 * getting encoded as "cf,CTLESC,81"
6248 * and here, converted to "cf,\,81" -
6249 * which does not go well with some flavors
6250 * of fnmatch() in unicode locales
6251 * (for example, glibc <= 2.22).
6253 * Lets add "\" only on the chars which need it.
6254 * Testcases for less obvious chars are shown.
6259 || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
6260 || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
6261 || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
6262 || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
6263 /* Some libc support [^negate], that's why "^" also needs love */
6264 || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
6270 #if BASH_PATTERN_SUBST
6271 else if (slash_position && p == str + *slash_position) {
6272 /* stop handling globbing */
6274 *slash_position = q - r;
6275 slash_position = NULL;
6278 protect_against_glob = globbing;
6283 if (flag & RMESCAPE_GROW) {
6285 STADJUST(q - r + 1, expdest);
6289 #define pmatch(a, b) !fnmatch((a), (b), 0)
6292 * Prepare a pattern for a expmeta (internal glob(3)) call.
6294 * Returns an stalloced string.
6297 preglob(const char *pattern, int flag)
6299 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB, NULL);
6303 * Put a string on the stack.
6306 memtodest(const char *p, size_t len, int syntax, int quotes)
6313 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
6316 unsigned char c = *p++;
6318 if (quotes & QUOTES_ESC) {
6319 int n = SIT(c, syntax);
6321 || (syntax != BASESYNTAX && n == CBACK)
6326 } else if (!(quotes & QUOTES_KEEPNUL))
6335 strtodest(const char *p, int syntax, int quotes)
6337 size_t len = strlen(p);
6338 memtodest(p, len, syntax, quotes);
6343 * Record the fact that we have to scan this region of the
6344 * string for IFS characters.
6347 recordregion(int start, int end, int nulonly)
6349 struct ifsregion *ifsp;
6351 if (ifslastp == NULL) {
6355 ifsp = ckzalloc(sizeof(*ifsp));
6356 /*ifsp->next = NULL; - ckzalloc did it */
6357 ifslastp->next = ifsp;
6361 ifslastp->begoff = start;
6362 ifslastp->endoff = end;
6363 ifslastp->nulonly = nulonly;
6367 removerecordregions(int endoff)
6369 if (ifslastp == NULL)
6372 if (ifsfirst.endoff > endoff) {
6373 while (ifsfirst.next) {
6374 struct ifsregion *ifsp;
6376 ifsp = ifsfirst.next->next;
6377 free(ifsfirst.next);
6378 ifsfirst.next = ifsp;
6381 if (ifsfirst.begoff > endoff) {
6384 ifslastp = &ifsfirst;
6385 ifsfirst.endoff = endoff;
6390 ifslastp = &ifsfirst;
6391 while (ifslastp->next && ifslastp->next->begoff < endoff)
6392 ifslastp = ifslastp->next;
6393 while (ifslastp->next) {
6394 struct ifsregion *ifsp;
6396 ifsp = ifslastp->next->next;
6397 free(ifslastp->next);
6398 ifslastp->next = ifsp;
6401 if (ifslastp->endoff > endoff)
6402 ifslastp->endoff = endoff;
6406 exptilde(char *startp, char *p, int flags)
6412 int quotes = flags & QUOTES_ESC;
6416 while ((c = *++p) != '\0') {
6423 if (flags & EXP_VARTILDE)
6433 if (*name == '\0') {
6434 home = lookupvar("HOME");
6436 pw = getpwnam(name);
6441 if (!home || !*home)
6444 strtodest(home, SQSYNTAX, quotes);
6452 * Execute a command inside back quotes. If it's a builtin command, we
6453 * want to save its output in a block obtained from malloc. Otherwise
6454 * we fork off a subprocess and get the output of the command via a pipe.
6455 * Should be called with interrupts off.
6457 struct backcmd { /* result of evalbackcmd */
6458 int fd; /* file descriptor to read from */
6459 int nleft; /* number of chars in buffer */
6460 char *buf; /* buffer */
6461 struct job *jp; /* job structure for command */
6464 /* These forward decls are needed to use "eval" code for backticks handling: */
6465 /* flags in argument to evaltree */
6466 #define EV_EXIT 01 /* exit after evaluating tree */
6467 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
6468 static int evaltree(union node *, int);
6470 /* An evaltree() which is known to never return.
6471 * Used to use an alias:
6472 * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
6473 * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
6475 static ALWAYS_INLINE NORETURN void
6476 evaltreenr(union node *n, int flags)
6479 bb_unreachable(abort());
6483 static void FAST_FUNC
6484 evalbackcmd(union node *n, struct backcmd *result)
6498 ash_msg_and_raise_perror("can't create pipe");
6499 jp = makejob(/*n,*/ 1);
6500 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6506 dup2_or_raise(pip[1], 1);
6509 /* TODO: eflag clearing makes the following not abort:
6510 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6511 * which is what bash does (unless it is in POSIX mode).
6512 * dash deleted "eflag = 0" line in the commit
6513 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6514 * [EVAL] Don't clear eflag in evalbackcmd
6515 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6519 evaltreenr(n, EV_EXIT);
6524 result->fd = pip[0];
6528 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6529 result->fd, result->buf, result->nleft, result->jp));
6533 * Expand stuff in backwards quotes.
6536 expbackq(union node *cmd, int flag)
6544 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6545 struct stackmark smark;
6548 startloc = expdest - (char *)stackblock();
6549 pushstackmark(&smark, startloc);
6550 evalbackcmd(cmd, &in);
6551 popstackmark(&smark);
6558 memtodest(p, i, syntax, flag & QUOTES_ESC);
6562 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6563 TRACE(("expbackq: read returns %d\n", i));
6572 back_exitstatus = waitforjob(in.jp);
6576 /* Eat all trailing newlines */
6578 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6582 if (!(flag & EXP_QUOTED))
6583 recordregion(startloc, dest - (char *)stackblock(), 0);
6584 TRACE(("evalbackq: size:%d:'%.*s'\n",
6585 (int)((dest - (char *)stackblock()) - startloc),
6586 (int)((dest - (char *)stackblock()) - startloc),
6587 stackblock() + startloc));
6590 #if ENABLE_FEATURE_SH_MATH
6592 * Expand arithmetic expression. Backup to start of expression,
6593 * evaluate, place result in (backed up) result, adjust string position.
6605 * This routine is slightly over-complicated for
6606 * efficiency. Next we scan backwards looking for the
6607 * start of arithmetic.
6609 start = stackblock();
6616 while ((unsigned char)*p != CTLARI) {
6620 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6625 esc = esclen(start, p);
6635 removerecordregions(begoff);
6639 if (flag & QUOTES_ESC)
6640 rmescapes(p + 1, 0, NULL);
6642 len = cvtnum(ash_arith(p + 1));
6644 if (!(flag & EXP_QUOTED))
6645 recordregion(begoff, begoff + len, 0);
6649 /* argstr needs it */
6650 static char *evalvar(char *p, int flags);
6653 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6654 * characters to allow for further processing. Otherwise treat
6655 * $@ like $* since no splitting will be performed.
6658 argstr(char *p, int flags)
6660 static const char spclchars[] ALIGN1 = {
6668 #if ENABLE_FEATURE_SH_MATH
6673 const char *reject = spclchars;
6674 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6679 if (!(flags & EXP_VARTILDE)) {
6681 } else if (flags & EXP_VARTILDE2) {
6686 if (flags & EXP_TILDE) {
6689 flags &= ~EXP_TILDE;
6693 p = exptilde(p, q, flags);
6696 startloc = expdest - (char *)stackblock();
6700 length += strcspn(p + length, reject);
6704 IF_FEATURE_SH_MATH(|| c == CTLENDARI)
6706 /* c == '=' || c == ':' || c == CTLENDARI */
6712 expdest = stack_nputstr(p, length, expdest);
6713 newloc = expdest - (char *)stackblock();
6714 if (breakall && !inquotes && newloc > startloc) {
6715 recordregion(startloc, newloc, 0);
6726 if (flags & EXP_VARTILDE2) {
6730 flags |= EXP_VARTILDE2;
6735 * sort of a hack - expand tildes in variable
6736 * assignments (after the first '=' and after ':'s).
6745 case CTLENDVAR: /* ??? */
6748 /* "$@" syntax adherence hack */
6749 if (!inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6750 p = evalvar(p + 1, flags | EXP_QUOTED) + 1;
6753 inquotes ^= EXP_QUOTED;
6755 if (flags & QUOTES_ESC) {
6766 TRACE(("argstr: evalvar('%s')\n", p));
6767 p = evalvar(p, flags | inquotes);
6768 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6771 expbackq(argbackq->n, flags | inquotes);
6772 argbackq = argbackq->next;
6774 #if ENABLE_FEATURE_SH_MATH
6777 expari(flags | inquotes);
6786 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6787 char *pattern, int quotes, int zero)
6796 const char *s = loc2;
6803 match = pmatch(pattern, s);
6808 if (quotes && (unsigned char)*loc == CTLESC)
6817 scanright(char *startp, char *rmesc, char *rmescend,
6818 char *pattern, int quotes, int match_at_start)
6820 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6821 int try2optimize = match_at_start;
6827 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6828 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6829 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6831 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6832 * and on each iteration they go back two/one char until they reach the beginning.
6833 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6835 /* TODO: document in what other circumstances we are called. */
6837 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6840 const char *s = loc2;
6841 if (match_at_start) {
6845 match = pmatch(pattern, s);
6846 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6850 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6852 /* Maybe we can optimize this:
6853 * if pattern ends with unescaped *, we can avoid checking
6854 * shorter strings: if "foo*" doesn't match "raw_value_of_v",
6855 * it won't match truncated "raw_value_of_" strings too.
6857 unsigned plen = strlen(pattern);
6858 /* Does it end with "*"? */
6859 if (plen != 0 && pattern[--plen] == '*') {
6860 /* "xxxx*" is not escaped */
6861 /* "xxx\*" is escaped */
6862 /* "xx\\*" is not escaped */
6863 /* "x\\\*" is escaped */
6865 while (plen != 0 && pattern[--plen] == '\\')
6868 break; /* ends with unescaped "*" */
6876 esc = esclen(startp, loc);
6887 static void varunset(const char *, const char *, const char *, int) NORETURN;
6889 varunset(const char *end, const char *var, const char *umsg, int varflags)
6895 msg = "parameter not set";
6897 if ((unsigned char)*end == CTLENDVAR) {
6898 if (varflags & VSNUL)
6904 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6908 subevalvar(char *p, char *varname, int strloc, int subtype,
6909 int startloc, int varflags, int flag)
6911 struct nodelist *saveargbackq = argbackq;
6912 int quotes = flag & QUOTES_ESC;
6915 char *rmesc, *rmescend;
6917 int amount, resetloc;
6919 IF_BASH_PATTERN_SUBST(int workloc;)
6920 IF_BASH_PATTERN_SUBST(int slash_pos;)
6921 IF_BASH_PATTERN_SUBST(char *repl;)
6923 char *(*scan)(char*, char*, char*, char*, int, int);
6925 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6926 // p, varname, strloc, subtype, startloc, varflags, quotes);
6928 #if BASH_PATTERN_SUBST
6929 /* For "${v/pattern/repl}", we must find the delimiter _before_
6930 * argstr() call expands possible variable references in pattern:
6931 * think about "v=a; a=a/; echo ${v/$a/r}" case.
6934 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6935 /* Find '/' and replace with NUL */
6937 /* The pattern can't be empty.
6938 * IOW: if the first char after "${v//" is a slash,
6939 * it does not terminate the pattern - it's the first char of the pattern:
6940 * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
6941 * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
6946 if (*repl == '\0') {
6954 /* Handle escaped slashes, e.g. "${v/\//_}" (they are CTLESC'ed by this point) */
6955 if ((unsigned char)*repl == CTLESC && repl[1])
6961 argstr_flags = EXP_TILDE;
6962 if (subtype != VSASSIGN
6963 && subtype != VSQUESTION
6965 && subtype != VSSUBSTR
6968 /* EXP_CASE keeps CTLESC's */
6969 argstr_flags = EXP_TILDE | EXP_CASE;
6971 argstr(p, argstr_flags);
6972 //bb_error_msg("str0:'%s'", (char *)stackblock() + strloc);
6973 #if BASH_PATTERN_SUBST
6976 slash_pos = expdest - ((char *)stackblock() + strloc);
6977 STPUTC('/', expdest);
6978 //bb_error_msg("repl+1:'%s'", repl + 1);
6979 argstr(repl + 1, EXP_TILDE); /* EXP_TILDE: echo "${v/x/~}" expands ~ ! */
6983 STPUTC('\0', expdest);
6984 argbackq = saveargbackq;
6985 startp = (char *)stackblock() + startloc;
6986 //bb_error_msg("str1:'%s'", (char *)stackblock() + strloc);
6990 setvar0(varname, startp);
6991 amount = startp - expdest;
6992 STADJUST(amount, expdest);
6996 varunset(p, varname, startp, varflags);
7001 int pos, len, orig_len;
7004 loc = str = stackblock() + strloc;
7006 /* Read POS in ${var:POS:LEN} */
7007 colon = strchr(loc, ':');
7008 if (colon) *colon = '\0';
7009 pos = substr_atoi(loc);
7010 if (colon) *colon = ':';
7012 /* Read LEN in ${var:POS:LEN} */
7013 len = str - startp - 1;
7014 /* *loc != '\0', guaranteed by parser */
7017 /* Adjust the length by the number of escapes */
7018 for (ptr = startp; ptr < (str - 1); ptr++) {
7019 if ((unsigned char)*ptr == CTLESC) {
7026 if (*loc++ == ':') {
7028 len = substr_atoi(loc);
7030 /* Skip POS in ${var:POS:LEN} */
7032 while (*loc && *loc != ':')
7035 len = substr_atoi(loc);
7038 /* ${VAR:$((-n)):l} starts n chars from the end */
7039 pos = orig_len + pos;
7041 if ((unsigned)pos >= orig_len) {
7042 /* apart from obvious ${VAR:999999:l},
7043 * covers ${VAR:$((-9999999)):l} - result is ""
7050 /* ${VAR:N:-M} sets LEN to strlen()-M */
7051 len = (orig_len - pos) + len;
7053 if ((unsigned)len > (orig_len - pos))
7054 len = orig_len - pos;
7056 for (str = startp; pos; str++, pos--) {
7057 if (quotes && (unsigned char)*str == CTLESC)
7060 for (loc = startp; len; len--) {
7061 if (quotes && (unsigned char)*str == CTLESC)
7066 amount = loc - expdest;
7067 STADJUST(amount, expdest);
7070 #endif /* BASH_SUBSTR */
7073 resetloc = expdest - (char *)stackblock();
7075 #if BASH_PATTERN_SUBST
7078 /* We'll comeback here if we grow the stack while handling
7079 * a VSREPLACE or VSREPLACEALL, since our pointers into the
7080 * stack will need rebasing, and we'll need to remove our work
7086 amount = expdest - ((char *)stackblock() + resetloc);
7087 STADJUST(-amount, expdest);
7088 startp = (char *)stackblock() + startloc;
7091 rmescend = (char *)stackblock() + strloc;
7092 //bb_error_msg("str7:'%s'", rmescend);
7094 //TODO: how to handle slash_pos here if string changes (shortens?)
7095 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW, NULL);
7096 if (rmesc != startp) {
7098 startp = (char *)stackblock() + startloc;
7102 str = (char *)stackblock() + strloc;
7104 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
7105 * The result is a_\_z_c (not a\_\_z_c)!
7107 * The search pattern and replace string treat backslashes differently!
7108 * "&slash_pos" causes rmescapes() to work differently on the pattern
7109 * and string. It's only used on the first call.
7111 //bb_error_msg("str8:'%s' slash_pos:%d", str, slash_pos);
7112 rmescapes(str, RMESCAPE_GLOB,
7113 repl ? NULL : (slash_pos < 0 ? NULL : &slash_pos)
7116 #if BASH_PATTERN_SUBST
7117 workloc = expdest - (char *)stackblock();
7118 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
7123 //bb_error_msg("str9:'%s' slash_pos:%d", str, slash_pos);
7125 if (slash_pos >= 0) {
7126 repl = str + slash_pos;
7130 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
7132 /* If there's no pattern to match, return the expansion unmolested */
7141 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
7142 //bb_error_msg("scanright('%s'):'%s'", str, loc);
7144 /* No match, advance */
7145 char *restart_detect = stackblock();
7147 STPUTC(*idx, expdest);
7148 if (quotes && (unsigned char)*idx == CTLESC) {
7151 STPUTC(*idx, expdest);
7153 if (stackblock() != restart_detect)
7158 /* continue; - prone to quadratic behavior, smarter code: */
7161 if (str[0] == '*') {
7162 /* Pattern is "*foo". If "*foo" does not match "long_string",
7163 * it would never match "ong_string" etc, no point in trying.
7170 if (subtype == VSREPLACEALL) {
7172 if (quotes && (unsigned char)*idx == CTLESC)
7181 //bb_error_msg("repl:'%s'", repl);
7182 for (loc = (char*)repl; *loc; loc++) {
7183 char *restart_detect = stackblock();
7184 if (quotes && *loc == '\\') {
7185 STPUTC(CTLESC, expdest);
7188 STPUTC(*loc, expdest);
7189 if (stackblock() != restart_detect)
7194 if (subtype == VSREPLACE) {
7195 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
7197 char *restart_detect = stackblock();
7198 STPUTC(*idx, expdest);
7199 if (stackblock() != restart_detect)
7208 /* We've put the replaced text into a buffer at workloc, now
7209 * move it to the right place and adjust the stack.
7211 STPUTC('\0', expdest);
7212 startp = (char *)stackblock() + startloc;
7213 memmove(startp, (char *)stackblock() + workloc, len + 1);
7214 //bb_error_msg("startp:'%s'", startp);
7215 amount = expdest - (startp + len);
7216 STADJUST(-amount, expdest);
7219 #endif /* BASH_PATTERN_SUBST */
7221 subtype -= VSTRIMRIGHT;
7223 if (subtype < 0 || subtype > 7)
7226 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
7227 zero = subtype >> 1;
7228 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
7229 scan = (subtype & 1) ^ zero ? scanleft : scanright;
7231 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
7234 memmove(startp, loc, str - loc);
7235 loc = startp + (str - loc) - 1;
7238 amount = loc - expdest;
7239 STADJUST(amount, expdest);
7245 * Add the value of a specialized variable to the stack string.
7246 * name parameter (examples):
7247 * ash -c 'echo $1' name:'1='
7248 * ash -c 'echo $qwe' name:'qwe='
7249 * ash -c 'echo $$' name:'$='
7250 * ash -c 'echo ${$}' name:'$='
7251 * ash -c 'echo ${$##q}' name:'$=q'
7252 * ash -c 'echo ${#$}' name:'$='
7253 * note: examples with bad shell syntax:
7254 * ash -c 'echo ${#$1}' name:'$=1'
7255 * ash -c 'echo ${#1#}' name:'1=#'
7257 static NOINLINE ssize_t
7258 varvalue(char *name, int varflags, int flags, int quoted)
7265 int subtype = varflags & VSTYPE;
7266 int discard = subtype == VSPLUS || subtype == VSLENGTH;
7267 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
7270 sep = (flags & EXP_FULL) << CHAR_BIT;
7271 syntax = quoted ? DQSYNTAX : BASESYNTAX;
7281 num = shellparam.nparam;
7289 goto check_1char_name;
7291 expdest = makestrspace(NOPTS, expdest);
7292 for (i = NOPTS - 1; i >= 0; i--) {
7293 if (optlist[i] && optletters(i)) {
7294 USTPUTC(optletters(i), expdest);
7300 /* handles cases similar to ${#$1} */
7301 if (name[2] != '\0')
7302 raise_error_syntax("bad substitution");
7314 /* We will set c to 0 or ~0 depending on whether
7315 * we're doing field splitting. We won't do field
7316 * splitting if either we're quoted or sep is zero.
7318 * Instead of testing (quoted || !sep) the following
7319 * trick optimises away any branches by using the
7320 * fact that EXP_QUOTED (which is the only bit that
7321 * can be set in quoted) is the same as EXP_FULL <<
7322 * CHAR_BIT (which is the only bit that can be set
7325 #if EXP_QUOTED >> CHAR_BIT != EXP_FULL
7326 #error The following two lines expect EXP_QUOTED == EXP_FULL << CHAR_BIT
7328 c = !((quoted | ~sep) & EXP_QUOTED) - 1;
7330 sep |= ifsset() ? (unsigned char)(c & ifsval()[0]) : ' ';
7336 while ((p = *ap++) != NULL) {
7337 len += strtodest(p, syntax, quotes);
7341 memtodest(&sepc, 1, syntax, quotes);
7356 num = atoi(name); /* number(name) fails on ${N#str} etc */
7357 if (num < 0 || num > shellparam.nparam)
7359 p = num ? shellparam.p[num - 1] : arg0;
7362 /* NB: name has form "VAR=..." */
7363 p = lookupvar(name);
7368 len = strtodest(p, syntax, quotes);
7369 #if ENABLE_UNICODE_SUPPORT
7370 if (subtype == VSLENGTH && len > 0) {
7371 reinit_unicode_for_ash();
7372 if (unicode_status == UNICODE_ON) {
7373 STADJUST(-len, expdest);
7375 len = unicode_strlen(p);
7383 STADJUST(-len, expdest);
7388 * Expand a variable, and return a pointer to the next character in the
7392 evalvar(char *p, int flag)
7402 varflags = (unsigned char) *p++;
7403 subtype = varflags & VSTYPE;
7406 raise_error_syntax("bad substitution");
7408 quoted = flag & EXP_QUOTED;
7410 startloc = expdest - (char *)stackblock();
7411 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
7414 varlen = varvalue(var, varflags, flag, quoted);
7415 if (varflags & VSNUL)
7418 if (subtype == VSPLUS) {
7419 varlen = -1 - varlen;
7423 if (subtype == VSMINUS) {
7428 flag | EXP_TILDE | EXP_WORD
7435 if (subtype == VSASSIGN || subtype == VSQUESTION) {
7439 subevalvar(p, var, 0, subtype, startloc, varflags,
7440 flag & ~QUOTES_ESC);
7443 * Remove any recorded regions beyond
7446 removerecordregions(startloc);
7450 if (varlen < 0 && uflag)
7451 varunset(p, var, 0, 0);
7453 if (subtype == VSLENGTH) {
7454 cvtnum(varlen > 0 ? varlen : 0);
7458 if (subtype == VSNORMAL) {
7461 quoted = *var == '@' && shellparam.nparam;
7465 recordregion(startloc, expdest - (char *)stackblock(), quoted);
7474 case VSTRIMRIGHTMAX:
7478 #if BASH_PATTERN_SUBST
7490 * Terminate the string and start recording the pattern
7493 STPUTC('\0', expdest);
7494 patloc = expdest - (char *)stackblock();
7495 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
7496 startloc, varflags, flag)) {
7497 int amount = expdest - (
7498 (char *)stackblock() + patloc - 1
7500 STADJUST(-amount, expdest);
7502 /* Remove any recorded regions beyond start of variable */
7503 removerecordregions(startloc);
7508 if (subtype != VSNORMAL) { /* skip to end of alternative */
7511 unsigned char c = *p++;
7514 else if (c == CTLBACKQ) {
7516 argbackq = argbackq->next;
7517 } else if (c == CTLVAR) {
7518 if ((*p++ & VSTYPE) != VSNORMAL)
7520 } else if (c == CTLENDVAR) {
7530 * Add a file name to the list.
7533 addfname(const char *name)
7537 sp = stzalloc(sizeof(*sp));
7538 sp->text = sstrdup(name);
7540 exparg.lastp = &sp->next;
7543 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7545 hasmeta(const char *p)
7547 static const char chars[] ALIGN1 = {
7548 '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
7552 p = strpbrk(p, chars);
7555 switch ((unsigned char)*p) {
7559 if ((unsigned char)*p == CTLQUOTEMARK)
7561 if ((unsigned char)*p == CTLESC)
7563 if (*p == '\0') /* huh? */
7574 if (!strchr(p + 1, ']')) {
7575 /* It's not a properly closed [] pattern,
7576 * but other metas may follow. Continue checking.
7577 * my[file* _is_ globbed by bash
7578 * and matches filenames like "my[file1".
7594 /* If we want to use glob() from libc... */
7595 #if !ENABLE_ASH_INTERNAL_GLOB
7597 /* Add the result of glob() to the list */
7599 addglob(const glob_t *pglob)
7601 char **p = pglob->gl_pathv;
7608 expandmeta(struct strlist *str /*, int flag*/)
7610 /* TODO - EXP_REDIR */
7620 if (!hasmeta(str->text))
7624 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7625 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7626 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7628 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7629 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7630 // Which means you need to unescape the string, right? Not so fast:
7631 // if there _is_ a file named "file\?" (with backslash), it is returned
7632 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7633 // You DON'T KNOW by looking at the result whether you need to unescape it.
7635 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7636 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7637 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7638 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7639 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7640 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7641 i = glob(p, 0, NULL, &pglob);
7642 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7647 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7648 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7649 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7661 *exparg.lastp = str;
7662 rmescapes(str->text, 0, NULL);
7663 exparg.lastp = &str->next;
7665 default: /* GLOB_NOSPACE */
7668 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7675 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7678 * Do metacharacter (i.e. *, ?, [...]) expansion.
7680 typedef struct exp_t {
7685 expmeta(exp_t *exp, char *name, unsigned name_len, unsigned expdir_len)
7687 #define expdir exp->dir
7688 #define expdir_max exp->dir_max
7689 char *enddir = expdir + expdir_len;
7704 for (p = name; esc = 0, *p; p += esc + 1) {
7705 if (*p == '*' || *p == '?')
7707 else if (*p == '[') {
7714 if (*q == '/' || *q == '\0')
7722 if (*p == '\\' && p[1])
7724 if (p[esc] == '/') {
7727 start = p + esc + 1;
7731 if (metaflag == 0) { /* we've reached the end of the file name */
7736 if (*p == '\\' && p[1])
7740 if (lstat(expdir, &statb) == 0)
7748 if (*p == '\\' && p[1])
7751 } while (p < start);
7755 expdir_len = enddir - cp;
7761 if (*endname == 0) {
7768 name_len -= endname - name;
7775 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7776 if (dp->d_name[0] == '.' && !matchdot)
7778 if (pmatch(start, dp->d_name)) {
7780 strcpy(enddir, dp->d_name);
7786 p = stpcpy(enddir, dp->d_name);
7789 offset = p - expdir + 1;
7790 len = offset + name_len + NAME_MAX;
7791 if (len > expdir_max) {
7793 expdir = ckrealloc(expdir, len);
7797 expmeta(exp, endname, name_len, offset);
7798 enddir = expdir + expdir_len;
7804 endname[-esc - 1] = esc ? '\\' : '/';
7809 static struct strlist *
7810 msort(struct strlist *list, int len)
7812 struct strlist *p, *q = NULL;
7813 struct strlist **lpp;
7821 for (n = half; --n >= 0;) {
7825 q->next = NULL; /* terminate first half of list */
7826 q = msort(list, half); /* sort first half of list */
7827 p = msort(p, len - half); /* sort second half */
7830 #if ENABLE_LOCALE_SUPPORT
7831 if (strcoll(p->text, q->text) < 0)
7833 if (strcmp(p->text, q->text) < 0)
7857 * Sort the results of file name expansion. It calculates the number of
7858 * strings to sort and then calls msort (short for merge sort) to do the
7861 static struct strlist *
7862 expsort(struct strlist *str)
7868 for (sp = str; sp; sp = sp->next)
7870 return msort(str, len);
7874 expandmeta(struct strlist *str /*, int flag*/)
7876 /* TODO - EXP_REDIR */
7880 struct strlist **savelastp;
7887 if (!hasmeta(str->text))
7889 savelastp = exparg.lastp;
7892 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7894 exp.dir_max = len + PATH_MAX;
7895 exp.dir = ckmalloc(exp.dir_max);
7897 expmeta(&exp, p, len, 0);
7902 if (exparg.lastp == savelastp) {
7907 *exparg.lastp = str;
7908 rmescapes(str->text, 0, NULL);
7909 exparg.lastp = &str->next;
7911 *exparg.lastp = NULL;
7912 *savelastp = sp = expsort(*savelastp);
7913 while (sp->next != NULL)
7915 exparg.lastp = &sp->next;
7920 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7923 * Perform variable substitution and command substitution on an argument,
7924 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7925 * perform splitting and file name expansion. When arglist is NULL, perform
7926 * here document expansion.
7929 expandarg(union node *arg, struct arglist *arglist, int flag)
7934 argbackq = arg->narg.backquote;
7935 STARTSTACKSTR(expdest);
7936 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7937 argstr(arg->narg.text, flag);
7938 p = _STPUTC('\0', expdest);
7940 if (arglist == NULL) {
7941 /* here document expanded */
7944 p = grabstackstr(p);
7945 TRACE(("expandarg: p:'%s'\n", p));
7946 exparg.lastp = &exparg.list;
7950 if (flag & EXP_FULL) {
7951 ifsbreakup(p, &exparg);
7952 *exparg.lastp = NULL;
7953 exparg.lastp = &exparg.list;
7954 expandmeta(exparg.list /*, flag*/);
7956 sp = stzalloc(sizeof(*sp));
7959 exparg.lastp = &sp->next;
7961 *exparg.lastp = NULL;
7963 *arglist->lastp = exparg.list;
7964 arglist->lastp = exparg.lastp;
7972 * Expand shell variables and backquotes inside a here document.
7975 expandhere(union node *arg, int fd)
7977 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7978 full_write(fd, stackblock(), expdest - (char *)stackblock());
7982 * Returns true if the pattern matches the string.
7985 patmatch(char *pattern, const char *string)
7987 char *p = preglob(pattern, 0);
7988 int r = pmatch(p, string);
7989 //bb_error_msg("!fnmatch(pattern:'%s',str:'%s',0):%d", p, string, r);
7994 * See if a pattern matches in a case statement.
7997 casematch(union node *pattern, char *val)
7999 struct stackmark smark;
8002 setstackmark(&smark);
8003 argbackq = pattern->narg.backquote;
8004 STARTSTACKSTR(expdest);
8005 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
8006 STACKSTRNUL(expdest);
8008 result = patmatch(stackblock(), val);
8009 popstackmark(&smark);
8014 /* ============ find_command */
8018 int (*builtin)(int, char **) FAST_FUNC;
8019 /* unsigned flags; */
8021 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
8022 /* "regular" builtins always take precedence over commands,
8023 * regardless of PATH=....%builtin... position */
8024 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
8025 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
8028 smallint cmdtype; /* CMDxxx */
8031 /* index >= 0 for commands without path (slashes) */
8032 /* (TODO: what exactly does the value mean? PATH position?) */
8033 /* index == -1 for commands with slashes */
8034 /* index == (-2 - applet_no) for NOFORK applets */
8035 const struct builtincmd *cmd;
8036 struct funcnode *func;
8039 /* values of cmdtype */
8040 #define CMDUNKNOWN -1 /* no entry in table for command */
8041 #define CMDNORMAL 0 /* command is an executable program */
8042 #define CMDFUNCTION 1 /* command is a shell function */
8043 #define CMDBUILTIN 2 /* command is a shell builtin */
8045 /* action to find_command() */
8046 #define DO_ERR 0x01 /* prints errors */
8047 #define DO_ABS 0x02 /* checks absolute paths */
8048 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
8049 #define DO_ALTPATH 0x08 /* using alternate path */
8050 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
8052 static void find_command(char *, struct cmdentry *, int, const char *);
8055 /* ============ Hashing commands */
8058 * When commands are first encountered, they are entered in a hash table.
8059 * This ensures that a full path search will not have to be done for them
8060 * on each invocation.
8062 * We should investigate converting to a linear search, even though that
8063 * would make the command name "hash" a misnomer.
8067 struct tblentry *next; /* next entry in hash chain */
8068 union param param; /* definition of builtin function */
8069 smallint cmdtype; /* CMDxxx */
8070 char rehash; /* if set, cd done since entry created */
8071 char cmdname[1]; /* name of command */
8074 static struct tblentry **cmdtable;
8075 #define INIT_G_cmdtable() do { \
8076 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
8079 static int builtinloc = -1; /* index in path of %builtin, or -1 */
8083 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
8085 #if ENABLE_FEATURE_SH_STANDALONE
8086 if (applet_no >= 0) {
8087 if (APPLET_IS_NOEXEC(applet_no)) {
8091 popredir(/*drop:*/ 1);
8092 run_noexec_applet_and_exit(applet_no, cmd, argv);
8094 /* re-exec ourselves with the new arguments */
8095 execve(bb_busybox_exec_path, argv, envp);
8096 /* If they called chroot or otherwise made the binary no longer
8097 * executable, fall through */
8104 execve(cmd, argv, envp);
8105 } while (errno == EINTR);
8107 execve(cmd, argv, envp);
8110 if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
8111 /* Run "cmd" as a shell script:
8112 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
8113 * "If the execve() function fails with ENOEXEC, the shell
8114 * shall execute a command equivalent to having a shell invoked
8115 * with the command name as its first operand,
8116 * with any remaining arguments passed to the new shell"
8118 * That is, do not use $SHELL, user's shell, or /bin/sh;
8119 * just call ourselves.
8121 * Note that bash reads ~80 chars of the file, and if it sees
8122 * a zero byte before it sees newline, it doesn't try to
8123 * interpret it, but fails with "cannot execute binary file"
8124 * message and exit code 126. For one, this prevents attempts
8125 * to interpret foreign ELF binaries as shell scripts.
8127 argv[0] = (char*) cmd;
8128 cmd = bb_busybox_exec_path;
8129 /* NB: this is only possible because all callers of shellexec()
8130 * ensure that the argv[-1] slot exists!
8133 argv[0] = (char*) "ash";
8139 * Exec a program. Never returns. If you change this routine, you may
8140 * have to change the find_command routine as well.
8141 * argv[-1] must exist and be writable! See tryexec() for why.
8143 static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
8144 static void shellexec(char *prog, char **argv, const char *path, int idx)
8150 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
8152 envp = listvars(VEXPORT, VUNSET, /*strlist:*/ NULL, /*end:*/ NULL);
8153 if (strchr(prog, '/') != NULL
8154 #if ENABLE_FEATURE_SH_STANDALONE
8155 || (applet_no = find_applet_by_name(prog)) >= 0
8158 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
8159 if (applet_no >= 0) {
8160 /* We tried execing ourself, but it didn't work.
8161 * Maybe /proc/self/exe doesn't exist?
8170 while ((cmdname = path_advance(&path, prog)) != NULL) {
8171 if (--idx < 0 && pathopt == NULL) {
8172 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
8173 if (errno != ENOENT && errno != ENOTDIR)
8180 /* Map to POSIX errors */
8192 exitstatus = exerrno;
8193 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
8194 prog, e, suppress_int));
8195 ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
8200 printentry(struct tblentry *cmdp)
8206 idx = cmdp->param.index;
8209 name = path_advance(&path, cmdp->cmdname);
8211 } while (--idx >= 0);
8212 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
8216 * Clear out command entries. The argument specifies the first entry in
8217 * PATH which has changed.
8220 clearcmdentry(int firstchange)
8222 struct tblentry **tblp;
8223 struct tblentry **pp;
8224 struct tblentry *cmdp;
8227 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
8229 while ((cmdp = *pp) != NULL) {
8230 if ((cmdp->cmdtype == CMDNORMAL &&
8231 cmdp->param.index >= firstchange)
8232 || (cmdp->cmdtype == CMDBUILTIN &&
8233 builtinloc >= firstchange)
8246 * Locate a command in the command hash table. If "add" is nonzero,
8247 * add the command to the table if it is not already present. The
8248 * variable "lastcmdentry" is set to point to the address of the link
8249 * pointing to the entry, so that delete_cmd_entry can delete the
8252 * Interrupts must be off if called with add != 0.
8254 static struct tblentry **lastcmdentry;
8256 static struct tblentry *
8257 cmdlookup(const char *name, int add)
8259 unsigned int hashval;
8261 struct tblentry *cmdp;
8262 struct tblentry **pp;
8265 hashval = (unsigned char)*p << 4;
8267 hashval += (unsigned char)*p++;
8269 pp = &cmdtable[hashval % CMDTABLESIZE];
8270 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8271 if (strcmp(cmdp->cmdname, name) == 0)
8275 if (add && cmdp == NULL) {
8276 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
8278 /* + 1 - already done because
8279 * tblentry::cmdname is char[1] */);
8280 /*cmdp->next = NULL; - ckzalloc did it */
8281 cmdp->cmdtype = CMDUNKNOWN;
8282 strcpy(cmdp->cmdname, name);
8289 * Delete the command entry returned on the last lookup.
8292 delete_cmd_entry(void)
8294 struct tblentry *cmdp;
8297 cmdp = *lastcmdentry;
8298 *lastcmdentry = cmdp->next;
8299 if (cmdp->cmdtype == CMDFUNCTION)
8300 freefunc(cmdp->param.func);
8306 * Add a new command entry, replacing any existing command entry for
8307 * the same name - except special builtins.
8310 addcmdentry(char *name, struct cmdentry *entry)
8312 struct tblentry *cmdp;
8314 cmdp = cmdlookup(name, 1);
8315 if (cmdp->cmdtype == CMDFUNCTION) {
8316 freefunc(cmdp->param.func);
8318 cmdp->cmdtype = entry->cmdtype;
8319 cmdp->param = entry->u;
8323 static int FAST_FUNC
8324 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8326 struct tblentry **pp;
8327 struct tblentry *cmdp;
8329 struct cmdentry entry;
8332 if (nextopt("r") != '\0') {
8337 if (*argptr == NULL) {
8338 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8339 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8340 if (cmdp->cmdtype == CMDNORMAL)
8348 while ((name = *argptr) != NULL) {
8349 cmdp = cmdlookup(name, 0);
8351 && (cmdp->cmdtype == CMDNORMAL
8352 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
8356 find_command(name, &entry, DO_ERR, pathval());
8357 if (entry.cmdtype == CMDUNKNOWN)
8365 * Called when a cd is done. Marks all commands so the next time they
8366 * are executed they will be rehashed.
8371 struct tblentry **pp;
8372 struct tblentry *cmdp;
8374 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8375 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8376 if (cmdp->cmdtype == CMDNORMAL
8377 || (cmdp->cmdtype == CMDBUILTIN
8378 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
8388 * Fix command hash table when PATH changed.
8389 * Called before PATH is changed. The argument is the new value of PATH;
8390 * pathval() still returns the old value at this point.
8391 * Called with interrupts off.
8393 static void FAST_FUNC
8394 changepath(const char *new)
8402 firstchange = 9999; /* assume no change */
8408 if ((*old == '\0' && *new == ':')
8409 || (*old == ':' && *new == '\0')
8413 old = new; /* ignore subsequent differences */
8417 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
8424 if (builtinloc < 0 && idx_bltin >= 0)
8425 builtinloc = idx_bltin; /* zap builtins */
8426 if (builtinloc >= 0 && idx_bltin < 0)
8428 clearcmdentry(firstchange);
8429 builtinloc = idx_bltin;
8465 typedef smallint token_id_t;
8467 /* Nth bit indicates if token marks the end of a list */
8470 /* 0 */ | (1u << TEOF)
8471 /* 1 */ | (0u << TNL)
8472 /* 2 */ | (0u << TREDIR)
8473 /* 3 */ | (0u << TWORD)
8474 /* 4 */ | (0u << TSEMI)
8475 /* 5 */ | (0u << TBACKGND)
8476 /* 6 */ | (0u << TAND)
8477 /* 7 */ | (0u << TOR)
8478 /* 8 */ | (0u << TPIPE)
8479 /* 9 */ | (0u << TLP)
8480 /* 10 */ | (1u << TRP)
8481 /* 11 */ | (1u << TENDCASE)
8482 /* 12 */ | (1u << TENDBQUOTE)
8483 /* 13 */ | (0u << TNOT)
8484 /* 14 */ | (0u << TCASE)
8485 /* 15 */ | (1u << TDO)
8486 /* 16 */ | (1u << TDONE)
8487 /* 17 */ | (1u << TELIF)
8488 /* 18 */ | (1u << TELSE)
8489 /* 19 */ | (1u << TESAC)
8490 /* 20 */ | (1u << TFI)
8491 /* 21 */ | (0u << TFOR)
8493 /* 22 */ | (0u << TFUNCTION)
8495 /* 23 */ | (0u << TIF)
8496 /* 24 */ | (0u << TIN)
8497 /* 25 */ | (1u << TTHEN)
8498 /* 26 */ | (0u << TUNTIL)
8499 /* 27 */ | (0u << TWHILE)
8500 /* 28 */ | (0u << TBEGIN)
8501 /* 29 */ | (1u << TEND)
8502 , /* thus far 29 bits used */
8505 static const char *const tokname_array[] = {
8519 #define KWDOFFSET 13
8520 /* the following are keywords */
8542 /* Wrapper around strcmp for qsort/bsearch/... */
8544 pstrcmp(const void *a, const void *b)
8546 return strcmp((char*)a, *(char**)b);
8549 static const char *const *
8550 findkwd(const char *s)
8552 return bsearch(s, tokname_array + KWDOFFSET,
8553 ARRAY_SIZE(tokname_array) - KWDOFFSET,
8554 sizeof(tokname_array[0]), pstrcmp);
8558 * Locate and print what a word is...
8561 describe_command(char *command, const char *path, int describe_command_verbose)
8563 struct cmdentry entry;
8564 #if ENABLE_ASH_ALIAS
8565 const struct alias *ap;
8568 path = path ? path : pathval();
8570 if (describe_command_verbose) {
8574 /* First look at the keywords */
8575 if (findkwd(command)) {
8576 out1str(describe_command_verbose ? " is a shell keyword" : command);
8580 #if ENABLE_ASH_ALIAS
8581 /* Then look at the aliases */
8582 ap = lookupalias(command, 0);
8584 if (!describe_command_verbose) {
8589 out1fmt(" is an alias for %s", ap->val);
8594 find_command(command, &entry, DO_ABS, path);
8596 switch (entry.cmdtype) {
8598 int j = entry.u.index;
8604 p = path_advance(&path, command);
8608 if (describe_command_verbose) {
8609 out1fmt(" is %s", p);
8617 if (describe_command_verbose) {
8618 /*out1str(" is a shell function");*/
8619 out1str(" is a function"); /* bash says this */
8626 if (describe_command_verbose) {
8627 out1fmt(" is a %sshell builtin",
8628 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8629 "special " : nullstr
8637 if (describe_command_verbose) {
8638 out1str(": not found\n");
8647 static int FAST_FUNC
8648 typecmd(int argc UNUSED_PARAM, char **argv)
8654 /* type -p ... ? (we don't bother checking for 'p') */
8655 if (argv[1] && argv[1][0] == '-') {
8660 err |= describe_command(argv[i++], NULL, verbose);
8665 #if ENABLE_ASH_CMDCMD
8666 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8668 parse_command_args(char **argv, const char **path)
8681 if (c == '-' && !*cp) {
8689 *path = bb_default_path;
8692 /* run 'typecmd' for other options */
8701 static int FAST_FUNC
8702 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8710 const char *path = NULL;
8712 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8713 * never reaches this function.
8716 while ((c = nextopt("pvV")) != '\0')
8718 verify |= VERIFY_VERBOSE;
8720 /*verify |= VERIFY_BRIEF*/;
8726 path = bb_default_path;
8728 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8730 if (/*verify && */ cmd)
8731 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8738 /*static int funcblocksize; // size of structures in function */
8739 /*static int funcstringsize; // size of strings in node */
8740 static void *funcblock; /* block to allocate function from */
8741 static char *funcstring_end; /* end of block to allocate strings from */
8743 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8744 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8745 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8746 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8747 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8748 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8749 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8750 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8751 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8752 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8753 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8754 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8755 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8756 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8757 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8758 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8759 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8760 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8761 #if BASH_REDIR_OUTPUT
8762 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8764 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8765 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8766 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8767 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8768 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8769 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8770 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8771 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8772 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8775 static int calcsize(int funcblocksize, union node *n);
8778 sizenodelist(int funcblocksize, struct nodelist *lp)
8781 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8782 funcblocksize = calcsize(funcblocksize, lp->n);
8785 return funcblocksize;
8789 calcsize(int funcblocksize, union node *n)
8792 return funcblocksize;
8793 funcblocksize += nodesize[n->type];
8796 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8797 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8798 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8801 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8806 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8807 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8814 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8815 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8818 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8819 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8820 funcblocksize = calcsize(funcblocksize, n->nif.test);
8823 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8824 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8825 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8828 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8829 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8832 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8833 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8834 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8837 funcblocksize = calcsize(funcblocksize, n->ndefun.body);
8838 funcblocksize += SHELL_ALIGN(strlen(n->ndefun.text) + 1);
8841 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8842 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8843 funcblocksize = calcsize(funcblocksize, n->narg.next);
8846 #if BASH_REDIR_OUTPUT
8853 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8854 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8858 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8859 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8863 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8864 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8867 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8870 return funcblocksize;
8874 nodeckstrdup(char *s)
8876 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8877 return strcpy(funcstring_end, s);
8880 static union node *copynode(union node *);
8882 static struct nodelist *
8883 copynodelist(struct nodelist *lp)
8885 struct nodelist *start;
8886 struct nodelist **lpp;
8891 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8892 (*lpp)->n = copynode(lp->n);
8894 lpp = &(*lpp)->next;
8901 copynode(union node *n)
8908 funcblock = (char *) funcblock + nodesize[n->type];
8912 new->ncmd.redirect = copynode(n->ncmd.redirect);
8913 new->ncmd.args = copynode(n->ncmd.args);
8914 new->ncmd.assign = copynode(n->ncmd.assign);
8915 new->ncmd.linno = n->ncmd.linno;
8918 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8919 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8924 new->nredir.redirect = copynode(n->nredir.redirect);
8925 new->nredir.n = copynode(n->nredir.n);
8926 new->nredir.linno = n->nredir.linno;
8933 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8934 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8937 new->nif.elsepart = copynode(n->nif.elsepart);
8938 new->nif.ifpart = copynode(n->nif.ifpart);
8939 new->nif.test = copynode(n->nif.test);
8942 new->nfor.var = nodeckstrdup(n->nfor.var);
8943 new->nfor.body = copynode(n->nfor.body);
8944 new->nfor.args = copynode(n->nfor.args);
8945 new->nfor.linno = n->nfor.linno;
8948 new->ncase.cases = copynode(n->ncase.cases);
8949 new->ncase.expr = copynode(n->ncase.expr);
8950 new->ncase.linno = n->ncase.linno;
8953 new->nclist.body = copynode(n->nclist.body);
8954 new->nclist.pattern = copynode(n->nclist.pattern);
8955 new->nclist.next = copynode(n->nclist.next);
8958 new->ndefun.body = copynode(n->ndefun.body);
8959 new->ndefun.text = nodeckstrdup(n->ndefun.text);
8960 new->ndefun.linno = n->ndefun.linno;
8963 new->narg.backquote = copynodelist(n->narg.backquote);
8964 new->narg.text = nodeckstrdup(n->narg.text);
8965 new->narg.next = copynode(n->narg.next);
8968 #if BASH_REDIR_OUTPUT
8975 new->nfile.fname = copynode(n->nfile.fname);
8976 new->nfile.fd = n->nfile.fd;
8977 new->nfile.next = copynode(n->nfile.next);
8981 new->ndup.vname = copynode(n->ndup.vname);
8982 new->ndup.dupfd = n->ndup.dupfd;
8983 new->ndup.fd = n->ndup.fd;
8984 new->ndup.next = copynode(n->ndup.next);
8988 new->nhere.doc = copynode(n->nhere.doc);
8989 new->nhere.fd = n->nhere.fd;
8990 new->nhere.next = copynode(n->nhere.next);
8993 new->nnot.com = copynode(n->nnot.com);
8996 new->type = n->type;
9001 * Make a copy of a parse tree.
9003 static struct funcnode *
9004 copyfunc(union node *n)
9009 /*funcstringsize = 0;*/
9010 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
9011 f = ckzalloc(blocksize /* + funcstringsize */);
9012 funcblock = (char *) f + offsetof(struct funcnode, n);
9013 funcstring_end = (char *) f + blocksize;
9015 /* f->count = 0; - ckzalloc did it */
9020 * Define a shell function.
9023 defun(union node *func)
9025 struct cmdentry entry;
9028 entry.cmdtype = CMDFUNCTION;
9029 entry.u.func = copyfunc(func);
9030 addcmdentry(func->ndefun.text, &entry);
9034 /* Reasons for skipping commands (see comment on breakcmd routine) */
9035 #define SKIPBREAK (1 << 0)
9036 #define SKIPCONT (1 << 1)
9037 #define SKIPFUNC (1 << 2)
9038 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
9039 static int skipcount; /* number of levels to skip */
9040 static int loopnest; /* current loop nesting level */
9041 static int funcline; /* starting line number of current function, or 0 if not in a function */
9043 /* Forward decl way out to parsing code - dotrap needs it */
9044 static int evalstring(char *s, int flags);
9046 /* Called to execute a trap.
9047 * Single callsite - at the end of evaltree().
9048 * If we return non-zero, evaltree raises EXEXIT exception.
9050 * Perhaps we should avoid entering new trap handlers
9051 * while we are executing a trap handler. [is it a TODO?]
9058 uint8_t last_status;
9063 last_status = exitstatus;
9067 TRACE(("dotrap entered\n"));
9068 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
9080 /* non-trapped SIGINT is handled separately by raise_interrupt,
9081 * don't upset it by resetting gotsig[SIGINT-1] */
9082 if (sig == SIGINT && !p)
9085 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
9091 exitstatus = last_status;
9092 TRACE(("dotrap returns\n"));
9095 /* forward declarations - evaluation is fairly recursive business... */
9096 static int evalloop(union node *, int);
9097 static int evalfor(union node *, int);
9098 static int evalcase(union node *, int);
9099 static int evalsubshell(union node *, int);
9100 static void expredir(union node *);
9101 static int evalpipe(union node *, int);
9102 static int evalcommand(union node *, int);
9103 static int evalbltin(const struct builtincmd *, int, char **, int);
9104 static void prehash(union node *);
9107 * Evaluate a parse tree. The value is left in the global variable
9111 evaltree(union node *n, int flags)
9114 int (*evalfn)(union node *, int);
9115 struct stackmark smark;
9118 setstackmark(&smark);
9121 TRACE(("evaltree(NULL) called\n"));
9124 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
9131 out1fmt("Node type = %d\n", n->type);
9136 status = !evaltree(n->nnot.com, EV_TESTED);
9139 errlinno = lineno = n->nredir.linno;
9141 lineno -= funcline - 1;
9142 expredir(n->nredir.redirect);
9143 pushredir(n->nredir.redirect);
9144 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
9146 status = evaltree(n->nredir.n, flags & EV_TESTED);
9148 if (n->nredir.redirect)
9149 popredir(/*drop:*/ 0);
9152 evalfn = evalcommand;
9154 if (eflag && !(flags & EV_TESTED))
9166 evalfn = evalsubshell;
9179 #error NAND + 1 != NOR
9181 #if NOR + 1 != NSEMI
9182 #error NOR + 1 != NSEMI
9184 unsigned is_or = n->type - NAND;
9187 (flags | ((is_or >> 1) - 1)) & EV_TESTED
9189 if ((!status) == is_or || evalskip)
9195 status = evalfn(n, flags);
9199 status = evaltree(n->nif.test, EV_TESTED);
9206 if (n->nif.elsepart) {
9207 n = n->nif.elsepart;
9214 /* Not necessary. To test it:
9215 * "false; f() { qwerty; }; echo $?" should print 0.
9219 exitstatus = status;
9223 /* Order of checks below is important:
9224 * signal handlers trigger before exit caused by "set -e".
9228 if (checkexit & status)
9229 raise_exception(EXEXIT);
9230 if (flags & EV_EXIT)
9231 raise_exception(EXEXIT);
9233 popstackmark(&smark);
9234 TRACE(("leaving evaltree (no interrupts)\n"));
9241 int skip = evalskip;
9248 if (--skipcount <= 0) {
9259 evalloop(union node *n, int flags)
9270 i = evaltree(n->nbinary.ch1, EV_TESTED);
9272 if (skip == SKIPFUNC)
9276 if (n->type != NWHILE)
9280 status = evaltree(n->nbinary.ch2, flags);
9282 } while (!(skip & ~SKIPCONT));
9289 evalfor(union node *n, int flags)
9291 struct arglist arglist;
9296 errlinno = lineno = n->ncase.linno;
9298 lineno -= funcline - 1;
9300 arglist.list = NULL;
9301 arglist.lastp = &arglist.list;
9302 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
9303 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9305 *arglist.lastp = NULL;
9309 for (sp = arglist.list; sp; sp = sp->next) {
9310 setvar0(n->nfor.var, sp->text);
9311 status = evaltree(n->nfor.body, flags);
9312 if (skiploop() & ~SKIPCONT)
9321 evalcase(union node *n, int flags)
9325 struct arglist arglist;
9328 errlinno = lineno = n->ncase.linno;
9330 lineno -= funcline - 1;
9332 arglist.list = NULL;
9333 arglist.lastp = &arglist.list;
9334 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
9335 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
9336 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
9337 if (casematch(patp, arglist.list->text)) {
9338 /* Ensure body is non-empty as otherwise
9339 * EV_EXIT may prevent us from setting the
9342 if (evalskip == 0 && cp->nclist.body) {
9343 status = evaltree(cp->nclist.body, flags);
9354 * Kick off a subshell to evaluate a tree.
9357 evalsubshell(union node *n, int flags)
9360 int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
9363 errlinno = lineno = n->nredir.linno;
9365 lineno -= funcline - 1;
9367 expredir(n->nredir.redirect);
9368 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
9371 if (backgnd == FORK_FG)
9373 jp = makejob(/*n,*/ 1);
9374 if (forkshell(jp, n, backgnd) == 0) {
9379 flags &= ~EV_TESTED;
9381 redirect(n->nredir.redirect, 0);
9382 evaltreenr(n->nredir.n, flags);
9387 if (backgnd == FORK_FG)
9388 status = waitforjob(jp);
9394 * Compute the names of the files in a redirection list.
9396 static void fixredir(union node *, const char *, int);
9398 expredir(union node *n)
9402 for (redir = n; redir; redir = redir->nfile.next) {
9406 fn.lastp = &fn.list;
9407 switch (redir->type) {
9411 #if BASH_REDIR_OUTPUT
9416 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
9417 TRACE(("expredir expanded to '%s'\n", fn.list->text));
9418 #if BASH_REDIR_OUTPUT
9422 // By the design of stack allocator, the loop of this kind:
9423 // while true; do while true; do break; done </dev/null; done
9424 // will look like a memory leak: ash plans to free expfname's
9425 // of "/dev/null" as soon as it finishes running the loop
9426 // (in this case, never).
9427 // This "fix" is wrong:
9428 if (redir->nfile.expfname)
9429 stunalloc(redir->nfile.expfname);
9430 // It results in corrupted state of stacked allocations.
9432 redir->nfile.expfname = fn.list->text;
9435 case NTOFD: /* >& */
9436 if (redir->ndup.vname) {
9437 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
9438 if (fn.list == NULL)
9439 ash_msg_and_raise_error("redir error");
9440 #if BASH_REDIR_OUTPUT
9441 //FIXME: we used expandarg with different args!
9442 if (!isdigit_str9(fn.list->text)) {
9443 /* >&file, not >&fd */
9444 if (redir->nfile.fd != 1) /* 123>&file - BAD */
9445 ash_msg_and_raise_error("redir error");
9447 goto store_expfname;
9450 fixredir(redir, fn.list->text, 1);
9458 * Evaluate a pipeline. All the processes in the pipeline are children
9459 * of the process creating the pipeline. (This differs from some versions
9460 * of the shell, which make the last process in a pipeline the parent
9464 evalpipe(union node *n, int flags)
9467 struct nodelist *lp;
9473 TRACE(("evalpipe(0x%lx) called\n", (long)n));
9475 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
9479 if (n->npipe.pipe_backgnd == 0)
9481 jp = makejob(/*n,*/ pipelen);
9483 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
9487 if (pipe(pip) < 0) {
9489 ash_msg_and_raise_perror("can't create pipe");
9492 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
9506 evaltreenr(lp->n, flags);
9513 /* Don't want to trigger debugging */
9517 if (n->npipe.pipe_backgnd == 0) {
9518 status = waitforjob(jp);
9519 TRACE(("evalpipe: job done exit status %d\n", status));
9526 /* setinteractive needs this forward reference */
9527 #if EDITING_HAS_get_exe_name
9528 static const char *get_builtin_name(int i) FAST_FUNC;
9532 * Controls whether the shell is interactive or not.
9535 setinteractive(int on)
9537 static smallint is_interactive;
9539 if (++on == is_interactive)
9541 is_interactive = on;
9545 if (is_interactive > 1) {
9546 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9547 /* Looks like they want an interactive shell */
9548 static smallint did_banner;
9551 /* note: ash and hush share this string */
9552 out1fmt("\n\n%s %s\n"
9553 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
9556 "built-in shell (ash)"
9561 #if ENABLE_FEATURE_EDITING
9562 if (!line_input_state) {
9563 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
9564 # if EDITING_HAS_get_exe_name
9565 line_input_state->get_exe_name = get_builtin_name;
9578 setinteractive(iflag);
9580 #if ENABLE_FEATURE_EDITING_VI
9581 if (line_input_state) {
9583 line_input_state->flags |= VI_MODE;
9585 line_input_state->flags &= ~VI_MODE;
9588 viflag = 0; /* forcibly keep the option off */
9592 struct localvar_list {
9593 struct localvar_list *next;
9594 struct localvar *lv;
9597 static struct localvar_list *localvar_stack;
9600 * Called after a function returns.
9601 * Interrupts must be off.
9604 poplocalvars(int keep)
9606 struct localvar_list *ll;
9607 struct localvar *lvp, *next;
9611 ll = localvar_stack;
9612 localvar_stack = ll->next;
9617 while ((lvp = next) != NULL) {
9620 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9622 int bits = VSTRFIXED;
9624 if (lvp->flags != VUNSET) {
9625 if (vp->var_text == lvp->text)
9627 else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
9628 free((char*)lvp->text);
9632 vp->flags |= (lvp->flags & bits);
9635 (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
9636 unsetvar(vp->var_text);
9637 } else if (vp == NULL) { /* $- saved */
9638 memcpy(optlist, lvp->text, sizeof(optlist));
9639 free((char*)lvp->text);
9641 } else if (lvp->flags == VUNSET) {
9642 vp->flags &= ~(VSTRFIXED|VREADONLY);
9643 unsetvar(vp->var_text);
9646 vp->var_func(var_end(lvp->text));
9647 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9648 free((char*)vp->var_text);
9649 vp->flags = lvp->flags;
9650 vp->var_text = lvp->text;
9658 * Create a new localvar environment.
9660 static struct localvar_list *
9663 struct localvar_list *ll;
9666 ll = ckzalloc(sizeof(*ll));
9667 /*ll->lv = NULL; - zalloc did it */
9668 ll->next = localvar_stack;
9669 localvar_stack = ll;
9676 unwindlocalvars(struct localvar_list *stop)
9678 while (localvar_stack != stop)
9683 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9685 volatile struct shparam saveparam;
9686 struct jmploc *volatile savehandler;
9687 struct jmploc jmploc;
9691 saveparam = shellparam;
9692 savefuncline = funcline;
9693 savehandler = exception_handler;
9694 e = setjmp(jmploc.loc);
9699 exception_handler = &jmploc;
9700 shellparam.malloced = 0;
9702 funcline = func->n.ndefun.linno;
9704 shellparam.nparam = argc - 1;
9705 shellparam.p = argv + 1;
9706 #if ENABLE_ASH_GETOPTS
9707 shellparam.optind = 1;
9708 shellparam.optoff = -1;
9710 evaltree(func->n.ndefun.body, flags & EV_TESTED);
9713 funcline = savefuncline;
9715 freeparam(&shellparam);
9716 shellparam = saveparam;
9717 exception_handler = savehandler;
9719 evalskip &= ~SKIPFUNC;
9724 * Make a variable a local variable. When a variable is made local, it's
9725 * value and flags are saved in a localvar structure. The saved values
9726 * will be restored when the shell function returns. We handle the name
9727 * "-" as a special case: it makes changes to "set +-options" local
9728 * (options will be restored on return from the function).
9733 struct localvar *lvp;
9736 char *eq = strchr(name, '=');
9739 /* Cater for duplicate "local". Examples:
9740 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9741 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9743 lvp = localvar_stack->lv;
9745 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9749 * it's a duplicate "local VAR" declaration, do nothing
9756 lvp = ckzalloc(sizeof(*lvp));
9757 if (LONE_DASH(name)) {
9759 p = ckmalloc(sizeof(optlist));
9760 lvp->text = memcpy(p, optlist, sizeof(optlist));
9763 vpp = hashvar(name);
9764 vp = *findvar(vpp, name);
9766 /* variable did not exist yet */
9768 vp = setvareq(name, VSTRFIXED);
9770 vp = setvar(name, NULL, VSTRFIXED);
9771 lvp->flags = VUNSET;
9773 lvp->text = vp->var_text;
9774 lvp->flags = vp->flags;
9775 /* make sure neither "struct var" nor string gets freed
9776 * during (un)setting:
9778 vp->flags |= VSTRFIXED|VTEXTFIXED;
9782 /* "local VAR" unsets VAR: */
9783 setvar0(name, NULL);
9787 lvp->next = localvar_stack->lv;
9788 localvar_stack->lv = lvp;
9794 * The "local" command.
9796 static int FAST_FUNC
9797 localcmd(int argc UNUSED_PARAM, char **argv)
9801 if (!localvar_stack)
9802 ash_msg_and_raise_error("not in a function");
9805 while ((name = *argv++) != NULL) {
9811 static int FAST_FUNC
9812 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9817 static int FAST_FUNC
9818 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9823 static int FAST_FUNC
9824 execcmd(int argc UNUSED_PARAM, char **argv)
9827 while (nextopt("a:") != '\0')
9828 /* nextopt() sets optionarg to "-a ARGV0" */;
9834 iflag = 0; /* exit on error */
9837 /* We should set up signals for "exec CMD"
9838 * the same way as for "CMD" without "exec".
9839 * But optschanged->setinteractive->setsignal
9840 * still thought we are a root shell. Therefore, for example,
9841 * SIGQUIT is still set to IGN. Fix it:
9845 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9846 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9847 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9851 argv[0] = optionarg;
9852 shellexec(prog, argv, pathval(), 0);
9859 * The return command.
9861 static int FAST_FUNC
9862 returncmd(int argc UNUSED_PARAM, char **argv)
9865 * If called outside a function, do what ksh does;
9866 * skip the rest of the file.
9868 evalskip = SKIPFUNC;
9869 return argv[1] ? number(argv[1]) : exitstatus;
9872 /* Forward declarations for builtintab[] */
9873 static int breakcmd(int, char **) FAST_FUNC;
9874 static int dotcmd(int, char **) FAST_FUNC;
9875 static int evalcmd(int, char **, int) FAST_FUNC;
9876 static int exitcmd(int, char **) FAST_FUNC;
9877 static int exportcmd(int, char **) FAST_FUNC;
9878 #if ENABLE_ASH_GETOPTS
9879 static int getoptscmd(int, char **) FAST_FUNC;
9882 static int helpcmd(int, char **) FAST_FUNC;
9885 static int historycmd(int, char **) FAST_FUNC;
9887 #if ENABLE_FEATURE_SH_MATH
9888 static int letcmd(int, char **) FAST_FUNC;
9890 static int readcmd(int, char **) FAST_FUNC;
9891 static int setcmd(int, char **) FAST_FUNC;
9892 static int shiftcmd(int, char **) FAST_FUNC;
9893 static int timescmd(int, char **) FAST_FUNC;
9894 static int trapcmd(int, char **) FAST_FUNC;
9895 static int umaskcmd(int, char **) FAST_FUNC;
9896 static int unsetcmd(int, char **) FAST_FUNC;
9897 static int ulimitcmd(int, char **) FAST_FUNC;
9899 #define BUILTIN_NOSPEC "0"
9900 #define BUILTIN_SPECIAL "1"
9901 #define BUILTIN_REGULAR "2"
9902 #define BUILTIN_SPEC_REG "3"
9903 #define BUILTIN_ASSIGN "4"
9904 #define BUILTIN_SPEC_ASSG "5"
9905 #define BUILTIN_REG_ASSG "6"
9906 #define BUILTIN_SPEC_REG_ASSG "7"
9908 /* Stubs for calling non-FAST_FUNC's */
9910 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9912 #if ENABLE_ASH_PRINTF
9913 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9915 #if ENABLE_ASH_TEST || BASH_TEST2
9916 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9919 /* Keep these in proper order since it is searched via bsearch() */
9920 static const struct builtincmd builtintab[] = {
9921 { BUILTIN_SPEC_REG "." , dotcmd },
9922 { BUILTIN_SPEC_REG ":" , truecmd },
9924 { BUILTIN_REGULAR "[" , testcmd },
9927 { BUILTIN_REGULAR "[[" , testcmd },
9929 #if ENABLE_ASH_ALIAS
9930 { BUILTIN_REG_ASSG "alias" , aliascmd },
9933 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9935 { BUILTIN_SPEC_REG "break" , breakcmd },
9936 { BUILTIN_REGULAR "cd" , cdcmd },
9937 { BUILTIN_NOSPEC "chdir" , cdcmd },
9938 #if ENABLE_ASH_CMDCMD
9939 { BUILTIN_REGULAR "command" , commandcmd },
9941 { BUILTIN_SPEC_REG "continue", breakcmd },
9943 { BUILTIN_REGULAR "echo" , echocmd },
9945 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9946 { BUILTIN_SPEC_REG "exec" , execcmd },
9947 { BUILTIN_SPEC_REG "exit" , exitcmd },
9948 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9949 { BUILTIN_REGULAR "false" , falsecmd },
9951 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9953 #if ENABLE_ASH_GETOPTS
9954 { BUILTIN_REGULAR "getopts" , getoptscmd },
9956 { BUILTIN_NOSPEC "hash" , hashcmd },
9958 { BUILTIN_NOSPEC "help" , helpcmd },
9961 { BUILTIN_NOSPEC "history" , historycmd },
9964 { BUILTIN_REGULAR "jobs" , jobscmd },
9965 { BUILTIN_REGULAR "kill" , killcmd },
9967 #if ENABLE_FEATURE_SH_MATH
9968 { BUILTIN_NOSPEC "let" , letcmd },
9970 { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
9971 #if ENABLE_ASH_PRINTF
9972 { BUILTIN_REGULAR "printf" , printfcmd },
9974 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9975 { BUILTIN_REGULAR "read" , readcmd },
9976 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9977 { BUILTIN_SPEC_REG "return" , returncmd },
9978 { BUILTIN_SPEC_REG "set" , setcmd },
9979 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9981 { BUILTIN_SPEC_REG "source" , dotcmd },
9984 { BUILTIN_REGULAR "test" , testcmd },
9986 { BUILTIN_SPEC_REG "times" , timescmd },
9987 { BUILTIN_SPEC_REG "trap" , trapcmd },
9988 { BUILTIN_REGULAR "true" , truecmd },
9989 { BUILTIN_NOSPEC "type" , typecmd },
9990 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9991 { BUILTIN_REGULAR "umask" , umaskcmd },
9992 #if ENABLE_ASH_ALIAS
9993 { BUILTIN_REGULAR "unalias" , unaliascmd },
9995 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9996 { BUILTIN_REGULAR "wait" , waitcmd },
9999 /* Should match the above table! */
10000 #define COMMANDCMD (builtintab + \
10002 /* [ */ 1 * ENABLE_ASH_TEST + \
10003 /* [[ */ 1 * BASH_TEST2 + \
10004 /* alias */ 1 * ENABLE_ASH_ALIAS + \
10005 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
10006 /* break cd cddir */ 3)
10007 #define EVALCMD (COMMANDCMD + \
10008 /* command */ 1 * ENABLE_ASH_CMDCMD + \
10009 /* continue */ 1 + \
10010 /* echo */ 1 * ENABLE_ASH_ECHO + \
10012 #define EXECCMD (EVALCMD + \
10016 * Search the table of builtin commands.
10019 pstrcmp1(const void *a, const void *b)
10021 return strcmp((char*)a, *(char**)b + 1);
10023 static struct builtincmd *
10024 find_builtin(const char *name)
10026 struct builtincmd *bp;
10029 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
10035 #if EDITING_HAS_get_exe_name
10036 static const char * FAST_FUNC
10037 get_builtin_name(int i)
10039 return /*i >= 0 &&*/ i < ARRAY_SIZE(builtintab) ? builtintab[i].name + 1 : NULL;
10044 * Execute a simple command.
10046 static void unwindfiles(struct parsefile *stop);
10048 isassignment(const char *p)
10050 const char *q = endofname(p);
10055 static int FAST_FUNC
10056 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10058 /* Preserve exitstatus of a previous possible redirection
10059 * as POSIX mandates */
10060 return back_exitstatus;
10063 evalcommand(union node *cmd, int flags)
10065 static const struct builtincmd null_bltin = {
10066 "\0\0", bltincmd /* why three NULs? */
10068 struct localvar_list *localvar_stop;
10069 struct parsefile *file_stop;
10070 struct redirtab *redir_stop;
10072 struct arglist arglist;
10073 struct arglist varlist;
10076 const struct strlist *sp;
10077 struct cmdentry cmdentry;
10084 smallint cmd_is_exec;
10086 errlinno = lineno = cmd->ncmd.linno;
10088 lineno -= funcline - 1;
10090 /* First expand the arguments. */
10091 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
10092 localvar_stop = pushlocalvars();
10093 file_stop = g_parsefile;
10094 back_exitstatus = 0;
10096 cmdentry.cmdtype = CMDBUILTIN;
10097 cmdentry.u.cmd = &null_bltin;
10098 varlist.lastp = &varlist.list;
10099 *varlist.lastp = NULL;
10100 arglist.lastp = &arglist.list;
10101 *arglist.lastp = NULL;
10104 if (cmd->ncmd.args) {
10105 struct builtincmd *bcmd;
10106 smallint pseudovarflag;
10108 bcmd = find_builtin(cmd->ncmd.args->narg.text);
10109 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
10111 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
10112 struct strlist **spp;
10114 spp = arglist.lastp;
10115 if (pseudovarflag && isassignment(argp->narg.text))
10116 expandarg(argp, &arglist, EXP_VARTILDE);
10118 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
10120 for (sp = *spp; sp; sp = sp->next)
10125 /* Reserve one extra spot at the front for shellexec. */
10126 nargv = stalloc(sizeof(char *) * (argc + 2));
10128 for (sp = arglist.list; sp; sp = sp->next) {
10129 TRACE(("evalcommand arg: %s\n", sp->text));
10130 *nargv++ = sp->text;
10135 if (iflag && funcline == 0 && argc > 0)
10136 lastarg = nargv[-1];
10138 expredir(cmd->ncmd.redirect);
10139 redir_stop = pushredir(cmd->ncmd.redirect);
10141 if (BASH_XTRACEFD && xflag) {
10142 /* NB: bash closes fd == $BASH_XTRACEFD when it is changed.
10143 * we do not emulate this. We only use its value.
10145 const char *xtracefd = lookupvar("BASH_XTRACEFD");
10146 if (xtracefd && is_number(xtracefd))
10147 preverrout_fd = atoi(xtracefd);
10150 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
10152 path = vpath.var_text;
10153 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
10154 struct strlist **spp;
10157 spp = varlist.lastp;
10158 expandarg(argp, &varlist, EXP_VARTILDE);
10160 mklocal((*spp)->text);
10163 * Modify the command lookup path, if a PATH= assignment
10167 if (varcmp(p, path) == 0)
10171 /* Print the command if xflag is set. */
10173 const char *pfx = "";
10175 fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
10179 char *varval = sp->text;
10180 char *eq = strchrnul(varval, '=');
10183 fdprintf(preverrout_fd, "%s%.*s%s",
10185 (int)(eq - varval), varval,
10186 maybe_single_quote(eq)
10194 fdprintf(preverrout_fd, "%s%s",
10196 /* always quote if matches reserved word: */
10198 ? single_quote(sp->text)
10199 : maybe_single_quote(sp->text)
10204 safe_write(preverrout_fd, "\n", 1);
10210 /* Now locate the command. */
10212 int cmd_flag = DO_ERR;
10213 #if ENABLE_ASH_CMDCMD
10214 const char *oldpath = path + 5;
10218 find_command(argv[0], &cmdentry, cmd_flag, path);
10219 if (cmdentry.cmdtype == CMDUNKNOWN) {
10220 flush_stdout_stderr();
10225 /* implement bltin and command here */
10226 if (cmdentry.cmdtype != CMDBUILTIN)
10229 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
10230 if (cmdentry.u.cmd == EXECCMD)
10232 #if ENABLE_ASH_CMDCMD
10233 if (cmdentry.u.cmd == COMMANDCMD) {
10235 nargv = parse_command_args(argv, &path);
10238 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
10239 * nargv => "PROG". path is updated if -p.
10241 argc -= nargv - argv;
10243 cmd_flag |= DO_NOFUNC;
10252 exitstatus = status;
10254 /* We have a redirection error. */
10256 raise_exception(EXERROR);
10261 /* Execute the command. */
10262 switch (cmdentry.cmdtype) {
10265 #if ENABLE_FEATURE_SH_STANDALONE \
10266 && ENABLE_FEATURE_SH_NOFORK \
10268 /* (1) BUG: if variables are set, we need to fork, or save/restore them
10269 * around run_nofork_applet() call.
10270 * (2) Should this check also be done in forkshell()?
10271 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
10273 /* find_command() encodes applet_no as (-2 - applet_no) */
10274 int applet_no = (- cmdentry.u.index - 2);
10275 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
10279 sv_environ = environ;
10280 environ = listvars(VEXPORT, VUNSET, varlist.list, /*end:*/ NULL);
10282 * Run <applet>_main().
10283 * Signals (^C) can't interrupt here.
10284 * Otherwise we can mangle stdio or malloc internal state.
10285 * This makes applets which can run for a long time
10286 * and/or wait for user input ineligible for NOFORK:
10287 * for example, "yes" or "rm" (rm -i waits for input).
10289 status = run_nofork_applet(applet_no, argv);
10290 environ = sv_environ;
10292 * Try enabling NOFORK for "yes" applet.
10293 * ^C _will_ stop it (write returns EINTR),
10294 * but this causes stdout FILE to be stuck
10295 * and needing clearerr(). What if other applets
10296 * also can get EINTRs? Do we need to switch
10297 * our signals to SA_RESTART?
10299 /*clearerr(stdout);*/
10304 /* Can we avoid forking? For example, very last command
10305 * in a script or a subshell does not need forking,
10306 * we can just exec it.
10308 if (!(flags & EV_EXIT) || may_have_traps) {
10309 /* No, forking off a child is necessary */
10312 jp = makejob(/*cmd,*/ 1);
10313 if (forkshell(jp, cmd, FORK_FG) != 0) {
10315 status = waitforjob(jp);
10317 TRACE(("forked child exited with %d\n", status));
10322 /* fall through to exec'ing external program */
10324 listsetvar(varlist.list, VEXPORT|VSTACK);
10325 shellexec(argv[0], argv, path, cmdentry.u.index);
10329 if (spclbltin > 0 || argc == 0) {
10331 if (cmd_is_exec && argc > 1)
10332 listsetvar(varlist.list, VEXPORT);
10335 /* Tight loop with builtins only:
10336 * "while kill -0 $child; do true; done"
10337 * will never exit even if $child died, unless we do this
10338 * to reap the zombie and make kill detect that it's gone: */
10339 dowait(DOWAIT_NONBLOCK, NULL);
10341 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
10342 if (exception_type == EXERROR && spclbltin <= 0) {
10347 longjmp(exception_handler->loc, 1);
10352 /* See above for the rationale */
10353 dowait(DOWAIT_NONBLOCK, NULL);
10354 if (evalfun(cmdentry.u.func, argc, argv, flags))
10357 status = exitstatus;
10362 if (cmd->ncmd.redirect)
10363 popredir(/*drop:*/ cmd_is_exec);
10364 unwindredir(redir_stop);
10365 unwindfiles(file_stop);
10366 unwindlocalvars(localvar_stop);
10368 /* dsl: I think this is intended to be used to support
10369 * '_' in 'vi' command mode during line editing...
10370 * However I implemented that within libedit itself.
10372 setvar0("_", lastarg);
10379 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
10381 char *volatile savecmdname;
10382 struct jmploc *volatile savehandler;
10383 struct jmploc jmploc;
10387 savecmdname = commandname;
10388 savehandler = exception_handler;
10389 i = setjmp(jmploc.loc);
10392 exception_handler = &jmploc;
10393 commandname = argv[0];
10395 optptr = NULL; /* initialize nextopt */
10396 if (cmd == EVALCMD)
10397 status = evalcmd(argc, argv, flags);
10399 status = (*cmd->builtin)(argc, argv);
10400 flush_stdout_stderr();
10401 status |= ferror(stdout);
10402 exitstatus = status;
10405 commandname = savecmdname;
10406 exception_handler = savehandler;
10412 goodname(const char *p)
10414 return endofname(p)[0] == '\0';
10419 * Search for a command. This is called before we fork so that the
10420 * location of the command will be available in the parent as well as
10421 * the child. The check for "goodname" is an overly conservative
10422 * check that the name will not be subject to expansion.
10425 prehash(union node *n)
10427 struct cmdentry entry;
10429 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
10430 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
10434 /* ============ Builtin commands
10436 * Builtin commands whose functions are closely tied to evaluation
10437 * are implemented here.
10441 * Handle break and continue commands. Break, continue, and return are
10442 * all handled by setting the evalskip flag. The evaluation routines
10443 * above all check this flag, and if it is set they start skipping
10444 * commands rather than executing them. The variable skipcount is
10445 * the number of loops to break/continue, or the number of function
10446 * levels to return. (The latter is always 1.) It should probably
10447 * be an error to break out of more loops than exist, but it isn't
10448 * in the standard shell so we don't make it one here.
10450 static int FAST_FUNC
10451 breakcmd(int argc UNUSED_PARAM, char **argv)
10453 int n = argv[1] ? number(argv[1]) : 1;
10456 ash_msg_and_raise_error(msg_illnum, argv[1]);
10460 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
10468 * This implements the input routines used by the parser.
10472 INPUT_PUSH_FILE = 1,
10473 INPUT_NOFILE_OK = 2,
10476 static smallint checkkwd;
10477 /* values of checkkwd variable */
10478 #define CHKALIAS 0x1
10481 #define CHKEOFMARK 0x8
10484 * Push a string back onto the input at this current parsefile level.
10485 * We handle aliases this way.
10487 #if !ENABLE_ASH_ALIAS
10488 #define pushstring(s, ap) pushstring(s)
10491 pushstring(char *s, struct alias *ap)
10493 struct strpush *sp;
10498 if (g_parsefile->strpush) {
10499 sp = ckzalloc(sizeof(*sp));
10500 sp->prev = g_parsefile->strpush;
10502 sp = &(g_parsefile->basestrpush);
10504 g_parsefile->strpush = sp;
10505 sp->prev_string = g_parsefile->next_to_pgetc;
10506 sp->prev_left_in_line = g_parsefile->left_in_line;
10507 sp->unget = g_parsefile->unget;
10508 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
10509 #if ENABLE_ASH_ALIAS
10512 ap->flag |= ALIASINUSE;
10516 g_parsefile->next_to_pgetc = s;
10517 g_parsefile->left_in_line = len;
10518 g_parsefile->unget = 0;
10525 struct strpush *sp = g_parsefile->strpush;
10528 #if ENABLE_ASH_ALIAS
10530 if (g_parsefile->next_to_pgetc[-1] == ' '
10531 || g_parsefile->next_to_pgetc[-1] == '\t'
10533 checkkwd |= CHKALIAS;
10535 if (sp->string != sp->ap->val) {
10538 sp->ap->flag &= ~ALIASINUSE;
10539 if (sp->ap->flag & ALIASDEAD) {
10540 unalias(sp->ap->name);
10544 g_parsefile->next_to_pgetc = sp->prev_string;
10545 g_parsefile->left_in_line = sp->prev_left_in_line;
10546 g_parsefile->unget = sp->unget;
10547 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
10548 g_parsefile->strpush = sp->prev;
10549 if (sp != &(g_parsefile->basestrpush))
10558 char *buf = g_parsefile->buf;
10560 g_parsefile->next_to_pgetc = buf;
10561 #if ENABLE_FEATURE_EDITING
10563 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
10564 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10566 # if ENABLE_ASH_IDLE_TIMEOUT
10568 const char *tmout_var = lookupvar("TMOUT");
10570 timeout = atoi(tmout_var) * 1000;
10574 line_input_state->timeout = timeout;
10576 # if ENABLE_FEATURE_TAB_COMPLETION
10577 line_input_state->path_lookup = pathval();
10579 reinit_unicode_for_ash();
10580 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ);
10582 /* ^C pressed, "convert" to SIGINT */
10583 write(STDOUT_FILENO, "^C", 2);
10584 if (trap[SIGINT]) {
10590 exitstatus = 128 + SIGINT;
10596 /* Ctrl+D pressed */
10599 # if ENABLE_ASH_IDLE_TIMEOUT
10600 else if (errno == EAGAIN && timeout > 0) {
10601 puts("\007timed out waiting for input: auto-logout");
10608 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10611 #if 0 /* disabled: nonblock_immune_read() handles this problem */
10613 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
10614 int flags = fcntl(0, F_GETFL);
10615 if (flags >= 0 && (flags & O_NONBLOCK)) {
10616 flags &= ~O_NONBLOCK;
10617 if (fcntl(0, F_SETFL, flags) >= 0) {
10618 out2str("sh: turning off NDELAY mode\n");
10629 * Refill the input buffer and return the next input character:
10631 * 1) If a string was pushed back on the input, pop it;
10632 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
10633 * or we are reading from a string so we can't refill the buffer,
10635 * 3) If there is more stuff in this buffer, use it else call read to fill it.
10636 * 4) Process input up to the next newline, deleting nul characters.
10638 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
10639 #define pgetc_debug(...) ((void)0)
10640 static int pgetc(void);
10647 if (g_parsefile->strpush) {
10648 #if ENABLE_ASH_ALIAS
10649 if (g_parsefile->left_in_line == -1
10650 && g_parsefile->strpush->ap
10651 && g_parsefile->next_to_pgetc[-1] != ' '
10652 && g_parsefile->next_to_pgetc[-1] != '\t'
10654 pgetc_debug("preadbuffer PEOA");
10661 /* on both branches above g_parsefile->left_in_line < 0.
10662 * "pgetc" needs refilling.
10665 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
10666 * pungetc() may increment it a few times.
10667 * Assuming it won't increment it to less than -90.
10669 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
10670 pgetc_debug("preadbuffer PEOF1");
10671 /* even in failure keep left_in_line and next_to_pgetc
10672 * in lock step, for correct multi-layer pungetc.
10673 * left_in_line was decremented before preadbuffer(),
10674 * must inc next_to_pgetc: */
10675 g_parsefile->next_to_pgetc++;
10679 more = g_parsefile->left_in_buffer;
10681 flush_stdout_stderr();
10685 /* don't try reading again */
10686 g_parsefile->left_in_line = -99;
10687 pgetc_debug("preadbuffer PEOF2");
10688 g_parsefile->next_to_pgetc++;
10693 /* Find out where's the end of line.
10694 * Set g_parsefile->left_in_line
10695 * and g_parsefile->left_in_buffer acordingly.
10696 * NUL chars are deleted.
10698 q = g_parsefile->next_to_pgetc;
10706 memmove(q, q + 1, more);
10710 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10716 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10717 if (g_parsefile->left_in_line < 0)
10722 g_parsefile->left_in_buffer = more;
10727 out2str(g_parsefile->next_to_pgetc);
10731 pgetc_debug("preadbuffer at %d:%p'%s'",
10732 g_parsefile->left_in_line,
10733 g_parsefile->next_to_pgetc,
10734 g_parsefile->next_to_pgetc);
10735 return (unsigned char)*g_parsefile->next_to_pgetc++;
10741 g_parsefile->linno++;
10742 setprompt_if(doprompt, 2);
10747 g_parsefile->linno++;
10748 needprompt = doprompt;
10756 pgetc_debug("pgetc at %d:%p'%s'",
10757 g_parsefile->left_in_line,
10758 g_parsefile->next_to_pgetc,
10759 g_parsefile->next_to_pgetc);
10760 if (g_parsefile->unget)
10761 return g_parsefile->lastc[--g_parsefile->unget];
10763 if (--g_parsefile->left_in_line >= 0)
10764 c = (unsigned char)*g_parsefile->next_to_pgetc++;
10768 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10769 g_parsefile->lastc[0] = c;
10774 #if ENABLE_ASH_ALIAS
10776 pgetc_without_PEOA(void)
10780 pgetc_debug("pgetc at %d:%p'%s'",
10781 g_parsefile->left_in_line,
10782 g_parsefile->next_to_pgetc,
10783 g_parsefile->next_to_pgetc);
10785 } while (c == PEOA);
10789 # define pgetc_without_PEOA() pgetc()
10793 * Undo a call to pgetc. Only two characters may be pushed back.
10794 * PEOF may be pushed back.
10799 g_parsefile->unget++;
10802 /* This one eats backslash+newline */
10808 while ((c = pgetc()) == '\\') {
10809 if (pgetc() != '\n') {
10822 uint8_t innerdq :1;
10823 uint8_t varpushed :1;
10824 uint8_t dblquote :1;
10825 int varnest; /* levels of variables expansion */
10826 int dqvarnest; /* levels of variables expansion within double quotes */
10827 int parenlevel; /* levels of parens in arithmetic */
10828 struct synstack *prev;
10829 struct synstack *next;
10833 synstack_push(struct synstack **stack, struct synstack *next, int syntax)
10835 memset(next, 0, sizeof(*next));
10836 next->syntax = syntax;
10837 next->next = *stack;
10838 (*stack)->prev = next;
10842 static ALWAYS_INLINE void
10843 synstack_pop(struct synstack **stack)
10845 *stack = (*stack)->next;
10849 * To handle the "." command, a stack of input files is used. Pushfile
10850 * adds a new entry to the stack and popfile restores the previous level.
10855 struct parsefile *pf;
10857 pf = ckzalloc(sizeof(*pf));
10858 pf->prev = g_parsefile;
10860 /*pf->strpush = NULL; - ckzalloc did it */
10861 /*pf->basestrpush.prev = NULL;*/
10869 struct parsefile *pf = g_parsefile;
10875 if (pf->pf_fd >= 0)
10878 while (pf->strpush)
10880 g_parsefile = pf->prev;
10886 unwindfiles(struct parsefile *stop)
10888 while (g_parsefile != stop)
10893 * Return to top level.
10898 unwindfiles(&basepf);
10902 * Close the file(s) that the shell is reading commands from. Called
10903 * after a fork is done.
10909 if (g_parsefile->pf_fd > 0) {
10910 close(g_parsefile->pf_fd);
10911 g_parsefile->pf_fd = 0;
10916 * Like setinputfile, but takes an open file descriptor. Call this with
10920 setinputfd(int fd, int push)
10924 g_parsefile->buf = NULL;
10926 g_parsefile->pf_fd = fd;
10927 if (g_parsefile->buf == NULL)
10928 g_parsefile->buf = ckmalloc(IBUFSIZ);
10929 g_parsefile->left_in_buffer = 0;
10930 g_parsefile->left_in_line = 0;
10931 g_parsefile->linno = 1;
10935 * Set the input to take input from a file. If push is set, push the
10936 * old input onto the stack first.
10939 setinputfile(const char *fname, int flags)
10944 fd = open(fname, O_RDONLY | O_CLOEXEC);
10946 if (flags & INPUT_NOFILE_OK)
10949 ash_msg_and_raise_perror("can't open '%s'", fname);
10953 else if (O_CLOEXEC == 0) /* old libc */
10954 close_on_exec_on(fd);
10956 setinputfd(fd, flags & INPUT_PUSH_FILE);
10963 * Like setinputfile, but takes input from a string.
10966 setinputstring(char *string)
10970 g_parsefile->next_to_pgetc = string;
10971 g_parsefile->left_in_line = strlen(string);
10972 g_parsefile->buf = NULL;
10973 g_parsefile->linno = 1;
10979 * Routines to check for mail.
10982 #if ENABLE_ASH_MAIL
10984 /* Hash of mtimes of mailboxes */
10985 static unsigned mailtime_hash;
10986 /* Set if MAIL or MAILPATH is changed. */
10987 static smallint mail_var_path_changed;
10990 * Print appropriate message(s) if mail has arrived.
10991 * If mail_var_path_changed is set,
10992 * then the value of MAIL has mail_var_path_changed,
10993 * so we just update the values.
11002 struct stackmark smark;
11005 setstackmark(&smark);
11006 mpath = mpathset() ? mpathval() : mailval();
11009 p = path_advance(&mpath, nullstr);
11014 for (q = p; *q; q++)
11020 q[-1] = '\0'; /* delete trailing '/' */
11021 if (stat(p, &statb) < 0) {
11024 /* Very simplistic "hash": just a sum of all mtimes */
11025 new_hash += (unsigned)statb.st_mtime;
11027 if (!mail_var_path_changed && mailtime_hash != new_hash) {
11028 if (mailtime_hash != 0)
11029 out2str("you have mail\n");
11030 mailtime_hash = new_hash;
11032 mail_var_path_changed = 0;
11033 popstackmark(&smark);
11036 static void FAST_FUNC
11037 changemail(const char *val UNUSED_PARAM)
11039 mail_var_path_changed = 1;
11042 #endif /* ASH_MAIL */
11045 /* ============ ??? */
11048 * Set the shell parameters.
11051 setparam(char **argv)
11057 for (nparam = 0; argv[nparam]; nparam++)
11059 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
11061 *ap++ = ckstrdup(*argv++);
11064 freeparam(&shellparam);
11065 shellparam.malloced = 1;
11066 shellparam.nparam = nparam;
11067 shellparam.p = newparam;
11068 #if ENABLE_ASH_GETOPTS
11069 shellparam.optind = 1;
11070 shellparam.optoff = -1;
11075 * Process shell options. The global variable argptr contains a pointer
11076 * to the argument list; we advance it past the options.
11078 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
11079 * For a non-interactive shell, an error condition encountered
11080 * by a special built-in ... shall cause the shell to write a diagnostic message
11081 * to standard error and exit as shown in the following table:
11082 * Error Special Built-In
11084 * Utility syntax error (option or operand error) Shall exit
11086 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
11087 * we see that bash does not do that (set "finishes" with error code 1 instead,
11088 * and shell continues), and people rely on this behavior!
11090 * set -o barfoo 2>/dev/null
11093 * Oh well. Let's mimic that.
11096 plus_minus_o(char *name, int val)
11101 for (i = 0; i < NOPTS; i++) {
11102 if (strcmp(name, optnames(i)) == 0) {
11107 ash_msg("illegal option %co %s", val ? '-' : '+', name);
11110 for (i = 0; i < NOPTS; i++) {
11111 if (optnames(i)[0] == '\0')
11114 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
11116 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
11122 setoption(int flag, int val)
11126 for (i = 0; i < NOPTS; i++) {
11127 if (optletters(i) == flag && optnames(i)[0] != '\0') {
11132 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
11135 /* If login_sh is not NULL, we are called to parse command line opts,
11139 options(int *login_sh)
11147 while ((p = *argptr) != NULL) {
11149 if (c != '-' && c != '+')
11152 val = 0; /* val = 0 if c == '+' */
11155 if (p[0] == '\0' || LONE_DASH(p)) {
11157 /* "-" means turn off -x and -v */
11160 /* "--" means reset params */
11161 else if (*argptr == NULL)
11164 break; /* "-" or "--" terminates options */
11167 /* first char was + or - */
11168 while ((c = *p++) != '\0') {
11170 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
11172 minusc = p; /* command is after shell args */
11176 if (c == 's') { /* -s, +s */
11180 if (c == 'i') { /* -i, +i */
11185 *login_sh = 1; /* -l or +l == --login */
11188 /* bash does not accept +-login, we also won't */
11189 if (val && (c == '-')) { /* long options */
11190 if (strcmp(p, "login") == 0) {
11197 if (plus_minus_o(*argptr, val)) {
11198 /* it already printed err message */
11199 return 1; /* error */
11212 * The shift builtin command.
11214 static int FAST_FUNC
11215 shiftcmd(int argc UNUSED_PARAM, char **argv)
11222 n = number(argv[1]);
11223 if (n > shellparam.nparam)
11226 shellparam.nparam -= n;
11227 for (ap1 = shellparam.p; --n >= 0; ap1++) {
11228 if (shellparam.malloced)
11231 ap2 = shellparam.p;
11232 while ((*ap2++ = *ap1++) != NULL)
11234 #if ENABLE_ASH_GETOPTS
11235 shellparam.optind = 1;
11236 shellparam.optoff = -1;
11243 * POSIX requires that 'set' (but not export or readonly) output the
11244 * variables in lexicographic order - by the locale's collating order (sigh).
11245 * Maybe we could keep them in an ordered balanced binary tree
11246 * instead of hashed lists.
11247 * For now just roll 'em through qsort for printing...
11250 showvars(const char *sep_prefix, int on, int off)
11253 char **ep, **epend;
11255 ep = listvars(on, off, /*strlist:*/ NULL, &epend);
11256 qsort(ep, epend - ep, sizeof(char *), vpcmp);
11258 sep = *sep_prefix ? " " : sep_prefix;
11260 for (; ep < epend; ep++) {
11264 p = endofname(*ep);
11265 /* Used to have simple "p = strchrnul(*ep, '=')" here instead, but this
11266 * makes "export -p" to have output not suitable for "eval":
11268 * os.environ["test-test"]="test"
11269 * if os.fork() == 0:
11270 * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
11271 * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ])
11275 q = single_quote(++p);
11276 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
11282 * The set command builtin.
11284 static int FAST_FUNC
11285 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
11290 return showvars(nullstr, 0, VUNSET);
11293 retval = options(/*login_sh:*/ NULL);
11294 if (retval == 0) { /* if no parse error... */
11296 if (*argptr != NULL) {
11304 #if ENABLE_ASH_RANDOM_SUPPORT
11305 static void FAST_FUNC
11306 change_random(const char *value)
11310 if (value == NULL) {
11311 /* "get", generate */
11312 t = next_random(&random_gen);
11313 /* set without recursion */
11314 setvar(vrandom.var_text, utoa(t), VNOFUNC);
11315 vrandom.flags &= ~VNOFUNC;
11318 t = strtoul(value, NULL, 10);
11319 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
11324 #if BASH_EPOCH_VARS
11325 static void FAST_FUNC
11326 change_epoch(struct var *vepoch, const char *fmt)
11329 char buffer[sizeof("%lu.nnnnnn") + sizeof(long)*3];
11331 gettimeofday(&tv, NULL);
11332 sprintf(buffer, fmt, (unsigned long)tv.tv_sec, (unsigned)tv.tv_usec);
11333 setvar(vepoch->var_text, buffer, VNOFUNC);
11334 vepoch->flags &= ~VNOFUNC;
11337 static void FAST_FUNC
11338 change_seconds(const char *value UNUSED_PARAM)
11340 change_epoch(&vepochs, "%lu");
11343 static void FAST_FUNC
11344 change_realtime(const char *value UNUSED_PARAM)
11346 change_epoch(&vepochr, "%lu.%06u");
11350 #if ENABLE_ASH_GETOPTS
11352 getopts(char *optstr, char *optvar, char **optfirst)
11359 int ind = shellparam.optind;
11360 int off = shellparam.optoff;
11364 shellparam.optind = -1;
11365 optnext = optfirst + ind - 1;
11367 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
11370 p = optnext[-1] + off;
11371 if (p == NULL || *p == '\0') {
11372 /* Current word is done, advance */
11374 if (p == NULL || *p != '-' || *++p == '\0') {
11376 unsetvar("OPTARG");
11382 if (LONE_DASH(p)) /* check for "--" */
11387 for (q = optstr; *q != c;) {
11389 /* OPTERR is a bashism */
11390 const char *cp = lookupvar("OPTERR");
11391 if ((cp && LONE_CHAR(cp, '0'))
11392 || (optstr[0] == ':')
11395 /*sbuf[1] = '\0'; - already is */
11396 setvar0("OPTARG", sbuf);
11398 fprintf(stderr, "Illegal option -%c\n", c);
11399 unsetvar("OPTARG");
11409 if (*p == '\0' && (p = *optnext) == NULL) {
11410 /* OPTERR is a bashism */
11411 const char *cp = lookupvar("OPTERR");
11412 if ((cp && LONE_CHAR(cp, '0'))
11413 || (optstr[0] == ':')
11416 /*sbuf[1] = '\0'; - already is */
11417 setvar0("OPTARG", sbuf);
11420 fprintf(stderr, "No arg for -%c option\n", c);
11421 unsetvar("OPTARG");
11429 setvar0("OPTARG", p);
11432 setvar0("OPTARG", nullstr);
11434 ind = optnext - optfirst + 1;
11435 setvar("OPTIND", itoa(ind), VNOFUNC);
11437 /*sbuf[1] = '\0'; - already is */
11438 setvar0(optvar, sbuf);
11440 shellparam.optoff = p ? p - *(optnext - 1) : -1;
11441 shellparam.optind = ind;
11447 * The getopts builtin. Shellparam.optnext points to the next argument
11448 * to be processed. Shellparam.optptr points to the next character to
11449 * be processed in the current argument. If shellparam.optnext is NULL,
11450 * then it's the first time getopts has been called.
11452 static int FAST_FUNC
11453 getoptscmd(int argc, char **argv)
11458 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
11460 optbase = shellparam.p;
11461 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
11462 shellparam.optind = 1;
11463 shellparam.optoff = -1;
11466 optbase = &argv[3];
11467 if ((unsigned)shellparam.optind > argc - 2) {
11468 shellparam.optind = 1;
11469 shellparam.optoff = -1;
11473 return getopts(argv[1], argv[2], optbase);
11475 #endif /* ASH_GETOPTS */
11478 /* ============ Shell parser */
11481 struct heredoc *next; /* next here document in list */
11482 union node *here; /* redirection node */
11483 char *eofmark; /* string indicating end of input */
11484 smallint striptabs; /* if set, strip leading tabs */
11487 static smallint tokpushback; /* last token pushed back */
11488 static smallint quoteflag; /* set if (part of) last token was quoted */
11489 static token_id_t lasttoken; /* last token read (integer id Txxx) */
11490 static struct heredoc *heredoclist; /* list of here documents to read */
11491 static char *wordtext; /* text of last word returned by readtoken */
11492 static struct nodelist *backquotelist;
11493 static union node *redirnode;
11494 static struct heredoc *heredoc;
11496 static const char *
11497 tokname(char *buf, int tok)
11500 return tokname_array[tok];
11501 sprintf(buf, "\"%s\"", tokname_array[tok]);
11505 /* raise_error_unexpected_syntax:
11506 * Called when an unexpected token is read during the parse. The argument
11507 * is the token that is expected, or -1 if more than one type of token can
11508 * occur at this point.
11510 static void raise_error_unexpected_syntax(int) NORETURN;
11512 raise_error_unexpected_syntax(int token)
11518 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
11520 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
11521 raise_error_syntax(msg);
11525 /* parsing is heavily cross-recursive, need these forward decls */
11526 static union node *andor(void);
11527 static union node *pipeline(void);
11528 static union node *parse_command(void);
11529 static void parseheredoc(void);
11530 static int peektoken(void);
11531 static int readtoken(void);
11533 static union node *
11536 union node *n1, *n2, *n3;
11541 switch (peektoken()) {
11549 if (!n1 && (nlflag & 1))
11555 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11556 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
11562 if (tok == TBACKGND) {
11563 if (n2->type == NPIPE) {
11564 n2->npipe.pipe_backgnd = 1;
11566 if (n2->type != NREDIR) {
11567 n3 = stzalloc(sizeof(struct nredir));
11569 /*n3->nredir.redirect = NULL; - stzalloc did it */
11572 n2->type = NBACKGND;
11578 n3 = stzalloc(sizeof(struct nbinary));
11580 n3->nbinary.ch1 = n1;
11581 n3->nbinary.ch2 = n2;
11594 raise_error_unexpected_syntax(-1);
11601 static union node *
11604 union node *n1, *n2, *n3;
11612 } else if (t == TOR) {
11618 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11620 n3 = stzalloc(sizeof(struct nbinary));
11622 n3->nbinary.ch1 = n1;
11623 n3->nbinary.ch2 = n2;
11628 static union node *
11631 union node *n1, *n2, *pipenode;
11632 struct nodelist *lp, *prev;
11636 TRACE(("pipeline: entered\n"));
11637 if (readtoken() == TNOT) {
11639 checkkwd = CHKKWD | CHKALIAS;
11642 n1 = parse_command();
11643 if (readtoken() == TPIPE) {
11644 pipenode = stzalloc(sizeof(struct npipe));
11645 pipenode->type = NPIPE;
11646 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
11647 lp = stzalloc(sizeof(struct nodelist));
11648 pipenode->npipe.cmdlist = lp;
11652 lp = stzalloc(sizeof(struct nodelist));
11653 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11654 lp->n = parse_command();
11656 } while (readtoken() == TPIPE);
11662 n2 = stzalloc(sizeof(struct nnot));
11670 static union node *
11675 n = stzalloc(sizeof(struct narg));
11677 /*n->narg.next = NULL; - stzalloc did it */
11678 n->narg.text = wordtext;
11679 n->narg.backquote = backquotelist;
11684 fixredir(union node *n, const char *text, int err)
11688 TRACE(("Fix redir %s %d\n", text, err));
11690 n->ndup.vname = NULL;
11692 fd = bb_strtou(text, NULL, 10);
11693 if (!errno && fd >= 0)
11694 n->ndup.dupfd = fd;
11695 else if (LONE_DASH(text))
11696 n->ndup.dupfd = -1;
11699 raise_error_syntax("bad fd number");
11700 n->ndup.vname = makename();
11707 union node *n = redirnode;
11709 if (n->type == NHERE)
11710 checkkwd = CHKEOFMARK;
11711 if (readtoken() != TWORD)
11712 raise_error_unexpected_syntax(-1);
11713 if (n->type == NHERE) {
11714 struct heredoc *here = heredoc;
11717 if (quoteflag == 0)
11719 TRACE(("Here document %d\n", n->type));
11720 rmescapes(wordtext, 0, NULL);
11721 here->eofmark = wordtext;
11723 if (heredoclist == NULL)
11724 heredoclist = here;
11726 for (p = heredoclist; p->next; p = p->next)
11730 } else if (n->type == NTOFD || n->type == NFROMFD) {
11731 fixredir(n, wordtext, 0);
11733 n->nfile.fname = makename();
11737 static union node *
11740 union node *args, **app;
11741 union node *n = NULL;
11742 union node *vars, **vpp;
11743 union node **rpp, *redir;
11747 smallint double_brackets_flag = 0;
11749 IF_BASH_FUNCTION(smallint function_flag = 0;)
11758 savecheckkwd = CHKALIAS;
11759 savelinno = g_parsefile->linno;
11762 checkkwd = savecheckkwd;
11767 if (peektoken() != TWORD)
11768 raise_error_unexpected_syntax(TWORD);
11773 case TAND: /* "&&" */
11774 case TOR: /* "||" */
11775 if (!double_brackets_flag) {
11779 wordtext = (char *) (t == TAND ? "-a" : "-o");
11782 n = stzalloc(sizeof(struct narg));
11784 /*n->narg.next = NULL; - stzalloc did it */
11785 n->narg.text = wordtext;
11787 if (strcmp("[[", wordtext) == 0)
11788 double_brackets_flag = 1;
11789 else if (strcmp("]]", wordtext) == 0)
11790 double_brackets_flag = 0;
11792 n->narg.backquote = backquotelist;
11793 if (savecheckkwd && isassignment(wordtext)) {
11795 vpp = &n->narg.next;
11798 app = &n->narg.next;
11802 if (function_flag) {
11803 checkkwd = CHKNL | CHKKWD;
11804 switch (peektoken()) {
11817 if (strcmp("[[", wordtext) == 0)
11822 raise_error_unexpected_syntax(-1);
11828 *rpp = n = redirnode;
11829 rpp = &n->nfile.next;
11830 parsefname(); /* read name of redirection file */
11833 IF_BASH_FUNCTION(do_func:)
11834 if (args && app == &args->narg.next
11837 struct builtincmd *bcmd;
11840 /* We have a function */
11841 if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
11842 raise_error_unexpected_syntax(TRP);
11843 name = n->narg.text;
11844 if (!goodname(name)
11845 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11847 raise_error_syntax("bad function name");
11850 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11851 n->ndefun.text = n->narg.text;
11852 n->ndefun.linno = g_parsefile->linno;
11853 n->ndefun.body = parse_command();
11856 IF_BASH_FUNCTION(function_flag = 0;)
11867 n = stzalloc(sizeof(struct ncmd));
11870 n->ncmd.linno = savelinno;
11871 n->ncmd.args = args;
11872 n->ncmd.assign = vars;
11873 n->ncmd.redirect = redir;
11877 static union node *
11878 parse_command(void)
11880 union node *n1, *n2;
11881 union node *ap, **app;
11882 union node *cp, **cpp;
11883 union node *redir, **rpp;
11891 savelinno = g_parsefile->linno;
11893 switch (readtoken()) {
11895 raise_error_unexpected_syntax(-1);
11898 n1 = stzalloc(sizeof(struct nif));
11900 n1->nif.test = list(0);
11901 if (readtoken() != TTHEN)
11902 raise_error_unexpected_syntax(TTHEN);
11903 n1->nif.ifpart = list(0);
11905 while (readtoken() == TELIF) {
11906 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11907 n2 = n2->nif.elsepart;
11909 n2->nif.test = list(0);
11910 if (readtoken() != TTHEN)
11911 raise_error_unexpected_syntax(TTHEN);
11912 n2->nif.ifpart = list(0);
11914 if (lasttoken == TELSE)
11915 n2->nif.elsepart = list(0);
11917 n2->nif.elsepart = NULL;
11925 n1 = stzalloc(sizeof(struct nbinary));
11926 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11927 n1->nbinary.ch1 = list(0);
11930 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11931 got == TWORD ? wordtext : ""));
11932 raise_error_unexpected_syntax(TDO);
11934 n1->nbinary.ch2 = list(0);
11939 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11940 raise_error_syntax("bad for loop variable");
11941 n1 = stzalloc(sizeof(struct nfor));
11943 n1->nfor.linno = savelinno;
11944 n1->nfor.var = wordtext;
11945 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11946 if (readtoken() == TIN) {
11948 while (readtoken() == TWORD) {
11949 n2 = stzalloc(sizeof(struct narg));
11951 /*n2->narg.next = NULL; - stzalloc did it */
11952 n2->narg.text = wordtext;
11953 n2->narg.backquote = backquotelist;
11955 app = &n2->narg.next;
11958 n1->nfor.args = ap;
11959 if (lasttoken != TNL && lasttoken != TSEMI)
11960 raise_error_unexpected_syntax(-1);
11962 n2 = stzalloc(sizeof(struct narg));
11964 /*n2->narg.next = NULL; - stzalloc did it */
11965 n2->narg.text = (char *)dolatstr;
11966 /*n2->narg.backquote = NULL;*/
11967 n1->nfor.args = n2;
11969 * Newline or semicolon here is optional (but note
11970 * that the original Bourne shell only allowed NL).
11972 if (lasttoken != TSEMI)
11975 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11976 if (readtoken() != TDO)
11977 raise_error_unexpected_syntax(TDO);
11978 n1->nfor.body = list(0);
11982 n1 = stzalloc(sizeof(struct ncase));
11984 n1->ncase.linno = savelinno;
11985 if (readtoken() != TWORD)
11986 raise_error_unexpected_syntax(TWORD);
11987 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11989 /*n2->narg.next = NULL; - stzalloc did it */
11990 n2->narg.text = wordtext;
11991 n2->narg.backquote = backquotelist;
11992 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11993 if (readtoken() != TIN)
11994 raise_error_unexpected_syntax(TIN);
11995 cpp = &n1->ncase.cases;
11997 checkkwd = CHKNL | CHKKWD;
11999 while (t != TESAC) {
12000 if (lasttoken == TLP)
12002 *cpp = cp = stzalloc(sizeof(struct nclist));
12004 app = &cp->nclist.pattern;
12006 *app = ap = stzalloc(sizeof(struct narg));
12008 /*ap->narg.next = NULL; - stzalloc did it */
12009 ap->narg.text = wordtext;
12010 ap->narg.backquote = backquotelist;
12011 if (readtoken() != TPIPE)
12013 app = &ap->narg.next;
12016 //ap->narg.next = NULL;
12017 if (lasttoken != TRP)
12018 raise_error_unexpected_syntax(TRP);
12019 cp->nclist.body = list(2);
12021 cpp = &cp->nclist.next;
12023 checkkwd = CHKNL | CHKKWD;
12027 raise_error_unexpected_syntax(TENDCASE);
12034 n1 = stzalloc(sizeof(struct nredir));
12035 n1->type = NSUBSHELL;
12036 n1->nredir.linno = savelinno;
12037 n1->nredir.n = list(0);
12038 /*n1->nredir.redirect = NULL; - stzalloc did it */
12045 IF_BASH_FUNCTION(case TFUNCTION:)
12049 return simplecmd();
12052 if (readtoken() != t)
12053 raise_error_unexpected_syntax(t);
12056 /* Now check for redirection which may follow command */
12057 checkkwd = CHKKWD | CHKALIAS;
12059 while (readtoken() == TREDIR) {
12060 *rpp = n2 = redirnode;
12061 rpp = &n2->nfile.next;
12067 if (n1->type != NSUBSHELL) {
12068 n2 = stzalloc(sizeof(struct nredir));
12070 n2->nredir.linno = savelinno;
12074 n1->nredir.redirect = redir;
12079 #if BASH_DOLLAR_SQUOTE
12081 decode_dollar_squote(void)
12083 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
12089 p = strchr(C_escapes, c);
12094 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
12098 } while ((unsigned char)(c - '0') <= 7 && --cnt);
12100 } else if (c == 'x') { /* \xHH */
12104 } while (isxdigit(c) && --cnt);
12106 if (cnt == 3) { /* \x but next char is "bad" */
12110 } else { /* simple seq like \\ or \t */
12115 c = bb_process_escape_sequence((void*)&p);
12116 } else { /* unrecognized "\z": print both chars unless ' or " */
12117 if (c != '\'' && c != '"') {
12119 c |= 0x100; /* "please encode \, then me" */
12126 /* Used by expandstr to get here-doc like behaviour. */
12127 #define FAKEEOFMARK ((char*)(uintptr_t)1)
12129 static ALWAYS_INLINE int
12130 realeofmark(const char *eofmark)
12132 return eofmark && eofmark != FAKEEOFMARK;
12136 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
12137 * is not NULL, read a here document. In the latter case, eofmark is the
12138 * word which marks the end of the document and striptabs is true if
12139 * leading tabs should be stripped from the document. The argument c
12140 * is the first character of the input token or document.
12142 * Because C does not have internal subroutines, I have simulated them
12143 * using goto's to implement the subroutine linkage. The following macros
12144 * will run code that appears at the end of readtoken1.
12146 #define CHECKEND() {goto checkend; checkend_return:;}
12147 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
12148 #define PARSESUB() {goto parsesub; parsesub_return:;}
12149 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
12150 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
12151 #define PARSEARITH() {goto parsearith; parsearith_return:;}
12153 readtoken1(int c, int syntax, char *eofmark, int striptabs)
12155 /* NB: syntax parameter fits into smallint */
12156 /* c parameter is an unsigned char or PEOF or PEOA */
12159 struct nodelist *bqlist;
12162 smallint pssyntax; /* we are expanding a prompt string */
12163 IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
12165 struct synstack synbase = { };
12166 struct synstack *synstack = &synbase;
12168 #if ENABLE_ASH_EXPAND_PRMT
12169 pssyntax = (syntax == PSSYNTAX);
12173 pssyntax = 0; /* constant */
12175 synstack->syntax = syntax;
12177 if (syntax == DQSYNTAX)
12178 synstack->dblquote = 1;
12182 STARTSTACKSTR(out);
12184 /* For each line, until end of word */
12185 CHECKEND(); /* set c to PEOF if at end of here document */
12186 for (;;) { /* until end of line or end of word */
12187 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
12188 switch (SIT(c, synstack->syntax)) {
12189 case CNL: /* '\n' */
12190 if (synstack->syntax == BASESYNTAX
12191 && !synstack->varnest
12193 goto endword; /* exit outer loop */
12197 c = synstack->syntax == SQSYNTAX ? pgetc() : pgetc_eatbnl();
12198 goto loop; /* continue outer loop */
12203 #if BASH_DOLLAR_SQUOTE
12204 if (c == '\\' && bash_dollar_squote) {
12205 c = decode_dollar_squote();
12207 /* skip $'\000', $'\x00' (like bash) */
12211 /* Unknown escape. Encode as '\z' */
12212 c = (unsigned char)c;
12213 if (eofmark == NULL || synstack->dblquote)
12214 USTPUTC(CTLESC, out);
12215 USTPUTC('\\', out);
12219 if (!eofmark || synstack->dblquote || synstack->varnest)
12220 USTPUTC(CTLESC, out);
12223 case CBACK: /* backslash */
12224 c = pgetc_without_PEOA();
12226 USTPUTC(CTLESC, out);
12227 USTPUTC('\\', out);
12230 if (pssyntax && c == '$') {
12231 USTPUTC(CTLESC, out);
12232 USTPUTC('\\', out);
12234 /* Backslash is retained if we are in "str"
12235 * and next char isn't dquote-special.
12237 if (synstack->dblquote
12241 && (c != '"' || (eofmark != NULL && !synstack->varnest))
12242 && (c != '}' || !synstack->varnest)
12244 USTPUTC(CTLESC, out); /* protect '\' from glob */
12245 USTPUTC('\\', out);
12247 USTPUTC(CTLESC, out);
12253 synstack->syntax = SQSYNTAX;
12255 if (eofmark == NULL) {
12256 USTPUTC(CTLQUOTEMARK, out);
12260 synstack->syntax = DQSYNTAX;
12261 synstack->dblquote = 1;
12263 if (synstack->varnest)
12264 synstack->innerdq ^= 1;
12267 IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
12268 if (eofmark != NULL && synstack->varnest == 0) {
12273 if (synstack->dqvarnest == 0) {
12274 synstack->syntax = BASESYNTAX;
12275 synstack->dblquote = 0;
12284 case CVAR: /* '$' */
12285 PARSESUB(); /* parse substitution */
12287 case CENDVAR: /* '}' */
12288 if (!synstack->innerdq && synstack->varnest > 0) {
12289 if (!--synstack->varnest && synstack->varpushed)
12290 synstack_pop(&synstack);
12291 else if (synstack->dqvarnest > 0)
12292 synstack->dqvarnest--;
12297 #if ENABLE_FEATURE_SH_MATH
12298 case CLP: /* '(' in arithmetic */
12299 synstack->parenlevel++;
12302 case CRP: /* ')' in arithmetic */
12303 if (synstack->parenlevel > 0) {
12304 synstack->parenlevel--;
12306 if (pgetc_eatbnl() == ')') {
12308 synstack_pop(&synstack);
12311 * unbalanced parens
12312 * (don't 2nd guess - no error)
12320 case CBQUOTE: /* '`' */
12321 if (checkkwd & CHKEOFMARK) {
12330 goto endword; /* exit outer loop */
12334 if (synstack->varnest == 0) {
12335 #if BASH_REDIR_OUTPUT
12337 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
12338 if (pgetc() == '>')
12339 c = 0x100 + '>'; /* flag &> */
12343 goto endword; /* exit outer loop */
12345 IF_ASH_ALIAS(if (c != PEOA))
12348 c = synstack->syntax == SQSYNTAX ? pgetc() : pgetc_eatbnl();
12352 #if ENABLE_FEATURE_SH_MATH
12353 if (synstack->syntax == ARISYNTAX)
12354 raise_error_syntax("missing '))'");
12356 if (synstack->syntax != BASESYNTAX && eofmark == NULL)
12357 raise_error_syntax("unterminated quoted string");
12358 if (synstack->varnest != 0) {
12360 raise_error_syntax("missing '}'");
12362 USTPUTC('\0', out);
12363 len = out - (char *)stackblock();
12364 out = stackblock();
12365 if (eofmark == NULL) {
12366 if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
12369 if (isdigit_str9(out)) {
12370 PARSEREDIR(); /* passed as params: out, c */
12371 lasttoken = TREDIR;
12374 /* else: non-number X seen, interpret it
12375 * as "NNNX>file" = "NNNX >file" */
12379 quoteflag = quotef;
12380 backquotelist = bqlist;
12381 grabstackblock(len);
12385 /* end of readtoken routine */
12388 * Check to see whether we are at the end of the here document. When this
12389 * is called, c is set to the first character of the next input line. If
12390 * we are at the end of the here document, this routine sets the c to PEOF.
12393 if (realeofmark(eofmark)) {
12397 #if ENABLE_ASH_ALIAS
12399 c = pgetc_without_PEOA();
12402 while (c == '\t') {
12403 c = pgetc_without_PEOA();
12407 markloc = out - (char *)stackblock();
12408 for (p = eofmark; STPUTC(c, out), *p; p++) {
12411 /* FIXME: fails for backslash-newlined terminator:
12416 * (see heredoc_bkslash_newline2.tests)
12418 c = pgetc_without_PEOA();
12421 if (c == '\n' || c == PEOF) {
12423 g_parsefile->linno++;
12424 needprompt = doprompt;
12429 p = (char *)stackblock() + markloc + 1;
12430 len_here = out - p;
12433 len_here -= (c >= PEOF);
12439 str = alloca(len_here + 1);
12440 *(char *)mempcpy(str, p, len_here) = '\0';
12442 pushstring(str, NULL);
12447 STADJUST((char *)stackblock() + markloc - out, out);
12449 goto checkend_return;
12453 * Parse a redirection operator. The variable "out" points to a string
12454 * specifying the fd to be redirected. The variable "c" contains the
12455 * first character of the redirection operator.
12458 /* out is already checked to be a valid number or "" */
12459 int fd = (*out == '\0' ? -1 : atoi(out));
12462 np = stzalloc(sizeof(struct nfile));
12465 c = pgetc_eatbnl();
12467 np->type = NAPPEND;
12469 np->type = NCLOBBER;
12472 /* it also can be NTO2 (>&file), but we can't figure it out yet */
12478 #if BASH_REDIR_OUTPUT
12479 else if (c == 0x100 + '>') { /* this flags &> redirection */
12481 pgetc(); /* this is '>', no need to check */
12485 else { /* c == '<' */
12486 /*np->nfile.fd = 0; - stzalloc did it */
12487 c = pgetc_eatbnl();
12490 if (sizeof(struct nfile) != sizeof(struct nhere)) {
12491 np = stzalloc(sizeof(struct nhere));
12492 /*np->nfile.fd = 0; - stzalloc did it */
12495 heredoc = stzalloc(sizeof(struct heredoc));
12496 heredoc->here = np;
12497 c = pgetc_eatbnl();
12499 heredoc->striptabs = 1;
12501 /*heredoc->striptabs = 0; - stzalloc did it */
12507 np->type = NFROMFD;
12511 np->type = NFROMTO;
12523 goto parseredir_return;
12527 * Parse a substitution. At this point, we have read the dollar sign
12528 * and nothing else.
12531 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
12532 * (assuming ascii char codes, as the original implementation did) */
12533 #define is_special(c) \
12534 (((unsigned)(c) - 33 < 32) \
12535 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
12537 unsigned char subtype;
12540 c = pgetc_eatbnl();
12541 if ((checkkwd & CHKEOFMARK)
12542 || c > 255 /* PEOA or PEOF */
12543 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
12545 #if BASH_DOLLAR_SQUOTE
12546 if (synstack->syntax != DQSYNTAX && c == '\'')
12547 bash_dollar_squote = 1;
12552 } else if (c == '(') {
12553 /* $(command) or $((arith)) */
12554 if (pgetc_eatbnl() == '(') {
12555 #if ENABLE_FEATURE_SH_MATH
12558 raise_error_syntax("support for $((arith)) is disabled");
12565 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
12566 smalluint newsyn = synstack->syntax;
12568 USTPUTC(CTLVAR, out);
12569 typeloc = out - (char *)stackblock();
12571 subtype = VSNORMAL;
12573 c = pgetc_eatbnl();
12578 /* $[{[#]]NAME[}] */
12581 c = pgetc_eatbnl();
12582 } while (is_in_name(c));
12583 } else if (isdigit(c)) {
12584 /* $[{[#]]NUM[}] */
12587 c = pgetc_eatbnl();
12588 } while (isdigit(c));
12589 } else if (c != '}') {
12590 /* $[{[#]]<specialchar>[}] */
12593 c = pgetc_eatbnl();
12594 if (!subtype && cc == '#') {
12595 subtype = VSLENGTH;
12596 if (c == '_' || isalnum(c))
12599 c = pgetc_eatbnl();
12600 if (cc == '}' || c != '}') {
12608 if (!is_special(cc)) {
12609 if (subtype == VSLENGTH)
12618 if (c != '}' && subtype == VSLENGTH) {
12619 /* ${#VAR didn't end with } */
12623 if (subtype == 0) {
12624 static const char types[] ALIGN1 = "}-+?=";
12625 /* ${VAR...} but not $VAR or ${#VAR} */
12626 /* c == first char after VAR */
12631 c = pgetc_eatbnl();
12633 /* This check is only needed to not misinterpret
12634 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
12637 if (!strchr(types, c)) {
12638 subtype = VSSUBSTR;
12640 break; /* "goto badsub" is bigger (!) */
12646 const char *p = strchr(types, c);
12649 subtype |= p - types + VSNORMAL;
12654 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
12655 c = pgetc_eatbnl();
12661 newsyn = BASESYNTAX;
12663 #if BASH_PATTERN_SUBST
12665 /* ${v/[/]pattern/repl} */
12666 //TODO: encode pattern and repl separately.
12667 // Currently cases like: v=1;echo ${v/$((1/1))/ONE}
12668 // are broken (should print "ONE")
12669 subtype = VSREPLACE;
12670 newsyn = BASESYNTAX;
12671 c = pgetc_eatbnl();
12674 subtype++; /* VSREPLACEALL */
12683 if (newsyn == ARISYNTAX)
12686 if ((newsyn != synstack->syntax || synstack->innerdq)
12687 && subtype != VSNORMAL
12689 synstack_push(&synstack,
12690 synstack->prev ?: alloca(sizeof(*synstack)),
12693 synstack->varpushed = 1;
12694 synstack->dblquote = newsyn != BASESYNTAX;
12697 ((unsigned char *)stackblock())[typeloc] = subtype;
12698 if (subtype != VSNORMAL) {
12699 synstack->varnest++;
12700 if (synstack->dblquote)
12701 synstack->dqvarnest++;
12705 goto parsesub_return;
12709 * Called to parse command substitutions. Newstyle is set if the command
12710 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
12711 * list of commands (passed by reference), and savelen is the number of
12712 * characters on the top of the stack which must be preserved.
12715 struct nodelist **nlpp;
12719 smallint saveprompt = 0;
12722 savelen = out - (char *)stackblock();
12725 * FIXME: this can allocate very large block on stack and SEGV.
12727 * echo "..<100kbytes>..`true` $(true) `true` ..."
12728 * allocates 100kb for every command subst. With about
12729 * a hundred command substitutions stack overflows.
12730 * With larger prepended string, SEGV happens sooner.
12732 str = alloca(savelen);
12733 memcpy(str, stackblock(), savelen);
12737 /* We must read until the closing backquote, giving special
12738 * treatment to some slashes, and then push the string and
12739 * reread it as input, interpreting it normally.
12745 STARTSTACKSTR(pout);
12749 setprompt_if(needprompt, 2);
12750 pc = pgetc_eatbnl();
12756 pc = pgetc(); /* or pgetc_eatbnl()? why (example)? */
12757 if (pc != '\\' && pc != '`' && pc != '$'
12758 && (!synstack->dblquote || pc != '"')
12760 STPUTC('\\', pout);
12762 if (pc <= 255 /* not PEOA or PEOF */) {
12768 IF_ASH_ALIAS(case PEOA:)
12769 raise_error_syntax("EOF in backquote substitution");
12781 STPUTC('\0', pout);
12782 psavelen = pout - (char *)stackblock();
12783 if (psavelen > 0) {
12784 pstr = grabstackstr(pout);
12785 setinputstring(pstr);
12790 nlpp = &(*nlpp)->next;
12791 *nlpp = stzalloc(sizeof(**nlpp));
12792 /* (*nlpp)->next = NULL; - stzalloc did it */
12795 saveprompt = doprompt;
12802 doprompt = saveprompt;
12803 else if (readtoken() != TRP)
12804 raise_error_unexpected_syntax(TRP);
12809 * Start reading from old file again, ignoring any pushed back
12810 * tokens left from the backquote parsing
12815 while (stackblocksize() <= savelen)
12817 STARTSTACKSTR(out);
12819 memcpy(out, str, savelen);
12820 STADJUST(savelen, out);
12822 USTPUTC(CTLBACKQ, out);
12824 goto parsebackq_oldreturn;
12825 goto parsebackq_newreturn;
12828 #if ENABLE_FEATURE_SH_MATH
12830 * Parse an arithmetic expansion (indicate start of one and set state)
12834 synstack_push(&synstack,
12835 synstack->prev ?: alloca(sizeof(*synstack)),
12837 synstack->dblquote = 1;
12838 USTPUTC(CTLARI, out);
12839 goto parsearith_return;
12842 } /* end of readtoken */
12845 * Read the next input token.
12846 * If the token is a word, we set backquotelist to the list of cmds in
12847 * backquotes. We set quoteflag to true if any part of the word was
12849 * If the token is TREDIR, then we set redirnode to a structure containing
12852 * [Change comment: here documents and internal procedures]
12853 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12854 * word parsing code into a separate routine. In this case, readtoken
12855 * doesn't need to have any internal procedures, but parseword does.
12856 * We could also make parseoperator in essence the main routine, and
12857 * have parseword (readtoken1?) handle both words and redirection.]
12859 #define NEW_xxreadtoken
12860 #ifdef NEW_xxreadtoken
12861 /* singles must be first! */
12862 static const char xxreadtoken_chars[7] ALIGN1 = {
12863 '\n', '(', ')', /* singles */
12864 '&', '|', ';', /* doubles */
12868 #define xxreadtoken_singles 3
12869 #define xxreadtoken_doubles 3
12871 static const char xxreadtoken_tokens[] ALIGN1 = {
12872 TNL, TLP, TRP, /* only single occurrence allowed */
12873 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12874 TEOF, /* corresponds to trailing nul */
12875 TAND, TOR, TENDCASE /* if double occurrence */
12887 setprompt_if(needprompt, 2);
12888 for (;;) { /* until token or start of word found */
12889 c = pgetc_eatbnl();
12890 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12894 while ((c = pgetc()) != '\n' && c != PEOF)
12897 } else if (c == '\\') {
12898 break; /* return readtoken1(...) */
12902 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12908 p = strchr(xxreadtoken_chars, c);
12910 break; /* return readtoken1(...) */
12912 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12913 int cc = pgetc_eatbnl();
12914 if (cc == c) { /* double occurrence? */
12915 p += xxreadtoken_doubles + 1;
12918 #if BASH_REDIR_OUTPUT
12919 if (c == '&' && cc == '>') /* &> */
12920 break; /* return readtoken1(...) */
12925 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12930 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12932 #else /* old xxreadtoken */
12933 #define RETURN(token) return lasttoken = token
12943 setprompt_if(needprompt, 2);
12944 for (;;) { /* until token or start of word found */
12945 c = pgetc_eatbnl();
12947 case ' ': case '\t':
12948 IF_ASH_ALIAS(case PEOA:)
12951 while ((c = pgetc()) != '\n' && c != PEOF)
12961 if (pgetc_eatbnl() == '&')
12966 if (pgetc_eatbnl() == '|')
12971 if (pgetc_eatbnl() == ';')
12982 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12985 #endif /* old xxreadtoken */
12991 int kwd = checkkwd;
12993 smallint alreadyseen = tokpushback;
12996 #if ENABLE_ASH_ALIAS
13012 if (t != TWORD || quoteflag) {
13017 * check for keywords
13019 if (kwd & CHKKWD) {
13020 const char *const *pp;
13022 pp = findkwd(wordtext);
13024 lasttoken = t = pp - tokname_array;
13025 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
13030 if (checkkwd & CHKALIAS) {
13031 #if ENABLE_ASH_ALIAS
13033 ap = lookupalias(wordtext, 1);
13036 pushstring(ap->val, ap);
13046 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
13048 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
13064 * Read and parse a command. Returns NODE_EOF on end of file.
13065 * (NULL is a valid parse tree indicating a blank line.)
13067 static union node *
13068 parsecmd(int interact)
13073 doprompt = interact;
13074 setprompt_if(doprompt, doprompt);
13080 * Input any here documents.
13085 struct heredoc *here;
13088 here = heredoclist;
13089 heredoclist = NULL;
13093 setprompt_if(needprompt, 2);
13094 if (here->here->type == NHERE)
13095 readtoken1(pgetc(), SQSYNTAX, here->eofmark, here->striptabs);
13097 readtoken1(pgetc_eatbnl(), DQSYNTAX, here->eofmark, here->striptabs);
13098 n = stzalloc(sizeof(struct narg));
13099 n->narg.type = NARG;
13100 /*n->narg.next = NULL; - stzalloc did it */
13101 n->narg.text = wordtext;
13102 n->narg.backquote = backquotelist;
13103 here->here->nhere.doc = n;
13109 static const char *
13110 expandstr(const char *ps, int syntax_type)
13114 struct parsefile *file_stop = g_parsefile;
13115 volatile int saveint;
13116 struct jmploc *volatile savehandler = exception_handler;
13117 struct jmploc jmploc;
13118 const char *volatile result;
13121 /* XXX Fix (char *) cast. */
13122 setinputstring((char *)ps);
13124 saveprompt = doprompt;
13129 err = setjmp(jmploc.loc);
13133 /* readtoken1() might die horribly.
13134 * Try a prompt with syntactically wrong command:
13135 * PS1='$(date "+%H:%M:%S) > '
13137 exception_handler = &jmploc;
13138 readtoken1(pgetc(), syntax_type, FAKEEOFMARK, 0);
13140 n.narg.type = NARG;
13141 n.narg.next = NULL;
13142 n.narg.text = wordtext;
13143 n.narg.backquote = backquotelist;
13145 /* expandarg() might fail too:
13148 expandarg(&n, NULL, EXP_QUOTED);
13149 result = stackblock();
13152 exception_handler = savehandler;
13153 if (err && exception_type != EXERROR)
13154 longjmp(exception_handler->loc, 1);
13155 RESTORE_INT(saveint);
13157 doprompt = saveprompt;
13158 /* Try: PS1='`xxx(`' */
13159 unwindfiles(file_stop);
13167 return tokpushback && lasttoken == TEOF;
13171 * Execute a command or commands contained in a string.
13174 evalstring(char *s, int flags)
13176 struct jmploc *volatile savehandler;
13177 struct jmploc jmploc;
13181 struct stackmark smark;
13186 setstackmark(&smark);
13189 /* On exception inside execution loop, we must popfile().
13190 * Try interactively:
13192 * command eval "a=b" # throws "is read only" error
13193 * "command BLTIN" is not supposed to abort (even in non-interactive use).
13194 * But if we skip popfile(), we hit EOF in eval's string, and exit.
13196 savehandler = exception_handler;
13197 ex = setjmp(jmploc.loc);
13200 exception_handler = &jmploc;
13202 while ((n = parsecmd(0)) != NODE_EOF) {
13205 i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
13208 popstackmark(&smark);
13213 popstackmark(&smark);
13217 exception_handler = savehandler;
13219 longjmp(exception_handler->loc, ex);
13225 * The eval command.
13227 static int FAST_FUNC
13228 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
13237 STARTSTACKSTR(concat);
13239 concat = stack_putstr(p, concat);
13243 STPUTC(' ', concat);
13245 STPUTC('\0', concat);
13246 p = grabstackstr(concat);
13248 return evalstring(p, flags & EV_TESTED);
13254 * Read and execute commands.
13255 * "Top" is nonzero for the top level command loop;
13256 * it turns on prompting if the shell is interactive.
13262 struct stackmark smark;
13267 TRACE(("cmdloop(%d) called\n", top));
13271 setstackmark(&smark);
13274 showjobs(SHOW_CHANGED|SHOW_STDERR);
13277 if (iflag && top) {
13281 n = parsecmd(inter);
13283 if (DEBUG > 2 && debug && (n != NODE_EOF))
13286 if (n == NODE_EOF) {
13287 if (!top || numeof >= 50)
13289 if (!stoppedjobs()) {
13292 out2str("\nUse \"exit\" to leave shell.\n");
13295 } else if (nflag == 0) {
13298 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
13301 i = evaltree(n, 0);
13305 popstackmark(&smark);
13309 evalskip &= ~SKIPFUNC;
13317 * Take commands from a file. To be compatible we should do a path
13318 * search for the file, which is necessary to find sub-commands.
13321 find_dot_file(char *name)
13324 const char *path = pathval();
13327 /* don't try this for absolute or relative paths */
13328 if (strchr(name, '/'))
13331 while ((fullname = path_advance(&path, name)) != NULL) {
13332 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
13334 * Don't bother freeing here, since it will
13335 * be freed by the caller.
13339 if (fullname != name)
13340 stunalloc(fullname);
13342 /* not found in PATH */
13344 #if ENABLE_ASH_BASH_SOURCE_CURDIR
13347 ash_msg_and_raise_error("%s: not found", name);
13352 static int FAST_FUNC
13353 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
13355 /* "false; . empty_file; echo $?" should print 0, not 1: */
13359 char *args_need_save;
13360 volatile struct shparam saveparam;
13363 // struct strlist *sp;
13364 // for (sp = cmdenviron; sp; sp = sp->next)
13365 // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
13367 nextopt(nullstr); /* handle possible "--" */
13371 /* bash says: "bash: .: filename argument required" */
13372 return 2; /* bash compat */
13375 /* This aborts if file isn't found, which is POSIXly correct.
13376 * bash returns exitcode 1 instead.
13378 fullname = find_dot_file(argv[0]);
13380 args_need_save = argv[0];
13381 if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
13383 saveparam = shellparam;
13384 shellparam.malloced = 0;
13388 shellparam.nparam = argc;
13389 shellparam.p = argv;
13392 /* This aborts if file can't be opened, which is POSIXly correct.
13393 * bash returns exitcode 1 instead.
13395 setinputfile(fullname, INPUT_PUSH_FILE);
13396 commandname = fullname;
13397 status = cmdloop(0);
13400 if (args_need_save) {
13401 freeparam(&shellparam);
13402 shellparam = saveparam;
13408 static int FAST_FUNC
13409 exitcmd(int argc UNUSED_PARAM, char **argv)
13414 exitstatus = number(argv[1]);
13415 raise_exception(EXEXIT);
13420 * Read a file containing shell functions.
13423 readcmdfile(char *name)
13425 setinputfile(name, INPUT_PUSH_FILE);
13431 /* ============ find_command inplementation */
13434 * Resolve a command name. If you change this routine, you may have to
13435 * change the shellexec routine as well.
13438 find_command(char *name, struct cmdentry *entry, int act, const char *path)
13440 struct tblentry *cmdp;
13447 struct builtincmd *bcmd;
13449 /* If name contains a slash, don't use PATH or hash table */
13450 if (strchr(name, '/') != NULL) {
13451 entry->u.index = -1;
13452 if (act & DO_ABS) {
13453 while (stat(name, &statb) < 0) {
13455 if (errno == EINTR)
13458 entry->cmdtype = CMDUNKNOWN;
13462 entry->cmdtype = CMDNORMAL;
13466 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
13468 updatetbl = (path == pathval());
13471 if (strstr(path, "%builtin") != NULL)
13472 act |= DO_ALTBLTIN;
13475 /* If name is in the table, check answer will be ok */
13476 cmdp = cmdlookup(name, 0);
13477 if (cmdp != NULL) {
13480 switch (cmdp->cmdtype) {
13498 } else if (cmdp->rehash == 0)
13499 /* if not invalidated by cd, we're done */
13503 /* If %builtin not in path, check for builtin next */
13504 bcmd = find_builtin(name);
13506 if (IS_BUILTIN_REGULAR(bcmd))
13507 goto builtin_success;
13508 if (act & DO_ALTPATH) {
13509 if (!(act & DO_ALTBLTIN))
13510 goto builtin_success;
13511 } else if (builtinloc <= 0) {
13512 goto builtin_success;
13516 #if ENABLE_FEATURE_SH_STANDALONE
13518 int applet_no = find_applet_by_name(name);
13519 if (applet_no >= 0) {
13520 entry->cmdtype = CMDNORMAL;
13521 entry->u.index = -2 - applet_no;
13527 /* We have to search path. */
13528 prev = -1; /* where to start */
13529 if (cmdp && cmdp->rehash) { /* doing a rehash */
13530 if (cmdp->cmdtype == CMDBUILTIN)
13533 prev = cmdp->param.index;
13539 while ((fullname = path_advance(&path, name)) != NULL) {
13540 stunalloc(fullname);
13541 /* NB: code below will still use fullname
13542 * despite it being "unallocated" */
13545 if (prefix(pathopt, "builtin")) {
13547 goto builtin_success;
13550 if ((act & DO_NOFUNC)
13551 || !prefix(pathopt, "func")
13552 ) { /* ignore unimplemented options */
13556 /* if rehash, don't redo absolute path names */
13557 if (fullname[0] == '/' && idx <= prev) {
13560 TRACE(("searchexec \"%s\": no change\n", name));
13563 while (stat(fullname, &statb) < 0) {
13565 if (errno == EINTR)
13568 if (errno != ENOENT && errno != ENOTDIR)
13572 e = EACCES; /* if we fail, this will be the error */
13573 if (!S_ISREG(statb.st_mode))
13575 if (pathopt) { /* this is a %func directory */
13576 stalloc(strlen(fullname) + 1);
13577 /* NB: stalloc will return space pointed by fullname
13578 * (because we don't have any intervening allocations
13579 * between stunalloc above and this stalloc) */
13580 readcmdfile(fullname);
13581 cmdp = cmdlookup(name, 0);
13582 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
13583 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
13584 stunalloc(fullname);
13587 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
13589 entry->cmdtype = CMDNORMAL;
13590 entry->u.index = idx;
13594 cmdp = cmdlookup(name, 1);
13595 cmdp->cmdtype = CMDNORMAL;
13596 cmdp->param.index = idx;
13601 /* We failed. If there was an entry for this command, delete it */
13602 if (cmdp && updatetbl)
13603 delete_cmd_entry();
13604 if (act & DO_ERR) {
13605 #if ENABLE_ASH_BASH_NOT_FOUND_HOOK
13606 struct tblentry *hookp = cmdlookup("command_not_found_handle", 0);
13607 if (hookp && hookp->cmdtype == CMDFUNCTION) {
13609 argv[0] = (char*) "command_not_found_handle";
13612 evalfun(hookp->param.func, 2, argv, 0);
13613 entry->cmdtype = CMDUNKNOWN;
13617 ash_msg("%s: %s", name, errmsg(e, "not found"));
13619 entry->cmdtype = CMDUNKNOWN;
13624 entry->cmdtype = CMDBUILTIN;
13625 entry->u.cmd = bcmd;
13629 cmdp = cmdlookup(name, 1);
13630 cmdp->cmdtype = CMDBUILTIN;
13631 cmdp->param.cmd = bcmd;
13635 entry->cmdtype = cmdp->cmdtype;
13636 entry->u = cmdp->param;
13641 * The trap builtin.
13643 static int FAST_FUNC
13644 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13648 int signo, exitcode;
13653 for (signo = 0; signo < NSIG; signo++) {
13654 char *tr = trap_ptr[signo];
13656 /* note: bash adds "SIG", but only if invoked
13657 * as "bash". If called as "sh", or if set -o posix,
13658 * then it prints short signal names.
13659 * We are printing short names: */
13660 out1fmt("trap -- %s %s\n",
13662 get_signame(signo));
13663 /* trap_ptr != trap only if we are in special-cased `trap` code.
13664 * In this case, we will exit very soon, no need to free(). */
13665 /* if (trap_ptr != trap && tp[0]) */
13670 if (trap_ptr != trap) {
13678 /* Why the second check?
13679 * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
13680 * In this case, NUM is signal no, not an action.
13683 if (ap[1] && !is_number(ap[0]))
13688 signo = get_signum(*ap);
13690 /* Mimic bash message exactly */
13691 ash_msg("%s: invalid signal specification", *ap);
13697 if (LONE_DASH(action))
13700 if (action[0]) /* not NULL and not "" and not "-" */
13701 may_have_traps = 1;
13702 action = ckstrdup(action);
13706 trap[signo] = action;
13717 /* ============ Builtins */
13719 #if ENABLE_ASH_HELP
13720 static int FAST_FUNC
13721 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13727 "Built-in commands:\n"
13728 "------------------\n");
13729 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
13730 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
13731 builtintab[i].name + 1);
13737 # if ENABLE_FEATURE_SH_STANDALONE
13739 const char *a = applet_names;
13741 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
13746 while (*a++ != '\0')
13751 newline_and_flush(stdout);
13752 return EXIT_SUCCESS;
13757 static int FAST_FUNC
13758 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13760 if (line_input_state)
13761 show_history(line_input_state);
13762 return EXIT_SUCCESS;
13767 * The export and readonly commands.
13769 static int FAST_FUNC
13770 exportcmd(int argc UNUSED_PARAM, char **argv)
13780 /* "readonly" in bash accepts, but ignores -n.
13781 * We do the same: it saves a conditional in nextopt's param.
13784 while ((opt = nextopt("np")) != '\0') {
13786 flag_off = VEXPORT;
13789 if (argv[0][0] == 'r') {
13791 flag_off = 0; /* readonly ignores -n */
13793 flag_off = ~flag_off;
13795 /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
13801 p = strchr(name, '=');
13805 vp = *findvar(hashvar(name), name);
13807 vp->flags = ((vp->flags | flag) & flag_off);
13811 setvar(name, p, (flag & flag_off));
13812 } while ((name = *++aptr) != NULL);
13817 /* No arguments. Show the list of exported or readonly vars.
13820 showvars(argv[0], flag, 0);
13825 * Delete a function if it exists.
13828 unsetfunc(const char *name)
13830 struct tblentry *cmdp;
13832 cmdp = cmdlookup(name, 0);
13833 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
13834 delete_cmd_entry();
13838 * The unset builtin command. We unset the function before we unset the
13839 * variable to allow a function to be unset when there is a readonly variable
13840 * with the same name.
13842 static int FAST_FUNC
13843 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13849 while ((i = nextopt("vf")) != 0) {
13853 for (ap = argptr; *ap; ap++) {
13864 static const unsigned char timescmd_str[] ALIGN1 = {
13865 ' ', offsetof(struct tms, tms_utime),
13866 '\n', offsetof(struct tms, tms_stime),
13867 ' ', offsetof(struct tms, tms_cutime),
13868 '\n', offsetof(struct tms, tms_cstime),
13871 static int FAST_FUNC
13872 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13875 const unsigned char *p;
13878 clk_tck = bb_clk_tck();
13883 unsigned sec, frac;
13885 t = *(clock_t *)(((char *) &buf) + p[1]);
13887 frac = t % clk_tck;
13888 out1fmt("%um%u.%03us%c",
13889 sec / 60, sec % 60,
13890 (frac * 1000) / clk_tck,
13898 #if ENABLE_FEATURE_SH_MATH
13900 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13901 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13903 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13905 static int FAST_FUNC
13906 letcmd(int argc UNUSED_PARAM, char **argv)
13912 ash_msg_and_raise_error("expression expected");
13914 i = ash_arith(*argv);
13922 * The read builtin. Options:
13923 * -r Do not interpret '\' specially
13924 * -s Turn off echo (tty only)
13925 * -n NCHARS Read NCHARS max
13926 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13927 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13928 * -u FD Read from given FD instead of fd 0
13929 * -d DELIM End on DELIM char, not newline
13930 * This uses unbuffered input, which may be avoidable in some cases.
13931 * TODO: bash also has:
13932 * -a ARRAY Read into array[0],[1],etc
13933 * -e Use line editing (tty only)
13935 static int FAST_FUNC
13936 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13938 struct builtin_read_params params;
13942 memset(¶ms, 0, sizeof(params));
13944 while ((i = nextopt("p:u:rt:n:sd:")) != '\0') {
13947 params.opt_p = optionarg;
13950 params.opt_n = optionarg;
13953 params.read_flags |= BUILTIN_READ_SILENT;
13956 params.opt_t = optionarg;
13959 params.read_flags |= BUILTIN_READ_RAW;
13962 params.opt_u = optionarg;
13966 params.opt_d = optionarg;
13974 params.argv = argptr;
13975 params.setvar = setvar0;
13976 params.ifs = bltinlookup("IFS"); /* can be NULL */
13978 /* "read -s" needs to save/restore termios, can't allow ^C
13979 * to jump out of it.
13983 r = shell_builtin_read(¶ms);
13986 if ((uintptr_t)r == 1 && errno == EINTR) {
13987 /* To get SIGCHLD: sleep 1 & read x; echo $x
13988 * Correct behavior is to not exit "read"
13990 if (pending_sig == 0)
13994 if ((uintptr_t)r > 1)
13995 ash_msg_and_raise_error(r);
13997 return (uintptr_t)r;
14000 static int FAST_FUNC
14001 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
14003 static const char permuser[3] ALIGN1 = "ogu";
14006 int symbolic_mode = 0;
14008 while (nextopt("S") != '\0') {
14017 if (*argptr == NULL) {
14018 if (symbolic_mode) {
14019 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
14026 *p++ = permuser[i];
14028 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
14029 if (!(mask & 0400)) *p++ = 'r';
14030 if (!(mask & 0200)) *p++ = 'w';
14031 if (!(mask & 0100)) *p++ = 'x';
14039 out1fmt("%04o\n", mask);
14042 char *modestr = *argptr;
14043 /* numeric umasks are taken as-is */
14044 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
14045 if (!isdigit(modestr[0]))
14047 mask = bb_parse_mode(modestr, mask);
14048 if ((unsigned)mask > 0777) {
14049 ash_msg_and_raise_error("illegal mode: %s", modestr);
14051 if (!isdigit(modestr[0]))
14058 static int FAST_FUNC
14059 ulimitcmd(int argc UNUSED_PARAM, char **argv)
14061 return shell_builtin_ulimit(argv);
14064 /* ============ main() and helpers */
14067 * Called to exit the shell.
14076 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
14077 if (line_input_state)
14078 save_history(line_input_state);
14080 status = exitstatus;
14081 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
14082 if (setjmp(loc.loc)) {
14083 if (exception_type == EXEXIT)
14084 status = exitstatus;
14087 exception_handler = &loc;
14093 /*free(p); - we'll exit soon */
14096 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
14097 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
14100 flush_stdout_stderr();
14105 /* Don't inline: conserve stack of caller from having our locals too */
14106 static NOINLINE void
14109 /* we will never free this */
14110 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
14113 sigmode[SIGCHLD - 1] = S_DFL; /* ensure we install handler even if it is SIG_IGNed */
14114 setsignal(SIGCHLD);
14116 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
14117 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
14119 signal(SIGHUP, SIG_DFL);
14126 for (envp = environ; envp && *envp; envp++) {
14128 * p = endofname(*envp);
14129 * if (p != *envp && *p == '=') {
14130 * here to weed out badly-named variables, but this breaks
14131 * scenarios where people do want them passed to children:
14133 * os.environ["test-test"]="test"
14134 * if os.fork() == 0:
14135 * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
14136 * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ]) # breaks this
14138 if (strchr(*envp, '=')) {
14139 setvareq(*envp, VEXPORT|VTEXTFIXED);
14143 setvareq((char*)defifsvar, VTEXTFIXED);
14144 setvareq((char*)defoptindvar, VTEXTFIXED);
14146 setvar0("PPID", utoa(getppid()));
14148 p = lookupvar("SHLVL");
14149 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
14151 #if BASH_HOSTNAME_VAR
14152 if (!lookupvar("HOSTNAME")) {
14153 struct utsname uts;
14155 setvar0("HOSTNAME", uts.nodename);
14158 p = lookupvar("PWD");
14160 struct stat st1, st2;
14161 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
14162 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
14172 //usage:#define ash_trivial_usage
14173 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
14174 //usage:#define ash_full_usage "\n\n"
14175 //usage: "Unix shell interpreter"
14178 * Process the shell command line arguments.
14181 procargs(char **argv)
14184 const char *xminusc;
14189 login_sh = xargv[0] && xargv[0][0] == '-';
14190 #if NUM_SCRIPTS > 0
14195 /* if (xargv[0]) - mmm, this is always true! */
14198 for (i = 0; i < NOPTS; i++)
14200 if (options(&login_sh)) {
14201 /* it already printed err message */
14202 raise_exception(EXERROR);
14206 if (*xargv == NULL) {
14208 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
14211 if (iflag == 2 /* no explicit -i given */
14212 && sflag == 1 /* -s given (or implied) */
14213 && !minusc /* bash compat: ash -sc 'echo $-' is not interactive (dash is) */
14214 && isatty(0) && isatty(1) /* we are on tty */
14220 for (i = 0; i < NOPTS; i++)
14221 if (optlist[i] == 2)
14226 /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
14231 } else if (!sflag) {
14232 setinputfile(*xargv, 0);
14235 commandname = arg0;
14238 shellparam.p = xargv;
14239 #if ENABLE_ASH_GETOPTS
14240 shellparam.optind = 1;
14241 shellparam.optoff = -1;
14243 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
14245 shellparam.nparam++;
14254 * Read /etc/profile, ~/.profile, $ENV.
14257 read_profile(const char *name)
14259 name = expandstr(name, DQSYNTAX);
14260 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
14267 * This routine is called when an error or an interrupt occurs in an
14268 * interactive shell and control is returned to the main command loop.
14269 * (In dash, this function is auto-generated by build machinery).
14278 /* from expand.c: */
14281 /* from input.c: */
14282 g_parsefile->left_in_buffer = 0;
14283 g_parsefile->left_in_line = 0; /* clear input buffer */
14286 /* from redir.c: */
14290 unwindlocalvars(NULL);
14294 static short profile_buf[16384];
14295 extern int etext();
14299 * Main routine. We initialize things, parse the arguments, execute
14300 * profiles if we're a login shell, and then call cmdloop to execute
14301 * commands. The setjmp call sets up the location to jump to when an
14302 * exception occurs. When an exception occurs the variable "state"
14303 * is used to figure out how far we had gotten.
14305 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
14306 #if NUM_SCRIPTS > 0
14307 int ash_main(int argc, char **argv)
14309 int ash_main(int argc UNUSED_PARAM, char **argv)
14311 /* note: 'argc' is used only if embedded scripts are enabled */
14313 volatile smallint state;
14314 struct jmploc jmploc;
14315 struct stackmark smark;
14318 /* Initialize global data */
14322 #if ENABLE_ASH_ALIAS
14328 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
14332 if (setjmp(jmploc.loc)) {
14338 e = exception_type;
14340 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
14344 newline_and_flush(stderr);
14347 popstackmark(&smark);
14348 FORCE_INT_ON; /* enable interrupts */
14357 exception_handler = &jmploc;
14358 rootpid = getpid();
14361 setstackmark(&smark);
14363 #if NUM_SCRIPTS > 0
14365 /* Non-NULL minusc tells procargs that an embedded script is being run */
14366 minusc = get_script_content(-argc - 1);
14368 login_sh = procargs(argv);
14370 TRACE(("Shell args: "));
14371 trace_puts_args(argv);
14378 read_profile("/etc/profile");
14381 hp = lookupvar("HOME");
14383 read_profile("$HOME/.profile");
14389 getuid() == geteuid() && getgid() == getegid() &&
14393 const char *shinit = lookupvar("ENV");
14394 if (shinit != NULL && *shinit != '\0')
14395 read_profile(shinit);
14397 popstackmark(&smark);
14401 /* evalstring pushes parsefile stack.
14402 * Ensure we don't falsely claim that 0 (stdin)
14403 * is one of stacked source fds.
14404 * Testcase: ash -c 'exec 1>&0' must not complain. */
14406 // if (!sflag) g_parsefile->pf_fd = -1;
14407 // ^^ not necessary since now we special-case fd 0
14408 // in save_fd_on_redirect()
14410 // dash: evalstring(minusc, sflag ? 0 : EV_EXIT);
14412 // ash -sc 'echo $-'
14413 // continue reading input from stdin after running 'echo'.
14414 // bash does not do this: it prints "hBcs" and exits.
14415 evalstring(minusc, EV_EXIT);
14418 if (sflag || minusc == NULL) {
14419 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
14421 const char *hp = lookupvar("HISTFILE");
14423 hp = lookupvar("HOME");
14426 hp = concat_path_file(hp, ".ash_history");
14427 setvar0("HISTFILE", hp);
14430 hp = lookupvar("HISTFILE");
14434 line_input_state->hist_file = hp;
14435 # if ENABLE_FEATURE_SH_HISTFILESIZE
14436 hp = lookupvar("HISTFILESIZE");
14437 line_input_state->max_history = size_from_HISTFILESIZE(hp);
14441 state4: /* XXX ??? - why isn't this before the "if" statement */
14449 extern void _mcleanup(void);
14453 TRACE(("End of main reached\n"));
14460 * Copyright (c) 1989, 1991, 1993, 1994
14461 * The Regents of the University of California. All rights reserved.
14463 * This code is derived from software contributed to Berkeley by
14464 * Kenneth Almquist.
14466 * Redistribution and use in source and binary forms, with or without
14467 * modification, are permitted provided that the following conditions
14469 * 1. Redistributions of source code must retain the above copyright
14470 * notice, this list of conditions and the following disclaimer.
14471 * 2. Redistributions in binary form must reproduce the above copyright
14472 * notice, this list of conditions and the following disclaimer in the
14473 * documentation and/or other materials provided with the distribution.
14474 * 3. Neither the name of the University nor the names of its contributors
14475 * may be used to endorse or promote products derived from this software
14476 * without specific prior written permission.
14478 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
14479 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
14480 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
14481 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
14482 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
14483 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
14484 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
14485 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
14486 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
14487 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF