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 (77 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:config ASH_EMBEDDED_SCRIPTS
152 //config: bool "Embed scripts in the binary"
154 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
156 //config: Allow scripts to be compressed and embedded in the busybox
157 //config: binary. The scripts should be placed in the 'embed' directory
158 //config: at build time. Like applets, scripts can be run as
159 //config: 'busybox SCRIPT ...' or by linking their name to the binary.
161 //config:endif # ash options
163 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
164 // APPLET_ODDNAME:name main location suid_type help
165 //applet:IF_SH_IS_ASH( APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
166 //applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
168 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
169 //kbuild:lib-$(CONFIG_SH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
170 //kbuild:lib-$(CONFIG_BASH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
171 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
174 * DEBUG=1 to compile in debugging ('set -o debug' turns on)
175 * DEBUG=2 to compile in and turn on debugging.
176 * When debugging is on ("set -o debug" was executed, or DEBUG=2),
177 * debugging info is written to ./trace, quit signal generates core dump.
180 /* Tweak debug output verbosity here */
184 #define DEBUG_INTONOFF 0
188 #define JOBS ENABLE_ASH_JOB_CONTROL
191 #include <sys/times.h>
192 #include <sys/utsname.h> /* for setting $HOSTNAME */
193 #include "busybox.h" /* for applet_names */
194 #if ENABLE_ASH_EMBEDDED_SCRIPTS
195 # include "embedded_scripts.h"
197 # define NUM_SCRIPTS 0
200 /* So far, all bash compat is controlled by one config option */
201 /* Separate defines document which part of code implements what */
202 /* function keyword */
203 #define BASH_FUNCTION ENABLE_ASH_BASH_COMPAT
204 #define IF_BASH_FUNCTION IF_ASH_BASH_COMPAT
206 #define BASH_REDIR_OUTPUT ENABLE_ASH_BASH_COMPAT
207 #define IF_BASH_REDIR_OUTPUT IF_ASH_BASH_COMPAT
209 #define BASH_DOLLAR_SQUOTE ENABLE_ASH_BASH_COMPAT
210 #define IF_BASH_DOLLAR_SQUOTE IF_ASH_BASH_COMPAT
211 #define BASH_PATTERN_SUBST ENABLE_ASH_BASH_COMPAT
212 #define IF_BASH_PATTERN_SUBST IF_ASH_BASH_COMPAT
213 #define BASH_SUBSTR ENABLE_ASH_BASH_COMPAT
214 #define IF_BASH_SUBSTR IF_ASH_BASH_COMPAT
215 /* BASH_TEST2: [[ EXPR ]]
216 * Status of [[ support:
217 * We replace && and || with -a and -o
219 * singleword+noglob expansion:
220 * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
221 * [[ /bin/n* ]]; echo 0:$?
222 * -a/-o are not AND/OR ops! (they are just strings)
223 * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
224 * = is glob match operator, not equality operator: STR = GLOB
225 * (in GLOB, quoting is significant on char-by-char basis: a*cd"*")
227 * add =~ regex match operator: STR =~ REGEX
229 #define BASH_TEST2 (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)
230 #define BASH_SOURCE ENABLE_ASH_BASH_COMPAT
231 #define BASH_PIPEFAIL ENABLE_ASH_BASH_COMPAT
232 #define BASH_HOSTNAME_VAR ENABLE_ASH_BASH_COMPAT
233 #define BASH_SHLVL_VAR ENABLE_ASH_BASH_COMPAT
234 #define BASH_XTRACEFD ENABLE_ASH_BASH_COMPAT
235 #define BASH_READ_D ENABLE_ASH_BASH_COMPAT
236 #define IF_BASH_READ_D IF_ASH_BASH_COMPAT
238 #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
239 /* Bionic at least up to version 24 has no glob() */
240 # undef ENABLE_ASH_INTERNAL_GLOB
241 # define ENABLE_ASH_INTERNAL_GLOB 1
244 #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
245 # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
246 # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
247 # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
248 # error glob() should unbackslash them and match. uClibc does not unbackslash,
249 # error fails to match dirname, subsequently not expanding <pattern> in it.
251 // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
252 // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
255 #if !ENABLE_ASH_INTERNAL_GLOB
260 #include "shell_common.h"
261 #if ENABLE_FEATURE_SH_MATH
264 typedef long arith_t;
265 # define ARITH_FMT "%ld"
267 #if ENABLE_ASH_RANDOM_SUPPORT
270 # define CLEAR_RANDOM_T(rnd) ((void)0)
273 #include "NUM_APPLETS.h"
275 /* STANDALONE does not make sense, and won't compile */
276 # undef CONFIG_FEATURE_SH_STANDALONE
277 # undef ENABLE_FEATURE_SH_STANDALONE
278 # undef IF_FEATURE_SH_STANDALONE
279 # undef IF_NOT_FEATURE_SH_STANDALONE
280 # define ENABLE_FEATURE_SH_STANDALONE 0
281 # define IF_FEATURE_SH_STANDALONE(...)
282 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
285 #ifndef F_DUPFD_CLOEXEC
286 # define F_DUPFD_CLOEXEC F_DUPFD
292 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
296 # error "Do not even bother, ash will not run on NOMMU machine"
299 /* We use a trick to have more optimized code (fewer pointer reloads):
300 * ash.c: extern struct globals *const ash_ptr_to_globals;
301 * ash_ptr_hack.c: struct globals *ash_ptr_to_globals;
302 * This way, compiler in ash.c knows the pointer can not change.
304 * However, this may break on weird arches or toolchains. In this case,
305 * set "-DBB_GLOBAL_CONST=''" in CONFIG_EXTRA_CFLAGS to disable
308 #ifndef BB_GLOBAL_CONST
309 # define BB_GLOBAL_CONST const
313 /* ============ Hash table sizes. Configurable. */
317 #define CMDTABLESIZE 31 /* should be prime */
320 /* ============ Shell options */
322 static const char *const optletters_optnames[] = {
346 #define optletters(n) optletters_optnames[n][0]
347 #define optnames(n) (optletters_optnames[n] + 1)
349 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
352 /* ============ Misc data */
354 #define msg_illnum "Illegal number: %s"
357 * We enclose jmp_buf in a structure so that we can declare pointers to
358 * jump locations. The global variable handler contains the location to
359 * jump to when an exception occurs, and the global variable exception_type
360 * contains a code identifying the exception. To implement nested
361 * exception handlers, the user should save the value of handler on entry
362 * to an inner scope, set handler to point to a jmploc structure for the
363 * inner scope, and restore handler on exit from the scope.
369 struct globals_misc {
370 uint8_t exitstatus; /* exit status of last command */
371 uint8_t back_exitstatus;/* exit status of backquoted command */
372 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
373 int rootpid; /* pid of main shell */
374 /* shell level: 0 for the main shell, 1 for its children, and so on */
376 #define rootshell (!shlvl)
379 char *minusc; /* argument to -c option */
381 char *curdir; // = nullstr; /* current working directory */
382 char *physdir; // = nullstr; /* physical working directory */
384 char *arg0; /* value of $0 */
386 struct jmploc *exception_handler;
388 volatile int suppress_int; /* counter */
389 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
390 volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
391 volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
392 smallint exception_type; /* kind of exception (0..5) */
394 #define EXINT 0 /* SIGINT received */
395 #define EXERROR 1 /* a generic error */
396 #define EXEXIT 4 /* exit the shell */
398 char nullstr[1]; /* zero length string */
401 #define eflag optlist[0]
402 #define fflag optlist[1]
403 #define Iflag optlist[2]
404 #define iflag optlist[3]
405 #define mflag optlist[4]
406 #define nflag optlist[5]
407 #define sflag optlist[6]
408 #define xflag optlist[7]
409 #define vflag optlist[8]
410 #define Cflag optlist[9]
411 #define aflag optlist[10]
412 #define bflag optlist[11]
413 #define uflag optlist[12]
414 #define viflag optlist[13]
416 # define pipefail optlist[14]
421 # define nolog optlist[14 + BASH_PIPEFAIL]
422 # define debug optlist[15 + BASH_PIPEFAIL]
425 /* trap handler commands */
427 * Sigmode records the current value of the signal handlers for the various
428 * modes. A value of zero means that the current handler is not known.
429 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
431 char sigmode[NSIG - 1];
432 #define S_DFL 1 /* default signal handling (SIG_DFL) */
433 #define S_CATCH 2 /* signal is caught */
434 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
435 #define S_HARD_IGN 4 /* signal is ignored permanently (it was SIG_IGN on entry to shell) */
437 /* indicates specified signal received */
438 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
439 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
441 char **trap_ptr; /* used only by "trap hack" */
443 /* Rarely referenced stuff */
444 #if ENABLE_ASH_RANDOM_SUPPORT
447 pid_t backgndpid; /* pid of last background process */
449 extern struct globals_misc *BB_GLOBAL_CONST ash_ptr_to_globals_misc;
450 #define G_misc (*ash_ptr_to_globals_misc)
451 #define exitstatus (G_misc.exitstatus )
452 #define back_exitstatus (G_misc.back_exitstatus )
453 #define job_warning (G_misc.job_warning)
454 #define rootpid (G_misc.rootpid )
455 #define shlvl (G_misc.shlvl )
456 #define errlinno (G_misc.errlinno )
457 #define minusc (G_misc.minusc )
458 #define curdir (G_misc.curdir )
459 #define physdir (G_misc.physdir )
460 #define arg0 (G_misc.arg0 )
461 #define exception_handler (G_misc.exception_handler)
462 #define exception_type (G_misc.exception_type )
463 #define suppress_int (G_misc.suppress_int )
464 #define pending_int (G_misc.pending_int )
465 #define got_sigchld (G_misc.got_sigchld )
466 #define pending_sig (G_misc.pending_sig )
467 #define nullstr (G_misc.nullstr )
468 #define optlist (G_misc.optlist )
469 #define sigmode (G_misc.sigmode )
470 #define gotsig (G_misc.gotsig )
471 #define may_have_traps (G_misc.may_have_traps )
472 #define trap (G_misc.trap )
473 #define trap_ptr (G_misc.trap_ptr )
474 #define random_gen (G_misc.random_gen )
475 #define backgndpid (G_misc.backgndpid )
476 #define INIT_G_misc() do { \
477 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
485 /* ============ DEBUG */
487 static void trace_printf(const char *fmt, ...);
488 static void trace_vprintf(const char *fmt, va_list va);
489 # define TRACE(param) trace_printf param
490 # define TRACEV(param) trace_vprintf param
491 # define close(fd) do { \
493 if (close(dfd) < 0) \
494 bb_error_msg("bug on %d: closing %d(0x%x)", \
495 __LINE__, dfd, dfd); \
498 # define TRACE(param)
499 # define TRACEV(param)
503 /* ============ Utility functions */
504 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
505 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
508 isdigit_str9(const char *str)
510 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
511 while (--maxlen && isdigit(*str))
513 return (*str == '\0');
517 var_end(const char *var)
526 /* ============ Interrupts / exceptions */
528 static void exitshell(void) NORETURN;
531 * These macros allow the user to suspend the handling of interrupt signals
532 * over a period of time. This is similar to SIGHOLD or to sigblock, but
533 * much more efficient and portable. (But hacking the kernel is so much
534 * more fun than worrying about efficiency and portability. :-))
537 # define INT_OFF do { \
538 TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
543 # define INT_OFF do { \
550 * Called to raise an exception. Since C doesn't include exceptions, we
551 * just do a longjmp to the exception handler. The type of exception is
552 * stored in the global variable "exception_type".
554 static void raise_exception(int) NORETURN;
556 raise_exception(int e)
559 if (exception_handler == NULL)
564 longjmp(exception_handler->loc, 1);
567 #define raise_exception(e) do { \
568 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
569 raise_exception(e); \
574 * Called when a SIGINT is received. (If the user specifies
575 * that SIGINT is to be trapped or ignored using the trap builtin, then
576 * this routine is not called.) Suppressint is nonzero when interrupts
577 * are held using the INT_OFF macro. (The test for iflag is just
578 * defensive programming.)
580 static void raise_interrupt(void) NORETURN;
582 raise_interrupt(void)
585 /* Signal is not automatically unmasked after it is raised,
586 * do it ourself - unmask all signals */
587 sigprocmask_allsigs(SIG_UNBLOCK);
588 /* pending_sig = 0; - now done in signal_handler() */
590 if (!(rootshell && iflag)) {
591 /* Kill ourself with SIGINT */
592 signal(SIGINT, SIG_DFL);
595 /* bash: ^C even on empty command line sets $? */
596 exitstatus = SIGINT + 128;
597 raise_exception(EXINT);
601 #define raise_interrupt() do { \
602 TRACE(("raising interrupt on line %d\n", __LINE__)); \
607 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
611 if (--suppress_int == 0 && pending_int) {
616 # define INT_ON do { \
617 TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
621 # define INT_ON int_on()
623 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
631 #define FORCE_INT_ON force_int_on()
633 #define SAVE_INT(v) ((v) = suppress_int)
635 #define RESTORE_INT(v) do { \
637 suppress_int = (v); \
638 if (suppress_int == 0 && pending_int) \
643 /* ============ Stdout/stderr output */
646 outstr(const char *p, FILE *file)
654 flush_stdout_stderr(void)
661 /* Was called outcslow(c,FILE*), but c was always '\n' */
663 newline_and_flush(FILE *dest)
671 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
673 out1fmt(const char *fmt, ...)
680 r = vprintf(fmt, ap);
686 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
688 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
695 ret = vsnprintf(outbuf, length, fmt, ap);
702 out1str(const char *p)
708 out2str(const char *p)
711 flush_stdout_stderr();
715 /* ============ Parser structures */
717 /* control characters in argument strings */
718 #define CTL_FIRST CTLESC
719 #define CTLESC ((unsigned char)'\201') /* escape next character */
720 #define CTLVAR ((unsigned char)'\202') /* variable defn */
721 #define CTLENDVAR ((unsigned char)'\203')
722 #define CTLBACKQ ((unsigned char)'\204')
723 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
724 #define CTLENDARI ((unsigned char)'\207')
725 #define CTLQUOTEMARK ((unsigned char)'\210')
726 #define CTL_LAST CTLQUOTEMARK
728 /* variable substitution byte (follows CTLVAR) */
729 #define VSTYPE 0x0f /* type of variable substitution */
730 #define VSNUL 0x10 /* colon--treat the empty string as unset */
732 /* values of VSTYPE field */
733 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
734 #define VSMINUS 0x2 /* ${var-text} */
735 #define VSPLUS 0x3 /* ${var+text} */
736 #define VSQUESTION 0x4 /* ${var?message} */
737 #define VSASSIGN 0x5 /* ${var=text} */
738 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
739 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
740 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
741 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
742 #define VSLENGTH 0xa /* ${#var} */
744 #define VSSUBSTR 0xc /* ${var:position:length} */
746 #if BASH_PATTERN_SUBST
747 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
748 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
751 static const char dolatstr[] ALIGN1 = {
752 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
754 #define DOLATSTRLEN 6
773 #if BASH_REDIR_OUTPUT
790 smallint type; /* Nxxxx */
794 union node *redirect;
799 smallint pipe_backgnd;
800 struct nodelist *cmdlist;
807 union node *redirect;
820 union node *elsepart;
856 struct nodelist *backquote;
859 /* nfile and ndup layout must match!
860 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
861 * that it is actually NTO2 (>&file), and change its type.
878 char *_unused_expfname;
897 struct nredir nredir;
898 struct nbinary nbinary;
902 struct nclist nclist;
903 struct ndefun ndefun;
912 * NODE_EOF is returned by parsecmd when it encounters an end of file.
913 * It must be distinct from NULL.
915 #define NODE_EOF ((union node *) -1L)
918 struct nodelist *next;
931 freefunc(struct funcnode *f)
933 if (f && --f->count < 0)
938 /* ============ Debugging output */
942 static FILE *tracefile;
945 trace_printf(const char *fmt, ...)
952 fprintf(tracefile, "%u ", (int) time(NULL));
954 fprintf(tracefile, "[%u] ", (int) getpid());
956 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
958 vfprintf(tracefile, fmt, va);
963 trace_vprintf(const char *fmt, va_list va)
967 vfprintf(tracefile, fmt, va);
968 fprintf(tracefile, "\n");
972 trace_puts(const char *s)
980 trace_puts_quoted(char *s)
987 putc('"', tracefile);
988 for (p = s; *p; p++) {
989 switch ((unsigned char)*p) {
990 case '\n': c = 'n'; goto backslash;
991 case '\t': c = 't'; goto backslash;
992 case '\r': c = 'r'; goto backslash;
993 case '\"': c = '\"'; goto backslash;
994 case '\\': c = '\\'; goto backslash;
995 case CTLESC: c = 'e'; goto backslash;
996 case CTLVAR: c = 'v'; goto backslash;
997 case CTLBACKQ: c = 'q'; goto backslash;
999 putc('\\', tracefile);
1003 if (*p >= ' ' && *p <= '~')
1004 putc(*p, tracefile);
1006 putc('\\', tracefile);
1007 putc((*p >> 6) & 03, tracefile);
1008 putc((*p >> 3) & 07, tracefile);
1009 putc(*p & 07, tracefile);
1014 putc('"', tracefile);
1018 trace_puts_args(char **ap)
1025 trace_puts_quoted(*ap);
1027 putc('\n', tracefile);
1030 putc(' ', tracefile);
1045 /* leave open because libedit might be using it */
1048 strcpy(s, "./trace");
1050 if (!freopen(s, "a", tracefile)) {
1051 fprintf(stderr, "Can't re-open %s\n", s);
1056 tracefile = fopen(s, "a");
1057 if (tracefile == NULL) {
1058 fprintf(stderr, "Can't open %s\n", s);
1064 flags = fcntl(fileno(tracefile), F_GETFL);
1066 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
1068 setlinebuf(tracefile);
1069 fputs("\nTracing started.\n", tracefile);
1073 indent(int amount, char *pfx, FILE *fp)
1077 for (i = 0; i < amount; i++) {
1078 if (pfx && i == amount - 1)
1084 /* little circular references here... */
1085 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
1088 sharg(union node *arg, FILE *fp)
1091 struct nodelist *bqlist;
1092 unsigned char subtype;
1094 if (arg->type != NARG) {
1095 out1fmt("<node type %d>\n", arg->type);
1098 bqlist = arg->narg.backquote;
1099 for (p = arg->narg.text; *p; p++) {
1100 switch ((unsigned char)*p) {
1109 if (subtype == VSLENGTH)
1117 if (subtype & VSNUL)
1120 switch (subtype & VSTYPE) {
1146 case VSTRIMRIGHTMAX:
1153 out1fmt("<subtype %d>", subtype);
1162 shtree(bqlist->n, -1, NULL, fp);
1173 shcmd(union node *cmd, FILE *fp)
1181 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1187 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1191 switch (np->nfile.type) {
1192 case NTO: s = ">>"+1; dftfd = 1; break;
1193 case NCLOBBER: s = ">|"; dftfd = 1; break;
1194 case NAPPEND: s = ">>"; dftfd = 1; break;
1195 #if BASH_REDIR_OUTPUT
1198 case NTOFD: s = ">&"; dftfd = 1; break;
1199 case NFROM: s = "<"; break;
1200 case NFROMFD: s = "<&"; break;
1201 case NFROMTO: s = "<>"; break;
1202 default: s = "*error*"; break;
1204 if (np->nfile.fd != dftfd)
1205 fprintf(fp, "%d", np->nfile.fd);
1207 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1208 fprintf(fp, "%d", np->ndup.dupfd);
1210 sharg(np->nfile.fname, fp);
1217 shtree(union node *n, int ind, char *pfx, FILE *fp)
1219 struct nodelist *lp;
1225 indent(ind, pfx, fp);
1227 if (n == NODE_EOF) {
1242 shtree(n->nbinary.ch1, ind, NULL, fp);
1245 shtree(n->nbinary.ch2, ind, NULL, fp);
1253 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1254 shtree(lp->n, 0, NULL, fp);
1258 if (n->npipe.pipe_backgnd)
1264 fprintf(fp, "<node type %d>", n->type);
1272 showtree(union node *n)
1274 trace_puts("showtree called\n");
1275 shtree(n, 1, NULL, stderr);
1281 /* ============ Parser data */
1284 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1287 struct strlist *next;
1294 struct strpush *prev; /* preceding string on stack */
1296 int prev_left_in_line;
1297 #if ENABLE_ASH_ALIAS
1298 struct alias *ap; /* if push was associated with an alias */
1300 char *string; /* remember the string since it may change */
1302 /* Remember last two characters for pungetc. */
1305 /* Number of outstanding calls to pungetc. */
1310 * The parsefile structure pointed to by the global variable parsefile
1311 * contains information about the current file being read.
1314 struct parsefile *prev; /* preceding file on stack */
1315 int linno; /* current line */
1316 int pf_fd; /* file descriptor (or -1 if string) */
1317 int left_in_line; /* number of chars left in this line */
1318 int left_in_buffer; /* number of chars left in this buffer past the line */
1319 char *next_to_pgetc; /* next char in buffer */
1320 char *buf; /* input buffer */
1321 struct strpush *strpush; /* for pushing strings at this level */
1322 struct strpush basestrpush; /* so pushing one is fast */
1324 /* Remember last two characters for pungetc. */
1327 /* Number of outstanding calls to pungetc. */
1331 static struct parsefile basepf; /* top level input file */
1332 static struct parsefile *g_parsefile = &basepf; /* current input file */
1333 static char *commandname; /* currently executing command */
1336 /* ============ Message printing */
1339 ash_vmsg(const char *msg, va_list ap)
1341 fprintf(stderr, "%s: ", arg0);
1343 if (strcmp(arg0, commandname))
1344 fprintf(stderr, "%s: ", commandname);
1345 if (!iflag || g_parsefile->pf_fd > 0)
1346 fprintf(stderr, "line %d: ", errlinno);
1348 vfprintf(stderr, msg, ap);
1349 newline_and_flush(stderr);
1353 * Exverror is called to raise the error exception. If the second argument
1354 * is not NULL then error prints an error message using printf style
1355 * formatting. It then raises the error exception.
1357 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1359 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1363 TRACE(("ash_vmsg_and_raise(%d):", cond));
1366 TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
1371 flush_stdout_stderr();
1372 raise_exception(cond);
1376 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1378 ash_msg_and_raise_error(const char *msg, ...)
1385 ash_vmsg_and_raise(EXERROR, msg, ap);
1391 * 'fmt' must be a string literal.
1393 #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": "STRERROR_FMT, ##__VA_ARGS__ STRERROR_ERRNO)
1395 static void raise_error_syntax(const char *) NORETURN;
1397 raise_error_syntax(const char *msg)
1399 errlinno = g_parsefile->linno;
1400 ash_msg_and_raise_error("syntax error: %s", msg);
1404 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1406 ash_msg_and_raise(int cond, const char *msg, ...)
1411 ash_vmsg_and_raise(cond, msg, ap);
1417 * error/warning routines for external builtins
1420 ash_msg(const char *fmt, ...)
1430 * Return a string describing an error. The returned string may be a
1431 * pointer to a static buffer that will be overwritten on the next call.
1432 * Action describes the operation that got the error.
1435 errmsg(int e, const char *em)
1437 if (e == ENOENT || e == ENOTDIR) {
1444 /* ============ Memory allocation */
1447 /* I consider these wrappers nearly useless:
1448 * ok, they return you to nearest exception handler, but
1449 * how much memory do you leak in the process, making
1450 * memory starvation worse?
1453 ckrealloc(void * p, size_t nbytes)
1455 p = realloc(p, nbytes);
1457 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1462 ckmalloc(size_t nbytes)
1464 return ckrealloc(NULL, nbytes);
1468 ckzalloc(size_t nbytes)
1470 return memset(ckmalloc(nbytes), 0, nbytes);
1474 ckstrdup(const char *s)
1476 char *p = strdup(s);
1478 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1482 /* Using bbox equivalents. They exit if out of memory */
1483 # define ckrealloc xrealloc
1484 # define ckmalloc xmalloc
1485 # define ckzalloc xzalloc
1486 # define ckstrdup xstrdup
1490 * It appears that grabstackstr() will barf with such alignments
1491 * because stalloc() will return a string allocated in a new stackblock.
1493 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1495 /* Most machines require the value returned from malloc to be aligned
1496 * in some way. The following macro will get this right
1497 * on many machines. */
1498 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1499 /* Minimum size of a block */
1500 MINSIZE = SHELL_ALIGN(504),
1503 struct stack_block {
1504 struct stack_block *prev;
1505 char space[MINSIZE];
1509 struct stack_block *stackp;
1515 struct globals_memstack {
1516 struct stack_block *g_stackp; // = &stackbase;
1517 char *g_stacknxt; // = stackbase.space;
1518 char *sstrend; // = stackbase.space + MINSIZE;
1519 size_t g_stacknleft; // = MINSIZE;
1520 struct stack_block stackbase;
1522 extern struct globals_memstack *BB_GLOBAL_CONST ash_ptr_to_globals_memstack;
1523 #define G_memstack (*ash_ptr_to_globals_memstack)
1524 #define g_stackp (G_memstack.g_stackp )
1525 #define g_stacknxt (G_memstack.g_stacknxt )
1526 #define sstrend (G_memstack.sstrend )
1527 #define g_stacknleft (G_memstack.g_stacknleft)
1528 #define stackbase (G_memstack.stackbase )
1529 #define INIT_G_memstack() do { \
1530 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1532 g_stackp = &stackbase; \
1533 g_stacknxt = stackbase.space; \
1534 g_stacknleft = MINSIZE; \
1535 sstrend = stackbase.space + MINSIZE; \
1539 #define stackblock() ((void *)g_stacknxt)
1540 #define stackblocksize() g_stacknleft
1543 * Parse trees for commands are allocated in lifo order, so we use a stack
1544 * to make this more efficient, and also to avoid all sorts of exception
1545 * handling code to handle interrupts in the middle of a parse.
1547 * The size 504 was chosen because the Ultrix malloc handles that size
1551 stalloc(size_t nbytes)
1556 aligned = SHELL_ALIGN(nbytes);
1557 if (aligned > g_stacknleft) {
1560 struct stack_block *sp;
1562 blocksize = aligned;
1563 if (blocksize < MINSIZE)
1564 blocksize = MINSIZE;
1565 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1566 if (len < blocksize)
1567 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1570 sp->prev = g_stackp;
1571 g_stacknxt = sp->space;
1572 g_stacknleft = blocksize;
1573 sstrend = g_stacknxt + blocksize;
1578 g_stacknxt += aligned;
1579 g_stacknleft -= aligned;
1584 stzalloc(size_t nbytes)
1586 return memset(stalloc(nbytes), 0, nbytes);
1593 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1594 write(STDERR_FILENO, "stunalloc\n", 10);
1598 g_stacknleft += g_stacknxt - (char *)p;
1603 * Like strdup but works with the ash stack.
1606 sstrdup(const char *p)
1608 size_t len = strlen(p) + 1;
1609 return memcpy(stalloc(len), p, len);
1612 static ALWAYS_INLINE void
1613 grabstackblock(size_t len)
1619 pushstackmark(struct stackmark *mark, size_t len)
1621 mark->stackp = g_stackp;
1622 mark->stacknxt = g_stacknxt;
1623 mark->stacknleft = g_stacknleft;
1624 grabstackblock(len);
1628 setstackmark(struct stackmark *mark)
1630 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1634 popstackmark(struct stackmark *mark)
1636 struct stack_block *sp;
1642 while (g_stackp != mark->stackp) {
1644 g_stackp = sp->prev;
1647 g_stacknxt = mark->stacknxt;
1648 g_stacknleft = mark->stacknleft;
1649 sstrend = mark->stacknxt + mark->stacknleft;
1654 * When the parser reads in a string, it wants to stick the string on the
1655 * stack and only adjust the stack pointer when it knows how big the
1656 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1657 * of space on top of the stack and stackblocklen returns the length of
1658 * this block. Growstackblock will grow this space by at least one byte,
1659 * possibly moving it (like realloc). Grabstackblock actually allocates the
1660 * part of the block that has been used.
1663 growstackblock(void)
1667 newlen = g_stacknleft * 2;
1668 if (newlen < g_stacknleft)
1669 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1673 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1674 struct stack_block *sp;
1675 struct stack_block *prevstackp;
1680 prevstackp = sp->prev;
1681 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1682 sp = ckrealloc(sp, grosslen);
1683 sp->prev = prevstackp;
1685 g_stacknxt = sp->space;
1686 g_stacknleft = newlen;
1687 sstrend = sp->space + newlen;
1690 char *oldspace = g_stacknxt;
1691 size_t oldlen = g_stacknleft;
1692 char *p = stalloc(newlen);
1694 /* free the space we just allocated */
1695 g_stacknxt = memcpy(p, oldspace, oldlen);
1696 g_stacknleft += newlen;
1701 * The following routines are somewhat easier to use than the above.
1702 * The user declares a variable of type STACKSTR, which may be declared
1703 * to be a register. The macro STARTSTACKSTR initializes things. Then
1704 * the user uses the macro STPUTC to add characters to the string. In
1705 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1706 * grown as necessary. When the user is done, she can just leave the
1707 * string there and refer to it using stackblock(). Or she can allocate
1708 * the space for it using grabstackstr(). If it is necessary to allow
1709 * someone else to use the stack temporarily and then continue to grow
1710 * the string, the user should use grabstack to allocate the space, and
1711 * then call ungrabstr(p) to return to the previous mode of operation.
1713 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1714 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1715 * is space for at least one character.
1720 size_t len = stackblocksize();
1722 return (char *)stackblock() + len;
1726 * Called from CHECKSTRSPACE.
1729 makestrspace(size_t newlen, char *p)
1731 size_t len = p - g_stacknxt;
1737 size = stackblocksize();
1739 if (nleft >= newlen)
1743 return (char *)stackblock() + len;
1747 stack_nputstr(const char *s, size_t n, char *p)
1749 p = makestrspace(n, p);
1750 p = (char *)mempcpy(p, s, n);
1755 stack_putstr(const char *s, char *p)
1757 return stack_nputstr(s, strlen(s), p);
1761 _STPUTC(int c, char *p)
1769 #define STARTSTACKSTR(p) ((p) = stackblock())
1770 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1771 #define CHECKSTRSPACE(n, p) do { \
1774 size_t m = sstrend - q; \
1776 (p) = makestrspace(l, q); \
1778 #define USTPUTC(c, p) (*(p)++ = (c))
1779 #define STACKSTRNUL(p) do { \
1780 if ((p) == sstrend) \
1781 (p) = growstackstr(); \
1784 #define STUNPUTC(p) (--(p))
1785 #define STTOPC(p) ((p)[-1])
1786 #define STADJUST(amount, p) ((p) += (amount))
1788 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1789 #define ungrabstackstr(s, p) stunalloc(s)
1790 #define stackstrend() ((void *)sstrend)
1793 /* ============ String helpers */
1796 * prefix -- see if pfx is a prefix of string.
1799 prefix(const char *string, const char *pfx)
1802 if (*pfx++ != *string++)
1805 return (char *) string;
1809 * Check for a valid number. This should be elsewhere.
1812 is_number(const char *p)
1817 } while (*++p != '\0');
1822 * Convert a string of digits to an integer, printing an error message on
1826 number(const char *s)
1829 ash_msg_and_raise_error(msg_illnum, s);
1834 * Produce a single quoted string suitable as input to the shell.
1835 * The return string is allocated on the stack.
1838 single_quote(const char *s)
1848 len = strchrnul(s, '\'') - s;
1850 q = p = makestrspace(len + 3, p);
1853 q = (char *)mempcpy(q, s, len);
1862 do len++; while (*++s == '\'');
1864 q = p = makestrspace(len + 3, p);
1867 q = (char *)mempcpy(q, s - len, len);
1875 return stackblock();
1879 * Produce a possibly single quoted string suitable as input to the shell.
1880 * If quoting was done, the return string is allocated on the stack,
1881 * otherwise a pointer to the original string is returned.
1884 maybe_single_quote(const char *s)
1889 /* Assuming ACSII */
1890 /* quote ctrl_chars space !"#$%&'()* */
1894 if (*p >= ';' && *p <= '?')
1903 /* quote {|}~ DEL and high bytes */
1906 /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
1907 /* TODO: maybe avoid quoting % */
1913 return single_quote(s);
1917 /* ============ nextopt */
1919 static char **argptr; /* argument list for builtin commands */
1920 static char *optionarg; /* set by nextopt (like getopt) */
1921 static char *optptr; /* used by nextopt */
1924 * XXX - should get rid of. Have all builtins use getopt(3).
1925 * The library getopt must have the BSD extension static variable
1926 * "optreset", otherwise it can't be used within the shell safely.
1928 * Standard option processing (a la getopt) for builtin routines.
1929 * The only argument that is passed to nextopt is the option string;
1930 * the other arguments are unnecessary. It returns the character,
1931 * or '\0' on end of input.
1934 nextopt(const char *optstring)
1941 if (p == NULL || *p == '\0') {
1942 /* We ate entire "-param", take next one */
1948 if (*++p == '\0') /* just "-" ? */
1951 if (LONE_DASH(p)) /* "--" ? */
1953 /* p => next "-param" */
1955 /* p => some option char in the middle of a "-param" */
1957 for (q = optstring; *q != c;) {
1959 ash_msg_and_raise_error("illegal option -%c", c);
1967 ash_msg_and_raise_error("no arg for -%c option", c);
1977 /* ============ Shell variables */
1980 int nparam; /* # of positional parameters (without $0) */
1981 #if ENABLE_ASH_GETOPTS
1982 int optind; /* next parameter to be processed by getopts */
1983 int optoff; /* used by getopts */
1985 unsigned char malloced; /* if parameter list dynamically allocated */
1986 char **p; /* parameter list */
1990 * Free the list of positional parameters.
1993 freeparam(volatile struct shparam *param)
1995 if (param->malloced) {
1997 ap = ap1 = param->p;
2004 #if ENABLE_ASH_GETOPTS
2005 static void FAST_FUNC getoptsreset(const char *value);
2009 struct var *next; /* next entry in hash list */
2010 int flags; /* flags are defined above */
2011 const char *var_text; /* name=value */
2012 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
2013 /* the variable gets set/unset */
2017 struct localvar *next; /* next local variable in list */
2018 struct var *vp; /* the variable that was made local */
2019 int flags; /* saved flags */
2020 const char *text; /* saved text */
2024 #define VEXPORT 0x01 /* variable is exported */
2025 #define VREADONLY 0x02 /* variable cannot be modified */
2026 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
2027 #define VTEXTFIXED 0x08 /* text is statically allocated */
2028 #define VSTACK 0x10 /* text is allocated on the stack */
2029 #define VUNSET 0x20 /* the variable is not set */
2030 #define VNOFUNC 0x40 /* don't call the callback function */
2031 #define VNOSET 0x80 /* do not set variable - just readonly test */
2032 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
2033 #if ENABLE_ASH_RANDOM_SUPPORT
2034 # define VDYNAMIC 0x200 /* dynamic variable */
2040 /* Need to be before varinit_data[] */
2041 #if ENABLE_LOCALE_SUPPORT
2042 static void FAST_FUNC
2043 change_lc_all(const char *value)
2045 if (value && *value != '\0')
2046 setlocale(LC_ALL, value);
2048 static void FAST_FUNC
2049 change_lc_ctype(const char *value)
2051 if (value && *value != '\0')
2052 setlocale(LC_CTYPE, value);
2056 static void chkmail(void);
2057 static void changemail(const char *var_value) FAST_FUNC;
2059 # define chkmail() ((void)0)
2061 static void changepath(const char *) FAST_FUNC;
2062 #if ENABLE_ASH_RANDOM_SUPPORT
2063 static void change_random(const char *) FAST_FUNC;
2066 static const struct {
2068 const char *var_text;
2069 void (*var_func)(const char *) FAST_FUNC;
2070 } varinit_data[] = {
2072 * Note: VEXPORT would not work correctly here for NOFORK applets:
2073 * some environment strings may be constant.
2075 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
2077 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
2078 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
2080 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
2081 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
2082 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
2083 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
2084 #if ENABLE_ASH_GETOPTS
2085 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
2087 { VSTRFIXED|VTEXTFIXED , NULL /* inited to linenovar */, NULL },
2088 #if ENABLE_ASH_RANDOM_SUPPORT
2089 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
2091 #if ENABLE_LOCALE_SUPPORT
2092 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
2093 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
2095 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
2096 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
2102 struct globals_var {
2103 struct shparam shellparam; /* $@ current positional parameters */
2104 struct redirtab *redirlist;
2105 int preverrout_fd; /* stderr fd: usually 2, unless redirect moved it */
2106 struct var *vartab[VTABSIZE];
2107 struct var varinit[ARRAY_SIZE(varinit_data)];
2109 char linenovar[sizeof("LINENO=") + sizeof(int)*3];
2111 extern struct globals_var *BB_GLOBAL_CONST ash_ptr_to_globals_var;
2112 #define G_var (*ash_ptr_to_globals_var)
2113 #define shellparam (G_var.shellparam )
2114 //#define redirlist (G_var.redirlist )
2115 #define preverrout_fd (G_var.preverrout_fd)
2116 #define vartab (G_var.vartab )
2117 #define varinit (G_var.varinit )
2118 #define lineno (G_var.lineno )
2119 #define linenovar (G_var.linenovar )
2120 #define vifs varinit[0]
2122 # define vmail (&vifs)[1]
2123 # define vmpath (&vmail)[1]
2124 # define vpath (&vmpath)[1]
2126 # define vpath (&vifs)[1]
2128 #define vps1 (&vpath)[1]
2129 #define vps2 (&vps1)[1]
2130 #define vps4 (&vps2)[1]
2131 #if ENABLE_ASH_GETOPTS
2132 # define voptind (&vps4)[1]
2133 # define vlineno (&voptind)[1]
2134 # if ENABLE_ASH_RANDOM_SUPPORT
2135 # define vrandom (&vlineno)[1]
2138 # define vlineno (&vps4)[1]
2139 # if ENABLE_ASH_RANDOM_SUPPORT
2140 # define vrandom (&vlineno)[1]
2143 #define INIT_G_var() do { \
2145 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
2147 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
2148 varinit[i].flags = varinit_data[i].flags; \
2149 varinit[i].var_text = varinit_data[i].var_text; \
2150 varinit[i].var_func = varinit_data[i].var_func; \
2152 strcpy(linenovar, "LINENO="); \
2153 vlineno.var_text = linenovar; \
2157 * The following macros access the values of the above variables.
2158 * They have to skip over the name. They return the null string
2159 * for unset variables.
2161 #define ifsval() (vifs.var_text + 4)
2162 #define ifsset() ((vifs.flags & VUNSET) == 0)
2164 # define mailval() (vmail.var_text + 5)
2165 # define mpathval() (vmpath.var_text + 9)
2166 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2168 #define pathval() (vpath.var_text + 5)
2169 #define ps1val() (vps1.var_text + 4)
2170 #define ps2val() (vps2.var_text + 4)
2171 #define ps4val() (vps4.var_text + 4)
2172 #if ENABLE_ASH_GETOPTS
2173 # define optindval() (voptind.var_text + 7)
2176 #if ENABLE_ASH_GETOPTS
2177 static void FAST_FUNC
2178 getoptsreset(const char *value)
2180 shellparam.optind = 1;
2181 if (is_number(value))
2182 shellparam.optind = number(value) ?: 1;
2183 shellparam.optoff = -1;
2188 * Compares two strings up to the first = or '\0'. The first
2189 * string must be terminated by '='; the second may be terminated by
2190 * either '=' or '\0'.
2193 varcmp(const char *p, const char *q)
2197 while ((c = *p) == (d = *q)) {
2198 if (c == '\0' || c == '=')
2212 * Find the appropriate entry in the hash table from the name.
2214 static struct var **
2215 hashvar(const char *p)
2219 hashval = ((unsigned char) *p) << 4;
2220 while (*p && *p != '=')
2221 hashval += (unsigned char) *p++;
2222 return &vartab[hashval % VTABSIZE];
2226 vpcmp(const void *a, const void *b)
2228 return varcmp(*(const char **)a, *(const char **)b);
2232 * This routine initializes the builtin variables.
2242 * PS1 depends on uid
2244 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2245 vps1.var_text = "PS1=\\w \\$ ";
2248 vps1.var_text = "PS1=# ";
2251 end = vp + ARRAY_SIZE(varinit);
2253 vpp = hashvar(vp->var_text);
2256 } while (++vp < end);
2259 static struct var **
2260 findvar(struct var **vpp, const char *name)
2262 for (; *vpp; vpp = &(*vpp)->next) {
2263 if (varcmp((*vpp)->var_text, name) == 0) {
2271 * Find the value of a variable. Returns NULL if not set.
2273 static const char* FAST_FUNC
2274 lookupvar(const char *name)
2278 v = *findvar(hashvar(name), name);
2280 #if ENABLE_ASH_RANDOM_SUPPORT
2282 * Dynamic variables are implemented roughly the same way they are
2283 * in bash. Namely, they're "special" so long as they aren't unset.
2284 * As soon as they're unset, they're no longer dynamic, and dynamic
2285 * lookup will no longer happen at that point. -- PFM.
2287 if (v->flags & VDYNAMIC)
2290 if (!(v->flags & VUNSET)) {
2291 if (v == &vlineno && v->var_text == linenovar) {
2292 fmtstr(linenovar+7, sizeof(linenovar)-7, "%d", lineno);
2294 return var_end(v->var_text);
2300 #if ENABLE_UNICODE_SUPPORT
2302 reinit_unicode_for_ash(void)
2304 /* Unicode support should be activated even if LANG is set
2305 * _during_ shell execution, not only if it was set when
2306 * shell was started. Therefore, re-check LANG every time:
2308 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2309 || ENABLE_UNICODE_USING_LOCALE
2311 const char *s = lookupvar("LC_ALL");
2312 if (!s) s = lookupvar("LC_CTYPE");
2313 if (!s) s = lookupvar("LANG");
2318 # define reinit_unicode_for_ash() ((void)0)
2322 * Search the environment of a builtin command.
2324 static ALWAYS_INLINE const char *
2325 bltinlookup(const char *name)
2327 return lookupvar(name);
2331 * Same as setvar except that the variable and value are passed in
2332 * the first argument as name=value. Since the first argument will
2333 * be actually stored in the table, it should not be a string that
2335 * Called with interrupts off.
2338 setvareq(char *s, int flags)
2340 struct var *vp, **vpp;
2343 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2344 vpp = findvar(vpp, s);
2347 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2350 if (flags & VNOSAVE)
2354 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2360 if (vp->var_func && !(flags & VNOFUNC))
2361 vp->var_func(var_end(s));
2363 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2364 free((char*)vp->var_text);
2366 if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
2370 if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
2375 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2377 /* variable s is not found */
2380 if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
2382 vp = ckzalloc(sizeof(*vp));
2384 /*vp->func = NULL; - ckzalloc did it */
2387 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2397 * Set the value of a variable. The flags argument is ored with the
2398 * flags of the variable. If val is NULL, the variable is unset.
2401 setvar(const char *name, const char *val, int flags)
2410 q = endofname(name);
2411 p = strchrnul(q, '=');
2413 if (!namelen || p != q)
2414 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2419 vallen = strlen(val);
2423 nameeq = ckzalloc(namelen + vallen + 2);
2424 p = mempcpy(nameeq, name, namelen);
2427 memcpy(p, val, vallen);
2429 vp = setvareq(nameeq, flags | VNOSAVE);
2435 static void FAST_FUNC
2436 setvar0(const char *name, const char *val)
2438 setvar(name, val, 0);
2442 * Unset the specified variable.
2445 unsetvar(const char *s)
2451 * Process a linked list of variable assignments.
2454 listsetvar(struct strlist *list_set_var, int flags)
2456 struct strlist *lp = list_set_var;
2462 setvareq(lp->text, flags);
2469 * Generate a list of variables satisfying the given conditions.
2471 #if !ENABLE_FEATURE_SH_NOFORK
2472 # define listvars(on, off, lp, end) listvars(on, off, end)
2475 listvars(int on, int off, struct strlist *lp, char ***end)
2486 for (vp = *vpp; vp; vp = vp->next) {
2487 if ((vp->flags & mask) == on) {
2488 #if ENABLE_FEATURE_SH_NOFORK
2489 /* If variable with the same name is both
2490 * exported and temporarily set for a command:
2493 * then "ZVAR=6" will be both in vartab and
2494 * lp lists. Do not pass it twice to printenv.
2496 struct strlist *lp1 = lp;
2498 if (strcmp(lp1->text, vp->var_text) == 0)
2503 if (ep == stackstrend())
2504 ep = growstackstr();
2505 *ep++ = (char*)vp->var_text;
2506 #if ENABLE_FEATURE_SH_NOFORK
2511 } while (++vpp < vartab + VTABSIZE);
2513 #if ENABLE_FEATURE_SH_NOFORK
2515 if (ep == stackstrend())
2516 ep = growstackstr();
2522 if (ep == stackstrend())
2523 ep = growstackstr();
2527 return grabstackstr(ep);
2531 /* ============ Path search helper
2533 * The variable path (passed by reference) should be set to the start
2534 * of the path before the first call; path_advance will update
2535 * this value as it proceeds. Successive calls to path_advance will return
2536 * the possible path expansions in sequence. If an option (indicated by
2537 * a percent sign) appears in the path entry then the global variable
2538 * pathopt will be set to point to it; otherwise pathopt will be set to
2541 static const char *pathopt; /* set by path_advance */
2544 path_advance(const char **path, const char *name)
2554 for (p = start; *p && *p != ':' && *p != '%'; p++)
2556 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2557 while (stackblocksize() < len)
2561 q = mempcpy(q, start, p - start);
2568 while (*p && *p != ':')
2575 return stalloc(len);
2579 /* ============ Prompt */
2581 static smallint doprompt; /* if set, prompt the user */
2582 static smallint needprompt; /* true if interactive and at start of line */
2584 #if ENABLE_FEATURE_EDITING
2585 static line_input_t *line_input_state;
2586 static const char *cmdedit_prompt;
2588 putprompt(const char *s)
2590 if (ENABLE_ASH_EXPAND_PRMT) {
2591 free((char*)cmdedit_prompt);
2592 cmdedit_prompt = ckstrdup(s);
2599 putprompt(const char *s)
2605 /* expandstr() needs parsing machinery, so it is far away ahead... */
2606 static const char *expandstr(const char *ps, int syntax_type);
2607 /* Values for syntax param */
2608 #define BASESYNTAX 0 /* not in quotes */
2609 #define DQSYNTAX 1 /* in double quotes */
2610 #define SQSYNTAX 2 /* in single quotes */
2611 #define ARISYNTAX 3 /* in arithmetic */
2612 #if ENABLE_ASH_EXPAND_PRMT
2613 # define PSSYNTAX 4 /* prompt. never passed to SIT() */
2615 /* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
2618 * called by editline -- any expansions to the prompt should be added here.
2621 setprompt_if(smallint do_set, int whichprompt)
2624 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2631 switch (whichprompt) {
2641 #if ENABLE_ASH_EXPAND_PRMT
2642 pushstackmark(&smark, stackblocksize());
2643 putprompt(expandstr(prompt, PSSYNTAX));
2644 popstackmark(&smark);
2651 /* ============ The cd and pwd commands */
2653 #define CD_PHYSICAL 1
2663 while ((i = nextopt("LP")) != '\0') {
2665 flags ^= CD_PHYSICAL;
2674 * Update curdir (the name of the current directory) in response to a
2678 updatepwd(const char *dir)
2685 cdcomppath = sstrdup(dir);
2688 if (curdir == nullstr)
2690 new = stack_putstr(curdir, new);
2692 new = makestrspace(strlen(dir) + 2, new);
2693 lim = (char *)stackblock() + 1;
2697 if (new > lim && *lim == '/')
2702 if (dir[1] == '/' && dir[2] != '/') {
2708 p = strtok(cdcomppath, "/");
2712 if (p[1] == '.' && p[2] == '\0') {
2724 new = stack_putstr(p, new);
2727 p = strtok(NULL, "/");
2732 return stackblock();
2736 * Find out what the current directory is. If we already know the current
2737 * directory, this routine returns immediately.
2742 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2743 return dir ? dir : nullstr;
2747 setpwd(const char *val, int setold)
2751 oldcur = dir = curdir;
2754 setvar("OLDPWD", oldcur, VEXPORT);
2757 if (physdir != nullstr) {
2758 if (physdir != oldcur)
2762 if (oldcur == val || !val) {
2768 dir = ckstrdup(val);
2769 if (oldcur != dir && oldcur != nullstr) {
2774 setvar("PWD", dir, VEXPORT);
2777 static void hashcd(void);
2780 * Actually do the chdir. We also call hashcd to let other routines
2781 * know that the current directory has changed.
2784 docd(const char *dest, int flags)
2786 const char *dir = NULL;
2789 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2792 if (!(flags & CD_PHYSICAL)) {
2793 dir = updatepwd(dest);
2807 static int FAST_FUNC
2808 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2820 dest = bltinlookup("HOME");
2821 else if (LONE_DASH(dest)) {
2822 dest = bltinlookup("OLDPWD");
2844 path = bltinlookup("CDPATH");
2847 p = path_advance(&path, dest);
2848 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2852 if (!docd(p, flags))
2863 ash_msg_and_raise_perror("can't cd to %s", dest);
2866 if (flags & CD_PRINT)
2867 out1fmt("%s\n", curdir);
2871 static int FAST_FUNC
2872 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2875 const char *dir = curdir;
2879 if (physdir == nullstr)
2883 out1fmt("%s\n", dir);
2888 /* ============ ... */
2891 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2893 /* Syntax classes */
2894 #define CWORD 0 /* character is nothing special */
2895 #define CNL 1 /* newline character */
2896 #define CBACK 2 /* a backslash character */
2897 #define CSQUOTE 3 /* single quote */
2898 #define CDQUOTE 4 /* double quote */
2899 #define CENDQUOTE 5 /* a terminating quote */
2900 #define CBQUOTE 6 /* backwards single quote */
2901 #define CVAR 7 /* a dollar sign */
2902 #define CENDVAR 8 /* a '}' character */
2903 #define CLP 9 /* a left paren in arithmetic */
2904 #define CRP 10 /* a right paren in arithmetic */
2905 #define CENDFILE 11 /* end of file */
2906 #define CCTL 12 /* like CWORD, except it must be escaped */
2907 #define CSPCL 13 /* these terminate a word */
2908 #define CIGN 14 /* character should be ignored */
2911 #if ENABLE_ASH_ALIAS
2915 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2917 #if ENABLE_FEATURE_SH_MATH
2918 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2920 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2922 static const uint16_t S_I_T[] ALIGN2 = {
2923 #if ENABLE_ASH_ALIAS
2924 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2926 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2927 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2928 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2929 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2930 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2931 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2932 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2933 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2934 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2935 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2936 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2937 #if !USE_SIT_FUNCTION
2938 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2939 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2940 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2944 /* Constants below must match table above */
2946 #if ENABLE_ASH_ALIAS
2947 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2949 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2950 CNL_CNL_CNL_CNL , /* 2 */
2951 CWORD_CCTL_CCTL_CWORD , /* 3 */
2952 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2953 CVAR_CVAR_CWORD_CVAR , /* 5 */
2954 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2955 CSPCL_CWORD_CWORD_CLP , /* 7 */
2956 CSPCL_CWORD_CWORD_CRP , /* 8 */
2957 CBACK_CBACK_CCTL_CBACK , /* 9 */
2958 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2959 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2960 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2961 CWORD_CWORD_CWORD_CWORD , /* 13 */
2962 CCTL_CCTL_CCTL_CCTL , /* 14 */
2965 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2966 * caller must ensure proper cast on it if c is *char_ptr!
2968 #if USE_SIT_FUNCTION
2971 SIT(int c, int syntax)
2973 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2974 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2976 * This causes '/' to be prepended with CTLESC in dquoted string,
2977 * making "./file"* treated incorrectly because we feed
2978 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2979 * The "homegrown" glob implementation is okay with that,
2980 * but glibc one isn't. With '/' always treated as CWORD,
2983 # if ENABLE_ASH_ALIAS
2984 static const uint8_t syntax_index_table[] ALIGN1 = {
2985 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2986 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2987 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2991 static const uint8_t syntax_index_table[] ALIGN1 = {
2992 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2993 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2994 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
3003 # if ENABLE_ASH_ALIAS
3009 /* Cast is purely for paranoia here,
3010 * just in case someone passed signed char to us */
3011 if ((unsigned char)c >= CTL_FIRST
3012 && (unsigned char)c <= CTL_LAST
3016 s = strchrnul(spec_symbls, c);
3019 indx = syntax_index_table[s - spec_symbls];
3021 return (S_I_T[indx] >> (syntax*4)) & 0xf;
3024 #else /* !USE_SIT_FUNCTION */
3026 static const uint8_t syntax_index_table[] ALIGN1 = {
3027 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
3028 /* 0 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 1 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 2 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 3 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 4 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 5 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 6 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 7 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 8 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
3038 /* 10 "\n" */ CNL_CNL_CNL_CNL,
3039 /* 11 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 12 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 13 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 14 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 15 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 16 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 17 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 18 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 19 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 20 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 21 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 22 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 23 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 24 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 25 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 26 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 27 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 28 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 29 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 30 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 31 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
3061 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
3062 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
3063 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
3064 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
3065 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
3066 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
3067 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
3068 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
3069 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
3070 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
3071 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
3072 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
3073 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
3074 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
3075 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
3076 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
3077 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
3078 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
3079 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
3080 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
3081 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
3082 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
3083 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
3084 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
3085 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
3086 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
3087 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
3088 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
3089 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
3090 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
3091 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
3092 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
3093 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
3094 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
3095 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
3096 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
3097 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
3098 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
3099 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
3100 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
3101 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
3102 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
3103 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
3104 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
3105 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
3106 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
3107 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
3108 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
3109 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
3110 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
3111 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
3112 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
3113 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
3114 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
3115 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
3116 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
3117 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
3118 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
3119 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
3120 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
3121 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
3122 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
3123 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
3124 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
3125 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
3126 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
3127 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
3128 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
3129 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
3130 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
3131 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
3132 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
3133 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
3134 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
3135 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
3136 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
3137 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
3138 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
3139 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
3140 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3141 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3142 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3143 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3144 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3145 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3146 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3147 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3148 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3149 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3150 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3151 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3152 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3153 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3154 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3155 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3156 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
3157 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
3158 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
3159 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
3160 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
3161 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
3162 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
3163 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3164 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3165 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3166 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3167 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3168 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3169 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3170 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3171 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3172 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3173 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3174 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3175 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3176 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3177 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3178 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3179 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3180 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3181 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3182 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3183 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3184 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3185 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3186 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3187 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3188 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3189 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3190 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3191 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3192 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3193 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3194 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3195 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3196 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3197 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3198 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3199 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3200 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3201 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3202 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3203 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3204 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3205 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3206 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3207 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3208 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3209 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3210 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3211 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3212 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3213 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3214 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3215 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3216 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3217 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3218 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3219 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3220 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3221 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3222 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3223 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3224 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3225 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3226 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3227 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3228 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3229 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3230 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3231 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3232 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3233 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3234 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3235 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3236 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3237 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3238 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3239 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3240 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3241 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3242 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3243 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3244 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3245 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3246 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3247 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3248 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3249 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3250 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3251 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3252 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3253 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3254 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3255 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3256 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3257 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3258 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3259 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3260 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3261 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3262 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3263 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3264 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3265 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3266 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3267 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3268 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3269 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3270 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3271 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3272 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3273 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3274 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3275 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3276 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3277 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3278 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3279 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3280 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3281 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3282 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3283 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3284 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3285 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3286 # if ENABLE_ASH_ALIAS
3287 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3292 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3293 #else /* debug version, caught one signed char bug */
3294 # define SIT(c, syntax) \
3296 if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
3297 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3298 if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
3299 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3300 ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
3304 #endif /* !USE_SIT_FUNCTION */
3307 /* ============ Alias handling */
3309 #if ENABLE_ASH_ALIAS
3311 #define ALIASINUSE 1
3322 static struct alias **atab; // [ATABSIZE];
3323 #define INIT_G_alias() do { \
3324 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3328 static struct alias **
3329 __lookupalias(const char *name)
3331 unsigned int hashval;
3338 ch = (unsigned char)*p;
3342 ch = (unsigned char)*++p;
3344 app = &atab[hashval % ATABSIZE];
3346 for (; *app; app = &(*app)->next) {
3347 if (strcmp(name, (*app)->name) == 0) {
3355 static struct alias *
3356 lookupalias(const char *name, int check)
3358 struct alias *ap = *__lookupalias(name);
3360 if (check && ap && (ap->flag & ALIASINUSE))
3365 static struct alias *
3366 freealias(struct alias *ap)
3370 if (ap->flag & ALIASINUSE) {
3371 ap->flag |= ALIASDEAD;
3383 setalias(const char *name, const char *val)
3385 struct alias *ap, **app;
3387 app = __lookupalias(name);
3391 if (!(ap->flag & ALIASINUSE)) {
3394 ap->val = ckstrdup(val);
3395 ap->flag &= ~ALIASDEAD;
3398 ap = ckzalloc(sizeof(struct alias));
3399 ap->name = ckstrdup(name);
3400 ap->val = ckstrdup(val);
3401 /*ap->flag = 0; - ckzalloc did it */
3402 /*ap->next = NULL;*/
3409 unalias(const char *name)
3413 app = __lookupalias(name);
3417 *app = freealias(*app);
3428 struct alias *ap, **app;
3432 for (i = 0; i < ATABSIZE; i++) {
3434 for (ap = *app; ap; ap = *app) {
3435 *app = freealias(*app);
3445 printalias(const struct alias *ap)
3447 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3451 * TODO - sort output
3453 static int FAST_FUNC
3454 aliascmd(int argc UNUSED_PARAM, char **argv)
3463 for (i = 0; i < ATABSIZE; i++) {
3464 for (ap = atab[i]; ap; ap = ap->next) {
3470 while ((n = *++argv) != NULL) {
3471 v = strchr(n+1, '=');
3472 if (v == NULL) { /* n+1: funny ksh stuff */
3473 ap = *__lookupalias(n);
3475 fprintf(stderr, "%s: %s not found\n", "alias", n);
3488 static int FAST_FUNC
3489 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3493 while (nextopt("a") != '\0') {
3497 for (i = 0; *argptr; argptr++) {
3498 if (unalias(*argptr)) {
3499 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3507 #endif /* ASH_ALIAS */
3510 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3513 #define FORK_NOJOB 2
3515 /* mode flags for showjob(s) */
3516 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3517 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3518 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3519 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3522 * A job structure contains information about a job. A job is either a
3523 * single process or a set of processes contained in a pipeline. In the
3524 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3528 pid_t ps_pid; /* process id */
3529 int ps_status; /* last process status from wait() */
3530 char *ps_cmd; /* text of command being run */
3534 struct procstat ps0; /* status of process */
3535 struct procstat *ps; /* status or processes when more than one */
3537 int stopstatus; /* status of a stopped job */
3539 unsigned nprocs; /* number of processes */
3541 #define JOBRUNNING 0 /* at least one proc running */
3542 #define JOBSTOPPED 1 /* all procs are stopped */
3543 #define JOBDONE 2 /* all procs are completed */
3547 sigint: 1, /* job was killed by SIGINT */
3548 jobctl: 1, /* job running under job control */
3550 waited: 1, /* true if this entry has been waited for */
3551 used: 1, /* true if this entry is in used */
3552 changed: 1; /* true if status has changed */
3553 struct job *prev_job; /* previous job */
3556 static struct job *makejob(/*union node *,*/ int);
3557 static int forkshell(struct job *, union node *, int);
3558 static int waitforjob(struct job *);
3561 enum { doing_jobctl = 0 };
3562 #define setjobctl(on) do {} while (0)
3564 static smallint doing_jobctl; //references:8
3565 static void setjobctl(int);
3572 ignoresig(int signo)
3574 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3575 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3576 /* No, need to do it */
3577 signal(signo, SIG_IGN);
3579 sigmode[signo - 1] = S_HARD_IGN;
3583 * Only one usage site - in setsignal()
3586 signal_handler(int signo)
3588 if (signo == SIGCHLD) {
3594 gotsig[signo - 1] = 1;
3595 pending_sig = signo;
3597 if (signo == SIGINT && !trap[SIGINT]) {
3598 if (!suppress_int) {
3600 raise_interrupt(); /* does not return */
3607 * Set the signal handler for the specified signal. The routine figures
3608 * out what it should be set to.
3611 setsignal(int signo)
3614 char cur_act, new_act;
3615 struct sigaction act;
3619 if (t != NULL) { /* trap for this sig is set */
3621 if (t[0] == '\0') /* trap is "": ignore this sig */
3625 if (rootshell && new_act == S_DFL) {
3628 if (iflag || minusc || sflag == 0)
3637 * "In all cases, bash ignores SIGQUIT. Non-builtin
3638 * commands run by bash have signal handlers
3639 * set to the values inherited by the shell
3640 * from its parent". */
3656 /* if !rootshell, we reset SIGQUIT to DFL,
3657 * whereas we have to restore it to what shell got on entry.
3658 * This is handled by the fact that if signal was IGNored on entry,
3659 * then cur_act is S_HARD_IGN and we never change its sigaction
3663 if (signo == SIGCHLD)
3666 t = &sigmode[signo - 1];
3669 /* current setting is not yet known */
3670 if (sigaction(signo, NULL, &act)) {
3671 /* pretend it worked; maybe we should give a warning,
3672 * but other shells don't. We don't alter sigmode,
3673 * so we retry every time.
3674 * btw, in Linux it never fails. --vda */
3677 if (act.sa_handler == SIG_IGN) {
3678 cur_act = S_HARD_IGN;
3680 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3682 cur_act = S_IGN; /* don't hard ignore these */
3685 if (act.sa_handler == SIG_DFL && new_act == S_DFL) {
3686 /* installing SIG_DFL over SIG_DFL is a no-op */
3687 /* saves one sigaction call in each "sh -c SCRIPT" invocation */
3692 if (cur_act == S_HARD_IGN || cur_act == new_act)
3697 act.sa_handler = SIG_DFL;
3700 act.sa_handler = signal_handler;
3703 act.sa_handler = SIG_IGN;
3706 /* flags and mask matter only if !DFL and !IGN, but we do it
3707 * for all cases for more deterministic behavior:
3709 act.sa_flags = 0; //TODO: why not SA_RESTART?
3710 sigfillset(&act.sa_mask);
3712 sigaction_set(signo, &act);
3715 /* mode flags for set_curjob */
3716 #define CUR_DELETE 2
3717 #define CUR_RUNNING 1
3718 #define CUR_STOPPED 0
3721 /* pgrp of shell on invocation */
3722 static int initialpgrp; //references:2
3723 static int ttyfd = -1; //5
3726 static struct job *jobtab; //5
3728 static unsigned njobs; //4
3730 static struct job *curjob; //lots
3731 /* number of presumed living untracked jobs */
3732 static int jobless; //4
3735 /* Bash has a feature: it restores termios after a successful wait for
3736 * a foreground job which had at least one stopped or sigkilled member.
3737 * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
3738 * properly restoring tty state. Should we do this too?
3739 * A reproducer: ^Z an interactive python:
3742 * Python 2.7.12 (...)
3744 * { python leaves tty in -icanon -echo state. We do survive that... }
3745 * [1]+ Stopped python
3746 * { ...however, next program (python #2) does not survive it well: }
3748 * Python 2.7.12 (...)
3749 * >>> Traceback (most recent call last):
3750 * { above, I typed "qwerty<CR>", but -echo state is still in effect }
3751 * File "<stdin>", line 1, in <module>
3752 * NameError: name 'qwerty' is not defined
3754 * The implementation below is modeled on bash code and seems to work.
3755 * However, I'm not sure we should do this. For one: what if I'd fg
3756 * the stopped python instead? It'll be confused by "restored" tty state.
3758 static struct termios shell_tty_info;
3762 if (rootshell && ttyfd >= 0)
3763 tcgetattr(ttyfd, &shell_tty_info);
3768 /* if (rootshell) - caller ensures this */
3770 tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
3773 job_signal_status(struct job *jp)
3777 struct procstat *ps = jp->ps;
3778 for (i = 0; i < jp->nprocs; i++) {
3779 status = ps[i].ps_status;
3780 if (WIFSIGNALED(status) || WIFSTOPPED(status))
3786 restore_tty_if_stopped_or_signaled(struct job *jp)
3788 //TODO: check what happens if we come from waitforjob() in expbackq()
3790 int s = job_signal_status(jp);
3791 if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
3796 # define get_tty_state() ((void)0)
3797 # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
3801 set_curjob(struct job *jp, unsigned mode)
3804 struct job **jpp, **curp;
3806 /* first remove from list */
3807 jpp = curp = &curjob;
3812 jpp = &jp1->prev_job;
3814 *jpp = jp1->prev_job;
3816 /* Then re-insert in correct position */
3824 /* job being deleted */
3827 /* newly created job or backgrounded job,
3828 * put after all stopped jobs.
3833 if (!jp1 || jp1->state != JOBSTOPPED)
3836 jpp = &jp1->prev_job;
3842 /* newly stopped job - becomes curjob */
3843 jp->prev_job = *jpp;
3851 jobno(const struct job *jp)
3853 return jp - jobtab + 1;
3858 * Convert a job name to a job structure.
3861 #define getjob(name, getctl) getjob(name)
3864 getjob(const char *name, int getctl)
3868 const char *err_msg = "%s: no such job";
3872 char *(*match)(const char *, const char *);
3887 if (c == '+' || c == '%') {
3889 err_msg = "No current job";
3895 err_msg = "No previous job";
3905 if (num > 0 && num <= njobs) {
3906 jp = jobtab + num - 1;
3921 if (match(jp->ps[0].ps_cmd, p)) {
3925 err_msg = "%s: ambiguous";
3935 err_msg = "job %s not created under job control";
3936 if (getctl && jp->jobctl == 0)
3941 ash_msg_and_raise_error(err_msg, name);
3945 * Mark a job structure as unused.
3948 freejob(struct job *jp)
3950 struct procstat *ps;
3954 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3955 if (ps->ps_cmd != nullstr)
3958 if (jp->ps != &jp->ps0)
3961 set_curjob(jp, CUR_DELETE);
3967 xtcsetpgrp(int fd, pid_t pgrp)
3969 if (tcsetpgrp(fd, pgrp))
3970 ash_msg_and_raise_perror("can't set tty process group");
3974 * Turn job control on and off.
3976 * Note: This code assumes that the third arg to ioctl is a character
3977 * pointer, which is true on Berkeley systems but not System V. Since
3978 * System V doesn't have job control yet, this isn't a problem now.
3980 * Called with interrupts off.
3988 if (on == doing_jobctl || rootshell == 0)
3992 ofd = fd = open(_PATH_TTY, O_RDWR);
3994 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3995 * That sometimes helps to acquire controlling tty.
3996 * Obviously, a workaround for bugs when someone
3997 * failed to provide a controlling tty to bash! :) */
4003 /* fd is a tty at this point */
4004 fd = fcntl(fd, F_DUPFD_CLOEXEC, 10);
4005 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
4008 goto out; /* F_DUPFD failed */
4009 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
4010 close_on_exec_on(fd);
4011 while (1) { /* while we are in the background */
4012 pgrp = tcgetpgrp(fd);
4015 ash_msg("can't access tty; job control turned off");
4019 if (pgrp == getpgrp())
4030 xtcsetpgrp(fd, pgrp);
4032 /* turning job control off */
4035 /* was xtcsetpgrp, but this can make exiting ash
4036 * loop forever if pty is already deleted */
4037 tcsetpgrp(fd, pgrp);
4051 static int FAST_FUNC
4052 killcmd(int argc, char **argv)
4054 if (argv[1] && strcmp(argv[1], "-l") != 0) {
4057 if (argv[i][0] == '%') {
4059 * "kill %N" - job kill
4060 * Converting to pgrp / pid kill
4066 jp = getjob(argv[i], 0);
4068 * In jobs started under job control, we signal
4069 * entire process group by kill -PGRP_ID.
4070 * This happens, f.e., in interactive shell.
4072 * Otherwise, we signal each child via
4073 * kill PID1 PID2 PID3.
4075 * sh -c 'sleep 1|sleep 1 & kill %1'
4076 * sh -c 'true|sleep 2 & sleep 1; kill %1'
4077 * sh -c 'true|sleep 1 & sleep 2; kill %1'
4079 n = jp->nprocs; /* can't be 0 (I hope) */
4082 dst = alloca(n * sizeof(int)*4);
4084 for (j = 0; j < n; j++) {
4085 struct procstat *ps = &jp->ps[j];
4086 /* Skip non-running and not-stopped members
4087 * (i.e. dead members) of the job
4089 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
4092 * kill_main has matching code to expect
4093 * leading space. Needed to not confuse
4094 * negative pids with "kill -SIGNAL_NO" syntax
4096 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
4100 } while (argv[++i]);
4102 return kill_main(argc, argv);
4106 showpipe(struct job *jp /*, FILE *out*/)
4108 struct procstat *ps;
4109 struct procstat *psend;
4111 psend = jp->ps + jp->nprocs;
4112 for (ps = jp->ps + 1; ps < psend; ps++)
4113 printf(" | %s", ps->ps_cmd);
4114 newline_and_flush(stdout);
4115 flush_stdout_stderr();
4120 restartjob(struct job *jp, int mode)
4122 struct procstat *ps;
4128 if (jp->state == JOBDONE)
4130 jp->state = JOBRUNNING;
4131 pgid = jp->ps[0].ps_pid;
4132 if (mode == FORK_FG) {
4134 xtcsetpgrp(ttyfd, pgid);
4136 killpg(pgid, SIGCONT);
4140 if (WIFSTOPPED(ps->ps_status)) {
4146 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
4151 static int FAST_FUNC
4152 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
4158 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
4162 jp = getjob(*argv, 1);
4163 if (mode == FORK_BG) {
4164 set_curjob(jp, CUR_RUNNING);
4165 printf("[%d] ", jobno(jp));
4167 out1str(jp->ps[0].ps_cmd);
4168 showpipe(jp /*, stdout*/);
4169 retval = restartjob(jp, mode);
4170 } while (*argv && *++argv);
4176 sprint_status48(char *s, int status, int sigonly)
4182 if (!WIFEXITED(status)) {
4184 if (WIFSTOPPED(status))
4185 st = WSTOPSIG(status);
4188 st = WTERMSIG(status);
4190 if (st == SIGINT || st == SIGPIPE)
4193 if (WIFSTOPPED(status))
4198 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
4199 col = fmtstr(s, 32, strsignal(st));
4200 if (WCOREDUMP(status)) {
4201 strcpy(s + col, " (core dumped)");
4202 col += sizeof(" (core dumped)")-1;
4204 } else if (!sigonly) {
4205 st = WEXITSTATUS(status);
4206 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
4213 wait_block_or_sig(int *status)
4220 /* Poll all children for changes in their state */
4222 /* if job control is active, accept stopped processes too */
4223 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
4225 break; /* Error (e.g. EINTR, ECHILD) or pid */
4227 /* Children exist, but none are ready. Sleep until interesting signal */
4230 sigprocmask(SIG_SETMASK, &mask, &mask);
4231 while (!got_sigchld && !pending_sig)
4233 sigprocmask(SIG_SETMASK, &mask, NULL);
4234 #else /* unsafe: a signal can set pending_sig after check, but before pause() */
4235 while (!got_sigchld && !pending_sig)
4239 /* If it was SIGCHLD, poll children again */
4240 } while (got_sigchld);
4245 #define DOWAIT_NONBLOCK 0
4246 #define DOWAIT_BLOCK 1
4247 #define DOWAIT_BLOCK_OR_SIG 2
4250 dowait(int block, struct job *job)
4255 struct job *thisjob = NULL;
4257 TRACE(("dowait(0x%x) called\n", block));
4259 /* It's wrong to call waitpid() outside of INT_OFF region:
4260 * signal can arrive just after syscall return and handler can
4261 * longjmp away, losing stop/exit notification processing.
4262 * Thus, for "jobs" builtin, and for waiting for a fg job,
4263 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
4265 * However, for "wait" builtin it is wrong to simply call waitpid()
4266 * in INT_OFF region: "wait" needs to wait for any running job
4267 * to change state, but should exit on any trap too.
4268 * In INT_OFF region, a signal just before syscall entry can set
4269 * pending_sig variables, but we can't check them, and we would
4270 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
4272 * Because of this, we run inside INT_OFF, but use a special routine
4273 * which combines waitpid() and sigsuspend().
4274 * This is the reason why we need to have a handler for SIGCHLD:
4275 * SIG_DFL handler does not wake sigsuspend().
4278 if (block == DOWAIT_BLOCK_OR_SIG) {
4279 pid = wait_block_or_sig(&status);
4282 if (block == DOWAIT_NONBLOCK)
4283 wait_flags = WNOHANG;
4284 /* if job control is active, accept stopped processes too */
4286 wait_flags |= WUNTRACED;
4287 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4288 pid = waitpid(-1, &status, wait_flags);
4290 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4291 pid, status, errno, strerror(errno)));
4296 for (jp = curjob; jp; jp = jp->prev_job) {
4298 struct procstat *ps;
4299 struct procstat *psend;
4300 if (jp->state == JOBDONE)
4304 psend = ps + jp->nprocs;
4306 if (ps->ps_pid == pid) {
4307 TRACE(("Job %d: changing status of proc %d "
4308 "from 0x%x to 0x%x\n",
4309 jobno(jp), pid, ps->ps_status, status));
4310 ps->ps_status = status;
4313 if (ps->ps_status == -1)
4314 jobstate = JOBRUNNING;
4316 if (jobstate == JOBRUNNING)
4318 if (WIFSTOPPED(ps->ps_status)) {
4319 jp->stopstatus = ps->ps_status;
4320 jobstate = JOBSTOPPED;
4323 } while (++ps < psend);
4327 /* Found the job where one of its processes changed its state.
4328 * Is there at least one live and running process in this job? */
4329 if (jobstate != JOBRUNNING) {
4330 /* No. All live processes in the job are stopped
4331 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4333 thisjob->changed = 1;
4334 if (thisjob->state != jobstate) {
4335 TRACE(("Job %d: changing state from %d to %d\n",
4336 jobno(thisjob), thisjob->state, jobstate));
4337 thisjob->state = jobstate;
4339 if (jobstate == JOBSTOPPED)
4340 set_curjob(thisjob, CUR_STOPPED);
4346 /* The process wasn't found in job list */
4348 if (!WIFSTOPPED(status))
4354 if (thisjob && thisjob == job) {
4358 len = sprint_status48(s, status, 1);
4370 showjob(struct job *jp, int mode)
4372 struct procstat *ps;
4373 struct procstat *psend;
4376 char s[16 + 16 + 48];
4377 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4381 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4382 /* just output process (group) id of pipeline */
4383 fprintf(out, "%d\n", ps->ps_pid);
4387 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4392 else if (curjob && jp == curjob->prev_job)
4395 if (mode & SHOW_PIDS)
4396 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4398 psend = ps + jp->nprocs;
4400 if (jp->state == JOBRUNNING) {
4401 strcpy(s + col, "Running");
4402 col += sizeof("Running") - 1;
4404 int status = psend[-1].ps_status;
4405 if (jp->state == JOBSTOPPED)
4406 status = jp->stopstatus;
4407 col += sprint_status48(s + col, status, 0);
4409 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4411 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4412 * or prints several "PID | <cmdN>" lines,
4413 * depending on SHOW_PIDS bit.
4414 * We do not print status of individual processes
4415 * between PID and <cmdN>. bash does it, but not very well:
4416 * first line shows overall job status, not process status,
4417 * making it impossible to know 1st process status.
4421 /* for each process */
4424 if (mode & SHOW_PIDS)
4425 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4427 fprintf(out, "%s%*c%s%s",
4429 33 - col >= 0 ? 33 - col : 0, ' ',
4430 ps == jp->ps ? "" : "| ",
4433 } while (++ps != psend);
4434 newline_and_flush(out);
4438 if (jp->state == JOBDONE) {
4439 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4445 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4446 * statuses have changed since the last call to showjobs.
4453 TRACE(("showjobs(0x%x) called\n", mode));
4455 /* Handle all finished jobs */
4456 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4459 for (jp = curjob; jp; jp = jp->prev_job) {
4460 if (!(mode & SHOW_CHANGED) || jp->changed) {
4466 static int FAST_FUNC
4467 jobscmd(int argc UNUSED_PARAM, char **argv)
4472 while ((m = nextopt("lp")) != '\0') {
4476 mode |= SHOW_ONLY_PGID;
4482 showjob(getjob(*argv, 0), mode);
4492 /* Called only on finished or stopped jobs (no members are running) */
4494 getstatus(struct job *job)
4498 struct procstat *ps;
4500 /* Fetch last member's status */
4501 ps = job->ps + job->nprocs - 1;
4502 status = ps->ps_status;
4504 /* "set -o pipefail" mode: use last _nonzero_ status */
4505 while (status == 0 && --ps >= job->ps)
4506 status = ps->ps_status;
4509 retval = WEXITSTATUS(status);
4510 if (!WIFEXITED(status)) {
4512 retval = WSTOPSIG(status);
4513 if (!WIFSTOPPED(status))
4516 /* XXX: limits number of signals */
4517 retval = WTERMSIG(status);
4519 if (retval == SIGINT)
4525 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4526 jobno(job), job->nprocs, status, retval));
4530 static int FAST_FUNC
4531 waitcmd(int argc UNUSED_PARAM, char **argv)
4542 /* wait for all jobs */
4546 if (!jp) /* no running procs */
4548 if (jp->state == JOBRUNNING)
4554 * "When bash is waiting for an asynchronous command via
4555 * the wait builtin, the reception of a signal for which a trap
4556 * has been set will cause the wait builtin to return immediately
4557 * with an exit status greater than 128, immediately after which
4558 * the trap is executed."
4560 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4561 /* if child sends us a signal *and immediately exits*,
4562 * dowait() returns pid > 0. Check this case,
4563 * not "if (dowait() < 0)"!
4572 if (**argv != '%') {
4573 pid_t pid = number(*argv);
4578 if (job->ps[job->nprocs - 1].ps_pid == pid)
4580 job = job->prev_job;
4583 job = getjob(*argv, 0);
4585 /* loop until process terminated or stopped */
4586 while (job->state == JOBRUNNING) {
4587 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4592 retval = getstatus(job);
4599 retval = 128 + pending_sig;
4608 struct job *jp, *jq;
4610 len = njobs * sizeof(*jp);
4612 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4614 offset = (char *)jp - (char *)jq;
4616 /* Relocate pointers */
4619 jq = (struct job *)((char *)jq + l);
4623 #define joff(p) ((struct job *)((char *)(p) + l))
4624 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4625 if (joff(jp)->ps == &jq->ps0)
4626 jmove(joff(jp)->ps);
4627 if (joff(jp)->prev_job)
4628 jmove(joff(jp)->prev_job);
4638 jp = (struct job *)((char *)jp + len);
4642 } while (--jq >= jp);
4647 * Return a new job structure.
4648 * Called with interrupts off.
4651 makejob(/*union node *node,*/ int nprocs)
4656 for (i = njobs, jp = jobtab; ; jp++) {
4663 if (jp->state != JOBDONE || !jp->waited)
4672 memset(jp, 0, sizeof(*jp));
4674 /* jp->jobctl is a bitfield.
4675 * "jp->jobctl |= doing_jobctl" likely to give awful code */
4679 jp->prev_job = curjob;
4684 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4686 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4693 * Return a string identifying a command (to be printed by the
4696 static char *cmdnextc;
4699 cmdputs(const char *s)
4701 static const char vstype[VSTYPE + 1][3] = {
4702 "", "}", "-", "+", "?", "=",
4703 "%", "%%", "#", "##"
4704 IF_BASH_SUBSTR(, ":")
4705 IF_BASH_PATTERN_SUBST(, "/", "//")
4708 const char *p, *str;
4712 unsigned char subtype = 0;
4716 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4718 while ((c = *p++) != '\0') {
4726 if ((subtype & VSTYPE) == VSLENGTH)
4732 str = "\"}" + !(quoted & 1);
4739 #if ENABLE_FEATURE_SH_MATH
4754 if ((subtype & VSTYPE) != VSNORMAL)
4756 str = vstype[subtype & VSTYPE];
4757 if (subtype & VSNUL)
4766 /* These can only happen inside quotes */
4772 // [1]+ Done true ${\$} <<=== BUG: ${\$} is not a valid way to write $$ (${$} would be ok)
4783 while ((c = *str++) != '\0') {
4786 } /* while *p++ not NUL */
4789 USTPUTC('"', nextc);
4795 /* cmdtxt() and cmdlist() call each other */
4796 static void cmdtxt(union node *n);
4799 cmdlist(union node *np, int sep)
4801 for (; np; np = np->narg.next) {
4805 if (sep && np->narg.next)
4811 cmdtxt(union node *n)
4814 struct nodelist *lp;
4825 lp = n->npipe.cmdlist;
4843 cmdtxt(n->nbinary.ch1);
4859 cmdtxt(n->nif.test);
4861 if (n->nif.elsepart) {
4862 cmdtxt(n->nif.ifpart);
4864 n = n->nif.elsepart;
4882 cmdtxt(n->nbinary.ch1);
4892 cmdputs(n->nfor.var);
4894 cmdlist(n->nfor.args, 1);
4899 cmdputs(n->ndefun.text);
4903 cmdlist(n->ncmd.args, 1);
4904 cmdlist(n->ncmd.redirect, 0);
4917 cmdputs(n->ncase.expr->narg.text);
4919 for (np = n->ncase.cases; np; np = np->nclist.next) {
4920 cmdtxt(np->nclist.pattern);
4922 cmdtxt(np->nclist.body);
4936 #if BASH_REDIR_OUTPUT
4951 cmdputs(utoa(n->nfile.fd));
4953 if (n->type == NTOFD || n->type == NFROMFD) {
4954 if (n->ndup.dupfd >= 0)
4955 cmdputs(utoa(n->ndup.dupfd));
4966 commandtext(union node *n)
4970 STARTSTACKSTR(cmdnextc);
4972 name = stackblock();
4973 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4974 return ckstrdup(name);
4979 * Fork off a subshell. If we are doing job control, give the subshell its
4980 * own process group. Jp is a job structure that the job is to be added to.
4981 * N is the command that will be evaluated by the child. Both jp and n may
4982 * be NULL. The mode parameter can be one of the following:
4983 * FORK_FG - Fork off a foreground process.
4984 * FORK_BG - Fork off a background process.
4985 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4986 * process group even if job control is on.
4988 * When job control is turned off, background processes have their standard
4989 * input redirected to /dev/null (except for the second and later processes
4992 * Called with interrupts off.
4995 * Clear traps on a fork.
5003 for (tp = trap; tp < &trap[NSIG]; tp++) {
5004 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
5005 if (trap_ptr == trap)
5007 /* else: it "belongs" to trap_ptr vector, don't free */
5009 if ((tp - trap) != 0)
5010 setsignal(tp - trap);
5017 /* Lives far away from here, needed for forkchild */
5018 static void closescript(void);
5020 /* Called after fork(), in child */
5021 /* jp and n are NULL when called by openhere() for heredoc support */
5022 static NOINLINE void
5023 forkchild(struct job *jp, union node *n, int mode)
5027 TRACE(("Child shell %d\n", getpid()));
5031 /* man bash: "Non-builtin commands run by bash have signal handlers
5032 * set to the values inherited by the shell from its parent".
5033 * Do we do it correctly? */
5037 if (mode == FORK_NOJOB /* is it `xxx` ? */
5038 && n && n->type == NCMD /* is it single cmd? */
5039 /* && n->ncmd.args->type == NARG - always true? */
5040 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
5041 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
5042 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
5044 TRACE(("Trap hack\n"));
5045 /* Awful hack for `trap` or $(trap).
5047 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5048 * contains an example where "trap" is executed in a subshell:
5050 * save_traps=$(trap)
5052 * eval "$save_traps"
5054 * Standard does not say that "trap" in subshell shall print
5055 * parent shell's traps. It only says that its output
5056 * must have suitable form, but then, in the above example
5057 * (which is not supposed to be normative), it implies that.
5059 * bash (and probably other shell) does implement it
5060 * (traps are reset to defaults, but "trap" still shows them),
5061 * but as a result, "trap" logic is hopelessly messed up:
5064 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5065 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5066 * # true | trap <--- trap is in subshell - no output (ditto)
5067 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5068 * trap -- 'echo Ho' SIGWINCH
5069 * # echo `(trap)` <--- in subshell in subshell - output
5070 * trap -- 'echo Ho' SIGWINCH
5071 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5072 * trap -- 'echo Ho' SIGWINCH
5074 * The rules when to forget and when to not forget traps
5075 * get really complex and nonsensical.
5077 * Our solution: ONLY bare $(trap) or `trap` is special.
5079 /* Save trap handler strings for trap builtin to print */
5080 trap_ptr = xmemdup(trap, sizeof(trap));
5081 /* Fall through into clearing traps */
5085 /* do job control only in root shell */
5087 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
5090 if (jp->nprocs == 0)
5093 pgrp = jp->ps[0].ps_pid;
5094 /* this can fail because we are doing it in the parent also */
5096 if (mode == FORK_FG)
5097 xtcsetpgrp(ttyfd, pgrp);
5102 if (mode == FORK_BG) {
5103 /* man bash: "When job control is not in effect,
5104 * asynchronous commands ignore SIGINT and SIGQUIT" */
5107 if (jp->nprocs == 0) {
5109 if (open(bb_dev_null, O_RDONLY) != 0)
5110 ash_msg_and_raise_perror("can't open '%s'", bb_dev_null);
5114 if (iflag) { /* why if iflag only? */
5119 * "In all cases, bash ignores SIGQUIT. Non-builtin
5120 * commands run by bash have signal handlers
5121 * set to the values inherited by the shell
5123 * Take care of the second rule: */
5127 if (n && n->type == NCMD
5128 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
5130 TRACE(("Job hack\n"));
5131 /* "jobs": we do not want to clear job list for it,
5132 * instead we remove only _its_ own_ job from job list.
5133 * This makes "jobs .... | cat" more useful.
5139 for (jp = curjob; jp; jp = jp->prev_job)
5144 /* Called after fork(), in parent */
5146 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
5149 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
5151 TRACE(("In parent shell: child = %d\n", pid));
5153 /* jp is NULL when called by openhere() for heredoc support */
5154 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
5160 if (mode != FORK_NOJOB && jp->jobctl) {
5163 if (jp->nprocs == 0)
5166 pgrp = jp->ps[0].ps_pid;
5167 /* This can fail because we are doing it in the child also */
5171 if (mode == FORK_BG) {
5172 backgndpid = pid; /* set $! */
5173 set_curjob(jp, CUR_RUNNING);
5176 struct procstat *ps = &jp->ps[jp->nprocs++];
5179 ps->ps_cmd = nullstr;
5181 if (doing_jobctl && n)
5182 ps->ps_cmd = commandtext(n);
5187 /* jp and n are NULL when called by openhere() for heredoc support */
5189 forkshell(struct job *jp, union node *n, int mode)
5193 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
5196 TRACE(("Fork failed, errno=%d", errno));
5199 ash_msg_and_raise_perror("can't fork");
5202 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
5203 forkchild(jp, n, mode);
5205 forkparent(jp, n, mode, pid);
5211 * Wait for job to finish.
5213 * Under job control we have the problem that while a child process
5214 * is running interrupts generated by the user are sent to the child
5215 * but not to the shell. This means that an infinite loop started by
5216 * an interactive user may be hard to kill. With job control turned off,
5217 * an interactive user may place an interactive program inside a loop.
5218 * If the interactive program catches interrupts, the user doesn't want
5219 * these interrupts to also abort the loop. The approach we take here
5220 * is to have the shell ignore interrupt signals while waiting for a
5221 * foreground process to terminate, and then send itself an interrupt
5222 * signal if the child process was terminated by an interrupt signal.
5223 * Unfortunately, some programs want to do a bit of cleanup and then
5224 * exit on interrupt; unless these processes terminate themselves by
5225 * sending a signal to themselves (instead of calling exit) they will
5226 * confuse this approach.
5228 * Called with interrupts off.
5231 waitforjob(struct job *jp)
5235 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
5238 while (jp->state == JOBRUNNING) {
5239 /* In non-interactive shells, we _can_ get
5240 * a keyboard signal here and be EINTRed,
5241 * but we just loop back, waiting for command to complete.
5244 * "If bash is waiting for a command to complete and receives
5245 * a signal for which a trap has been set, the trap
5246 * will not be executed until the command completes."
5248 * Reality is that even if trap is not set, bash
5249 * will not act on the signal until command completes.
5250 * Try this. sleep5intoff.c:
5251 * #include <signal.h>
5252 * #include <unistd.h>
5255 * sigemptyset(&set);
5256 * sigaddset(&set, SIGINT);
5257 * sigaddset(&set, SIGQUIT);
5258 * sigprocmask(SIG_BLOCK, &set, NULL);
5262 * $ bash -c './sleep5intoff; echo hi'
5263 * ^C^C^C^C <--- pressing ^C once a second
5265 * $ bash -c './sleep5intoff; echo hi'
5266 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
5269 dowait(DOWAIT_BLOCK, jp);
5276 xtcsetpgrp(ttyfd, rootpid);
5277 restore_tty_if_stopped_or_signaled(jp);
5280 * This is truly gross.
5281 * If we're doing job control, then we did a TIOCSPGRP which
5282 * caused us (the shell) to no longer be in the controlling
5283 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
5284 * intuit from the subprocess exit status whether a SIGINT
5285 * occurred, and if so interrupt ourselves. Yuck. - mycroft
5287 if (jp->sigint) /* TODO: do the same with all signals */
5288 raise(SIGINT); /* ... by raise(jp->sig) instead? */
5290 if (jp->state == JOBDONE)
5297 * return 1 if there are stopped jobs, otherwise 0
5309 if (jp && jp->state == JOBSTOPPED) {
5310 out2str("You have stopped jobs.\n");
5320 * Code for dealing with input/output redirection.
5325 #define EMPTY -2 /* marks an unused slot in redirtab */
5326 #define CLOSED -1 /* marks a slot of previously-closed fd */
5329 * Handle here documents. Normally we fork off a process to write the
5330 * data to a pipe. If the document is short, we can stuff the data in
5331 * the pipe without forking.
5333 /* openhere needs this forward reference */
5334 static void expandhere(union node *arg, int fd);
5336 openhere(union node *redir)
5342 ash_msg_and_raise_perror("can't create pipe");
5343 if (redir->type == NHERE) {
5344 len = strlen(redir->nhere.doc->narg.text);
5345 if (len <= PIPE_BUF) {
5346 full_write(pip[1], redir->nhere.doc->narg.text, len);
5350 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5353 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5354 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5355 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5356 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5357 signal(SIGPIPE, SIG_DFL);
5358 if (redir->type == NHERE)
5359 full_write(pip[1], redir->nhere.doc->narg.text, len);
5361 expandhere(redir->nhere.doc, pip[1]);
5362 _exit(EXIT_SUCCESS);
5370 openredirect(union node *redir)
5376 switch (redir->nfile.type) {
5377 /* Can't happen, our single caller does this itself */
5383 return openhere(redir);
5386 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5387 * allocated space. Do it only when we know it is safe.
5389 fname = redir->nfile.expfname;
5391 switch (redir->nfile.type) {
5397 f = open(fname, O_RDONLY);
5402 f = open(fname, O_RDWR|O_CREAT, 0666);
5407 #if BASH_REDIR_OUTPUT
5410 /* Take care of noclobber mode. */
5412 if (stat(fname, &sb) < 0) {
5413 f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5416 } else if (!S_ISREG(sb.st_mode)) {
5417 f = open(fname, O_WRONLY, 0666);
5420 if (!fstat(f, &sb) && S_ISREG(sb.st_mode)) {
5433 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5438 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5446 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5448 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5452 * Copy a file descriptor to be >= 10. Throws exception on error.
5460 newfd = fcntl(from, F_DUPFD_CLOEXEC, 10);
5461 err = newfd < 0 ? errno : 0;
5464 ash_msg_and_raise_perror("%d", from);
5466 if (F_DUPFD_CLOEXEC == F_DUPFD)
5467 close_on_exec_on(newfd);
5473 dup2_or_raise(int from, int to)
5477 newfd = (from != to) ? dup2(from, to) : to;
5479 /* Happens when source fd is not open: try "echo >&99" */
5480 ash_msg_and_raise_perror("%d", from);
5485 dup_CLOEXEC(int fd, int avoid_fd)
5489 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
5491 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
5492 close_on_exec_on(newfd);
5493 } else { /* newfd < 0 */
5502 xdup_CLOEXEC_and_close(int fd, int avoid_fd)
5506 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
5512 /* fd was not open? */
5515 ash_msg_and_raise_perror("%d", newfd);
5517 if (F_DUPFD_CLOEXEC == F_DUPFD)
5518 close_on_exec_on(newfd);
5523 /* Struct def and variable are moved down to the first usage site */
5529 struct redirtab *next;
5531 struct squirrel two_fd[];
5533 #define redirlist (G_var.redirlist)
5536 add_squirrel_closed(struct redirtab *sq, int fd)
5543 for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
5544 /* If we collide with an already moved fd... */
5545 if (fd == sq->two_fd[i].orig_fd) {
5547 * "echo 3>FILE 3>&- 3>FILE"
5548 * "echo 3>&- 3>FILE"
5549 * No need for last redirect to insert
5550 * another "need to close 3" indicator.
5552 TRACE(("redirect_fd %d: already moved or closed\n", fd));
5556 TRACE(("redirect_fd %d: previous fd was closed\n", fd));
5557 sq->two_fd[i].orig_fd = fd;
5558 sq->two_fd[i].moved_to = CLOSED;
5562 save_fd_on_redirect(int fd, int avoid_fd, struct redirtab *sq)
5566 if (avoid_fd < 9) /* the important case here is that it can be -1 */
5571 /* Testcase: "ls -l /proc/$$/fd 10>&-" should work */
5572 ttyfd = xdup_CLOEXEC_and_close(ttyfd, avoid_fd);
5573 TRACE(("redirect_fd %d: matches ttyfd, moving it to %d\n", fd, ttyfd));
5574 return 1; /* "we closed fd" */
5577 /* Are we called from redirect(0)? E.g. redirect
5578 * in a forked child. No need to save fds,
5579 * we aren't going to use them anymore, ok to trash.
5584 /* If this one of script's fds? */
5586 struct parsefile *pf = g_parsefile;
5588 /* We skip fd == 0 case because of the following:
5589 * $ ash # running ash interactively
5591 * and in script.sh: "exec 9>&0".
5592 * Even though top-level pf_fd _is_ 0,
5593 * it's still ok to use it: "read" builtin uses it,
5594 * why should we cripple "exec" builtin?
5596 if (fd == pf->pf_fd) {
5597 pf->pf_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
5598 return 1; /* "we closed fd" */
5604 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
5606 /* First: do we collide with some already moved fds? */
5607 for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
5608 /* If we collide with an already moved fd... */
5609 if (fd == sq->two_fd[i].moved_to) {
5610 new_fd = dup_CLOEXEC(fd, avoid_fd);
5611 sq->two_fd[i].moved_to = new_fd;
5612 TRACE(("redirect_fd %d: already busy, moving to %d\n", fd, new_fd));
5613 if (new_fd < 0) /* what? */
5615 return 0; /* "we did not close fd" */
5617 if (fd == sq->two_fd[i].orig_fd) {
5618 /* Example: echo Hello >/dev/null 1>&2 */
5619 TRACE(("redirect_fd %d: already moved\n", fd));
5620 return 0; /* "we did not close fd" */
5624 /* If this fd is open, we move and remember it; if it's closed, new_fd = CLOSED (-1) */
5625 new_fd = dup_CLOEXEC(fd, avoid_fd);
5626 TRACE(("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, new_fd));
5630 /* new_fd = CLOSED; - already is -1 */
5632 sq->two_fd[i].moved_to = new_fd;
5633 sq->two_fd[i].orig_fd = fd;
5635 /* if we move stderr, let "set -x" code know */
5636 if (fd == preverrout_fd)
5637 preverrout_fd = new_fd;
5639 return 0; /* "we did not close fd" */
5643 internally_opened_fd(int fd, struct redirtab *sq)
5650 /* If this one of script's fds? */
5652 struct parsefile *pf = g_parsefile;
5654 if (fd == pf->pf_fd)
5660 if (sq) for (i = 0; i < sq->pair_count && sq->two_fd[i].orig_fd != EMPTY; i++) {
5661 if (fd == sq->two_fd[i].moved_to)
5668 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5669 * old file descriptors are stashed away so that the redirection can be
5670 * undone by calling popredir.
5672 /* flags passed to redirect */
5673 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5675 redirect(union node *redir, int flags)
5677 struct redirtab *sv;
5684 if (flags & REDIR_PUSH)
5692 fd = redir->nfile.fd;
5693 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5694 //bb_error_msg("doing %d > %d", fd, newfd);
5695 newfd = redir->ndup.dupfd;
5698 newfd = openredirect(redir); /* always >= 0 */
5700 /* open() gave us precisely the fd we wanted.
5701 * This means that this fd was not busy
5702 * (not opened to anywhere).
5703 * Remember to close it on restore:
5705 add_squirrel_closed(sv, fd);
5714 /* if "N>FILE": move newfd to fd */
5715 /* if "N>&M": dup newfd to fd */
5716 /* if "N>&-": close fd (newfd is -1) */
5718 IF_BASH_REDIR_OUTPUT(redirect_more:)
5720 closed = save_fd_on_redirect(fd, /*avoid:*/ newfd, sv);
5722 /* "N>&-" means "close me" */
5724 /* ^^^ optimization: saving may already
5725 * have closed it. If not... */
5729 /* if newfd is a script fd or saved fd, simulate EBADF */
5730 if (internally_opened_fd(newfd, sv)) {
5732 ash_msg_and_raise_perror("%d", newfd);
5734 dup2_or_raise(newfd, fd);
5735 if (close_fd >= 0) /* "N>FILE" or ">&FILE" or heredoc? */
5737 #if BASH_REDIR_OUTPUT
5738 if (redir->nfile.type == NTO2 && fd == 1) {
5739 /* ">&FILE". we already redirected to 1, now copy 1 to 2 */
5747 } while ((redir = redir->nfile.next) != NULL);
5750 //dash:#define REDIR_SAVEFD2 03 /* set preverrout */
5751 #define REDIR_SAVEFD2 0
5752 // dash has a bug: since REDIR_SAVEFD2=3 and REDIR_PUSH=1, this test
5753 // triggers for pure REDIR_PUSH too. Thus, this is done almost always,
5754 // not only for calls with flags containing REDIR_SAVEFD2.
5755 // We do this unconditionally (see save_fd_on_redirect()).
5756 //if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5757 // preverrout_fd = copied_fd2;
5761 redirectsafe(union node *redir, int flags)
5764 volatile int saveint;
5765 struct jmploc *volatile savehandler = exception_handler;
5766 struct jmploc jmploc;
5769 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5770 err = setjmp(jmploc.loc); /* was = setjmp(jmploc.loc) * 2; */
5772 exception_handler = &jmploc;
5773 redirect(redir, flags);
5775 exception_handler = savehandler;
5776 if (err && exception_type != EXERROR)
5777 longjmp(exception_handler->loc, 1);
5778 RESTORE_INT(saveint);
5782 static struct redirtab*
5783 pushredir(union node *redir)
5785 struct redirtab *sv;
5794 #if BASH_REDIR_OUTPUT
5795 if (redir->nfile.type == NTO2)
5798 redir = redir->nfile.next;
5801 sv = ckzalloc(sizeof(*sv) + i * sizeof(sv->two_fd[0]));
5804 sv->two_fd[i].orig_fd = sv->two_fd[i].moved_to = EMPTY;
5805 sv->next = redirlist;
5811 * Undo the effects of the last redirection.
5816 struct redirtab *rp;
5819 if (redirlist == NULL)
5823 for (i = 0; i < rp->pair_count; i++) {
5824 int fd = rp->two_fd[i].orig_fd;
5825 int copy = rp->two_fd[i].moved_to;
5826 if (copy == CLOSED) {
5831 if (copy != EMPTY) {
5834 dup2_or_raise(copy, fd);
5839 redirlist = rp->next;
5845 unwindredir(struct redirtab *stop)
5847 while (redirlist != stop)
5848 popredir(/*drop:*/ 0);
5852 /* ============ Routines to expand arguments to commands
5854 * We have to deal with backquotes, shell variables, and file metacharacters.
5857 #if ENABLE_FEATURE_SH_MATH
5859 ash_arith(const char *s)
5861 arith_state_t math_state;
5864 math_state.lookupvar = lookupvar;
5865 math_state.setvar = setvar0;
5866 //math_state.endofname = endofname;
5869 result = arith(&math_state, s);
5870 if (math_state.errmsg)
5871 ash_msg_and_raise_error(math_state.errmsg);
5878 # if ENABLE_FEATURE_SH_MATH
5879 static int substr_atoi(const char *s)
5881 arith_t t = ash_arith(s);
5882 if (sizeof(t) > sizeof(int)) {
5883 /* clamp very large or very large negative nums for ${v:N:M}:
5884 * else "${v:0:0x100000001}" would work as "${v:0:1}"
5894 # define substr_atoi(s) number(s)
5901 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5902 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5903 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5904 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5905 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5906 * POSIX says for this case:
5907 * Pathname expansion shall not be performed on the word by a
5908 * non-interactive shell; an interactive shell may perform it, but shall
5909 * do so only when the expansion would result in one word.
5910 * Currently, our code complies to the above rule by never globbing
5911 * redirection filenames.
5912 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5913 * (this means that on a typical Linux distro, bash almost always
5914 * performs globbing, and thus diverges from what we do).
5916 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5917 #define EXP_VARTILDE2 0x20 /* expand tildes after colons only */
5918 #define EXP_WORD 0x40 /* expand word in parameter expansion */
5919 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5923 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5924 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5925 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5926 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5928 /* Add CTLESC when necessary. */
5929 #define QUOTES_ESC (EXP_FULL | EXP_CASE)
5930 /* Do not skip NUL characters. */
5931 #define QUOTES_KEEPNUL EXP_TILDE
5934 * Structure specifying which parts of the string should be searched
5935 * for IFS characters.
5938 struct ifsregion *next; /* next region in list */
5939 int begoff; /* offset of start of region */
5940 int endoff; /* offset of end of region */
5941 int nulonly; /* search for nul bytes only */
5945 struct strlist *list;
5946 struct strlist **lastp;
5949 /* output of current string */
5950 static char *expdest;
5951 /* list of back quote expressions */
5952 static struct nodelist *argbackq;
5953 /* first struct in list of ifs regions */
5954 static struct ifsregion ifsfirst;
5955 /* last struct in list */
5956 static struct ifsregion *ifslastp;
5957 /* holds expanded arg list */
5958 static struct arglist exparg;
5962 * cvtnum() is used even if math support is off (to prepare $? values and such).
5969 /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
5970 len = sizeof(arith_t) * 3;
5971 /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
5972 if (sizeof(arith_t) < 4) len += 2;
5974 expdest = makestrspace(len, expdest);
5975 len = fmtstr(expdest, len, ARITH_FMT, num);
5976 STADJUST(len, expdest);
5981 * Break the argument string into pieces based upon IFS and add the
5982 * strings to the argument list. The regions of the string to be
5983 * searched for IFS characters have been stored by recordregion.
5986 ifsbreakup(char *string, struct arglist *arglist)
5988 struct ifsregion *ifsp;
5993 const char *ifs, *realifs;
5998 if (ifslastp != NULL) {
6001 realifs = ifsset() ? ifsval() : defifs;
6006 p = string + ifsp->begoff;
6008 nulonly = ifsp->nulonly;
6009 ifs = nulonly ? nullstr : realifs;
6011 while (p < string + ifsp->endoff) {
6013 if ((unsigned char)*p == CTLESC)
6015 if (!strchr(ifs, *p)) {
6019 if (!(afternul || nulonly))
6020 ifsspc = (strchr(defifs, *p) != NULL);
6021 /* Ignore IFS whitespace at start */
6022 if (q == start && ifsspc) {
6028 sp = stzalloc(sizeof(*sp));
6030 *arglist->lastp = sp;
6031 arglist->lastp = &sp->next;
6035 if (p >= string + ifsp->endoff) {
6039 if ((unsigned char)*p == CTLESC)
6041 if (strchr(ifs, *p) == NULL) {
6045 if (strchr(defifs, *p) == NULL) {
6060 } while (ifsp != NULL);
6069 sp = stzalloc(sizeof(*sp));
6071 *arglist->lastp = sp;
6072 arglist->lastp = &sp->next;
6078 struct ifsregion *p = ifsfirst.next;
6085 struct ifsregion *ifsp;
6090 ifsfirst.next = NULL;
6097 esclen(const char *start, const char *p)
6101 while (p > start && (unsigned char)*--p == CTLESC) {
6108 * Remove any CTLESC characters from a string.
6110 #if !BASH_PATTERN_SUBST
6111 #define rmescapes(str, flag, slash_position) \
6112 rmescapes(str, flag)
6115 rmescapes(char *str, int flag, int *slash_position)
6117 static const char qchars[] ALIGN1 = {
6118 IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
6121 unsigned protect_against_glob;
6124 p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash_position));
6130 if (flag & RMESCAPE_ALLOC) {
6131 size_t len = p - str;
6132 size_t fulllen = len + strlen(p) + 1;
6134 if (flag & RMESCAPE_GROW) {
6135 int strloc = str - (char *)stackblock();
6136 r = makestrspace(fulllen, expdest);
6137 /* p and str may be invalidated by makestrspace */
6138 str = (char *)stackblock() + strloc;
6140 } else if (flag & RMESCAPE_HEAP) {
6141 r = ckmalloc(fulllen);
6143 r = stalloc(fulllen);
6147 q = (char *)mempcpy(q, str, len);
6151 globbing = flag & RMESCAPE_GLOB;
6152 protect_against_glob = globbing;
6154 if ((unsigned char)*p == CTLQUOTEMARK) {
6155 // Note: protect_against_glob only affect whether
6156 // CTLESC,<ch> gets converted to <ch> or to \<ch>
6158 protect_against_glob = globbing;
6162 /* naked back slash */
6163 protect_against_glob = 0;
6166 if ((unsigned char)*p == CTLESC) {
6170 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
6172 if (protect_against_glob) {
6174 * We used to trust glob() and fnmatch() to eat
6175 * superfluous escapes (\z where z has no
6176 * special meaning anyway). But this causes
6177 * bugs such as string of one greek letter rho
6178 * (unicode-encoded as two bytes "cf,81")
6179 * getting encoded as "cf,CTLESC,81"
6180 * and here, converted to "cf,\,81" -
6181 * which does not go well with some flavors
6182 * of fnmatch() in unicode locales
6183 * (for example, glibc <= 2.22).
6185 * Lets add "\" only on the chars which need it.
6186 * Testcases for less obvious chars are shown.
6191 || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
6192 || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
6193 || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
6194 || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
6195 /* Some libc support [^negate], that's why "^" also needs love */
6196 || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
6202 #if BASH_PATTERN_SUBST
6203 else if (slash_position && p == str + *slash_position) {
6204 /* stop handling globbing */
6206 *slash_position = q - r;
6207 slash_position = NULL;
6210 protect_against_glob = globbing;
6215 if (flag & RMESCAPE_GROW) {
6217 STADJUST(q - r + 1, expdest);
6221 #define pmatch(a, b) !fnmatch((a), (b), 0)
6224 * Prepare a pattern for a expmeta (internal glob(3)) call.
6226 * Returns an stalloced string.
6229 preglob(const char *pattern, int flag)
6231 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB, NULL);
6235 * Put a string on the stack.
6238 memtodest(const char *p, size_t len, int syntax, int quotes)
6245 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
6248 unsigned char c = *p++;
6250 if (quotes & QUOTES_ESC) {
6251 int n = SIT(c, syntax);
6253 || (syntax != BASESYNTAX && n == CBACK)
6258 } else if (!(quotes & QUOTES_KEEPNUL))
6267 strtodest(const char *p, int syntax, int quotes)
6269 size_t len = strlen(p);
6270 memtodest(p, len, syntax, quotes);
6275 * Record the fact that we have to scan this region of the
6276 * string for IFS characters.
6279 recordregion(int start, int end, int nulonly)
6281 struct ifsregion *ifsp;
6283 if (ifslastp == NULL) {
6287 ifsp = ckzalloc(sizeof(*ifsp));
6288 /*ifsp->next = NULL; - ckzalloc did it */
6289 ifslastp->next = ifsp;
6293 ifslastp->begoff = start;
6294 ifslastp->endoff = end;
6295 ifslastp->nulonly = nulonly;
6299 removerecordregions(int endoff)
6301 if (ifslastp == NULL)
6304 if (ifsfirst.endoff > endoff) {
6305 while (ifsfirst.next) {
6306 struct ifsregion *ifsp;
6308 ifsp = ifsfirst.next->next;
6309 free(ifsfirst.next);
6310 ifsfirst.next = ifsp;
6313 if (ifsfirst.begoff > endoff) {
6316 ifslastp = &ifsfirst;
6317 ifsfirst.endoff = endoff;
6322 ifslastp = &ifsfirst;
6323 while (ifslastp->next && ifslastp->next->begoff < endoff)
6324 ifslastp = ifslastp->next;
6325 while (ifslastp->next) {
6326 struct ifsregion *ifsp;
6328 ifsp = ifslastp->next->next;
6329 free(ifslastp->next);
6330 ifslastp->next = ifsp;
6333 if (ifslastp->endoff > endoff)
6334 ifslastp->endoff = endoff;
6338 exptilde(char *startp, char *p, int flags)
6344 int quotes = flags & QUOTES_ESC;
6348 while ((c = *++p) != '\0') {
6355 if (flags & EXP_VARTILDE)
6365 if (*name == '\0') {
6366 home = lookupvar("HOME");
6368 pw = getpwnam(name);
6373 if (!home || !*home)
6376 strtodest(home, SQSYNTAX, quotes);
6384 * Execute a command inside back quotes. If it's a builtin command, we
6385 * want to save its output in a block obtained from malloc. Otherwise
6386 * we fork off a subprocess and get the output of the command via a pipe.
6387 * Should be called with interrupts off.
6389 struct backcmd { /* result of evalbackcmd */
6390 int fd; /* file descriptor to read from */
6391 int nleft; /* number of chars in buffer */
6392 char *buf; /* buffer */
6393 struct job *jp; /* job structure for command */
6396 /* These forward decls are needed to use "eval" code for backticks handling: */
6397 /* flags in argument to evaltree */
6398 #define EV_EXIT 01 /* exit after evaluating tree */
6399 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
6400 static int evaltree(union node *, int);
6402 /* An evaltree() which is known to never return.
6403 * Used to use an alias:
6404 * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
6405 * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
6407 static ALWAYS_INLINE NORETURN void
6408 evaltreenr(union node *n, int flags)
6411 bb_unreachable(abort());
6415 static void FAST_FUNC
6416 evalbackcmd(union node *n, struct backcmd *result)
6430 ash_msg_and_raise_perror("can't create pipe");
6431 jp = makejob(/*n,*/ 1);
6432 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6438 dup2_or_raise(pip[1], 1);
6441 /* TODO: eflag clearing makes the following not abort:
6442 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6443 * which is what bash does (unless it is in POSIX mode).
6444 * dash deleted "eflag = 0" line in the commit
6445 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6446 * [EVAL] Don't clear eflag in evalbackcmd
6447 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6451 evaltreenr(n, EV_EXIT);
6456 result->fd = pip[0];
6460 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6461 result->fd, result->buf, result->nleft, result->jp));
6465 * Expand stuff in backwards quotes.
6468 expbackq(union node *cmd, int flag)
6476 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6477 struct stackmark smark;
6480 startloc = expdest - (char *)stackblock();
6481 pushstackmark(&smark, startloc);
6482 evalbackcmd(cmd, &in);
6483 popstackmark(&smark);
6490 memtodest(p, i, syntax, flag & QUOTES_ESC);
6494 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6495 TRACE(("expbackq: read returns %d\n", i));
6504 back_exitstatus = waitforjob(in.jp);
6508 /* Eat all trailing newlines */
6510 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6514 if (!(flag & EXP_QUOTED))
6515 recordregion(startloc, dest - (char *)stackblock(), 0);
6516 TRACE(("evalbackq: size:%d:'%.*s'\n",
6517 (int)((dest - (char *)stackblock()) - startloc),
6518 (int)((dest - (char *)stackblock()) - startloc),
6519 stackblock() + startloc));
6522 #if ENABLE_FEATURE_SH_MATH
6524 * Expand arithmetic expression. Backup to start of expression,
6525 * evaluate, place result in (backed up) result, adjust string position.
6537 * This routine is slightly over-complicated for
6538 * efficiency. Next we scan backwards looking for the
6539 * start of arithmetic.
6541 start = stackblock();
6548 while ((unsigned char)*p != CTLARI) {
6552 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6557 esc = esclen(start, p);
6567 removerecordregions(begoff);
6571 if (flag & QUOTES_ESC)
6572 rmescapes(p + 1, 0, NULL);
6574 len = cvtnum(ash_arith(p + 1));
6576 if (!(flag & EXP_QUOTED))
6577 recordregion(begoff, begoff + len, 0);
6581 /* argstr needs it */
6582 static char *evalvar(char *p, int flags);
6585 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6586 * characters to allow for further processing. Otherwise treat
6587 * $@ like $* since no splitting will be performed.
6590 argstr(char *p, int flags)
6592 static const char spclchars[] ALIGN1 = {
6600 #if ENABLE_FEATURE_SH_MATH
6605 const char *reject = spclchars;
6606 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6611 if (!(flags & EXP_VARTILDE)) {
6613 } else if (flags & EXP_VARTILDE2) {
6618 if (flags & EXP_TILDE) {
6621 flags &= ~EXP_TILDE;
6625 p = exptilde(p, q, flags);
6628 startloc = expdest - (char *)stackblock();
6632 length += strcspn(p + length, reject);
6636 IF_FEATURE_SH_MATH(|| c == CTLENDARI)
6638 /* c == '=' || c == ':' || c == CTLENDARI */
6644 expdest = stack_nputstr(p, length, expdest);
6645 newloc = expdest - (char *)stackblock();
6646 if (breakall && !inquotes && newloc > startloc) {
6647 recordregion(startloc, newloc, 0);
6658 if (flags & EXP_VARTILDE2) {
6662 flags |= EXP_VARTILDE2;
6667 * sort of a hack - expand tildes in variable
6668 * assignments (after the first '=' and after ':'s).
6677 case CTLENDVAR: /* ??? */
6680 /* "$@" syntax adherence hack */
6681 if (!inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6682 p = evalvar(p + 1, flags | EXP_QUOTED) + 1;
6685 inquotes ^= EXP_QUOTED;
6687 if (flags & QUOTES_ESC) {
6698 TRACE(("argstr: evalvar('%s')\n", p));
6699 p = evalvar(p, flags | inquotes);
6700 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6703 expbackq(argbackq->n, flags | inquotes);
6704 argbackq = argbackq->next;
6706 #if ENABLE_FEATURE_SH_MATH
6709 expari(flags | inquotes);
6718 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6719 char *pattern, int quotes, int zero)
6728 const char *s = loc2;
6735 match = pmatch(pattern, s);
6740 if (quotes && (unsigned char)*loc == CTLESC)
6749 scanright(char *startp, char *rmesc, char *rmescend,
6750 char *pattern, int quotes, int match_at_start)
6752 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6753 int try2optimize = match_at_start;
6759 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6760 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6761 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6763 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6764 * and on each iteration they go back two/one char until they reach the beginning.
6765 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6767 /* TODO: document in what other circumstances we are called. */
6769 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6772 const char *s = loc2;
6773 if (match_at_start) {
6777 match = pmatch(pattern, s);
6778 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6782 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6784 /* Maybe we can optimize this:
6785 * if pattern ends with unescaped *, we can avoid checking
6786 * shorter strings: if "foo*" doesn't match "raw_value_of_v",
6787 * it won't match truncated "raw_value_of_" strings too.
6789 unsigned plen = strlen(pattern);
6790 /* Does it end with "*"? */
6791 if (plen != 0 && pattern[--plen] == '*') {
6792 /* "xxxx*" is not escaped */
6793 /* "xxx\*" is escaped */
6794 /* "xx\\*" is not escaped */
6795 /* "x\\\*" is escaped */
6797 while (plen != 0 && pattern[--plen] == '\\')
6800 break; /* ends with unescaped "*" */
6808 esc = esclen(startp, loc);
6819 static void varunset(const char *, const char *, const char *, int) NORETURN;
6821 varunset(const char *end, const char *var, const char *umsg, int varflags)
6827 msg = "parameter not set";
6829 if ((unsigned char)*end == CTLENDVAR) {
6830 if (varflags & VSNUL)
6836 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6840 subevalvar(char *p, char *varname, int strloc, int subtype,
6841 int startloc, int varflags, int flag)
6843 struct nodelist *saveargbackq = argbackq;
6844 int quotes = flag & QUOTES_ESC;
6847 char *rmesc, *rmescend;
6849 int amount, resetloc;
6851 IF_BASH_PATTERN_SUBST(int workloc;)
6852 IF_BASH_PATTERN_SUBST(int slash_pos;)
6853 IF_BASH_PATTERN_SUBST(char *repl;)
6855 char *(*scan)(char*, char*, char*, char*, int, int);
6857 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6858 // p, varname, strloc, subtype, startloc, varflags, quotes);
6860 #if BASH_PATTERN_SUBST
6861 /* For "${v/pattern/repl}", we must find the delimiter _before_
6862 * argstr() call expands possible variable references in pattern:
6863 * think about "v=a; a=a/; echo ${v/$a/r}" case.
6866 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6867 /* Find '/' and replace with NUL */
6869 /* The pattern can't be empty.
6870 * IOW: if the first char after "${v//" is a slash,
6871 * it does not terminate the pattern - it's the first char of the pattern:
6872 * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
6873 * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
6878 if (*repl == '\0') {
6886 /* Handle escaped slashes, e.g. "${v/\//_}" (they are CTLESC'ed by this point) */
6887 if ((unsigned char)*repl == CTLESC && repl[1])
6893 argstr_flags = EXP_TILDE;
6894 if (subtype != VSASSIGN
6895 && subtype != VSQUESTION
6897 && subtype != VSSUBSTR
6900 /* EXP_CASE keeps CTLESC's */
6901 argstr_flags = EXP_TILDE | EXP_CASE;
6903 argstr(p, argstr_flags);
6904 //bb_error_msg("str0:'%s'", (char *)stackblock() + strloc);
6905 #if BASH_PATTERN_SUBST
6908 slash_pos = expdest - ((char *)stackblock() + strloc);
6909 STPUTC('/', expdest);
6910 //bb_error_msg("repl+1:'%s'", repl + 1);
6911 argstr(repl + 1, EXP_TILDE); /* EXP_TILDE: echo "${v/x/~}" expands ~ ! */
6915 STPUTC('\0', expdest);
6916 argbackq = saveargbackq;
6917 startp = (char *)stackblock() + startloc;
6918 //bb_error_msg("str1:'%s'", (char *)stackblock() + strloc);
6922 setvar0(varname, startp);
6923 amount = startp - expdest;
6924 STADJUST(amount, expdest);
6928 varunset(p, varname, startp, varflags);
6933 int pos, len, orig_len;
6936 loc = str = stackblock() + strloc;
6938 /* Read POS in ${var:POS:LEN} */
6939 colon = strchr(loc, ':');
6940 if (colon) *colon = '\0';
6941 pos = substr_atoi(loc);
6942 if (colon) *colon = ':';
6944 /* Read LEN in ${var:POS:LEN} */
6945 len = str - startp - 1;
6946 /* *loc != '\0', guaranteed by parser */
6949 /* Adjust the length by the number of escapes */
6950 for (ptr = startp; ptr < (str - 1); ptr++) {
6951 if ((unsigned char)*ptr == CTLESC) {
6958 if (*loc++ == ':') {
6960 len = substr_atoi(loc);
6962 /* Skip POS in ${var:POS:LEN} */
6964 while (*loc && *loc != ':')
6967 len = substr_atoi(loc);
6970 /* ${VAR:$((-n)):l} starts n chars from the end */
6971 pos = orig_len + pos;
6973 if ((unsigned)pos >= orig_len) {
6974 /* apart from obvious ${VAR:999999:l},
6975 * covers ${VAR:$((-9999999)):l} - result is ""
6982 /* ${VAR:N:-M} sets LEN to strlen()-M */
6983 len = (orig_len - pos) + len;
6985 if ((unsigned)len > (orig_len - pos))
6986 len = orig_len - pos;
6988 for (str = startp; pos; str++, pos--) {
6989 if (quotes && (unsigned char)*str == CTLESC)
6992 for (loc = startp; len; len--) {
6993 if (quotes && (unsigned char)*str == CTLESC)
6998 amount = loc - expdest;
6999 STADJUST(amount, expdest);
7002 #endif /* BASH_SUBSTR */
7005 resetloc = expdest - (char *)stackblock();
7007 #if BASH_PATTERN_SUBST
7010 /* We'll comeback here if we grow the stack while handling
7011 * a VSREPLACE or VSREPLACEALL, since our pointers into the
7012 * stack will need rebasing, and we'll need to remove our work
7018 amount = expdest - ((char *)stackblock() + resetloc);
7019 STADJUST(-amount, expdest);
7020 startp = (char *)stackblock() + startloc;
7023 rmescend = (char *)stackblock() + strloc;
7024 //bb_error_msg("str7:'%s'", rmescend);
7026 //TODO: how to handle slash_pos here if string changes (shortens?)
7027 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW, NULL);
7028 if (rmesc != startp) {
7030 startp = (char *)stackblock() + startloc;
7034 str = (char *)stackblock() + strloc;
7036 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
7037 * The result is a_\_z_c (not a\_\_z_c)!
7039 * The search pattern and replace string treat backslashes differently!
7040 * "&slash_pos" causes rmescapes() to work differently on the pattern
7041 * and string. It's only used on the first call.
7043 //bb_error_msg("str8:'%s' slash_pos:%d", str, slash_pos);
7044 rmescapes(str, RMESCAPE_GLOB,
7045 repl ? NULL : (slash_pos < 0 ? NULL : &slash_pos)
7048 #if BASH_PATTERN_SUBST
7049 workloc = expdest - (char *)stackblock();
7050 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
7055 //bb_error_msg("str9:'%s' slash_pos:%d", str, slash_pos);
7057 if (slash_pos >= 0) {
7058 repl = str + slash_pos;
7062 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
7064 /* If there's no pattern to match, return the expansion unmolested */
7073 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
7074 //bb_error_msg("scanright('%s'):'%s'", str, loc);
7076 /* No match, advance */
7077 char *restart_detect = stackblock();
7079 STPUTC(*idx, expdest);
7080 if (quotes && (unsigned char)*idx == CTLESC) {
7083 STPUTC(*idx, expdest);
7085 if (stackblock() != restart_detect)
7090 /* continue; - prone to quadratic behavior, smarter code: */
7093 if (str[0] == '*') {
7094 /* Pattern is "*foo". If "*foo" does not match "long_string",
7095 * it would never match "ong_string" etc, no point in trying.
7102 if (subtype == VSREPLACEALL) {
7104 if (quotes && (unsigned char)*idx == CTLESC)
7113 //bb_error_msg("repl:'%s'", repl);
7114 for (loc = (char*)repl; *loc; loc++) {
7115 char *restart_detect = stackblock();
7116 if (quotes && *loc == '\\') {
7117 STPUTC(CTLESC, expdest);
7120 STPUTC(*loc, expdest);
7121 if (stackblock() != restart_detect)
7126 if (subtype == VSREPLACE) {
7127 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
7129 char *restart_detect = stackblock();
7130 STPUTC(*idx, expdest);
7131 if (stackblock() != restart_detect)
7140 /* We've put the replaced text into a buffer at workloc, now
7141 * move it to the right place and adjust the stack.
7143 STPUTC('\0', expdest);
7144 startp = (char *)stackblock() + startloc;
7145 memmove(startp, (char *)stackblock() + workloc, len + 1);
7146 //bb_error_msg("startp:'%s'", startp);
7147 amount = expdest - (startp + len);
7148 STADJUST(-amount, expdest);
7151 #endif /* BASH_PATTERN_SUBST */
7153 subtype -= VSTRIMRIGHT;
7155 if (subtype < 0 || subtype > 7)
7158 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
7159 zero = subtype >> 1;
7160 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
7161 scan = (subtype & 1) ^ zero ? scanleft : scanright;
7163 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
7166 memmove(startp, loc, str - loc);
7167 loc = startp + (str - loc) - 1;
7170 amount = loc - expdest;
7171 STADJUST(amount, expdest);
7177 * Add the value of a specialized variable to the stack string.
7178 * name parameter (examples):
7179 * ash -c 'echo $1' name:'1='
7180 * ash -c 'echo $qwe' name:'qwe='
7181 * ash -c 'echo $$' name:'$='
7182 * ash -c 'echo ${$}' name:'$='
7183 * ash -c 'echo ${$##q}' name:'$=q'
7184 * ash -c 'echo ${#$}' name:'$='
7185 * note: examples with bad shell syntax:
7186 * ash -c 'echo ${#$1}' name:'$=1'
7187 * ash -c 'echo ${#1#}' name:'1=#'
7189 static NOINLINE ssize_t
7190 varvalue(char *name, int varflags, int flags, int quoted)
7197 int subtype = varflags & VSTYPE;
7198 int discard = subtype == VSPLUS || subtype == VSLENGTH;
7199 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
7202 sep = (flags & EXP_FULL) << CHAR_BIT;
7203 syntax = quoted ? DQSYNTAX : BASESYNTAX;
7213 num = shellparam.nparam;
7221 goto check_1char_name;
7223 expdest = makestrspace(NOPTS, expdest);
7224 for (i = NOPTS - 1; i >= 0; i--) {
7225 if (optlist[i] && optletters(i)) {
7226 USTPUTC(optletters(i), expdest);
7232 /* handles cases similar to ${#$1} */
7233 if (name[2] != '\0')
7234 raise_error_syntax("bad substitution");
7246 /* We will set c to 0 or ~0 depending on whether
7247 * we're doing field splitting. We won't do field
7248 * splitting if either we're quoted or sep is zero.
7250 * Instead of testing (quoted || !sep) the following
7251 * trick optimises away any branches by using the
7252 * fact that EXP_QUOTED (which is the only bit that
7253 * can be set in quoted) is the same as EXP_FULL <<
7254 * CHAR_BIT (which is the only bit that can be set
7257 #if EXP_QUOTED >> CHAR_BIT != EXP_FULL
7258 #error The following two lines expect EXP_QUOTED == EXP_FULL << CHAR_BIT
7260 c = !((quoted | ~sep) & EXP_QUOTED) - 1;
7262 sep |= ifsset() ? (unsigned char)(c & ifsval()[0]) : ' ';
7268 while ((p = *ap++) != NULL) {
7269 len += strtodest(p, syntax, quotes);
7273 memtodest(&sepc, 1, syntax, quotes);
7288 num = atoi(name); /* number(name) fails on ${N#str} etc */
7289 if (num < 0 || num > shellparam.nparam)
7291 p = num ? shellparam.p[num - 1] : arg0;
7294 /* NB: name has form "VAR=..." */
7295 p = lookupvar(name);
7300 len = strtodest(p, syntax, quotes);
7301 #if ENABLE_UNICODE_SUPPORT
7302 if (subtype == VSLENGTH && len > 0) {
7303 reinit_unicode_for_ash();
7304 if (unicode_status == UNICODE_ON) {
7305 STADJUST(-len, expdest);
7307 len = unicode_strlen(p);
7315 STADJUST(-len, expdest);
7320 * Expand a variable, and return a pointer to the next character in the
7324 evalvar(char *p, int flag)
7334 varflags = (unsigned char) *p++;
7335 subtype = varflags & VSTYPE;
7338 raise_error_syntax("bad substitution");
7340 quoted = flag & EXP_QUOTED;
7342 startloc = expdest - (char *)stackblock();
7343 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
7346 varlen = varvalue(var, varflags, flag, quoted);
7347 if (varflags & VSNUL)
7350 if (subtype == VSPLUS) {
7351 varlen = -1 - varlen;
7355 if (subtype == VSMINUS) {
7360 flag | EXP_TILDE | EXP_WORD
7367 if (subtype == VSASSIGN || subtype == VSQUESTION) {
7371 subevalvar(p, var, 0, subtype, startloc, varflags,
7372 flag & ~QUOTES_ESC);
7375 * Remove any recorded regions beyond
7378 removerecordregions(startloc);
7382 if (varlen < 0 && uflag)
7383 varunset(p, var, 0, 0);
7385 if (subtype == VSLENGTH) {
7386 cvtnum(varlen > 0 ? varlen : 0);
7390 if (subtype == VSNORMAL) {
7393 quoted = *var == '@' && shellparam.nparam;
7397 recordregion(startloc, expdest - (char *)stackblock(), quoted);
7406 case VSTRIMRIGHTMAX:
7410 #if BASH_PATTERN_SUBST
7422 * Terminate the string and start recording the pattern
7425 STPUTC('\0', expdest);
7426 patloc = expdest - (char *)stackblock();
7427 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
7428 startloc, varflags, flag)) {
7429 int amount = expdest - (
7430 (char *)stackblock() + patloc - 1
7432 STADJUST(-amount, expdest);
7434 /* Remove any recorded regions beyond start of variable */
7435 removerecordregions(startloc);
7440 if (subtype != VSNORMAL) { /* skip to end of alternative */
7443 unsigned char c = *p++;
7446 else if (c == CTLBACKQ) {
7448 argbackq = argbackq->next;
7449 } else if (c == CTLVAR) {
7450 if ((*p++ & VSTYPE) != VSNORMAL)
7452 } else if (c == CTLENDVAR) {
7462 * Add a file name to the list.
7465 addfname(const char *name)
7469 sp = stzalloc(sizeof(*sp));
7470 sp->text = sstrdup(name);
7472 exparg.lastp = &sp->next;
7475 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7477 hasmeta(const char *p)
7479 static const char chars[] ALIGN1 = {
7480 '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
7484 p = strpbrk(p, chars);
7487 switch ((unsigned char)*p) {
7491 if ((unsigned char)*p == CTLQUOTEMARK)
7493 if ((unsigned char)*p == CTLESC)
7495 if (*p == '\0') /* huh? */
7506 if (!strchr(p + 1, ']')) {
7507 /* It's not a properly closed [] pattern,
7508 * but other metas may follow. Continue checking.
7509 * my[file* _is_ globbed by bash
7510 * and matches filenames like "my[file1".
7526 /* If we want to use glob() from libc... */
7527 #if !ENABLE_ASH_INTERNAL_GLOB
7529 /* Add the result of glob() to the list */
7531 addglob(const glob_t *pglob)
7533 char **p = pglob->gl_pathv;
7540 expandmeta(struct strlist *str /*, int flag*/)
7542 /* TODO - EXP_REDIR */
7552 if (!hasmeta(str->text))
7556 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7557 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7558 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7560 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7561 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7562 // Which means you need to unescape the string, right? Not so fast:
7563 // if there _is_ a file named "file\?" (with backslash), it is returned
7564 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7565 // You DON'T KNOW by looking at the result whether you need to unescape it.
7567 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7568 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7569 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7570 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7571 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7572 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7573 i = glob(p, 0, NULL, &pglob);
7574 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7579 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7580 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7581 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7593 *exparg.lastp = str;
7594 rmescapes(str->text, 0, NULL);
7595 exparg.lastp = &str->next;
7597 default: /* GLOB_NOSPACE */
7600 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7607 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7610 * Do metacharacter (i.e. *, ?, [...]) expansion.
7612 typedef struct exp_t {
7617 expmeta(exp_t *exp, char *name, unsigned name_len, unsigned expdir_len)
7619 #define expdir exp->dir
7620 #define expdir_max exp->dir_max
7621 char *enddir = expdir + expdir_len;
7636 for (p = name; esc = 0, *p; p += esc + 1) {
7637 if (*p == '*' || *p == '?')
7639 else if (*p == '[') {
7646 if (*q == '/' || *q == '\0')
7654 if (*p == '\\' && p[1])
7656 if (p[esc] == '/') {
7659 start = p + esc + 1;
7663 if (metaflag == 0) { /* we've reached the end of the file name */
7668 if (*p == '\\' && p[1])
7672 if (lstat(expdir, &statb) == 0)
7680 if (*p == '\\' && p[1])
7683 } while (p < start);
7687 expdir_len = enddir - cp;
7693 if (*endname == 0) {
7700 name_len -= endname - name;
7707 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7708 if (dp->d_name[0] == '.' && !matchdot)
7710 if (pmatch(start, dp->d_name)) {
7712 strcpy(enddir, dp->d_name);
7718 p = stpcpy(enddir, dp->d_name);
7721 offset = p - expdir + 1;
7722 len = offset + name_len + NAME_MAX;
7723 if (len > expdir_max) {
7725 expdir = ckrealloc(expdir, len);
7729 expmeta(exp, endname, name_len, offset);
7730 enddir = expdir + expdir_len;
7736 endname[-esc - 1] = esc ? '\\' : '/';
7741 static struct strlist *
7742 msort(struct strlist *list, int len)
7744 struct strlist *p, *q = NULL;
7745 struct strlist **lpp;
7753 for (n = half; --n >= 0;) {
7757 q->next = NULL; /* terminate first half of list */
7758 q = msort(list, half); /* sort first half of list */
7759 p = msort(p, len - half); /* sort second half */
7762 #if ENABLE_LOCALE_SUPPORT
7763 if (strcoll(p->text, q->text) < 0)
7765 if (strcmp(p->text, q->text) < 0)
7789 * Sort the results of file name expansion. It calculates the number of
7790 * strings to sort and then calls msort (short for merge sort) to do the
7793 static struct strlist *
7794 expsort(struct strlist *str)
7800 for (sp = str; sp; sp = sp->next)
7802 return msort(str, len);
7806 expandmeta(struct strlist *str /*, int flag*/)
7808 /* TODO - EXP_REDIR */
7812 struct strlist **savelastp;
7819 if (!hasmeta(str->text))
7821 savelastp = exparg.lastp;
7824 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7826 exp.dir_max = len + PATH_MAX;
7827 exp.dir = ckmalloc(exp.dir_max);
7829 expmeta(&exp, p, len, 0);
7834 if (exparg.lastp == savelastp) {
7839 *exparg.lastp = str;
7840 rmescapes(str->text, 0, NULL);
7841 exparg.lastp = &str->next;
7843 *exparg.lastp = NULL;
7844 *savelastp = sp = expsort(*savelastp);
7845 while (sp->next != NULL)
7847 exparg.lastp = &sp->next;
7852 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7855 * Perform variable substitution and command substitution on an argument,
7856 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7857 * perform splitting and file name expansion. When arglist is NULL, perform
7858 * here document expansion.
7861 expandarg(union node *arg, struct arglist *arglist, int flag)
7866 argbackq = arg->narg.backquote;
7867 STARTSTACKSTR(expdest);
7868 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7869 argstr(arg->narg.text, flag);
7870 p = _STPUTC('\0', expdest);
7872 if (arglist == NULL) {
7873 /* here document expanded */
7876 p = grabstackstr(p);
7877 TRACE(("expandarg: p:'%s'\n", p));
7878 exparg.lastp = &exparg.list;
7882 if (flag & EXP_FULL) {
7883 ifsbreakup(p, &exparg);
7884 *exparg.lastp = NULL;
7885 exparg.lastp = &exparg.list;
7886 expandmeta(exparg.list /*, flag*/);
7888 sp = stzalloc(sizeof(*sp));
7891 exparg.lastp = &sp->next;
7893 *exparg.lastp = NULL;
7895 *arglist->lastp = exparg.list;
7896 arglist->lastp = exparg.lastp;
7904 * Expand shell variables and backquotes inside a here document.
7907 expandhere(union node *arg, int fd)
7909 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7910 full_write(fd, stackblock(), expdest - (char *)stackblock());
7914 * Returns true if the pattern matches the string.
7917 patmatch(char *pattern, const char *string)
7919 char *p = preglob(pattern, 0);
7920 int r = pmatch(p, string);
7921 //bb_error_msg("!fnmatch(pattern:'%s',str:'%s',0):%d", p, string, r);
7926 * See if a pattern matches in a case statement.
7929 casematch(union node *pattern, char *val)
7931 struct stackmark smark;
7934 setstackmark(&smark);
7935 argbackq = pattern->narg.backquote;
7936 STARTSTACKSTR(expdest);
7937 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
7938 STACKSTRNUL(expdest);
7940 result = patmatch(stackblock(), val);
7941 popstackmark(&smark);
7946 /* ============ find_command */
7950 int (*builtin)(int, char **) FAST_FUNC;
7951 /* unsigned flags; */
7953 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7954 /* "regular" builtins always take precedence over commands,
7955 * regardless of PATH=....%builtin... position */
7956 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7957 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7960 smallint cmdtype; /* CMDxxx */
7963 /* index >= 0 for commands without path (slashes) */
7964 /* (TODO: what exactly does the value mean? PATH position?) */
7965 /* index == -1 for commands with slashes */
7966 /* index == (-2 - applet_no) for NOFORK applets */
7967 const struct builtincmd *cmd;
7968 struct funcnode *func;
7971 /* values of cmdtype */
7972 #define CMDUNKNOWN -1 /* no entry in table for command */
7973 #define CMDNORMAL 0 /* command is an executable program */
7974 #define CMDFUNCTION 1 /* command is a shell function */
7975 #define CMDBUILTIN 2 /* command is a shell builtin */
7977 /* action to find_command() */
7978 #define DO_ERR 0x01 /* prints errors */
7979 #define DO_ABS 0x02 /* checks absolute paths */
7980 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7981 #define DO_ALTPATH 0x08 /* using alternate path */
7982 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7984 static void find_command(char *, struct cmdentry *, int, const char *);
7987 /* ============ Hashing commands */
7990 * When commands are first encountered, they are entered in a hash table.
7991 * This ensures that a full path search will not have to be done for them
7992 * on each invocation.
7994 * We should investigate converting to a linear search, even though that
7995 * would make the command name "hash" a misnomer.
7999 struct tblentry *next; /* next entry in hash chain */
8000 union param param; /* definition of builtin function */
8001 smallint cmdtype; /* CMDxxx */
8002 char rehash; /* if set, cd done since entry created */
8003 char cmdname[1]; /* name of command */
8006 static struct tblentry **cmdtable;
8007 #define INIT_G_cmdtable() do { \
8008 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
8011 static int builtinloc = -1; /* index in path of %builtin, or -1 */
8015 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
8017 #if ENABLE_FEATURE_SH_STANDALONE
8018 if (applet_no >= 0) {
8019 # if NUM_SCRIPTS > 0
8020 if (applet_no < NUM_APPLETS)
8022 if (APPLET_IS_NOEXEC(applet_no)) {
8026 popredir(/*drop:*/ 1);
8027 run_noexec_applet_and_exit(applet_no, cmd, argv);
8029 /* re-exec ourselves with the new arguments */
8030 execve(bb_busybox_exec_path, argv, envp);
8031 /* If they called chroot or otherwise made the binary no longer
8032 * executable, fall through */
8039 execve(cmd, argv, envp);
8040 } while (errno == EINTR);
8042 execve(cmd, argv, envp);
8045 if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
8046 /* Run "cmd" as a shell script:
8047 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
8048 * "If the execve() function fails with ENOEXEC, the shell
8049 * shall execute a command equivalent to having a shell invoked
8050 * with the command name as its first operand,
8051 * with any remaining arguments passed to the new shell"
8053 * That is, do not use $SHELL, user's shell, or /bin/sh;
8054 * just call ourselves.
8056 * Note that bash reads ~80 chars of the file, and if it sees
8057 * a zero byte before it sees newline, it doesn't try to
8058 * interpret it, but fails with "cannot execute binary file"
8059 * message and exit code 126. For one, this prevents attempts
8060 * to interpret foreign ELF binaries as shell scripts.
8062 argv[0] = (char*) cmd;
8063 cmd = bb_busybox_exec_path;
8064 /* NB: this is only possible because all callers of shellexec()
8065 * ensure that the argv[-1] slot exists!
8068 argv[0] = (char*) "ash";
8074 * Exec a program. Never returns. If you change this routine, you may
8075 * have to change the find_command routine as well.
8076 * argv[-1] must exist and be writable! See tryexec() for why.
8078 static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
8079 static void shellexec(char *prog, char **argv, const char *path, int idx)
8085 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
8087 envp = listvars(VEXPORT, VUNSET, /*strlist:*/ NULL, /*end:*/ NULL);
8088 if (strchr(prog, '/') != NULL
8089 #if ENABLE_FEATURE_SH_STANDALONE
8090 || (applet_no = find_applet_by_name(prog)) >= 0
8091 # if NUM_SCRIPTS > 0
8092 || (applet_no = NUM_APPLETS + find_script_by_name(prog)) >= 0
8096 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
8097 if (applet_no >= 0) {
8098 /* We tried execing ourself, but it didn't work.
8099 * Maybe /proc/self/exe doesn't exist?
8108 while ((cmdname = path_advance(&path, prog)) != NULL) {
8109 if (--idx < 0 && pathopt == NULL) {
8110 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
8111 if (errno != ENOENT && errno != ENOTDIR)
8118 /* Map to POSIX errors */
8130 exitstatus = exerrno;
8131 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
8132 prog, e, suppress_int));
8133 ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
8138 printentry(struct tblentry *cmdp)
8144 idx = cmdp->param.index;
8147 name = path_advance(&path, cmdp->cmdname);
8149 } while (--idx >= 0);
8150 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
8154 * Clear out command entries. The argument specifies the first entry in
8155 * PATH which has changed.
8158 clearcmdentry(int firstchange)
8160 struct tblentry **tblp;
8161 struct tblentry **pp;
8162 struct tblentry *cmdp;
8165 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
8167 while ((cmdp = *pp) != NULL) {
8168 if ((cmdp->cmdtype == CMDNORMAL &&
8169 cmdp->param.index >= firstchange)
8170 || (cmdp->cmdtype == CMDBUILTIN &&
8171 builtinloc >= firstchange)
8184 * Locate a command in the command hash table. If "add" is nonzero,
8185 * add the command to the table if it is not already present. The
8186 * variable "lastcmdentry" is set to point to the address of the link
8187 * pointing to the entry, so that delete_cmd_entry can delete the
8190 * Interrupts must be off if called with add != 0.
8192 static struct tblentry **lastcmdentry;
8194 static struct tblentry *
8195 cmdlookup(const char *name, int add)
8197 unsigned int hashval;
8199 struct tblentry *cmdp;
8200 struct tblentry **pp;
8203 hashval = (unsigned char)*p << 4;
8205 hashval += (unsigned char)*p++;
8207 pp = &cmdtable[hashval % CMDTABLESIZE];
8208 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8209 if (strcmp(cmdp->cmdname, name) == 0)
8213 if (add && cmdp == NULL) {
8214 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
8216 /* + 1 - already done because
8217 * tblentry::cmdname is char[1] */);
8218 /*cmdp->next = NULL; - ckzalloc did it */
8219 cmdp->cmdtype = CMDUNKNOWN;
8220 strcpy(cmdp->cmdname, name);
8227 * Delete the command entry returned on the last lookup.
8230 delete_cmd_entry(void)
8232 struct tblentry *cmdp;
8235 cmdp = *lastcmdentry;
8236 *lastcmdentry = cmdp->next;
8237 if (cmdp->cmdtype == CMDFUNCTION)
8238 freefunc(cmdp->param.func);
8244 * Add a new command entry, replacing any existing command entry for
8245 * the same name - except special builtins.
8248 addcmdentry(char *name, struct cmdentry *entry)
8250 struct tblentry *cmdp;
8252 cmdp = cmdlookup(name, 1);
8253 if (cmdp->cmdtype == CMDFUNCTION) {
8254 freefunc(cmdp->param.func);
8256 cmdp->cmdtype = entry->cmdtype;
8257 cmdp->param = entry->u;
8261 static int FAST_FUNC
8262 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8264 struct tblentry **pp;
8265 struct tblentry *cmdp;
8267 struct cmdentry entry;
8270 if (nextopt("r") != '\0') {
8275 if (*argptr == NULL) {
8276 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8277 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8278 if (cmdp->cmdtype == CMDNORMAL)
8286 while ((name = *argptr) != NULL) {
8287 cmdp = cmdlookup(name, 0);
8289 && (cmdp->cmdtype == CMDNORMAL
8290 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
8294 find_command(name, &entry, DO_ERR, pathval());
8295 if (entry.cmdtype == CMDUNKNOWN)
8303 * Called when a cd is done. Marks all commands so the next time they
8304 * are executed they will be rehashed.
8309 struct tblentry **pp;
8310 struct tblentry *cmdp;
8312 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8313 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8314 if (cmdp->cmdtype == CMDNORMAL
8315 || (cmdp->cmdtype == CMDBUILTIN
8316 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
8326 * Fix command hash table when PATH changed.
8327 * Called before PATH is changed. The argument is the new value of PATH;
8328 * pathval() still returns the old value at this point.
8329 * Called with interrupts off.
8331 static void FAST_FUNC
8332 changepath(const char *new)
8340 firstchange = 9999; /* assume no change */
8346 if ((*old == '\0' && *new == ':')
8347 || (*old == ':' && *new == '\0')
8351 old = new; /* ignore subsequent differences */
8355 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
8362 if (builtinloc < 0 && idx_bltin >= 0)
8363 builtinloc = idx_bltin; /* zap builtins */
8364 if (builtinloc >= 0 && idx_bltin < 0)
8366 clearcmdentry(firstchange);
8367 builtinloc = idx_bltin;
8403 typedef smallint token_id_t;
8405 /* Nth bit indicates if token marks the end of a list */
8408 /* 0 */ | (1u << TEOF)
8409 /* 1 */ | (0u << TNL)
8410 /* 2 */ | (0u << TREDIR)
8411 /* 3 */ | (0u << TWORD)
8412 /* 4 */ | (0u << TSEMI)
8413 /* 5 */ | (0u << TBACKGND)
8414 /* 6 */ | (0u << TAND)
8415 /* 7 */ | (0u << TOR)
8416 /* 8 */ | (0u << TPIPE)
8417 /* 9 */ | (0u << TLP)
8418 /* 10 */ | (1u << TRP)
8419 /* 11 */ | (1u << TENDCASE)
8420 /* 12 */ | (1u << TENDBQUOTE)
8421 /* 13 */ | (0u << TNOT)
8422 /* 14 */ | (0u << TCASE)
8423 /* 15 */ | (1u << TDO)
8424 /* 16 */ | (1u << TDONE)
8425 /* 17 */ | (1u << TELIF)
8426 /* 18 */ | (1u << TELSE)
8427 /* 19 */ | (1u << TESAC)
8428 /* 20 */ | (1u << TFI)
8429 /* 21 */ | (0u << TFOR)
8431 /* 22 */ | (0u << TFUNCTION)
8433 /* 23 */ | (0u << TIF)
8434 /* 24 */ | (0u << TIN)
8435 /* 25 */ | (1u << TTHEN)
8436 /* 26 */ | (0u << TUNTIL)
8437 /* 27 */ | (0u << TWHILE)
8438 /* 28 */ | (0u << TBEGIN)
8439 /* 29 */ | (1u << TEND)
8440 , /* thus far 29 bits used */
8443 static const char *const tokname_array[] = {
8457 #define KWDOFFSET 13
8458 /* the following are keywords */
8480 /* Wrapper around strcmp for qsort/bsearch/... */
8482 pstrcmp(const void *a, const void *b)
8484 return strcmp((char*)a, *(char**)b);
8487 static const char *const *
8488 findkwd(const char *s)
8490 return bsearch(s, tokname_array + KWDOFFSET,
8491 ARRAY_SIZE(tokname_array) - KWDOFFSET,
8492 sizeof(tokname_array[0]), pstrcmp);
8496 * Locate and print what a word is...
8499 describe_command(char *command, const char *path, int describe_command_verbose)
8501 struct cmdentry entry;
8502 #if ENABLE_ASH_ALIAS
8503 const struct alias *ap;
8506 path = path ? path : pathval();
8508 if (describe_command_verbose) {
8512 /* First look at the keywords */
8513 if (findkwd(command)) {
8514 out1str(describe_command_verbose ? " is a shell keyword" : command);
8518 #if ENABLE_ASH_ALIAS
8519 /* Then look at the aliases */
8520 ap = lookupalias(command, 0);
8522 if (!describe_command_verbose) {
8527 out1fmt(" is an alias for %s", ap->val);
8532 find_command(command, &entry, DO_ABS, path);
8534 switch (entry.cmdtype) {
8536 int j = entry.u.index;
8542 p = path_advance(&path, command);
8546 if (describe_command_verbose) {
8547 out1fmt(" is %s", p);
8555 if (describe_command_verbose) {
8556 /*out1str(" is a shell function");*/
8557 out1str(" is a function"); /* bash says this */
8564 if (describe_command_verbose) {
8565 out1fmt(" is a %sshell builtin",
8566 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8567 "special " : nullstr
8575 if (describe_command_verbose) {
8576 out1str(": not found\n");
8585 static int FAST_FUNC
8586 typecmd(int argc UNUSED_PARAM, char **argv)
8592 /* type -p ... ? (we don't bother checking for 'p') */
8593 if (argv[1] && argv[1][0] == '-') {
8598 err |= describe_command(argv[i++], NULL, verbose);
8603 #if ENABLE_ASH_CMDCMD
8604 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8606 parse_command_args(char **argv, const char **path)
8619 if (c == '-' && !*cp) {
8627 *path = bb_default_path;
8630 /* run 'typecmd' for other options */
8639 static int FAST_FUNC
8640 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8648 const char *path = NULL;
8650 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8651 * never reaches this function.
8654 while ((c = nextopt("pvV")) != '\0')
8656 verify |= VERIFY_VERBOSE;
8658 /*verify |= VERIFY_BRIEF*/;
8664 path = bb_default_path;
8666 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8668 if (/*verify && */ cmd)
8669 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8676 /*static int funcblocksize; // size of structures in function */
8677 /*static int funcstringsize; // size of strings in node */
8678 static void *funcblock; /* block to allocate function from */
8679 static char *funcstring_end; /* end of block to allocate strings from */
8681 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8682 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8683 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8684 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8685 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8686 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8687 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8688 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8689 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8690 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8691 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8692 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8693 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8694 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8695 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8696 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8697 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8698 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8699 #if BASH_REDIR_OUTPUT
8700 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8702 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8703 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8704 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8705 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8706 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8707 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8708 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8709 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8710 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8713 static int calcsize(int funcblocksize, union node *n);
8716 sizenodelist(int funcblocksize, struct nodelist *lp)
8719 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8720 funcblocksize = calcsize(funcblocksize, lp->n);
8723 return funcblocksize;
8727 calcsize(int funcblocksize, union node *n)
8730 return funcblocksize;
8731 funcblocksize += nodesize[n->type];
8734 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8735 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8736 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8739 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8744 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8745 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8752 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8753 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8756 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8757 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8758 funcblocksize = calcsize(funcblocksize, n->nif.test);
8761 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8762 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8763 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8766 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8767 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8770 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8771 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8772 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8775 funcblocksize = calcsize(funcblocksize, n->ndefun.body);
8776 funcblocksize += SHELL_ALIGN(strlen(n->ndefun.text) + 1);
8779 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8780 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8781 funcblocksize = calcsize(funcblocksize, n->narg.next);
8784 #if BASH_REDIR_OUTPUT
8791 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8792 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8796 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8797 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8801 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8802 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8805 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8808 return funcblocksize;
8812 nodeckstrdup(char *s)
8814 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8815 return strcpy(funcstring_end, s);
8818 static union node *copynode(union node *);
8820 static struct nodelist *
8821 copynodelist(struct nodelist *lp)
8823 struct nodelist *start;
8824 struct nodelist **lpp;
8829 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8830 (*lpp)->n = copynode(lp->n);
8832 lpp = &(*lpp)->next;
8839 copynode(union node *n)
8846 funcblock = (char *) funcblock + nodesize[n->type];
8850 new->ncmd.redirect = copynode(n->ncmd.redirect);
8851 new->ncmd.args = copynode(n->ncmd.args);
8852 new->ncmd.assign = copynode(n->ncmd.assign);
8853 new->ncmd.linno = n->ncmd.linno;
8856 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8857 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8862 new->nredir.redirect = copynode(n->nredir.redirect);
8863 new->nredir.n = copynode(n->nredir.n);
8864 new->nredir.linno = n->nredir.linno;
8871 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8872 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8875 new->nif.elsepart = copynode(n->nif.elsepart);
8876 new->nif.ifpart = copynode(n->nif.ifpart);
8877 new->nif.test = copynode(n->nif.test);
8880 new->nfor.var = nodeckstrdup(n->nfor.var);
8881 new->nfor.body = copynode(n->nfor.body);
8882 new->nfor.args = copynode(n->nfor.args);
8883 new->nfor.linno = n->nfor.linno;
8886 new->ncase.cases = copynode(n->ncase.cases);
8887 new->ncase.expr = copynode(n->ncase.expr);
8888 new->ncase.linno = n->ncase.linno;
8891 new->nclist.body = copynode(n->nclist.body);
8892 new->nclist.pattern = copynode(n->nclist.pattern);
8893 new->nclist.next = copynode(n->nclist.next);
8896 new->ndefun.body = copynode(n->ndefun.body);
8897 new->ndefun.text = nodeckstrdup(n->ndefun.text);
8898 new->ndefun.linno = n->ndefun.linno;
8901 new->narg.backquote = copynodelist(n->narg.backquote);
8902 new->narg.text = nodeckstrdup(n->narg.text);
8903 new->narg.next = copynode(n->narg.next);
8906 #if BASH_REDIR_OUTPUT
8913 new->nfile.fname = copynode(n->nfile.fname);
8914 new->nfile.fd = n->nfile.fd;
8915 new->nfile.next = copynode(n->nfile.next);
8919 new->ndup.vname = copynode(n->ndup.vname);
8920 new->ndup.dupfd = n->ndup.dupfd;
8921 new->ndup.fd = n->ndup.fd;
8922 new->ndup.next = copynode(n->ndup.next);
8926 new->nhere.doc = copynode(n->nhere.doc);
8927 new->nhere.fd = n->nhere.fd;
8928 new->nhere.next = copynode(n->nhere.next);
8931 new->nnot.com = copynode(n->nnot.com);
8934 new->type = n->type;
8939 * Make a copy of a parse tree.
8941 static struct funcnode *
8942 copyfunc(union node *n)
8947 /*funcstringsize = 0;*/
8948 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8949 f = ckzalloc(blocksize /* + funcstringsize */);
8950 funcblock = (char *) f + offsetof(struct funcnode, n);
8951 funcstring_end = (char *) f + blocksize;
8953 /* f->count = 0; - ckzalloc did it */
8958 * Define a shell function.
8961 defun(union node *func)
8963 struct cmdentry entry;
8966 entry.cmdtype = CMDFUNCTION;
8967 entry.u.func = copyfunc(func);
8968 addcmdentry(func->ndefun.text, &entry);
8972 /* Reasons for skipping commands (see comment on breakcmd routine) */
8973 #define SKIPBREAK (1 << 0)
8974 #define SKIPCONT (1 << 1)
8975 #define SKIPFUNC (1 << 2)
8976 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8977 static int skipcount; /* number of levels to skip */
8978 static int loopnest; /* current loop nesting level */
8979 static int funcline; /* starting line number of current function, or 0 if not in a function */
8981 /* Forward decl way out to parsing code - dotrap needs it */
8982 static int evalstring(char *s, int flags);
8984 /* Called to execute a trap.
8985 * Single callsite - at the end of evaltree().
8986 * If we return non-zero, evaltree raises EXEXIT exception.
8988 * Perhaps we should avoid entering new trap handlers
8989 * while we are executing a trap handler. [is it a TODO?]
8996 uint8_t last_status;
9001 last_status = exitstatus;
9005 TRACE(("dotrap entered\n"));
9006 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
9018 /* non-trapped SIGINT is handled separately by raise_interrupt,
9019 * don't upset it by resetting gotsig[SIGINT-1] */
9020 if (sig == SIGINT && !p)
9023 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
9029 exitstatus = last_status;
9030 TRACE(("dotrap returns\n"));
9033 /* forward declarations - evaluation is fairly recursive business... */
9034 static int evalloop(union node *, int);
9035 static int evalfor(union node *, int);
9036 static int evalcase(union node *, int);
9037 static int evalsubshell(union node *, int);
9038 static void expredir(union node *);
9039 static int evalpipe(union node *, int);
9040 static int evalcommand(union node *, int);
9041 static int evalbltin(const struct builtincmd *, int, char **, int);
9042 static void prehash(union node *);
9045 * Evaluate a parse tree. The value is left in the global variable
9049 evaltree(union node *n, int flags)
9052 int (*evalfn)(union node *, int);
9056 TRACE(("evaltree(NULL) called\n"));
9059 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
9066 out1fmt("Node type = %d\n", n->type);
9071 status = !evaltree(n->nnot.com, EV_TESTED);
9074 errlinno = lineno = n->nredir.linno;
9076 lineno -= funcline - 1;
9077 expredir(n->nredir.redirect);
9078 pushredir(n->nredir.redirect);
9079 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
9081 status = evaltree(n->nredir.n, flags & EV_TESTED);
9083 if (n->nredir.redirect)
9084 popredir(/*drop:*/ 0);
9087 evalfn = evalcommand;
9089 if (eflag && !(flags & EV_TESTED))
9101 evalfn = evalsubshell;
9114 #error NAND + 1 != NOR
9116 #if NOR + 1 != NSEMI
9117 #error NOR + 1 != NSEMI
9119 unsigned is_or = n->type - NAND;
9122 (flags | ((is_or >> 1) - 1)) & EV_TESTED
9124 if ((!status) == is_or || evalskip)
9130 status = evalfn(n, flags);
9134 status = evaltree(n->nif.test, EV_TESTED);
9141 if (n->nif.elsepart) {
9142 n = n->nif.elsepart;
9149 /* Not necessary. To test it:
9150 * "false; f() { qwerty; }; echo $?" should print 0.
9154 exitstatus = status;
9158 /* Order of checks below is important:
9159 * signal handlers trigger before exit caused by "set -e".
9163 if (checkexit & status)
9164 raise_exception(EXEXIT);
9165 if (flags & EV_EXIT)
9166 raise_exception(EXEXIT);
9168 TRACE(("leaving evaltree (no interrupts)\n"));
9175 int skip = evalskip;
9182 if (--skipcount <= 0) {
9193 evalloop(union node *n, int flags)
9204 i = evaltree(n->nbinary.ch1, EV_TESTED);
9206 if (skip == SKIPFUNC)
9210 if (n->type != NWHILE)
9214 status = evaltree(n->nbinary.ch2, flags);
9216 } while (!(skip & ~SKIPCONT));
9223 evalfor(union node *n, int flags)
9225 struct arglist arglist;
9228 struct stackmark smark;
9231 errlinno = lineno = n->ncase.linno;
9233 lineno -= funcline - 1;
9235 setstackmark(&smark);
9236 arglist.list = NULL;
9237 arglist.lastp = &arglist.list;
9238 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
9239 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9241 *arglist.lastp = NULL;
9245 for (sp = arglist.list; sp; sp = sp->next) {
9246 setvar0(n->nfor.var, sp->text);
9247 status = evaltree(n->nfor.body, flags);
9248 if (skiploop() & ~SKIPCONT)
9252 popstackmark(&smark);
9258 evalcase(union node *n, int flags)
9262 struct arglist arglist;
9263 struct stackmark smark;
9266 errlinno = lineno = n->ncase.linno;
9268 lineno -= funcline - 1;
9270 setstackmark(&smark);
9271 arglist.list = NULL;
9272 arglist.lastp = &arglist.list;
9273 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
9274 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
9275 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
9276 if (casematch(patp, arglist.list->text)) {
9277 /* Ensure body is non-empty as otherwise
9278 * EV_EXIT may prevent us from setting the
9281 if (evalskip == 0 && cp->nclist.body) {
9282 status = evaltree(cp->nclist.body, flags);
9289 popstackmark(&smark);
9295 * Kick off a subshell to evaluate a tree.
9298 evalsubshell(union node *n, int flags)
9301 int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
9304 errlinno = lineno = n->nredir.linno;
9306 lineno -= funcline - 1;
9308 expredir(n->nredir.redirect);
9309 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
9312 if (backgnd == FORK_FG)
9314 jp = makejob(/*n,*/ 1);
9315 if (forkshell(jp, n, backgnd) == 0) {
9320 flags &= ~EV_TESTED;
9322 redirect(n->nredir.redirect, 0);
9323 evaltreenr(n->nredir.n, flags);
9328 if (backgnd == FORK_FG)
9329 status = waitforjob(jp);
9335 * Compute the names of the files in a redirection list.
9337 static void fixredir(union node *, const char *, int);
9339 expredir(union node *n)
9343 for (redir = n; redir; redir = redir->nfile.next) {
9347 fn.lastp = &fn.list;
9348 switch (redir->type) {
9352 #if BASH_REDIR_OUTPUT
9357 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
9358 TRACE(("expredir expanded to '%s'\n", fn.list->text));
9359 #if BASH_REDIR_OUTPUT
9363 // By the design of stack allocator, the loop of this kind:
9364 // while true; do while true; do break; done </dev/null; done
9365 // will look like a memory leak: ash plans to free expfname's
9366 // of "/dev/null" as soon as it finishes running the loop
9367 // (in this case, never).
9368 // This "fix" is wrong:
9369 if (redir->nfile.expfname)
9370 stunalloc(redir->nfile.expfname);
9371 // It results in corrupted state of stacked allocations.
9373 redir->nfile.expfname = fn.list->text;
9376 case NTOFD: /* >& */
9377 if (redir->ndup.vname) {
9378 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
9379 if (fn.list == NULL)
9380 ash_msg_and_raise_error("redir error");
9381 #if BASH_REDIR_OUTPUT
9382 //FIXME: we used expandarg with different args!
9383 if (!isdigit_str9(fn.list->text)) {
9384 /* >&file, not >&fd */
9385 if (redir->nfile.fd != 1) /* 123>&file - BAD */
9386 ash_msg_and_raise_error("redir error");
9388 goto store_expfname;
9391 fixredir(redir, fn.list->text, 1);
9399 * Evaluate a pipeline. All the processes in the pipeline are children
9400 * of the process creating the pipeline. (This differs from some versions
9401 * of the shell, which make the last process in a pipeline the parent
9405 evalpipe(union node *n, int flags)
9408 struct nodelist *lp;
9414 TRACE(("evalpipe(0x%lx) called\n", (long)n));
9416 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
9420 if (n->npipe.pipe_backgnd == 0)
9422 jp = makejob(/*n,*/ pipelen);
9424 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
9428 if (pipe(pip) < 0) {
9430 ash_msg_and_raise_perror("can't create pipe");
9433 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
9447 evaltreenr(lp->n, flags);
9454 /* Don't want to trigger debugging */
9458 if (n->npipe.pipe_backgnd == 0) {
9459 status = waitforjob(jp);
9460 TRACE(("evalpipe: job done exit status %d\n", status));
9468 * Controls whether the shell is interactive or not.
9471 setinteractive(int on)
9473 static smallint is_interactive;
9475 if (++on == is_interactive)
9477 is_interactive = on;
9481 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9482 if (is_interactive > 1) {
9483 /* Looks like they want an interactive shell */
9484 static smallint did_banner;
9487 /* note: ash and hush share this string */
9488 out1fmt("\n\n%s %s\n"
9489 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
9492 "built-in shell (ash)"
9506 setinteractive(iflag);
9508 #if ENABLE_FEATURE_EDITING_VI
9510 line_input_state->flags |= VI_MODE;
9512 line_input_state->flags &= ~VI_MODE;
9514 viflag = 0; /* forcibly keep the option off */
9518 struct localvar_list {
9519 struct localvar_list *next;
9520 struct localvar *lv;
9523 static struct localvar_list *localvar_stack;
9526 * Called after a function returns.
9527 * Interrupts must be off.
9530 poplocalvars(int keep)
9532 struct localvar_list *ll;
9533 struct localvar *lvp, *next;
9537 ll = localvar_stack;
9538 localvar_stack = ll->next;
9543 while ((lvp = next) != NULL) {
9546 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9548 int bits = VSTRFIXED;
9550 if (lvp->flags != VUNSET) {
9551 if (vp->var_text == lvp->text)
9553 else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
9554 free((char*)lvp->text);
9558 vp->flags |= (lvp->flags & bits);
9561 (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
9562 unsetvar(vp->var_text);
9563 } else if (vp == NULL) { /* $- saved */
9564 memcpy(optlist, lvp->text, sizeof(optlist));
9565 free((char*)lvp->text);
9567 } else if (lvp->flags == VUNSET) {
9568 vp->flags &= ~(VSTRFIXED|VREADONLY);
9569 unsetvar(vp->var_text);
9572 vp->var_func(var_end(lvp->text));
9573 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9574 free((char*)vp->var_text);
9575 vp->flags = lvp->flags;
9576 vp->var_text = lvp->text;
9584 * Create a new localvar environment.
9586 static struct localvar_list *
9589 struct localvar_list *ll;
9592 ll = ckzalloc(sizeof(*ll));
9593 /*ll->lv = NULL; - zalloc did it */
9594 ll->next = localvar_stack;
9595 localvar_stack = ll;
9602 unwindlocalvars(struct localvar_list *stop)
9604 while (localvar_stack != stop)
9609 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9611 volatile struct shparam saveparam;
9612 struct jmploc *volatile savehandler;
9613 struct jmploc jmploc;
9617 saveparam = shellparam;
9618 savefuncline = funcline;
9619 savehandler = exception_handler;
9620 e = setjmp(jmploc.loc);
9625 exception_handler = &jmploc;
9626 shellparam.malloced = 0;
9628 funcline = func->n.ndefun.linno;
9630 shellparam.nparam = argc - 1;
9631 shellparam.p = argv + 1;
9632 #if ENABLE_ASH_GETOPTS
9633 shellparam.optind = 1;
9634 shellparam.optoff = -1;
9636 evaltree(func->n.ndefun.body, flags & EV_TESTED);
9639 funcline = savefuncline;
9641 freeparam(&shellparam);
9642 shellparam = saveparam;
9643 exception_handler = savehandler;
9645 evalskip &= ~SKIPFUNC;
9650 * Make a variable a local variable. When a variable is made local, it's
9651 * value and flags are saved in a localvar structure. The saved values
9652 * will be restored when the shell function returns. We handle the name
9653 * "-" as a special case: it makes changes to "set +-options" local
9654 * (options will be restored on return from the function).
9659 struct localvar *lvp;
9662 char *eq = strchr(name, '=');
9665 /* Cater for duplicate "local". Examples:
9666 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9667 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9669 lvp = localvar_stack->lv;
9671 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9675 * it's a duplicate "local VAR" declaration, do nothing
9682 lvp = ckzalloc(sizeof(*lvp));
9683 if (LONE_DASH(name)) {
9685 p = ckmalloc(sizeof(optlist));
9686 lvp->text = memcpy(p, optlist, sizeof(optlist));
9689 vpp = hashvar(name);
9690 vp = *findvar(vpp, name);
9692 /* variable did not exist yet */
9694 vp = setvareq(name, VSTRFIXED);
9696 vp = setvar(name, NULL, VSTRFIXED);
9697 lvp->flags = VUNSET;
9699 lvp->text = vp->var_text;
9700 lvp->flags = vp->flags;
9701 /* make sure neither "struct var" nor string gets freed
9702 * during (un)setting:
9704 vp->flags |= VSTRFIXED|VTEXTFIXED;
9708 /* "local VAR" unsets VAR: */
9709 setvar0(name, NULL);
9713 lvp->next = localvar_stack->lv;
9714 localvar_stack->lv = lvp;
9720 * The "local" command.
9722 static int FAST_FUNC
9723 localcmd(int argc UNUSED_PARAM, char **argv)
9727 if (!localvar_stack)
9728 ash_msg_and_raise_error("not in a function");
9731 while ((name = *argv++) != NULL) {
9737 static int FAST_FUNC
9738 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9743 static int FAST_FUNC
9744 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9749 static int FAST_FUNC
9750 execcmd(int argc UNUSED_PARAM, char **argv)
9753 while (nextopt("a:") != '\0')
9754 /* nextopt() sets optionarg to "-a ARGV0" */;
9760 iflag = 0; /* exit on error */
9763 /* We should set up signals for "exec CMD"
9764 * the same way as for "CMD" without "exec".
9765 * But optschanged->setinteractive->setsignal
9766 * still thought we are a root shell. Therefore, for example,
9767 * SIGQUIT is still set to IGN. Fix it:
9771 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9772 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9773 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9777 argv[0] = optionarg;
9778 shellexec(prog, argv, pathval(), 0);
9785 * The return command.
9787 static int FAST_FUNC
9788 returncmd(int argc UNUSED_PARAM, char **argv)
9791 * If called outside a function, do what ksh does;
9792 * skip the rest of the file.
9794 evalskip = SKIPFUNC;
9795 return argv[1] ? number(argv[1]) : exitstatus;
9798 /* Forward declarations for builtintab[] */
9799 static int breakcmd(int, char **) FAST_FUNC;
9800 static int dotcmd(int, char **) FAST_FUNC;
9801 static int evalcmd(int, char **, int) FAST_FUNC;
9802 static int exitcmd(int, char **) FAST_FUNC;
9803 static int exportcmd(int, char **) FAST_FUNC;
9804 #if ENABLE_ASH_GETOPTS
9805 static int getoptscmd(int, char **) FAST_FUNC;
9808 static int helpcmd(int, char **) FAST_FUNC;
9811 static int historycmd(int, char **) FAST_FUNC;
9813 #if ENABLE_FEATURE_SH_MATH
9814 static int letcmd(int, char **) FAST_FUNC;
9816 static int readcmd(int, char **) FAST_FUNC;
9817 static int setcmd(int, char **) FAST_FUNC;
9818 static int shiftcmd(int, char **) FAST_FUNC;
9819 static int timescmd(int, char **) FAST_FUNC;
9820 static int trapcmd(int, char **) FAST_FUNC;
9821 static int umaskcmd(int, char **) FAST_FUNC;
9822 static int unsetcmd(int, char **) FAST_FUNC;
9823 static int ulimitcmd(int, char **) FAST_FUNC;
9825 #define BUILTIN_NOSPEC "0"
9826 #define BUILTIN_SPECIAL "1"
9827 #define BUILTIN_REGULAR "2"
9828 #define BUILTIN_SPEC_REG "3"
9829 #define BUILTIN_ASSIGN "4"
9830 #define BUILTIN_SPEC_ASSG "5"
9831 #define BUILTIN_REG_ASSG "6"
9832 #define BUILTIN_SPEC_REG_ASSG "7"
9834 /* Stubs for calling non-FAST_FUNC's */
9836 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9838 #if ENABLE_ASH_PRINTF
9839 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9841 #if ENABLE_ASH_TEST || BASH_TEST2
9842 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9845 /* Keep these in proper order since it is searched via bsearch() */
9846 static const struct builtincmd builtintab[] = {
9847 { BUILTIN_SPEC_REG "." , dotcmd },
9848 { BUILTIN_SPEC_REG ":" , truecmd },
9850 { BUILTIN_REGULAR "[" , testcmd },
9853 { BUILTIN_REGULAR "[[" , testcmd },
9855 #if ENABLE_ASH_ALIAS
9856 { BUILTIN_REG_ASSG "alias" , aliascmd },
9859 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9861 { BUILTIN_SPEC_REG "break" , breakcmd },
9862 { BUILTIN_REGULAR "cd" , cdcmd },
9863 { BUILTIN_NOSPEC "chdir" , cdcmd },
9864 #if ENABLE_ASH_CMDCMD
9865 { BUILTIN_REGULAR "command" , commandcmd },
9867 { BUILTIN_SPEC_REG "continue", breakcmd },
9869 { BUILTIN_REGULAR "echo" , echocmd },
9871 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9872 { BUILTIN_SPEC_REG "exec" , execcmd },
9873 { BUILTIN_SPEC_REG "exit" , exitcmd },
9874 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9875 { BUILTIN_REGULAR "false" , falsecmd },
9877 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9879 #if ENABLE_ASH_GETOPTS
9880 { BUILTIN_REGULAR "getopts" , getoptscmd },
9882 { BUILTIN_NOSPEC "hash" , hashcmd },
9884 { BUILTIN_NOSPEC "help" , helpcmd },
9887 { BUILTIN_NOSPEC "history" , historycmd },
9890 { BUILTIN_REGULAR "jobs" , jobscmd },
9891 { BUILTIN_REGULAR "kill" , killcmd },
9893 #if ENABLE_FEATURE_SH_MATH
9894 { BUILTIN_NOSPEC "let" , letcmd },
9896 { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
9897 #if ENABLE_ASH_PRINTF
9898 { BUILTIN_REGULAR "printf" , printfcmd },
9900 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9901 { BUILTIN_REGULAR "read" , readcmd },
9902 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9903 { BUILTIN_SPEC_REG "return" , returncmd },
9904 { BUILTIN_SPEC_REG "set" , setcmd },
9905 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9907 { BUILTIN_SPEC_REG "source" , dotcmd },
9910 { BUILTIN_REGULAR "test" , testcmd },
9912 { BUILTIN_SPEC_REG "times" , timescmd },
9913 { BUILTIN_SPEC_REG "trap" , trapcmd },
9914 { BUILTIN_REGULAR "true" , truecmd },
9915 { BUILTIN_NOSPEC "type" , typecmd },
9916 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9917 { BUILTIN_REGULAR "umask" , umaskcmd },
9918 #if ENABLE_ASH_ALIAS
9919 { BUILTIN_REGULAR "unalias" , unaliascmd },
9921 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9922 { BUILTIN_REGULAR "wait" , waitcmd },
9925 /* Should match the above table! */
9926 #define COMMANDCMD (builtintab + \
9928 /* [ */ 1 * ENABLE_ASH_TEST + \
9929 /* [[ */ 1 * BASH_TEST2 + \
9930 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9931 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9932 /* break cd cddir */ 3)
9933 #define EVALCMD (COMMANDCMD + \
9934 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9935 /* continue */ 1 + \
9936 /* echo */ 1 * ENABLE_ASH_ECHO + \
9938 #define EXECCMD (EVALCMD + \
9942 * Search the table of builtin commands.
9945 pstrcmp1(const void *a, const void *b)
9947 return strcmp((char*)a, *(char**)b + 1);
9949 static struct builtincmd *
9950 find_builtin(const char *name)
9952 struct builtincmd *bp;
9955 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9962 * Execute a simple command.
9964 static void unwindfiles(struct parsefile *stop);
9966 isassignment(const char *p)
9968 const char *q = endofname(p);
9973 static int FAST_FUNC
9974 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9976 /* Preserve exitstatus of a previous possible redirection
9977 * as POSIX mandates */
9978 return back_exitstatus;
9981 evalcommand(union node *cmd, int flags)
9983 static const struct builtincmd null_bltin = {
9984 "\0\0", bltincmd /* why three NULs? */
9986 struct localvar_list *localvar_stop;
9987 struct parsefile *file_stop;
9988 struct redirtab *redir_stop;
9989 struct stackmark smark;
9991 struct arglist arglist;
9992 struct arglist varlist;
9995 const struct strlist *sp;
9996 struct cmdentry cmdentry;
10003 smallint cmd_is_exec;
10005 errlinno = lineno = cmd->ncmd.linno;
10007 lineno -= funcline - 1;
10009 /* First expand the arguments. */
10010 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
10011 setstackmark(&smark);
10012 localvar_stop = pushlocalvars();
10013 file_stop = g_parsefile;
10014 back_exitstatus = 0;
10016 cmdentry.cmdtype = CMDBUILTIN;
10017 cmdentry.u.cmd = &null_bltin;
10018 varlist.lastp = &varlist.list;
10019 *varlist.lastp = NULL;
10020 arglist.lastp = &arglist.list;
10021 *arglist.lastp = NULL;
10024 if (cmd->ncmd.args) {
10025 struct builtincmd *bcmd;
10026 smallint pseudovarflag;
10028 bcmd = find_builtin(cmd->ncmd.args->narg.text);
10029 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
10031 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
10032 struct strlist **spp;
10034 spp = arglist.lastp;
10035 if (pseudovarflag && isassignment(argp->narg.text))
10036 expandarg(argp, &arglist, EXP_VARTILDE);
10038 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
10040 for (sp = *spp; sp; sp = sp->next)
10045 /* Reserve one extra spot at the front for shellexec. */
10046 nargv = stalloc(sizeof(char *) * (argc + 2));
10048 for (sp = arglist.list; sp; sp = sp->next) {
10049 TRACE(("evalcommand arg: %s\n", sp->text));
10050 *nargv++ = sp->text;
10055 if (iflag && funcline == 0 && argc > 0)
10056 lastarg = nargv[-1];
10058 expredir(cmd->ncmd.redirect);
10059 redir_stop = pushredir(cmd->ncmd.redirect);
10061 if (BASH_XTRACEFD && xflag) {
10062 /* NB: bash closes fd == $BASH_XTRACEFD when it is changed.
10063 * we do not emulate this. We only use its value.
10065 const char *xtracefd = lookupvar("BASH_XTRACEFD");
10066 if (xtracefd && is_number(xtracefd))
10067 preverrout_fd = atoi(xtracefd);
10070 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
10072 path = vpath.var_text;
10073 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
10074 struct strlist **spp;
10077 spp = varlist.lastp;
10078 expandarg(argp, &varlist, EXP_VARTILDE);
10080 mklocal((*spp)->text);
10083 * Modify the command lookup path, if a PATH= assignment
10087 if (varcmp(p, path) == 0)
10091 /* Print the command if xflag is set. */
10093 const char *pfx = "";
10095 fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
10099 char *varval = sp->text;
10100 char *eq = strchrnul(varval, '=');
10103 fdprintf(preverrout_fd, "%s%.*s%s",
10105 (int)(eq - varval), varval,
10106 maybe_single_quote(eq)
10114 fdprintf(preverrout_fd, "%s%s",
10116 /* always quote if matches reserved word: */
10118 ? single_quote(sp->text)
10119 : maybe_single_quote(sp->text)
10124 safe_write(preverrout_fd, "\n", 1);
10130 /* Now locate the command. */
10132 int cmd_flag = DO_ERR;
10133 #if ENABLE_ASH_CMDCMD
10134 const char *oldpath = path + 5;
10138 find_command(argv[0], &cmdentry, cmd_flag, path);
10139 if (cmdentry.cmdtype == CMDUNKNOWN) {
10140 flush_stdout_stderr();
10145 /* implement bltin and command here */
10146 if (cmdentry.cmdtype != CMDBUILTIN)
10149 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
10150 if (cmdentry.u.cmd == EXECCMD)
10152 #if ENABLE_ASH_CMDCMD
10153 if (cmdentry.u.cmd == COMMANDCMD) {
10155 nargv = parse_command_args(argv, &path);
10158 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
10159 * nargv => "PROG". path is updated if -p.
10161 argc -= nargv - argv;
10163 cmd_flag |= DO_NOFUNC;
10172 exitstatus = status;
10174 /* We have a redirection error. */
10176 raise_exception(EXERROR);
10181 /* Execute the command. */
10182 switch (cmdentry.cmdtype) {
10185 #if ENABLE_FEATURE_SH_STANDALONE \
10186 && ENABLE_FEATURE_SH_NOFORK \
10188 /* (1) BUG: if variables are set, we need to fork, or save/restore them
10189 * around run_nofork_applet() call.
10190 * (2) Should this check also be done in forkshell()?
10191 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
10193 /* find_command() encodes applet_no as (-2 - applet_no) */
10194 int applet_no = (- cmdentry.u.index - 2);
10195 # if NUM_SCRIPTS > 0
10196 /* Applets are ok, but not embedded scripts */
10197 if (applet_no < NUM_APPLETS)
10199 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
10203 sv_environ = environ;
10204 environ = listvars(VEXPORT, VUNSET, varlist.list, /*end:*/ NULL);
10206 * Run <applet>_main().
10207 * Signals (^C) can't interrupt here.
10208 * Otherwise we can mangle stdio or malloc internal state.
10209 * This makes applets which can run for a long time
10210 * and/or wait for user input ineligible for NOFORK:
10211 * for example, "yes" or "rm" (rm -i waits for input).
10213 status = run_nofork_applet(applet_no, argv);
10214 environ = sv_environ;
10216 * Try enabling NOFORK for "yes" applet.
10217 * ^C _will_ stop it (write returns EINTR),
10218 * but this causes stdout FILE to be stuck
10219 * and needing clearerr(). What if other applets
10220 * also can get EINTRs? Do we need to switch
10221 * our signals to SA_RESTART?
10223 /*clearerr(stdout);*/
10228 /* Can we avoid forking? For example, very last command
10229 * in a script or a subshell does not need forking,
10230 * we can just exec it.
10232 if (!(flags & EV_EXIT) || may_have_traps) {
10233 /* No, forking off a child is necessary */
10236 jp = makejob(/*cmd,*/ 1);
10237 if (forkshell(jp, cmd, FORK_FG) != 0) {
10239 status = waitforjob(jp);
10241 TRACE(("forked child exited with %d\n", status));
10246 /* fall through to exec'ing external program */
10248 listsetvar(varlist.list, VEXPORT|VSTACK);
10249 shellexec(argv[0], argv, path, cmdentry.u.index);
10253 if (spclbltin > 0 || argc == 0) {
10255 if (cmd_is_exec && argc > 1)
10256 listsetvar(varlist.list, VEXPORT);
10259 /* Tight loop with builtins only:
10260 * "while kill -0 $child; do true; done"
10261 * will never exit even if $child died, unless we do this
10262 * to reap the zombie and make kill detect that it's gone: */
10263 dowait(DOWAIT_NONBLOCK, NULL);
10265 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
10266 if (exception_type == EXERROR && spclbltin <= 0) {
10271 longjmp(exception_handler->loc, 1);
10276 /* See above for the rationale */
10277 dowait(DOWAIT_NONBLOCK, NULL);
10278 if (evalfun(cmdentry.u.func, argc, argv, flags))
10281 status = exitstatus;
10286 if (cmd->ncmd.redirect)
10287 popredir(/*drop:*/ cmd_is_exec);
10288 unwindredir(redir_stop);
10289 unwindfiles(file_stop);
10290 unwindlocalvars(localvar_stop);
10292 /* dsl: I think this is intended to be used to support
10293 * '_' in 'vi' command mode during line editing...
10294 * However I implemented that within libedit itself.
10296 setvar0("_", lastarg);
10298 popstackmark(&smark);
10304 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
10306 char *volatile savecmdname;
10307 struct jmploc *volatile savehandler;
10308 struct jmploc jmploc;
10312 savecmdname = commandname;
10313 savehandler = exception_handler;
10314 i = setjmp(jmploc.loc);
10317 exception_handler = &jmploc;
10318 commandname = argv[0];
10320 optptr = NULL; /* initialize nextopt */
10321 if (cmd == EVALCMD)
10322 status = evalcmd(argc, argv, flags);
10324 status = (*cmd->builtin)(argc, argv);
10325 flush_stdout_stderr();
10326 status |= ferror(stdout);
10327 exitstatus = status;
10330 commandname = savecmdname;
10331 exception_handler = savehandler;
10337 goodname(const char *p)
10339 return endofname(p)[0] == '\0';
10344 * Search for a command. This is called before we fork so that the
10345 * location of the command will be available in the parent as well as
10346 * the child. The check for "goodname" is an overly conservative
10347 * check that the name will not be subject to expansion.
10350 prehash(union node *n)
10352 struct cmdentry entry;
10354 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
10355 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
10359 /* ============ Builtin commands
10361 * Builtin commands whose functions are closely tied to evaluation
10362 * are implemented here.
10366 * Handle break and continue commands. Break, continue, and return are
10367 * all handled by setting the evalskip flag. The evaluation routines
10368 * above all check this flag, and if it is set they start skipping
10369 * commands rather than executing them. The variable skipcount is
10370 * the number of loops to break/continue, or the number of function
10371 * levels to return. (The latter is always 1.) It should probably
10372 * be an error to break out of more loops than exist, but it isn't
10373 * in the standard shell so we don't make it one here.
10375 static int FAST_FUNC
10376 breakcmd(int argc UNUSED_PARAM, char **argv)
10378 int n = argv[1] ? number(argv[1]) : 1;
10381 ash_msg_and_raise_error(msg_illnum, argv[1]);
10385 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
10393 * This implements the input routines used by the parser.
10397 INPUT_PUSH_FILE = 1,
10398 INPUT_NOFILE_OK = 2,
10401 static smallint checkkwd;
10402 /* values of checkkwd variable */
10403 #define CHKALIAS 0x1
10406 #define CHKEOFMARK 0x8
10409 * Push a string back onto the input at this current parsefile level.
10410 * We handle aliases this way.
10412 #if !ENABLE_ASH_ALIAS
10413 #define pushstring(s, ap) pushstring(s)
10416 pushstring(char *s, struct alias *ap)
10418 struct strpush *sp;
10423 if (g_parsefile->strpush) {
10424 sp = ckzalloc(sizeof(*sp));
10425 sp->prev = g_parsefile->strpush;
10427 sp = &(g_parsefile->basestrpush);
10429 g_parsefile->strpush = sp;
10430 sp->prev_string = g_parsefile->next_to_pgetc;
10431 sp->prev_left_in_line = g_parsefile->left_in_line;
10432 sp->unget = g_parsefile->unget;
10433 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
10434 #if ENABLE_ASH_ALIAS
10437 ap->flag |= ALIASINUSE;
10441 g_parsefile->next_to_pgetc = s;
10442 g_parsefile->left_in_line = len;
10443 g_parsefile->unget = 0;
10450 struct strpush *sp = g_parsefile->strpush;
10453 #if ENABLE_ASH_ALIAS
10455 if (g_parsefile->next_to_pgetc[-1] == ' '
10456 || g_parsefile->next_to_pgetc[-1] == '\t'
10458 checkkwd |= CHKALIAS;
10460 if (sp->string != sp->ap->val) {
10463 sp->ap->flag &= ~ALIASINUSE;
10464 if (sp->ap->flag & ALIASDEAD) {
10465 unalias(sp->ap->name);
10469 g_parsefile->next_to_pgetc = sp->prev_string;
10470 g_parsefile->left_in_line = sp->prev_left_in_line;
10471 g_parsefile->unget = sp->unget;
10472 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
10473 g_parsefile->strpush = sp->prev;
10474 if (sp != &(g_parsefile->basestrpush))
10483 char *buf = g_parsefile->buf;
10485 g_parsefile->next_to_pgetc = buf;
10486 #if ENABLE_FEATURE_EDITING
10488 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
10489 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10491 # if ENABLE_ASH_IDLE_TIMEOUT
10494 const char *tmout_var = lookupvar("TMOUT");
10496 timeout = atoi(tmout_var) * 1000;
10501 line_input_state->timeout = timeout;
10503 # if ENABLE_FEATURE_TAB_COMPLETION
10504 line_input_state->path_lookup = pathval();
10506 reinit_unicode_for_ash();
10507 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ);
10509 /* ^C pressed, "convert" to SIGINT */
10510 write(STDOUT_FILENO, "^C", 2);
10511 if (trap[SIGINT]) {
10517 exitstatus = 128 + SIGINT;
10523 /* Ctrl+D pressed */
10526 # if ENABLE_ASH_IDLE_TIMEOUT
10527 else if (errno == EAGAIN && timeout > 0) {
10528 puts("\007timed out waiting for input: auto-logout");
10535 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10538 #if 0 /* disabled: nonblock_immune_read() handles this problem */
10540 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
10541 int flags = fcntl(0, F_GETFL);
10542 if (flags >= 0 && (flags & O_NONBLOCK)) {
10543 flags &= ~O_NONBLOCK;
10544 if (fcntl(0, F_SETFL, flags) >= 0) {
10545 out2str("sh: turning off NDELAY mode\n");
10556 * Refill the input buffer and return the next input character:
10558 * 1) If a string was pushed back on the input, pop it;
10559 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
10560 * or we are reading from a string so we can't refill the buffer,
10562 * 3) If there is more stuff in this buffer, use it else call read to fill it.
10563 * 4) Process input up to the next newline, deleting nul characters.
10565 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
10566 #define pgetc_debug(...) ((void)0)
10567 static int pgetc(void);
10574 if (g_parsefile->strpush) {
10575 #if ENABLE_ASH_ALIAS
10576 if (g_parsefile->left_in_line == -1
10577 && g_parsefile->strpush->ap
10578 && g_parsefile->next_to_pgetc[-1] != ' '
10579 && g_parsefile->next_to_pgetc[-1] != '\t'
10581 pgetc_debug("preadbuffer PEOA");
10588 /* on both branches above g_parsefile->left_in_line < 0.
10589 * "pgetc" needs refilling.
10592 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
10593 * pungetc() may increment it a few times.
10594 * Assuming it won't increment it to less than -90.
10596 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
10597 pgetc_debug("preadbuffer PEOF1");
10598 /* even in failure keep left_in_line and next_to_pgetc
10599 * in lock step, for correct multi-layer pungetc.
10600 * left_in_line was decremented before preadbuffer(),
10601 * must inc next_to_pgetc: */
10602 g_parsefile->next_to_pgetc++;
10606 more = g_parsefile->left_in_buffer;
10608 flush_stdout_stderr();
10612 /* don't try reading again */
10613 g_parsefile->left_in_line = -99;
10614 pgetc_debug("preadbuffer PEOF2");
10615 g_parsefile->next_to_pgetc++;
10620 /* Find out where's the end of line.
10621 * Set g_parsefile->left_in_line
10622 * and g_parsefile->left_in_buffer acordingly.
10623 * NUL chars are deleted.
10625 q = g_parsefile->next_to_pgetc;
10633 memmove(q, q + 1, more);
10637 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10643 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10644 if (g_parsefile->left_in_line < 0)
10649 g_parsefile->left_in_buffer = more;
10654 out2str(g_parsefile->next_to_pgetc);
10658 pgetc_debug("preadbuffer at %d:%p'%s'",
10659 g_parsefile->left_in_line,
10660 g_parsefile->next_to_pgetc,
10661 g_parsefile->next_to_pgetc);
10662 return (unsigned char)*g_parsefile->next_to_pgetc++;
10668 g_parsefile->linno++;
10669 setprompt_if(doprompt, 2);
10674 g_parsefile->linno++;
10675 needprompt = doprompt;
10683 pgetc_debug("pgetc at %d:%p'%s'",
10684 g_parsefile->left_in_line,
10685 g_parsefile->next_to_pgetc,
10686 g_parsefile->next_to_pgetc);
10687 if (g_parsefile->unget)
10688 return g_parsefile->lastc[--g_parsefile->unget];
10690 if (--g_parsefile->left_in_line >= 0)
10691 c = (unsigned char)*g_parsefile->next_to_pgetc++;
10695 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10696 g_parsefile->lastc[0] = c;
10701 #if ENABLE_ASH_ALIAS
10703 pgetc_without_PEOA(void)
10707 pgetc_debug("pgetc at %d:%p'%s'",
10708 g_parsefile->left_in_line,
10709 g_parsefile->next_to_pgetc,
10710 g_parsefile->next_to_pgetc);
10712 } while (c == PEOA);
10716 # define pgetc_without_PEOA() pgetc()
10720 * Undo a call to pgetc. Only two characters may be pushed back.
10721 * PEOF may be pushed back.
10726 g_parsefile->unget++;
10729 /* This one eats backslash+newline */
10735 while ((c = pgetc()) == '\\') {
10736 if (pgetc() != '\n') {
10749 uint8_t innerdq :1;
10750 uint8_t varpushed :1;
10751 uint8_t dblquote :1;
10752 int varnest; /* levels of variables expansion */
10753 int dqvarnest; /* levels of variables expansion within double quotes */
10754 int parenlevel; /* levels of parens in arithmetic */
10755 struct synstack *prev;
10756 struct synstack *next;
10760 synstack_push(struct synstack **stack, struct synstack *next, int syntax)
10762 memset(next, 0, sizeof(*next));
10763 next->syntax = syntax;
10764 next->next = *stack;
10765 (*stack)->prev = next;
10769 static ALWAYS_INLINE void
10770 synstack_pop(struct synstack **stack)
10772 *stack = (*stack)->next;
10776 * To handle the "." command, a stack of input files is used. Pushfile
10777 * adds a new entry to the stack and popfile restores the previous level.
10782 struct parsefile *pf;
10784 pf = ckzalloc(sizeof(*pf));
10785 pf->prev = g_parsefile;
10787 /*pf->strpush = NULL; - ckzalloc did it */
10788 /*pf->basestrpush.prev = NULL;*/
10796 struct parsefile *pf = g_parsefile;
10802 if (pf->pf_fd >= 0)
10805 while (pf->strpush)
10807 g_parsefile = pf->prev;
10813 unwindfiles(struct parsefile *stop)
10815 while (g_parsefile != stop)
10820 * Return to top level.
10825 unwindfiles(&basepf);
10829 * Close the file(s) that the shell is reading commands from. Called
10830 * after a fork is done.
10836 if (g_parsefile->pf_fd > 0) {
10837 close(g_parsefile->pf_fd);
10838 g_parsefile->pf_fd = 0;
10843 * Like setinputfile, but takes an open file descriptor. Call this with
10847 setinputfd(int fd, int push)
10851 g_parsefile->buf = NULL;
10853 g_parsefile->pf_fd = fd;
10854 if (g_parsefile->buf == NULL)
10855 g_parsefile->buf = ckmalloc(IBUFSIZ);
10856 g_parsefile->left_in_buffer = 0;
10857 g_parsefile->left_in_line = 0;
10858 g_parsefile->linno = 1;
10862 * Set the input to take input from a file. If push is set, push the
10863 * old input onto the stack first.
10866 setinputfile(const char *fname, int flags)
10871 fd = open(fname, O_RDONLY | O_CLOEXEC);
10873 if (flags & INPUT_NOFILE_OK)
10876 ash_msg_and_raise_perror("can't open '%s'", fname);
10880 else if (O_CLOEXEC == 0) /* old libc */
10881 close_on_exec_on(fd);
10883 setinputfd(fd, flags & INPUT_PUSH_FILE);
10890 * Like setinputfile, but takes input from a string.
10893 setinputstring(char *string)
10897 g_parsefile->next_to_pgetc = string;
10898 g_parsefile->left_in_line = strlen(string);
10899 g_parsefile->buf = NULL;
10900 g_parsefile->linno = 1;
10906 * Routines to check for mail.
10909 #if ENABLE_ASH_MAIL
10911 /* Hash of mtimes of mailboxes */
10912 static unsigned mailtime_hash;
10913 /* Set if MAIL or MAILPATH is changed. */
10914 static smallint mail_var_path_changed;
10917 * Print appropriate message(s) if mail has arrived.
10918 * If mail_var_path_changed is set,
10919 * then the value of MAIL has mail_var_path_changed,
10920 * so we just update the values.
10929 struct stackmark smark;
10932 setstackmark(&smark);
10933 mpath = mpathset() ? mpathval() : mailval();
10936 p = path_advance(&mpath, nullstr);
10941 for (q = p; *q; q++)
10947 q[-1] = '\0'; /* delete trailing '/' */
10948 if (stat(p, &statb) < 0) {
10951 /* Very simplistic "hash": just a sum of all mtimes */
10952 new_hash += (unsigned)statb.st_mtime;
10954 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10955 if (mailtime_hash != 0)
10956 out2str("you have mail\n");
10957 mailtime_hash = new_hash;
10959 mail_var_path_changed = 0;
10960 popstackmark(&smark);
10963 static void FAST_FUNC
10964 changemail(const char *val UNUSED_PARAM)
10966 mail_var_path_changed = 1;
10969 #endif /* ASH_MAIL */
10972 /* ============ ??? */
10975 * Set the shell parameters.
10978 setparam(char **argv)
10984 for (nparam = 0; argv[nparam]; nparam++)
10986 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10988 *ap++ = ckstrdup(*argv++);
10991 freeparam(&shellparam);
10992 shellparam.malloced = 1;
10993 shellparam.nparam = nparam;
10994 shellparam.p = newparam;
10995 #if ENABLE_ASH_GETOPTS
10996 shellparam.optind = 1;
10997 shellparam.optoff = -1;
11002 * Process shell options. The global variable argptr contains a pointer
11003 * to the argument list; we advance it past the options.
11005 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
11006 * For a non-interactive shell, an error condition encountered
11007 * by a special built-in ... shall cause the shell to write a diagnostic message
11008 * to standard error and exit as shown in the following table:
11009 * Error Special Built-In
11011 * Utility syntax error (option or operand error) Shall exit
11013 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
11014 * we see that bash does not do that (set "finishes" with error code 1 instead,
11015 * and shell continues), and people rely on this behavior!
11017 * set -o barfoo 2>/dev/null
11020 * Oh well. Let's mimic that.
11023 plus_minus_o(char *name, int val)
11028 for (i = 0; i < NOPTS; i++) {
11029 if (strcmp(name, optnames(i)) == 0) {
11034 ash_msg("illegal option %co %s", val ? '-' : '+', name);
11037 for (i = 0; i < NOPTS; i++) {
11039 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
11041 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
11047 setoption(int flag, int val)
11051 for (i = 0; i < NOPTS; i++) {
11052 if (optletters(i) == flag) {
11057 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
11061 options(int cmdline, int *login_sh)
11069 while ((p = *argptr) != NULL) {
11071 if (c != '-' && c != '+')
11074 val = 0; /* val = 0 if c == '+' */
11077 if (p[0] == '\0' || LONE_DASH(p)) {
11079 /* "-" means turn off -x and -v */
11082 /* "--" means reset params */
11083 else if (*argptr == NULL)
11086 break; /* "-" or "--" terminates options */
11089 /* first char was + or - */
11090 while ((c = *p++) != '\0') {
11091 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
11092 if (c == 'c' && cmdline) {
11093 minusc = p; /* command is after shell args */
11094 } else if (c == 'o') {
11095 if (plus_minus_o(*argptr, val)) {
11096 /* it already printed err message */
11097 return 1; /* error */
11101 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
11104 /* bash does not accept +-login, we also won't */
11105 } else if (cmdline && val && (c == '-')) { /* long options */
11106 if (strcmp(p, "login") == 0) {
11120 * The shift builtin command.
11122 static int FAST_FUNC
11123 shiftcmd(int argc UNUSED_PARAM, char **argv)
11130 n = number(argv[1]);
11131 if (n > shellparam.nparam)
11134 shellparam.nparam -= n;
11135 for (ap1 = shellparam.p; --n >= 0; ap1++) {
11136 if (shellparam.malloced)
11139 ap2 = shellparam.p;
11140 while ((*ap2++ = *ap1++) != NULL)
11142 #if ENABLE_ASH_GETOPTS
11143 shellparam.optind = 1;
11144 shellparam.optoff = -1;
11151 * POSIX requires that 'set' (but not export or readonly) output the
11152 * variables in lexicographic order - by the locale's collating order (sigh).
11153 * Maybe we could keep them in an ordered balanced binary tree
11154 * instead of hashed lists.
11155 * For now just roll 'em through qsort for printing...
11158 showvars(const char *sep_prefix, int on, int off)
11161 char **ep, **epend;
11163 ep = listvars(on, off, /*strlist:*/ NULL, &epend);
11164 qsort(ep, epend - ep, sizeof(char *), vpcmp);
11166 sep = *sep_prefix ? " " : sep_prefix;
11168 for (; ep < epend; ep++) {
11172 p = endofname(*ep);
11173 /* Used to have simple "p = strchrnul(*ep, '=')" here instead, but this
11174 * makes "export -p" to have output not suitable for "eval":
11176 * os.environ["test-test"]="test"
11177 * if os.fork() == 0:
11178 * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
11179 * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ])
11183 q = single_quote(++p);
11184 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
11190 * The set command builtin.
11192 static int FAST_FUNC
11193 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
11198 return showvars(nullstr, 0, VUNSET);
11201 retval = options(/*cmdline:*/ 0, NULL);
11202 if (retval == 0) { /* if no parse error... */
11204 if (*argptr != NULL) {
11212 #if ENABLE_ASH_RANDOM_SUPPORT
11213 static void FAST_FUNC
11214 change_random(const char *value)
11218 if (value == NULL) {
11219 /* "get", generate */
11220 t = next_random(&random_gen);
11221 /* set without recursion */
11222 setvar(vrandom.var_text, utoa(t), VNOFUNC);
11223 vrandom.flags &= ~VNOFUNC;
11226 t = strtoul(value, NULL, 10);
11227 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
11232 #if ENABLE_ASH_GETOPTS
11234 getopts(char *optstr, char *optvar, char **optfirst)
11241 int ind = shellparam.optind;
11242 int off = shellparam.optoff;
11246 shellparam.optind = -1;
11247 optnext = optfirst + ind - 1;
11249 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
11252 p = optnext[-1] + off;
11253 if (p == NULL || *p == '\0') {
11254 /* Current word is done, advance */
11256 if (p == NULL || *p != '-' || *++p == '\0') {
11258 unsetvar("OPTARG");
11264 if (LONE_DASH(p)) /* check for "--" */
11269 for (q = optstr; *q != c;) {
11271 /* OPTERR is a bashism */
11272 const char *cp = lookupvar("OPTERR");
11273 if ((cp && LONE_CHAR(cp, '0'))
11274 || (optstr[0] == ':')
11277 /*sbuf[1] = '\0'; - already is */
11278 setvar0("OPTARG", sbuf);
11280 fprintf(stderr, "Illegal option -%c\n", c);
11281 unsetvar("OPTARG");
11291 if (*p == '\0' && (p = *optnext) == NULL) {
11292 /* OPTERR is a bashism */
11293 const char *cp = lookupvar("OPTERR");
11294 if ((cp && LONE_CHAR(cp, '0'))
11295 || (optstr[0] == ':')
11298 /*sbuf[1] = '\0'; - already is */
11299 setvar0("OPTARG", sbuf);
11302 fprintf(stderr, "No arg for -%c option\n", c);
11303 unsetvar("OPTARG");
11311 setvar0("OPTARG", p);
11314 setvar0("OPTARG", nullstr);
11316 ind = optnext - optfirst + 1;
11317 setvar("OPTIND", itoa(ind), VNOFUNC);
11319 /*sbuf[1] = '\0'; - already is */
11320 setvar0(optvar, sbuf);
11322 shellparam.optoff = p ? p - *(optnext - 1) : -1;
11323 shellparam.optind = ind;
11329 * The getopts builtin. Shellparam.optnext points to the next argument
11330 * to be processed. Shellparam.optptr points to the next character to
11331 * be processed in the current argument. If shellparam.optnext is NULL,
11332 * then it's the first time getopts has been called.
11334 static int FAST_FUNC
11335 getoptscmd(int argc, char **argv)
11340 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
11342 optbase = shellparam.p;
11343 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
11344 shellparam.optind = 1;
11345 shellparam.optoff = -1;
11348 optbase = &argv[3];
11349 if ((unsigned)shellparam.optind > argc - 2) {
11350 shellparam.optind = 1;
11351 shellparam.optoff = -1;
11355 return getopts(argv[1], argv[2], optbase);
11357 #endif /* ASH_GETOPTS */
11360 /* ============ Shell parser */
11363 struct heredoc *next; /* next here document in list */
11364 union node *here; /* redirection node */
11365 char *eofmark; /* string indicating end of input */
11366 smallint striptabs; /* if set, strip leading tabs */
11369 static smallint tokpushback; /* last token pushed back */
11370 static smallint quoteflag; /* set if (part of) last token was quoted */
11371 static token_id_t lasttoken; /* last token read (integer id Txxx) */
11372 static struct heredoc *heredoclist; /* list of here documents to read */
11373 static char *wordtext; /* text of last word returned by readtoken */
11374 static struct nodelist *backquotelist;
11375 static union node *redirnode;
11376 static struct heredoc *heredoc;
11378 static const char *
11379 tokname(char *buf, int tok)
11382 return tokname_array[tok];
11383 sprintf(buf, "\"%s\"", tokname_array[tok]);
11387 /* raise_error_unexpected_syntax:
11388 * Called when an unexpected token is read during the parse. The argument
11389 * is the token that is expected, or -1 if more than one type of token can
11390 * occur at this point.
11392 static void raise_error_unexpected_syntax(int) NORETURN;
11394 raise_error_unexpected_syntax(int token)
11400 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
11402 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
11403 raise_error_syntax(msg);
11407 /* parsing is heavily cross-recursive, need these forward decls */
11408 static union node *andor(void);
11409 static union node *pipeline(void);
11410 static union node *parse_command(void);
11411 static void parseheredoc(void);
11412 static int peektoken(void);
11413 static int readtoken(void);
11415 static union node *
11418 union node *n1, *n2, *n3;
11423 switch (peektoken()) {
11431 if (!n1 && (nlflag & 1))
11437 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11438 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
11444 if (tok == TBACKGND) {
11445 if (n2->type == NPIPE) {
11446 n2->npipe.pipe_backgnd = 1;
11448 if (n2->type != NREDIR) {
11449 n3 = stzalloc(sizeof(struct nredir));
11451 /*n3->nredir.redirect = NULL; - stzalloc did it */
11454 n2->type = NBACKGND;
11460 n3 = stzalloc(sizeof(struct nbinary));
11462 n3->nbinary.ch1 = n1;
11463 n3->nbinary.ch2 = n2;
11476 raise_error_unexpected_syntax(-1);
11483 static union node *
11486 union node *n1, *n2, *n3;
11494 } else if (t == TOR) {
11500 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11502 n3 = stzalloc(sizeof(struct nbinary));
11504 n3->nbinary.ch1 = n1;
11505 n3->nbinary.ch2 = n2;
11510 static union node *
11513 union node *n1, *n2, *pipenode;
11514 struct nodelist *lp, *prev;
11518 TRACE(("pipeline: entered\n"));
11519 if (readtoken() == TNOT) {
11521 checkkwd = CHKKWD | CHKALIAS;
11524 n1 = parse_command();
11525 if (readtoken() == TPIPE) {
11526 pipenode = stzalloc(sizeof(struct npipe));
11527 pipenode->type = NPIPE;
11528 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
11529 lp = stzalloc(sizeof(struct nodelist));
11530 pipenode->npipe.cmdlist = lp;
11534 lp = stzalloc(sizeof(struct nodelist));
11535 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11536 lp->n = parse_command();
11538 } while (readtoken() == TPIPE);
11544 n2 = stzalloc(sizeof(struct nnot));
11552 static union node *
11557 n = stzalloc(sizeof(struct narg));
11559 /*n->narg.next = NULL; - stzalloc did it */
11560 n->narg.text = wordtext;
11561 n->narg.backquote = backquotelist;
11566 fixredir(union node *n, const char *text, int err)
11570 TRACE(("Fix redir %s %d\n", text, err));
11572 n->ndup.vname = NULL;
11574 fd = bb_strtou(text, NULL, 10);
11575 if (!errno && fd >= 0)
11576 n->ndup.dupfd = fd;
11577 else if (LONE_DASH(text))
11578 n->ndup.dupfd = -1;
11581 raise_error_syntax("bad fd number");
11582 n->ndup.vname = makename();
11589 union node *n = redirnode;
11591 if (n->type == NHERE)
11592 checkkwd = CHKEOFMARK;
11593 if (readtoken() != TWORD)
11594 raise_error_unexpected_syntax(-1);
11595 if (n->type == NHERE) {
11596 struct heredoc *here = heredoc;
11599 if (quoteflag == 0)
11601 TRACE(("Here document %d\n", n->type));
11602 rmescapes(wordtext, 0, NULL);
11603 here->eofmark = wordtext;
11605 if (heredoclist == NULL)
11606 heredoclist = here;
11608 for (p = heredoclist; p->next; p = p->next)
11612 } else if (n->type == NTOFD || n->type == NFROMFD) {
11613 fixredir(n, wordtext, 0);
11615 n->nfile.fname = makename();
11619 static union node *
11622 union node *args, **app;
11623 union node *n = NULL;
11624 union node *vars, **vpp;
11625 union node **rpp, *redir;
11629 smallint double_brackets_flag = 0;
11631 IF_BASH_FUNCTION(smallint function_flag = 0;)
11640 savecheckkwd = CHKALIAS;
11641 savelinno = g_parsefile->linno;
11644 checkkwd = savecheckkwd;
11649 if (peektoken() != TWORD)
11650 raise_error_unexpected_syntax(TWORD);
11655 case TAND: /* "&&" */
11656 case TOR: /* "||" */
11657 if (!double_brackets_flag) {
11661 wordtext = (char *) (t == TAND ? "-a" : "-o");
11664 n = stzalloc(sizeof(struct narg));
11666 /*n->narg.next = NULL; - stzalloc did it */
11667 n->narg.text = wordtext;
11669 if (strcmp("[[", wordtext) == 0)
11670 double_brackets_flag = 1;
11671 else if (strcmp("]]", wordtext) == 0)
11672 double_brackets_flag = 0;
11674 n->narg.backquote = backquotelist;
11675 if (savecheckkwd && isassignment(wordtext)) {
11677 vpp = &n->narg.next;
11680 app = &n->narg.next;
11684 if (function_flag) {
11685 checkkwd = CHKNL | CHKKWD;
11686 switch (peektoken()) {
11699 if (strcmp("[[", wordtext) == 0)
11704 raise_error_unexpected_syntax(-1);
11710 *rpp = n = redirnode;
11711 rpp = &n->nfile.next;
11712 parsefname(); /* read name of redirection file */
11715 IF_BASH_FUNCTION(do_func:)
11716 if (args && app == &args->narg.next
11719 struct builtincmd *bcmd;
11722 /* We have a function */
11723 if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
11724 raise_error_unexpected_syntax(TRP);
11725 name = n->narg.text;
11726 if (!goodname(name)
11727 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11729 raise_error_syntax("bad function name");
11732 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11733 n->ndefun.text = n->narg.text;
11734 n->ndefun.linno = g_parsefile->linno;
11735 n->ndefun.body = parse_command();
11738 IF_BASH_FUNCTION(function_flag = 0;)
11749 n = stzalloc(sizeof(struct ncmd));
11752 n->ncmd.linno = savelinno;
11753 n->ncmd.args = args;
11754 n->ncmd.assign = vars;
11755 n->ncmd.redirect = redir;
11759 static union node *
11760 parse_command(void)
11762 union node *n1, *n2;
11763 union node *ap, **app;
11764 union node *cp, **cpp;
11765 union node *redir, **rpp;
11773 savelinno = g_parsefile->linno;
11775 switch (readtoken()) {
11777 raise_error_unexpected_syntax(-1);
11780 n1 = stzalloc(sizeof(struct nif));
11782 n1->nif.test = list(0);
11783 if (readtoken() != TTHEN)
11784 raise_error_unexpected_syntax(TTHEN);
11785 n1->nif.ifpart = list(0);
11787 while (readtoken() == TELIF) {
11788 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11789 n2 = n2->nif.elsepart;
11791 n2->nif.test = list(0);
11792 if (readtoken() != TTHEN)
11793 raise_error_unexpected_syntax(TTHEN);
11794 n2->nif.ifpart = list(0);
11796 if (lasttoken == TELSE)
11797 n2->nif.elsepart = list(0);
11799 n2->nif.elsepart = NULL;
11807 n1 = stzalloc(sizeof(struct nbinary));
11808 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11809 n1->nbinary.ch1 = list(0);
11812 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11813 got == TWORD ? wordtext : ""));
11814 raise_error_unexpected_syntax(TDO);
11816 n1->nbinary.ch2 = list(0);
11821 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11822 raise_error_syntax("bad for loop variable");
11823 n1 = stzalloc(sizeof(struct nfor));
11825 n1->nfor.linno = savelinno;
11826 n1->nfor.var = wordtext;
11827 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11828 if (readtoken() == TIN) {
11830 while (readtoken() == TWORD) {
11831 n2 = stzalloc(sizeof(struct narg));
11833 /*n2->narg.next = NULL; - stzalloc did it */
11834 n2->narg.text = wordtext;
11835 n2->narg.backquote = backquotelist;
11837 app = &n2->narg.next;
11840 n1->nfor.args = ap;
11841 if (lasttoken != TNL && lasttoken != TSEMI)
11842 raise_error_unexpected_syntax(-1);
11844 n2 = stzalloc(sizeof(struct narg));
11846 /*n2->narg.next = NULL; - stzalloc did it */
11847 n2->narg.text = (char *)dolatstr;
11848 /*n2->narg.backquote = NULL;*/
11849 n1->nfor.args = n2;
11851 * Newline or semicolon here is optional (but note
11852 * that the original Bourne shell only allowed NL).
11854 if (lasttoken != TSEMI)
11857 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11858 if (readtoken() != TDO)
11859 raise_error_unexpected_syntax(TDO);
11860 n1->nfor.body = list(0);
11864 n1 = stzalloc(sizeof(struct ncase));
11866 n1->ncase.linno = savelinno;
11867 if (readtoken() != TWORD)
11868 raise_error_unexpected_syntax(TWORD);
11869 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11871 /*n2->narg.next = NULL; - stzalloc did it */
11872 n2->narg.text = wordtext;
11873 n2->narg.backquote = backquotelist;
11874 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11875 if (readtoken() != TIN)
11876 raise_error_unexpected_syntax(TIN);
11877 cpp = &n1->ncase.cases;
11879 checkkwd = CHKNL | CHKKWD;
11881 while (t != TESAC) {
11882 if (lasttoken == TLP)
11884 *cpp = cp = stzalloc(sizeof(struct nclist));
11886 app = &cp->nclist.pattern;
11888 *app = ap = stzalloc(sizeof(struct narg));
11890 /*ap->narg.next = NULL; - stzalloc did it */
11891 ap->narg.text = wordtext;
11892 ap->narg.backquote = backquotelist;
11893 if (readtoken() != TPIPE)
11895 app = &ap->narg.next;
11898 //ap->narg.next = NULL;
11899 if (lasttoken != TRP)
11900 raise_error_unexpected_syntax(TRP);
11901 cp->nclist.body = list(2);
11903 cpp = &cp->nclist.next;
11905 checkkwd = CHKNL | CHKKWD;
11909 raise_error_unexpected_syntax(TENDCASE);
11916 n1 = stzalloc(sizeof(struct nredir));
11917 n1->type = NSUBSHELL;
11918 n1->nredir.linno = savelinno;
11919 n1->nredir.n = list(0);
11920 /*n1->nredir.redirect = NULL; - stzalloc did it */
11927 IF_BASH_FUNCTION(case TFUNCTION:)
11931 return simplecmd();
11934 if (readtoken() != t)
11935 raise_error_unexpected_syntax(t);
11938 /* Now check for redirection which may follow command */
11939 checkkwd = CHKKWD | CHKALIAS;
11941 while (readtoken() == TREDIR) {
11942 *rpp = n2 = redirnode;
11943 rpp = &n2->nfile.next;
11949 if (n1->type != NSUBSHELL) {
11950 n2 = stzalloc(sizeof(struct nredir));
11952 n2->nredir.linno = savelinno;
11956 n1->nredir.redirect = redir;
11961 #if BASH_DOLLAR_SQUOTE
11963 decode_dollar_squote(void)
11965 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11971 p = strchr(C_escapes, c);
11976 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11980 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11982 } else if (c == 'x') { /* \xHH */
11986 } while (isxdigit(c) && --cnt);
11988 if (cnt == 3) { /* \x but next char is "bad" */
11992 } else { /* simple seq like \\ or \t */
11997 c = bb_process_escape_sequence((void*)&p);
11998 } else { /* unrecognized "\z": print both chars unless ' or " */
11999 if (c != '\'' && c != '"') {
12001 c |= 0x100; /* "please encode \, then me" */
12008 /* Used by expandstr to get here-doc like behaviour. */
12009 #define FAKEEOFMARK ((char*)(uintptr_t)1)
12011 static ALWAYS_INLINE int
12012 realeofmark(const char *eofmark)
12014 return eofmark && eofmark != FAKEEOFMARK;
12018 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
12019 * is not NULL, read a here document. In the latter case, eofmark is the
12020 * word which marks the end of the document and striptabs is true if
12021 * leading tabs should be stripped from the document. The argument c
12022 * is the first character of the input token or document.
12024 * Because C does not have internal subroutines, I have simulated them
12025 * using goto's to implement the subroutine linkage. The following macros
12026 * will run code that appears at the end of readtoken1.
12028 #define CHECKEND() {goto checkend; checkend_return:;}
12029 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
12030 #define PARSESUB() {goto parsesub; parsesub_return:;}
12031 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
12032 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
12033 #define PARSEARITH() {goto parsearith; parsearith_return:;}
12035 readtoken1(int c, int syntax, char *eofmark, int striptabs)
12037 /* NB: syntax parameter fits into smallint */
12038 /* c parameter is an unsigned char or PEOF or PEOA */
12041 struct nodelist *bqlist;
12044 smallint pssyntax; /* we are expanding a prompt string */
12045 IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
12047 struct synstack synbase = { };
12048 struct synstack *synstack = &synbase;
12050 #if ENABLE_ASH_EXPAND_PRMT
12051 pssyntax = (syntax == PSSYNTAX);
12055 pssyntax = 0; /* constant */
12057 synstack->syntax = syntax;
12059 if (syntax == DQSYNTAX)
12060 synstack->dblquote = 1;
12064 STARTSTACKSTR(out);
12066 /* For each line, until end of word */
12067 CHECKEND(); /* set c to PEOF if at end of here document */
12068 for (;;) { /* until end of line or end of word */
12069 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
12070 switch (SIT(c, synstack->syntax)) {
12071 case CNL: /* '\n' */
12072 if (synstack->syntax == BASESYNTAX
12073 && !synstack->varnest
12075 goto endword; /* exit outer loop */
12080 goto loop; /* continue outer loop */
12085 #if BASH_DOLLAR_SQUOTE
12086 if (c == '\\' && bash_dollar_squote) {
12087 c = decode_dollar_squote();
12089 /* skip $'\000', $'\x00' (like bash) */
12093 /* Unknown escape. Encode as '\z' */
12094 c = (unsigned char)c;
12095 if (eofmark == NULL || synstack->dblquote)
12096 USTPUTC(CTLESC, out);
12097 USTPUTC('\\', out);
12101 if (!eofmark || synstack->dblquote || synstack->varnest)
12102 USTPUTC(CTLESC, out);
12105 case CBACK: /* backslash */
12106 c = pgetc_without_PEOA();
12108 USTPUTC(CTLESC, out);
12109 USTPUTC('\\', out);
12111 } else if (c == '\n') {
12114 if (pssyntax && c == '$') {
12115 USTPUTC(CTLESC, out);
12116 USTPUTC('\\', out);
12118 /* Backslash is retained if we are in "str"
12119 * and next char isn't dquote-special.
12121 if (synstack->dblquote
12125 && (c != '"' || (eofmark != NULL && !synstack->varnest))
12126 && (c != '}' || !synstack->varnest)
12128 USTPUTC(CTLESC, out); /* protect '\' from glob */
12129 USTPUTC('\\', out);
12131 USTPUTC(CTLESC, out);
12137 synstack->syntax = SQSYNTAX;
12139 if (eofmark == NULL) {
12140 USTPUTC(CTLQUOTEMARK, out);
12144 synstack->syntax = DQSYNTAX;
12145 synstack->dblquote = 1;
12147 if (synstack->varnest)
12148 synstack->innerdq ^= 1;
12151 IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
12152 if (eofmark != NULL && synstack->varnest == 0) {
12157 if (synstack->dqvarnest == 0) {
12158 synstack->syntax = BASESYNTAX;
12159 synstack->dblquote = 0;
12168 case CVAR: /* '$' */
12169 PARSESUB(); /* parse substitution */
12171 case CENDVAR: /* '}' */
12172 if (!synstack->innerdq && synstack->varnest > 0) {
12173 if (!--synstack->varnest && synstack->varpushed)
12174 synstack_pop(&synstack);
12175 else if (synstack->dqvarnest > 0)
12176 synstack->dqvarnest--;
12181 #if ENABLE_FEATURE_SH_MATH
12182 case CLP: /* '(' in arithmetic */
12183 synstack->parenlevel++;
12186 case CRP: /* ')' in arithmetic */
12187 if (synstack->parenlevel > 0) {
12188 synstack->parenlevel--;
12190 if (pgetc_eatbnl() == ')') {
12192 synstack_pop(&synstack);
12195 * unbalanced parens
12196 * (don't 2nd guess - no error)
12204 case CBQUOTE: /* '`' */
12205 if (checkkwd & CHKEOFMARK) {
12214 goto endword; /* exit outer loop */
12218 if (synstack->varnest == 0) {
12219 #if BASH_REDIR_OUTPUT
12221 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
12222 if (pgetc() == '>')
12223 c = 0x100 + '>'; /* flag &> */
12227 goto endword; /* exit outer loop */
12229 IF_ASH_ALIAS(if (c != PEOA))
12236 #if ENABLE_FEATURE_SH_MATH
12237 if (synstack->syntax == ARISYNTAX)
12238 raise_error_syntax("missing '))'");
12240 if (synstack->syntax != BASESYNTAX && eofmark == NULL)
12241 raise_error_syntax("unterminated quoted string");
12242 if (synstack->varnest != 0) {
12244 raise_error_syntax("missing '}'");
12246 USTPUTC('\0', out);
12247 len = out - (char *)stackblock();
12248 out = stackblock();
12249 if (eofmark == NULL) {
12250 if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
12253 if (isdigit_str9(out)) {
12254 PARSEREDIR(); /* passed as params: out, c */
12255 lasttoken = TREDIR;
12258 /* else: non-number X seen, interpret it
12259 * as "NNNX>file" = "NNNX >file" */
12263 quoteflag = quotef;
12264 backquotelist = bqlist;
12265 grabstackblock(len);
12269 /* end of readtoken routine */
12272 * Check to see whether we are at the end of the here document. When this
12273 * is called, c is set to the first character of the next input line. If
12274 * we are at the end of the here document, this routine sets the c to PEOF.
12277 if (realeofmark(eofmark)) {
12281 #if ENABLE_ASH_ALIAS
12283 c = pgetc_without_PEOA();
12286 while (c == '\t') {
12287 c = pgetc_without_PEOA();
12291 markloc = out - (char *)stackblock();
12292 for (p = eofmark; STPUTC(c, out), *p; p++) {
12296 c = pgetc_without_PEOA();
12299 if (c == '\n' || c == PEOF) {
12301 g_parsefile->linno++;
12302 needprompt = doprompt;
12307 p = (char *)stackblock() + markloc + 1;
12308 len_here = out - p;
12311 len_here -= (c >= PEOF);
12317 str = alloca(len_here + 1);
12318 *(char *)mempcpy(str, p, len_here) = '\0';
12320 pushstring(str, NULL);
12325 STADJUST((char *)stackblock() + markloc - out, out);
12327 goto checkend_return;
12331 * Parse a redirection operator. The variable "out" points to a string
12332 * specifying the fd to be redirected. The variable "c" contains the
12333 * first character of the redirection operator.
12336 /* out is already checked to be a valid number or "" */
12337 int fd = (*out == '\0' ? -1 : atoi(out));
12340 np = stzalloc(sizeof(struct nfile));
12343 c = pgetc_eatbnl();
12345 np->type = NAPPEND;
12347 np->type = NCLOBBER;
12350 /* it also can be NTO2 (>&file), but we can't figure it out yet */
12356 #if BASH_REDIR_OUTPUT
12357 else if (c == 0x100 + '>') { /* this flags &> redirection */
12359 pgetc(); /* this is '>', no need to check */
12363 else { /* c == '<' */
12364 /*np->nfile.fd = 0; - stzalloc did it */
12365 c = pgetc_eatbnl();
12368 if (sizeof(struct nfile) != sizeof(struct nhere)) {
12369 np = stzalloc(sizeof(struct nhere));
12370 /*np->nfile.fd = 0; - stzalloc did it */
12373 heredoc = stzalloc(sizeof(struct heredoc));
12374 heredoc->here = np;
12375 c = pgetc_eatbnl();
12377 heredoc->striptabs = 1;
12379 /*heredoc->striptabs = 0; - stzalloc did it */
12385 np->type = NFROMFD;
12389 np->type = NFROMTO;
12401 goto parseredir_return;
12405 * Parse a substitution. At this point, we have read the dollar sign
12406 * and nothing else.
12409 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
12410 * (assuming ascii char codes, as the original implementation did) */
12411 #define is_special(c) \
12412 (((unsigned)(c) - 33 < 32) \
12413 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
12415 unsigned char subtype;
12418 c = pgetc_eatbnl();
12419 if ((checkkwd & CHKEOFMARK)
12420 || c > 255 /* PEOA or PEOF */
12421 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
12423 #if BASH_DOLLAR_SQUOTE
12424 if (synstack->syntax != DQSYNTAX && c == '\'')
12425 bash_dollar_squote = 1;
12430 } else if (c == '(') {
12431 /* $(command) or $((arith)) */
12432 if (pgetc_eatbnl() == '(') {
12433 #if ENABLE_FEATURE_SH_MATH
12436 raise_error_syntax("support for $((arith)) is disabled");
12443 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
12444 smalluint newsyn = synstack->syntax;
12446 USTPUTC(CTLVAR, out);
12447 typeloc = out - (char *)stackblock();
12449 subtype = VSNORMAL;
12451 c = pgetc_eatbnl();
12456 /* $[{[#]]NAME[}] */
12459 c = pgetc_eatbnl();
12460 } while (is_in_name(c));
12461 } else if (isdigit(c)) {
12462 /* $[{[#]]NUM[}] */
12465 c = pgetc_eatbnl();
12466 } while (isdigit(c));
12467 } else if (c != '}') {
12468 /* $[{[#]]<specialchar>[}] */
12471 c = pgetc_eatbnl();
12472 if (!subtype && cc == '#') {
12473 subtype = VSLENGTH;
12474 if (c == '_' || isalnum(c))
12477 c = pgetc_eatbnl();
12478 if (cc == '}' || c != '}') {
12486 if (!is_special(cc)) {
12487 if (subtype == VSLENGTH)
12496 if (c != '}' && subtype == VSLENGTH) {
12497 /* ${#VAR didn't end with } */
12501 if (subtype == 0) {
12502 static const char types[] ALIGN1 = "}-+?=";
12503 /* ${VAR...} but not $VAR or ${#VAR} */
12504 /* c == first char after VAR */
12509 c = pgetc_eatbnl();
12511 /* This check is only needed to not misinterpret
12512 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
12515 if (!strchr(types, c)) {
12516 subtype = VSSUBSTR;
12518 break; /* "goto badsub" is bigger (!) */
12524 const char *p = strchr(types, c);
12527 subtype |= p - types + VSNORMAL;
12532 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
12533 c = pgetc_eatbnl();
12539 newsyn = BASESYNTAX;
12541 #if BASH_PATTERN_SUBST
12543 /* ${v/[/]pattern/repl} */
12544 //TODO: encode pattern and repl separately.
12545 // Currently cases like: v=1;echo ${v/$((1/1))/ONE}
12546 // are broken (should print "ONE")
12547 subtype = VSREPLACE;
12548 newsyn = BASESYNTAX;
12549 c = pgetc_eatbnl();
12552 subtype++; /* VSREPLACEALL */
12561 if (newsyn == ARISYNTAX)
12564 if ((newsyn != synstack->syntax || synstack->innerdq)
12565 && subtype != VSNORMAL
12567 synstack_push(&synstack,
12568 synstack->prev ?: alloca(sizeof(*synstack)),
12571 synstack->varpushed = 1;
12572 synstack->dblquote = newsyn != BASESYNTAX;
12575 ((unsigned char *)stackblock())[typeloc] = subtype;
12576 if (subtype != VSNORMAL) {
12577 synstack->varnest++;
12578 if (synstack->dblquote)
12579 synstack->dqvarnest++;
12583 goto parsesub_return;
12587 * Called to parse command substitutions. Newstyle is set if the command
12588 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
12589 * list of commands (passed by reference), and savelen is the number of
12590 * characters on the top of the stack which must be preserved.
12593 struct nodelist **nlpp;
12597 smallint saveprompt = 0;
12600 savelen = out - (char *)stackblock();
12603 * FIXME: this can allocate very large block on stack and SEGV.
12605 * echo "..<100kbytes>..`true` $(true) `true` ..."
12606 * allocates 100kb for every command subst. With about
12607 * a hundred command substitutions stack overflows.
12608 * With larger prepended string, SEGV happens sooner.
12610 str = alloca(savelen);
12611 memcpy(str, stackblock(), savelen);
12615 /* We must read until the closing backquote, giving special
12616 * treatment to some slashes, and then push the string and
12617 * reread it as input, interpreting it normally.
12623 STARTSTACKSTR(pout);
12627 setprompt_if(needprompt, 2);
12628 pc = pgetc_eatbnl();
12634 pc = pgetc(); /* or pgetc_eatbnl()? why (example)? */
12635 if (pc != '\\' && pc != '`' && pc != '$'
12636 && (!synstack->dblquote || pc != '"')
12638 STPUTC('\\', pout);
12640 if (pc <= 255 /* not PEOA or PEOF */) {
12646 IF_ASH_ALIAS(case PEOA:)
12647 raise_error_syntax("EOF in backquote substitution");
12659 STPUTC('\0', pout);
12660 psavelen = pout - (char *)stackblock();
12661 if (psavelen > 0) {
12662 pstr = grabstackstr(pout);
12663 setinputstring(pstr);
12668 nlpp = &(*nlpp)->next;
12669 *nlpp = stzalloc(sizeof(**nlpp));
12670 /* (*nlpp)->next = NULL; - stzalloc did it */
12673 saveprompt = doprompt;
12680 doprompt = saveprompt;
12681 else if (readtoken() != TRP)
12682 raise_error_unexpected_syntax(TRP);
12687 * Start reading from old file again, ignoring any pushed back
12688 * tokens left from the backquote parsing
12693 while (stackblocksize() <= savelen)
12695 STARTSTACKSTR(out);
12697 memcpy(out, str, savelen);
12698 STADJUST(savelen, out);
12700 USTPUTC(CTLBACKQ, out);
12702 goto parsebackq_oldreturn;
12703 goto parsebackq_newreturn;
12706 #if ENABLE_FEATURE_SH_MATH
12708 * Parse an arithmetic expansion (indicate start of one and set state)
12712 synstack_push(&synstack,
12713 synstack->prev ?: alloca(sizeof(*synstack)),
12715 synstack->dblquote = 1;
12716 USTPUTC(CTLARI, out);
12717 goto parsearith_return;
12720 } /* end of readtoken */
12723 * Read the next input token.
12724 * If the token is a word, we set backquotelist to the list of cmds in
12725 * backquotes. We set quoteflag to true if any part of the word was
12727 * If the token is TREDIR, then we set redirnode to a structure containing
12730 * [Change comment: here documents and internal procedures]
12731 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12732 * word parsing code into a separate routine. In this case, readtoken
12733 * doesn't need to have any internal procedures, but parseword does.
12734 * We could also make parseoperator in essence the main routine, and
12735 * have parseword (readtoken1?) handle both words and redirection.]
12737 #define NEW_xxreadtoken
12738 #ifdef NEW_xxreadtoken
12739 /* singles must be first! */
12740 static const char xxreadtoken_chars[7] ALIGN1 = {
12741 '\n', '(', ')', /* singles */
12742 '&', '|', ';', /* doubles */
12746 #define xxreadtoken_singles 3
12747 #define xxreadtoken_doubles 3
12749 static const char xxreadtoken_tokens[] ALIGN1 = {
12750 TNL, TLP, TRP, /* only single occurrence allowed */
12751 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12752 TEOF, /* corresponds to trailing nul */
12753 TAND, TOR, TENDCASE /* if double occurrence */
12765 setprompt_if(needprompt, 2);
12766 for (;;) { /* until token or start of word found */
12767 c = pgetc_eatbnl();
12768 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12772 while ((c = pgetc()) != '\n' && c != PEOF)
12775 } else if (c == '\\') {
12776 break; /* return readtoken1(...) */
12780 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12786 p = strchr(xxreadtoken_chars, c);
12788 break; /* return readtoken1(...) */
12790 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12791 int cc = pgetc_eatbnl();
12792 if (cc == c) { /* double occurrence? */
12793 p += xxreadtoken_doubles + 1;
12796 #if BASH_REDIR_OUTPUT
12797 if (c == '&' && cc == '>') /* &> */
12798 break; /* return readtoken1(...) */
12803 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12808 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12810 #else /* old xxreadtoken */
12811 #define RETURN(token) return lasttoken = token
12821 setprompt_if(needprompt, 2);
12822 for (;;) { /* until token or start of word found */
12823 c = pgetc_eatbnl();
12825 case ' ': case '\t':
12826 IF_ASH_ALIAS(case PEOA:)
12829 while ((c = pgetc()) != '\n' && c != PEOF)
12839 if (pgetc_eatbnl() == '&')
12844 if (pgetc_eatbnl() == '|')
12849 if (pgetc_eatbnl() == ';')
12860 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12863 #endif /* old xxreadtoken */
12869 int kwd = checkkwd;
12871 smallint alreadyseen = tokpushback;
12874 #if ENABLE_ASH_ALIAS
12890 if (t != TWORD || quoteflag) {
12895 * check for keywords
12897 if (kwd & CHKKWD) {
12898 const char *const *pp;
12900 pp = findkwd(wordtext);
12902 lasttoken = t = pp - tokname_array;
12903 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12908 if (checkkwd & CHKALIAS) {
12909 #if ENABLE_ASH_ALIAS
12911 ap = lookupalias(wordtext, 1);
12914 pushstring(ap->val, ap);
12924 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12926 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12942 * Read and parse a command. Returns NODE_EOF on end of file.
12943 * (NULL is a valid parse tree indicating a blank line.)
12945 static union node *
12946 parsecmd(int interact)
12951 doprompt = interact;
12952 setprompt_if(doprompt, doprompt);
12958 * Input any here documents.
12963 struct heredoc *here;
12966 here = heredoclist;
12967 heredoclist = NULL;
12970 setprompt_if(needprompt, 2);
12971 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12972 here->eofmark, here->striptabs);
12973 n = stzalloc(sizeof(struct narg));
12974 n->narg.type = NARG;
12975 /*n->narg.next = NULL; - stzalloc did it */
12976 n->narg.text = wordtext;
12977 n->narg.backquote = backquotelist;
12978 here->here->nhere.doc = n;
12984 static const char *
12985 expandstr(const char *ps, int syntax_type)
12990 /* XXX Fix (char *) cast. */
12991 setinputstring((char *)ps);
12993 saveprompt = doprompt;
12996 /* readtoken1() might die horribly.
12997 * Try a prompt with syntactically wrong command:
12998 * PS1='$(date "+%H:%M:%S) > '
13001 volatile int saveint;
13002 struct jmploc *volatile savehandler = exception_handler;
13003 struct jmploc jmploc;
13005 if (setjmp(jmploc.loc) == 0) {
13006 exception_handler = &jmploc;
13007 readtoken1(pgetc(), syntax_type, FAKEEOFMARK, 0);
13009 exception_handler = savehandler;
13010 RESTORE_INT(saveint);
13013 doprompt = saveprompt;
13017 n.narg.type = NARG;
13018 n.narg.next = NULL;
13019 n.narg.text = wordtext;
13020 n.narg.backquote = backquotelist;
13022 expandarg(&n, NULL, EXP_QUOTED);
13023 return stackblock();
13029 return tokpushback && lasttoken == TEOF;
13033 * Execute a command or commands contained in a string.
13036 evalstring(char *s, int flags)
13038 struct jmploc *volatile savehandler;
13039 struct jmploc jmploc;
13043 struct stackmark smark;
13048 setstackmark(&smark);
13051 /* On exception inside execution loop, we must popfile().
13052 * Try interactively:
13054 * command eval "a=b" # throws "is read only" error
13055 * "command BLTIN" is not supposed to abort (even in non-interactive use).
13056 * But if we skip popfile(), we hit EOF in eval's string, and exit.
13058 savehandler = exception_handler;
13059 ex = setjmp(jmploc.loc);
13062 exception_handler = &jmploc;
13064 while ((n = parsecmd(0)) != NODE_EOF) {
13067 i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
13070 popstackmark(&smark);
13075 popstackmark(&smark);
13079 exception_handler = savehandler;
13081 longjmp(exception_handler->loc, ex);
13087 * The eval command.
13089 static int FAST_FUNC
13090 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
13099 STARTSTACKSTR(concat);
13101 concat = stack_putstr(p, concat);
13105 STPUTC(' ', concat);
13107 STPUTC('\0', concat);
13108 p = grabstackstr(concat);
13110 return evalstring(p, flags & EV_TESTED);
13116 * Read and execute commands.
13117 * "Top" is nonzero for the top level command loop;
13118 * it turns on prompting if the shell is interactive.
13124 struct stackmark smark;
13129 TRACE(("cmdloop(%d) called\n", top));
13133 setstackmark(&smark);
13136 showjobs(SHOW_CHANGED|SHOW_STDERR);
13139 if (iflag && top) {
13143 n = parsecmd(inter);
13145 if (DEBUG > 2 && debug && (n != NODE_EOF))
13148 if (n == NODE_EOF) {
13149 if (!top || numeof >= 50)
13151 if (!stoppedjobs()) {
13154 out2str("\nUse \"exit\" to leave shell.\n");
13157 } else if (nflag == 0) {
13160 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
13163 i = evaltree(n, 0);
13167 popstackmark(&smark);
13171 evalskip &= ~SKIPFUNC;
13179 * Take commands from a file. To be compatible we should do a path
13180 * search for the file, which is necessary to find sub-commands.
13183 find_dot_file(char *name)
13186 const char *path = pathval();
13189 /* don't try this for absolute or relative paths */
13190 if (strchr(name, '/'))
13193 while ((fullname = path_advance(&path, name)) != NULL) {
13194 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
13196 * Don't bother freeing here, since it will
13197 * be freed by the caller.
13201 if (fullname != name)
13202 stunalloc(fullname);
13204 /* not found in PATH */
13206 #if ENABLE_ASH_BASH_SOURCE_CURDIR
13209 ash_msg_and_raise_error("%s: not found", name);
13214 static int FAST_FUNC
13215 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
13217 /* "false; . empty_file; echo $?" should print 0, not 1: */
13221 char *args_need_save;
13222 volatile struct shparam saveparam;
13225 // struct strlist *sp;
13226 // for (sp = cmdenviron; sp; sp = sp->next)
13227 // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
13229 nextopt(nullstr); /* handle possible "--" */
13233 /* bash says: "bash: .: filename argument required" */
13234 return 2; /* bash compat */
13237 /* This aborts if file isn't found, which is POSIXly correct.
13238 * bash returns exitcode 1 instead.
13240 fullname = find_dot_file(argv[0]);
13242 args_need_save = argv[0];
13243 if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
13245 saveparam = shellparam;
13246 shellparam.malloced = 0;
13250 shellparam.nparam = argc;
13251 shellparam.p = argv;
13254 /* This aborts if file can't be opened, which is POSIXly correct.
13255 * bash returns exitcode 1 instead.
13257 setinputfile(fullname, INPUT_PUSH_FILE);
13258 commandname = fullname;
13259 status = cmdloop(0);
13262 if (args_need_save) {
13263 freeparam(&shellparam);
13264 shellparam = saveparam;
13270 static int FAST_FUNC
13271 exitcmd(int argc UNUSED_PARAM, char **argv)
13276 exitstatus = number(argv[1]);
13277 raise_exception(EXEXIT);
13282 * Read a file containing shell functions.
13285 readcmdfile(char *name)
13287 setinputfile(name, INPUT_PUSH_FILE);
13293 /* ============ find_command inplementation */
13296 * Resolve a command name. If you change this routine, you may have to
13297 * change the shellexec routine as well.
13300 find_command(char *name, struct cmdentry *entry, int act, const char *path)
13302 struct tblentry *cmdp;
13309 struct builtincmd *bcmd;
13311 /* If name contains a slash, don't use PATH or hash table */
13312 if (strchr(name, '/') != NULL) {
13313 entry->u.index = -1;
13314 if (act & DO_ABS) {
13315 while (stat(name, &statb) < 0) {
13317 if (errno == EINTR)
13320 entry->cmdtype = CMDUNKNOWN;
13324 entry->cmdtype = CMDNORMAL;
13328 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
13330 updatetbl = (path == pathval());
13333 if (strstr(path, "%builtin") != NULL)
13334 act |= DO_ALTBLTIN;
13337 /* If name is in the table, check answer will be ok */
13338 cmdp = cmdlookup(name, 0);
13339 if (cmdp != NULL) {
13342 switch (cmdp->cmdtype) {
13360 } else if (cmdp->rehash == 0)
13361 /* if not invalidated by cd, we're done */
13365 /* If %builtin not in path, check for builtin next */
13366 bcmd = find_builtin(name);
13368 if (IS_BUILTIN_REGULAR(bcmd))
13369 goto builtin_success;
13370 if (act & DO_ALTPATH) {
13371 if (!(act & DO_ALTBLTIN))
13372 goto builtin_success;
13373 } else if (builtinloc <= 0) {
13374 goto builtin_success;
13378 #if ENABLE_FEATURE_SH_STANDALONE
13380 int applet_no = find_applet_by_name(name);
13381 # if NUM_SCRIPTS > 0
13383 /* embedded script indices are offset by NUM_APPLETS */
13384 applet_no = NUM_APPLETS + find_script_by_name(name);
13386 if (applet_no >= 0) {
13387 entry->cmdtype = CMDNORMAL;
13388 entry->u.index = -2 - applet_no;
13394 /* We have to search path. */
13395 prev = -1; /* where to start */
13396 if (cmdp && cmdp->rehash) { /* doing a rehash */
13397 if (cmdp->cmdtype == CMDBUILTIN)
13400 prev = cmdp->param.index;
13406 while ((fullname = path_advance(&path, name)) != NULL) {
13407 stunalloc(fullname);
13408 /* NB: code below will still use fullname
13409 * despite it being "unallocated" */
13412 if (prefix(pathopt, "builtin")) {
13414 goto builtin_success;
13417 if ((act & DO_NOFUNC)
13418 || !prefix(pathopt, "func")
13419 ) { /* ignore unimplemented options */
13423 /* if rehash, don't redo absolute path names */
13424 if (fullname[0] == '/' && idx <= prev) {
13427 TRACE(("searchexec \"%s\": no change\n", name));
13430 while (stat(fullname, &statb) < 0) {
13432 if (errno == EINTR)
13435 if (errno != ENOENT && errno != ENOTDIR)
13439 e = EACCES; /* if we fail, this will be the error */
13440 if (!S_ISREG(statb.st_mode))
13442 if (pathopt) { /* this is a %func directory */
13443 stalloc(strlen(fullname) + 1);
13444 /* NB: stalloc will return space pointed by fullname
13445 * (because we don't have any intervening allocations
13446 * between stunalloc above and this stalloc) */
13447 readcmdfile(fullname);
13448 cmdp = cmdlookup(name, 0);
13449 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
13450 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
13451 stunalloc(fullname);
13454 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
13456 entry->cmdtype = CMDNORMAL;
13457 entry->u.index = idx;
13461 cmdp = cmdlookup(name, 1);
13462 cmdp->cmdtype = CMDNORMAL;
13463 cmdp->param.index = idx;
13468 /* We failed. If there was an entry for this command, delete it */
13469 if (cmdp && updatetbl)
13470 delete_cmd_entry();
13471 if (act & DO_ERR) {
13472 #if ENABLE_ASH_BASH_NOT_FOUND_HOOK
13473 struct tblentry *hookp = cmdlookup("command_not_found_handle", 0);
13474 if (hookp && hookp->cmdtype == CMDFUNCTION) {
13476 argv[0] = (char*) "command_not_found_handle";
13479 evalfun(hookp->param.func, 2, argv, 0);
13480 entry->cmdtype = CMDUNKNOWN;
13484 ash_msg("%s: %s", name, errmsg(e, "not found"));
13486 entry->cmdtype = CMDUNKNOWN;
13491 entry->cmdtype = CMDBUILTIN;
13492 entry->u.cmd = bcmd;
13496 cmdp = cmdlookup(name, 1);
13497 cmdp->cmdtype = CMDBUILTIN;
13498 cmdp->param.cmd = bcmd;
13502 entry->cmdtype = cmdp->cmdtype;
13503 entry->u = cmdp->param;
13508 * The trap builtin.
13510 static int FAST_FUNC
13511 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13515 int signo, exitcode;
13520 for (signo = 0; signo < NSIG; signo++) {
13521 char *tr = trap_ptr[signo];
13523 /* note: bash adds "SIG", but only if invoked
13524 * as "bash". If called as "sh", or if set -o posix,
13525 * then it prints short signal names.
13526 * We are printing short names: */
13527 out1fmt("trap -- %s %s\n",
13529 get_signame(signo));
13530 /* trap_ptr != trap only if we are in special-cased `trap` code.
13531 * In this case, we will exit very soon, no need to free(). */
13532 /* if (trap_ptr != trap && tp[0]) */
13537 if (trap_ptr != trap) {
13545 /* Why the second check?
13546 * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
13547 * In this case, NUM is signal no, not an action.
13550 if (ap[1] && !is_number(ap[0]))
13555 signo = get_signum(*ap);
13557 /* Mimic bash message exactly */
13558 ash_msg("%s: invalid signal specification", *ap);
13564 if (LONE_DASH(action))
13567 if (action[0]) /* not NULL and not "" and not "-" */
13568 may_have_traps = 1;
13569 action = ckstrdup(action);
13573 trap[signo] = action;
13584 /* ============ Builtins */
13586 #if ENABLE_ASH_HELP
13587 static int FAST_FUNC
13588 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13594 "Built-in commands:\n"
13595 "------------------\n");
13596 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
13597 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
13598 builtintab[i].name + 1);
13604 # if ENABLE_FEATURE_SH_STANDALONE
13606 const char *a = applet_names;
13608 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
13613 while (*a++ != '\0')
13618 newline_and_flush(stdout);
13619 return EXIT_SUCCESS;
13624 static int FAST_FUNC
13625 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13627 show_history(line_input_state);
13628 return EXIT_SUCCESS;
13633 * The export and readonly commands.
13635 static int FAST_FUNC
13636 exportcmd(int argc UNUSED_PARAM, char **argv)
13646 /* "readonly" in bash accepts, but ignores -n.
13647 * We do the same: it saves a conditional in nextopt's param.
13650 while ((opt = nextopt("np")) != '\0') {
13652 flag_off = VEXPORT;
13655 if (argv[0][0] == 'r') {
13657 flag_off = 0; /* readonly ignores -n */
13659 flag_off = ~flag_off;
13661 /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
13667 p = strchr(name, '=');
13671 vp = *findvar(hashvar(name), name);
13673 vp->flags = ((vp->flags | flag) & flag_off);
13677 setvar(name, p, (flag & flag_off));
13678 } while ((name = *++aptr) != NULL);
13683 /* No arguments. Show the list of exported or readonly vars.
13686 showvars(argv[0], flag, 0);
13691 * Delete a function if it exists.
13694 unsetfunc(const char *name)
13696 struct tblentry *cmdp;
13698 cmdp = cmdlookup(name, 0);
13699 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
13700 delete_cmd_entry();
13704 * The unset builtin command. We unset the function before we unset the
13705 * variable to allow a function to be unset when there is a readonly variable
13706 * with the same name.
13708 static int FAST_FUNC
13709 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13715 while ((i = nextopt("vf")) != 0) {
13719 for (ap = argptr; *ap; ap++) {
13730 static const unsigned char timescmd_str[] ALIGN1 = {
13731 ' ', offsetof(struct tms, tms_utime),
13732 '\n', offsetof(struct tms, tms_stime),
13733 ' ', offsetof(struct tms, tms_cutime),
13734 '\n', offsetof(struct tms, tms_cstime),
13737 static int FAST_FUNC
13738 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13741 const unsigned char *p;
13744 clk_tck = bb_clk_tck();
13749 unsigned sec, frac;
13751 t = *(clock_t *)(((char *) &buf) + p[1]);
13753 frac = t % clk_tck;
13754 out1fmt("%um%u.%03us%c",
13755 sec / 60, sec % 60,
13756 (frac * 1000) / clk_tck,
13764 #if ENABLE_FEATURE_SH_MATH
13766 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13767 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13769 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13771 static int FAST_FUNC
13772 letcmd(int argc UNUSED_PARAM, char **argv)
13778 ash_msg_and_raise_error("expression expected");
13780 i = ash_arith(*argv);
13788 * The read builtin. Options:
13789 * -r Do not interpret '\' specially
13790 * -s Turn off echo (tty only)
13791 * -n NCHARS Read NCHARS max
13792 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13793 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13794 * -u FD Read from given FD instead of fd 0
13795 * -d DELIM End on DELIM char, not newline
13796 * This uses unbuffered input, which may be avoidable in some cases.
13797 * TODO: bash also has:
13798 * -a ARRAY Read into array[0],[1],etc
13799 * -e Use line editing (tty only)
13801 static int FAST_FUNC
13802 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13804 struct builtin_read_params params;
13808 memset(¶ms, 0, sizeof(params));
13810 while ((i = nextopt("p:u:rt:n:sd:")) != '\0') {
13813 params.opt_p = optionarg;
13816 params.opt_n = optionarg;
13819 params.read_flags |= BUILTIN_READ_SILENT;
13822 params.opt_t = optionarg;
13825 params.read_flags |= BUILTIN_READ_RAW;
13828 params.opt_u = optionarg;
13832 params.opt_d = optionarg;
13840 params.argv = argptr;
13841 params.setvar = setvar0;
13842 params.ifs = bltinlookup("IFS"); /* can be NULL */
13844 /* "read -s" needs to save/restore termios, can't allow ^C
13845 * to jump out of it.
13849 r = shell_builtin_read(¶ms);
13852 if ((uintptr_t)r == 1 && errno == EINTR) {
13853 /* To get SIGCHLD: sleep 1 & read x; echo $x
13854 * Correct behavior is to not exit "read"
13856 if (pending_sig == 0)
13860 if ((uintptr_t)r > 1)
13861 ash_msg_and_raise_error(r);
13863 return (uintptr_t)r;
13866 static int FAST_FUNC
13867 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13869 static const char permuser[3] ALIGN1 = "ogu";
13872 int symbolic_mode = 0;
13874 while (nextopt("S") != '\0') {
13883 if (*argptr == NULL) {
13884 if (symbolic_mode) {
13885 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13892 *p++ = permuser[i];
13894 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13895 if (!(mask & 0400)) *p++ = 'r';
13896 if (!(mask & 0200)) *p++ = 'w';
13897 if (!(mask & 0100)) *p++ = 'x';
13905 out1fmt("%04o\n", mask);
13908 char *modestr = *argptr;
13909 /* numeric umasks are taken as-is */
13910 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13911 if (!isdigit(modestr[0]))
13913 mask = bb_parse_mode(modestr, mask);
13914 if ((unsigned)mask > 0777) {
13915 ash_msg_and_raise_error("illegal mode: %s", modestr);
13917 if (!isdigit(modestr[0]))
13924 static int FAST_FUNC
13925 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13927 return shell_builtin_ulimit(argv);
13930 /* ============ main() and helpers */
13933 * Called to exit the shell.
13942 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13943 save_history(line_input_state);
13945 status = exitstatus;
13946 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13947 if (setjmp(loc.loc)) {
13948 if (exception_type == EXEXIT)
13949 status = exitstatus;
13952 exception_handler = &loc;
13958 /*free(p); - we'll exit soon */
13961 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13962 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13965 flush_stdout_stderr();
13970 /* Don't inline: conserve stack of caller from having our locals too */
13971 static NOINLINE void
13974 /* we will never free this */
13975 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13978 sigmode[SIGCHLD - 1] = S_DFL; /* ensure we install handler even if it is SIG_IGNed */
13979 setsignal(SIGCHLD);
13981 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13982 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13984 signal(SIGHUP, SIG_DFL);
13991 for (envp = environ; envp && *envp; envp++) {
13993 * p = endofname(*envp);
13994 * if (p != *envp && *p == '=') {
13995 * here to weed out badly-named variables, but this breaks
13996 * scenarios where people do want them passed to children:
13998 * os.environ["test-test"]="test"
13999 * if os.fork() == 0:
14000 * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
14001 * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ]) # breaks this
14003 if (strchr(*envp, '=')) {
14004 setvareq(*envp, VEXPORT|VTEXTFIXED);
14008 setvareq((char*)defifsvar, VTEXTFIXED);
14009 setvareq((char*)defoptindvar, VTEXTFIXED);
14011 setvar0("PPID", utoa(getppid()));
14013 p = lookupvar("SHLVL");
14014 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
14016 #if BASH_HOSTNAME_VAR
14017 if (!lookupvar("HOSTNAME")) {
14018 struct utsname uts;
14020 setvar0("HOSTNAME", uts.nodename);
14023 p = lookupvar("PWD");
14025 struct stat st1, st2;
14026 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
14027 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
14037 //usage:#define ash_trivial_usage
14038 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
14039 //usage:#define ash_full_usage "\n\n"
14040 //usage: "Unix shell interpreter"
14043 * Process the shell command line arguments.
14046 procargs(char **argv)
14049 const char *xminusc;
14054 login_sh = xargv[0] && xargv[0][0] == '-';
14055 #if NUM_SCRIPTS > 0
14060 /* if (xargv[0]) - mmm, this is always true! */
14063 for (i = 0; i < NOPTS; i++)
14065 if (options(/*cmdline:*/ 1, &login_sh)) {
14066 /* it already printed err message */
14067 raise_exception(EXERROR);
14071 if (*xargv == NULL) {
14073 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
14076 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
14080 for (i = 0; i < NOPTS; i++)
14081 if (optlist[i] == 2)
14086 /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
14091 } else if (!sflag) {
14092 setinputfile(*xargv, 0);
14095 commandname = arg0;
14098 shellparam.p = xargv;
14099 #if ENABLE_ASH_GETOPTS
14100 shellparam.optind = 1;
14101 shellparam.optoff = -1;
14103 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
14105 shellparam.nparam++;
14114 * Read /etc/profile, ~/.profile, $ENV.
14117 read_profile(const char *name)
14119 name = expandstr(name, DQSYNTAX);
14120 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
14127 * This routine is called when an error or an interrupt occurs in an
14128 * interactive shell and control is returned to the main command loop.
14129 * (In dash, this function is auto-generated by build machinery).
14138 /* from expand.c: */
14141 /* from input.c: */
14142 g_parsefile->left_in_buffer = 0;
14143 g_parsefile->left_in_line = 0; /* clear input buffer */
14146 /* from redir.c: */
14150 unwindlocalvars(NULL);
14154 static short profile_buf[16384];
14155 extern int etext();
14159 * Main routine. We initialize things, parse the arguments, execute
14160 * profiles if we're a login shell, and then call cmdloop to execute
14161 * commands. The setjmp call sets up the location to jump to when an
14162 * exception occurs. When an exception occurs the variable "state"
14163 * is used to figure out how far we had gotten.
14165 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
14166 #if NUM_SCRIPTS > 0
14167 int ash_main(int argc, char **argv)
14169 int ash_main(int argc UNUSED_PARAM, char **argv)
14171 /* note: 'argc' is used only if embedded scripts are enabled */
14173 volatile smallint state;
14174 struct jmploc jmploc;
14175 struct stackmark smark;
14178 /* Initialize global data */
14182 #if ENABLE_ASH_ALIAS
14188 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
14191 #if ENABLE_FEATURE_EDITING
14192 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
14195 if (setjmp(jmploc.loc)) {
14201 e = exception_type;
14203 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
14207 newline_and_flush(stderr);
14210 popstackmark(&smark);
14211 FORCE_INT_ON; /* enable interrupts */
14220 exception_handler = &jmploc;
14221 rootpid = getpid();
14224 setstackmark(&smark);
14226 #if NUM_SCRIPTS > 0
14228 /* Non-NULL minusc tells procargs that an embedded script is being run */
14229 minusc = get_script_content(-argc - 1);
14231 login_sh = procargs(argv);
14233 TRACE(("Shell args: "));
14234 trace_puts_args(argv);
14241 read_profile("/etc/profile");
14244 hp = lookupvar("HOME");
14246 read_profile("$HOME/.profile");
14252 getuid() == geteuid() && getgid() == getegid() &&
14256 const char *shinit = lookupvar("ENV");
14257 if (shinit != NULL && *shinit != '\0')
14258 read_profile(shinit);
14260 popstackmark(&smark);
14264 /* evalstring pushes parsefile stack.
14265 * Ensure we don't falsely claim that 0 (stdin)
14266 * is one of stacked source fds.
14267 * Testcase: ash -c 'exec 1>&0' must not complain. */
14268 // if (!sflag) g_parsefile->pf_fd = -1;
14269 // ^^ not necessary since now we special-case fd 0
14270 // in save_fd_on_redirect()
14271 evalstring(minusc, sflag ? 0 : EV_EXIT);
14274 if (sflag || minusc == NULL) {
14275 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
14277 const char *hp = lookupvar("HISTFILE");
14279 hp = lookupvar("HOME");
14282 hp = concat_path_file(hp, ".ash_history");
14283 setvar0("HISTFILE", hp);
14286 hp = lookupvar("HISTFILE");
14290 line_input_state->hist_file = hp;
14291 # if ENABLE_FEATURE_SH_HISTFILESIZE
14292 hp = lookupvar("HISTFILESIZE");
14293 line_input_state->max_history = size_from_HISTFILESIZE(hp);
14297 state4: /* XXX ??? - why isn't this before the "if" statement */
14305 extern void _mcleanup(void);
14309 TRACE(("End of main reached\n"));
14316 * Copyright (c) 1989, 1991, 1993, 1994
14317 * The Regents of the University of California. All rights reserved.
14319 * This code is derived from software contributed to Berkeley by
14320 * Kenneth Almquist.
14322 * Redistribution and use in source and binary forms, with or without
14323 * modification, are permitted provided that the following conditions
14325 * 1. Redistributions of source code must retain the above copyright
14326 * notice, this list of conditions and the following disclaimer.
14327 * 2. Redistributions in binary form must reproduce the above copyright
14328 * notice, this list of conditions and the following disclaimer in the
14329 * documentation and/or other materials provided with the distribution.
14330 * 3. Neither the name of the University nor the names of its contributors
14331 * may be used to endorse or promote products derived from this software
14332 * without specific prior written permission.
14334 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
14335 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
14336 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
14337 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
14338 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
14339 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
14340 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
14341 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
14342 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
14343 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF