1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * This code is derived from software contributed to Berkeley by
8 * Original BSD copyright notice is retained at the end of this file.
10 * Copyright (c) 1989, 1991, 1993, 1994
11 * The Regents of the University of California. All rights reserved.
13 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
14 * was re-ported from NetBSD and debianized.
16 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
19 //config: bool "ash (78 kb)"
21 //config: depends on !NOMMU
23 //config: The most complete and most pedantically correct shell included with
24 //config: busybox. This shell is actually a derivative of the Debian 'dash'
25 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
26 //config: (written by Kenneth Almquist) from NetBSD.
28 //config:# ash options
29 //config:# note: Don't remove !NOMMU part in the next line; it would break
30 //config:# menuconfig's indenting.
31 //config:if !NOMMU && (ASH || SH_IS_ASH || BASH_IS_ASH)
33 //config:config ASH_OPTIMIZE_FOR_SIZE
34 //config: bool "Optimize for size instead of speed"
36 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
38 //config:config ASH_INTERNAL_GLOB
39 //config: bool "Use internal glob() implementation"
40 //config: default y # Y is bigger, but because of uclibc glob() bug, let Y be default for now
41 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
43 //config: Do not use glob() function from libc, use internal implementation.
44 //config: Use this if you are getting "glob.h: No such file or directory"
45 //config: or similar build errors.
46 //config: Note that as of now (2017-01), uclibc and musl glob() both have bugs
47 //config: which would break ash if you select N here.
49 //config:config ASH_BASH_COMPAT
50 //config: bool "bash-compatible extensions"
52 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
54 //config:config ASH_BASH_SOURCE_CURDIR
55 //config: bool "'source' and '.' builtins search current directory after $PATH"
56 //config: default n # do not encourage non-standard behavior
57 //config: depends on ASH_BASH_COMPAT
59 //config: This is not compliant with standards. Avoid if possible.
61 //config:config ASH_BASH_NOT_FOUND_HOOK
62 //config: bool "command_not_found_handle hook support"
64 //config: depends on ASH_BASH_COMPAT
66 //config: Enable support for the 'command_not_found_handle' hook function,
67 //config: from GNU bash, which allows for alternative command not found
70 //config:config ASH_JOB_CONTROL
71 //config: bool "Job control"
73 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
75 //config:config ASH_ALIAS
76 //config: bool "Alias support"
78 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
80 //config:config ASH_RANDOM_SUPPORT
81 //config: bool "Pseudorandom generator and $RANDOM variable"
83 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
85 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
86 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
87 //config: You can reset the generator by using a specified start value.
88 //config: After "unset RANDOM" the generator will switch off and this
89 //config: variable will no longer have special treatment.
91 //config:config ASH_EXPAND_PRMT
92 //config: bool "Expand prompt string"
94 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
96 //config: $PS# may contain volatile content, such as backquote commands.
97 //config: This option recreates the prompt string from the environment
98 //config: variable each time it is displayed.
100 //config:config ASH_IDLE_TIMEOUT
101 //config: bool "Idle timeout variable $TMOUT"
103 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
105 //config: Enable bash-like auto-logout after $TMOUT seconds of idle time.
107 //config:config ASH_MAIL
108 //config: bool "Check for new mail in interactive shell"
110 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
112 //config: Enable "check for new mail" function:
113 //config: if set, $MAIL file and $MAILPATH list of files
114 //config: are checked for mtime changes, and "you have mail"
115 //config: message is printed if change is detected.
117 //config:config ASH_ECHO
118 //config: bool "echo builtin"
120 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
122 //config:config ASH_PRINTF
123 //config: bool "printf builtin"
125 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
127 //config:config ASH_TEST
128 //config: bool "test builtin"
130 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
132 //config:config ASH_HELP
133 //config: bool "help builtin"
135 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
137 //config:config ASH_GETOPTS
138 //config: bool "getopts builtin"
140 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
142 //config:config ASH_CMDCMD
143 //config: bool "command builtin"
145 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
147 //config: Enable support for the 'command' builtin, which allows
148 //config: you to run the specified command or builtin,
149 //config: even when there is a function with the same name.
151 //config:endif # ash options
153 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
154 // APPLET_ODDNAME:name main location suid_type help
155 //applet:IF_SH_IS_ASH( APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
156 //applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
158 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
159 //kbuild:lib-$(CONFIG_SH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
160 //kbuild:lib-$(CONFIG_BASH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
161 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
164 * DEBUG=1 to compile in debugging ('set -o debug' turns on)
165 * DEBUG=2 to compile in and turn on debugging.
166 * When debugging is on ("set -o debug" was executed, or DEBUG=2),
167 * debugging info is written to ./trace, quit signal generates core dump.
170 /* Tweak debug output verbosity here */
174 #define DEBUG_INTONOFF 0
178 #define JOBS ENABLE_ASH_JOB_CONTROL
181 #include <sys/times.h>
182 #include <sys/utsname.h> /* for setting $HOSTNAME */
183 #include "busybox.h" /* for applet_names */
184 #if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS
185 # include "embedded_scripts.h"
187 # define NUM_SCRIPTS 0
190 /* So far, all bash compat is controlled by one config option */
191 /* Separate defines document which part of code implements what */
192 /* function keyword */
193 #define BASH_FUNCTION ENABLE_ASH_BASH_COMPAT
194 #define IF_BASH_FUNCTION IF_ASH_BASH_COMPAT
196 #define BASH_REDIR_OUTPUT ENABLE_ASH_BASH_COMPAT
197 #define IF_BASH_REDIR_OUTPUT IF_ASH_BASH_COMPAT
199 #define BASH_DOLLAR_SQUOTE ENABLE_ASH_BASH_COMPAT
200 #define IF_BASH_DOLLAR_SQUOTE IF_ASH_BASH_COMPAT
201 #define BASH_PATTERN_SUBST ENABLE_ASH_BASH_COMPAT
202 #define IF_BASH_PATTERN_SUBST IF_ASH_BASH_COMPAT
203 #define BASH_SUBSTR ENABLE_ASH_BASH_COMPAT
204 #define IF_BASH_SUBSTR IF_ASH_BASH_COMPAT
205 /* BASH_TEST2: [[ EXPR ]]
206 * Status of [[ support:
207 * We replace && and || with -a and -o
209 * singleword+noglob expansion:
210 * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
211 * [[ /bin/n* ]]; echo 0:$?
212 * -a/-o are not AND/OR ops! (they are just strings)
213 * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
214 * = is glob match operator, not equality operator: STR = GLOB
215 * (in GLOB, quoting is significant on char-by-char basis: a*cd"*")
217 * add =~ regex match operator: STR =~ REGEX
219 #define BASH_TEST2 (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)
220 #define BASH_SOURCE ENABLE_ASH_BASH_COMPAT
221 #define BASH_PIPEFAIL ENABLE_ASH_BASH_COMPAT
222 #define BASH_HOSTNAME_VAR ENABLE_ASH_BASH_COMPAT
223 #define BASH_SHLVL_VAR ENABLE_ASH_BASH_COMPAT
224 #define BASH_XTRACEFD ENABLE_ASH_BASH_COMPAT
225 #define BASH_READ_D ENABLE_ASH_BASH_COMPAT
226 #define IF_BASH_READ_D IF_ASH_BASH_COMPAT
228 #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
229 /* Bionic at least up to version 24 has no glob() */
230 # undef ENABLE_ASH_INTERNAL_GLOB
231 # define ENABLE_ASH_INTERNAL_GLOB 1
234 #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
235 # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
236 # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
237 # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
238 # error glob() should unbackslash them and match. uClibc does not unbackslash,
239 # error fails to match dirname, subsequently not expanding <pattern> in it.
241 // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
242 // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
245 #if !ENABLE_ASH_INTERNAL_GLOB
250 #include "shell_common.h"
251 #if ENABLE_FEATURE_SH_MATH
254 typedef long arith_t;
255 # define ARITH_FMT "%ld"
257 #if ENABLE_ASH_RANDOM_SUPPORT
260 # define CLEAR_RANDOM_T(rnd) ((void)0)
263 #include "NUM_APPLETS.h"
265 /* STANDALONE does not make sense, and won't compile */
266 # undef CONFIG_FEATURE_SH_STANDALONE
267 # undef ENABLE_FEATURE_SH_STANDALONE
268 # undef IF_FEATURE_SH_STANDALONE
269 # undef IF_NOT_FEATURE_SH_STANDALONE
270 # define ENABLE_FEATURE_SH_STANDALONE 0
271 # define IF_FEATURE_SH_STANDALONE(...)
272 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
275 #ifndef F_DUPFD_CLOEXEC
276 # define F_DUPFD_CLOEXEC F_DUPFD
282 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
286 # error "Do not even bother, ash will not run on NOMMU machine"
289 /* We use a trick to have more optimized code (fewer pointer reloads):
290 * ash.c: extern struct globals *const ash_ptr_to_globals;
291 * ash_ptr_hack.c: struct globals *ash_ptr_to_globals;
292 * This way, compiler in ash.c knows the pointer can not change.
294 * However, this may break on weird arches or toolchains. In this case,
295 * set "-DBB_GLOBAL_CONST=''" in CONFIG_EXTRA_CFLAGS to disable
298 #ifndef BB_GLOBAL_CONST
299 # define BB_GLOBAL_CONST const
303 /* ============ Hash table sizes. Configurable. */
307 #define CMDTABLESIZE 31 /* should be prime */
310 /* ============ Shell options */
312 static const char *const optletters_optnames[] = {
336 #define optletters(n) optletters_optnames[n][0]
337 #define optnames(n) (optletters_optnames[n] + 1)
339 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
342 /* ============ Misc data */
344 #define msg_illnum "Illegal number: %s"
347 * We enclose jmp_buf in a structure so that we can declare pointers to
348 * jump locations. The global variable handler contains the location to
349 * jump to when an exception occurs, and the global variable exception_type
350 * contains a code identifying the exception. To implement nested
351 * exception handlers, the user should save the value of handler on entry
352 * to an inner scope, set handler to point to a jmploc structure for the
353 * inner scope, and restore handler on exit from the scope.
359 struct globals_misc {
360 uint8_t exitstatus; /* exit status of last command */
361 uint8_t back_exitstatus;/* exit status of backquoted command */
362 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
363 int rootpid; /* pid of main shell */
364 /* shell level: 0 for the main shell, 1 for its children, and so on */
366 #define rootshell (!shlvl)
369 char *minusc; /* argument to -c option */
371 char *curdir; // = nullstr; /* current working directory */
372 char *physdir; // = nullstr; /* physical working directory */
374 char *arg0; /* value of $0 */
376 struct jmploc *exception_handler;
378 volatile int suppress_int; /* counter */
379 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
380 volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
381 volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
382 smallint exception_type; /* kind of exception (0..5) */
384 #define EXINT 0 /* SIGINT received */
385 #define EXERROR 1 /* a generic error */
386 #define EXEXIT 4 /* exit the shell */
388 char nullstr[1]; /* zero length string */
391 #define eflag optlist[0]
392 #define fflag optlist[1]
393 #define Iflag optlist[2]
394 #define iflag optlist[3]
395 #define mflag optlist[4]
396 #define nflag optlist[5]
397 #define sflag optlist[6]
398 #define xflag optlist[7]
399 #define vflag optlist[8]
400 #define Cflag optlist[9]
401 #define aflag optlist[10]
402 #define bflag optlist[11]
403 #define uflag optlist[12]
404 #define viflag optlist[13]
406 # define pipefail optlist[14]
411 # define nolog optlist[14 + BASH_PIPEFAIL]
412 # define debug optlist[15 + BASH_PIPEFAIL]
415 /* trap handler commands */
417 * Sigmode records the current value of the signal handlers for the various
418 * modes. A value of zero means that the current handler is not known.
419 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
421 char sigmode[NSIG - 1];
422 #define S_DFL 1 /* default signal handling (SIG_DFL) */
423 #define S_CATCH 2 /* signal is caught */
424 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
425 #define S_HARD_IGN 4 /* signal is ignored permanently (it was SIG_IGN on entry to shell) */
427 /* indicates specified signal received */
428 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
429 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
431 char **trap_ptr; /* used only by "trap hack" */
433 /* Rarely referenced stuff */
434 #if ENABLE_ASH_RANDOM_SUPPORT
437 pid_t backgndpid; /* pid of last background process */
439 extern struct globals_misc *BB_GLOBAL_CONST ash_ptr_to_globals_misc;
440 #define G_misc (*ash_ptr_to_globals_misc)
441 #define exitstatus (G_misc.exitstatus )
442 #define back_exitstatus (G_misc.back_exitstatus )
443 #define job_warning (G_misc.job_warning)
444 #define rootpid (G_misc.rootpid )
445 #define shlvl (G_misc.shlvl )
446 #define errlinno (G_misc.errlinno )
447 #define minusc (G_misc.minusc )
448 #define curdir (G_misc.curdir )
449 #define physdir (G_misc.physdir )
450 #define arg0 (G_misc.arg0 )
451 #define exception_handler (G_misc.exception_handler)
452 #define exception_type (G_misc.exception_type )
453 #define suppress_int (G_misc.suppress_int )
454 #define pending_int (G_misc.pending_int )
455 #define got_sigchld (G_misc.got_sigchld )
456 #define pending_sig (G_misc.pending_sig )
457 #define nullstr (G_misc.nullstr )
458 #define optlist (G_misc.optlist )
459 #define sigmode (G_misc.sigmode )
460 #define gotsig (G_misc.gotsig )
461 #define may_have_traps (G_misc.may_have_traps )
462 #define trap (G_misc.trap )
463 #define trap_ptr (G_misc.trap_ptr )
464 #define random_gen (G_misc.random_gen )
465 #define backgndpid (G_misc.backgndpid )
466 #define INIT_G_misc() do { \
467 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
475 /* ============ DEBUG */
477 static void trace_printf(const char *fmt, ...);
478 static void trace_vprintf(const char *fmt, va_list va);
479 # define TRACE(param) trace_printf param
480 # define TRACEV(param) trace_vprintf param
481 # define close(fd) do { \
483 if (close(dfd) < 0) \
484 bb_error_msg("bug on %d: closing %d(0x%x)", \
485 __LINE__, dfd, dfd); \
488 # define TRACE(param)
489 # define TRACEV(param)
493 /* ============ Utility functions */
494 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
495 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
498 isdigit_str9(const char *str)
500 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
501 while (--maxlen && isdigit(*str))
503 return (*str == '\0');
507 var_end(const char *var)
516 /* ============ Interrupts / exceptions */
518 static void exitshell(void) NORETURN;
521 * These macros allow the user to suspend the handling of interrupt signals
522 * over a period of time. This is similar to SIGHOLD or to sigblock, but
523 * much more efficient and portable. (But hacking the kernel is so much
524 * more fun than worrying about efficiency and portability. :-))
527 # define INT_OFF do { \
528 TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
533 # define INT_OFF do { \
540 * Called to raise an exception. Since C doesn't include exceptions, we
541 * just do a longjmp to the exception handler. The type of exception is
542 * stored in the global variable "exception_type".
544 static void raise_exception(int) NORETURN;
546 raise_exception(int e)
549 if (exception_handler == NULL)
554 longjmp(exception_handler->loc, 1);
557 #define raise_exception(e) do { \
558 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
559 raise_exception(e); \
564 * Called when a SIGINT is received. (If the user specifies
565 * that SIGINT is to be trapped or ignored using the trap builtin, then
566 * this routine is not called.) Suppressint is nonzero when interrupts
567 * are held using the INT_OFF macro. (The test for iflag is just
568 * defensive programming.)
570 static void raise_interrupt(void) NORETURN;
572 raise_interrupt(void)
575 /* Signal is not automatically unmasked after it is raised,
576 * do it ourself - unmask all signals */
577 sigprocmask_allsigs(SIG_UNBLOCK);
578 /* pending_sig = 0; - now done in signal_handler() */
580 if (!(rootshell && iflag)) {
581 /* Kill ourself with SIGINT */
582 signal(SIGINT, SIG_DFL);
585 /* bash: ^C even on empty command line sets $? */
586 exitstatus = SIGINT + 128;
587 raise_exception(EXINT);
591 #define raise_interrupt() do { \
592 TRACE(("raising interrupt on line %d\n", __LINE__)); \
597 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
601 if (--suppress_int == 0 && pending_int) {
606 # define INT_ON do { \
607 TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
611 # define INT_ON int_on()
613 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
621 #define FORCE_INT_ON force_int_on()
623 #define SAVE_INT(v) ((v) = suppress_int)
625 #define RESTORE_INT(v) do { \
627 suppress_int = (v); \
628 if (suppress_int == 0 && pending_int) \
633 /* ============ Stdout/stderr output */
636 outstr(const char *p, FILE *file)
644 flush_stdout_stderr(void)
651 /* Was called outcslow(c,FILE*), but c was always '\n' */
653 newline_and_flush(FILE *dest)
661 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
663 out1fmt(const char *fmt, ...)
670 r = vprintf(fmt, ap);
676 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
678 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
685 ret = vsnprintf(outbuf, length, fmt, ap);
692 out1str(const char *p)
698 out2str(const char *p)
701 flush_stdout_stderr();
705 /* ============ Parser structures */
707 /* control characters in argument strings */
708 #define CTL_FIRST CTLESC
709 #define CTLESC ((unsigned char)'\201') /* escape next character */
710 #define CTLVAR ((unsigned char)'\202') /* variable defn */
711 #define CTLENDVAR ((unsigned char)'\203')
712 #define CTLBACKQ ((unsigned char)'\204')
713 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
714 #define CTLENDARI ((unsigned char)'\207')
715 #define CTLQUOTEMARK ((unsigned char)'\210')
716 #define CTL_LAST CTLQUOTEMARK
718 /* variable substitution byte (follows CTLVAR) */
719 #define VSTYPE 0x0f /* type of variable substitution */
720 #define VSNUL 0x10 /* colon--treat the empty string as unset */
722 /* values of VSTYPE field */
723 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
724 #define VSMINUS 0x2 /* ${var-text} */
725 #define VSPLUS 0x3 /* ${var+text} */
726 #define VSQUESTION 0x4 /* ${var?message} */
727 #define VSASSIGN 0x5 /* ${var=text} */
728 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
729 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
730 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
731 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
732 #define VSLENGTH 0xa /* ${#var} */
734 #define VSSUBSTR 0xc /* ${var:position:length} */
736 #if BASH_PATTERN_SUBST
737 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
738 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
741 static const char dolatstr[] ALIGN1 = {
742 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
744 #define DOLATSTRLEN 6
763 #if BASH_REDIR_OUTPUT
780 smallint type; /* Nxxxx */
784 union node *redirect;
789 smallint pipe_backgnd;
790 struct nodelist *cmdlist;
797 union node *redirect;
810 union node *elsepart;
846 struct nodelist *backquote;
849 /* nfile and ndup layout must match!
850 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
851 * that it is actually NTO2 (>&file), and change its type.
868 char *_unused_expfname;
887 struct nredir nredir;
888 struct nbinary nbinary;
892 struct nclist nclist;
893 struct ndefun ndefun;
902 * NODE_EOF is returned by parsecmd when it encounters an end of file.
903 * It must be distinct from NULL.
905 #define NODE_EOF ((union node *) -1L)
908 struct nodelist *next;
921 freefunc(struct funcnode *f)
923 if (f && --f->count < 0)
928 /* ============ Debugging output */
932 static FILE *tracefile;
935 trace_printf(const char *fmt, ...)
942 fprintf(tracefile, "%u ", (int) time(NULL));
944 fprintf(tracefile, "[%u] ", (int) getpid());
946 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
948 vfprintf(tracefile, fmt, va);
953 trace_vprintf(const char *fmt, va_list va)
957 vfprintf(tracefile, fmt, va);
958 fprintf(tracefile, "\n");
962 trace_puts(const char *s)
970 trace_puts_quoted(char *s)
977 putc('"', tracefile);
978 for (p = s; *p; p++) {
979 switch ((unsigned char)*p) {
980 case '\n': c = 'n'; goto backslash;
981 case '\t': c = 't'; goto backslash;
982 case '\r': c = 'r'; goto backslash;
983 case '\"': c = '\"'; goto backslash;
984 case '\\': c = '\\'; goto backslash;
985 case CTLESC: c = 'e'; goto backslash;
986 case CTLVAR: c = 'v'; goto backslash;
987 case CTLBACKQ: c = 'q'; goto backslash;
989 putc('\\', tracefile);
993 if (*p >= ' ' && *p <= '~')
996 putc('\\', tracefile);
997 putc((*p >> 6) & 03, tracefile);
998 putc((*p >> 3) & 07, tracefile);
999 putc(*p & 07, tracefile);
1004 putc('"', tracefile);
1008 trace_puts_args(char **ap)
1015 trace_puts_quoted(*ap);
1017 putc('\n', tracefile);
1020 putc(' ', tracefile);
1035 /* leave open because libedit might be using it */
1038 strcpy(s, "./trace");
1040 if (!freopen(s, "a", tracefile)) {
1041 fprintf(stderr, "Can't re-open %s\n", s);
1046 tracefile = fopen(s, "a");
1047 if (tracefile == NULL) {
1048 fprintf(stderr, "Can't open %s\n", s);
1054 flags = fcntl(fileno(tracefile), F_GETFL);
1056 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
1058 setlinebuf(tracefile);
1059 fputs("\nTracing started.\n", tracefile);
1063 indent(int amount, char *pfx, FILE *fp)
1067 for (i = 0; i < amount; i++) {
1068 if (pfx && i == amount - 1)
1074 /* little circular references here... */
1075 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
1078 sharg(union node *arg, FILE *fp)
1081 struct nodelist *bqlist;
1082 unsigned char subtype;
1084 if (arg->type != NARG) {
1085 out1fmt("<node type %d>\n", arg->type);
1088 bqlist = arg->narg.backquote;
1089 for (p = arg->narg.text; *p; p++) {
1090 switch ((unsigned char)*p) {
1099 if (subtype == VSLENGTH)
1107 if (subtype & VSNUL)
1110 switch (subtype & VSTYPE) {
1136 case VSTRIMRIGHTMAX:
1143 out1fmt("<subtype %d>", subtype);
1152 shtree(bqlist->n, -1, NULL, fp);
1163 shcmd(union node *cmd, FILE *fp)
1171 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1177 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1181 switch (np->nfile.type) {
1182 case NTO: s = ">>"+1; dftfd = 1; break;
1183 case NCLOBBER: s = ">|"; dftfd = 1; break;
1184 case NAPPEND: s = ">>"; dftfd = 1; break;
1185 #if BASH_REDIR_OUTPUT
1188 case NTOFD: s = ">&"; dftfd = 1; break;
1189 case NFROM: s = "<"; break;
1190 case NFROMFD: s = "<&"; break;
1191 case NFROMTO: s = "<>"; break;
1192 default: s = "*error*"; break;
1194 if (np->nfile.fd != dftfd)
1195 fprintf(fp, "%d", np->nfile.fd);
1197 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1198 fprintf(fp, "%d", np->ndup.dupfd);
1200 sharg(np->nfile.fname, fp);
1207 shtree(union node *n, int ind, char *pfx, FILE *fp)
1209 struct nodelist *lp;
1215 indent(ind, pfx, fp);
1217 if (n == NODE_EOF) {
1232 shtree(n->nbinary.ch1, ind, NULL, fp);
1235 shtree(n->nbinary.ch2, ind, NULL, fp);
1243 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1244 shtree(lp->n, 0, NULL, fp);
1248 if (n->npipe.pipe_backgnd)
1254 fprintf(fp, "<node type %d>", n->type);
1262 showtree(union node *n)
1264 trace_puts("showtree called\n");
1265 shtree(n, 1, NULL, stderr);
1271 /* ============ Parser data */
1274 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1277 struct strlist *next;
1284 struct strpush *prev; /* preceding string on stack */
1286 int prev_left_in_line;
1287 #if ENABLE_ASH_ALIAS
1288 struct alias *ap; /* if push was associated with an alias */
1290 char *string; /* remember the string since it may change */
1292 /* Remember last two characters for pungetc. */
1295 /* Number of outstanding calls to pungetc. */
1300 * The parsefile structure pointed to by the global variable parsefile
1301 * contains information about the current file being read.
1304 struct parsefile *prev; /* preceding file on stack */
1305 int linno; /* current line */
1306 int pf_fd; /* file descriptor (or -1 if string) */
1307 int left_in_line; /* number of chars left in this line */
1308 int left_in_buffer; /* number of chars left in this buffer past the line */
1309 char *next_to_pgetc; /* next char in buffer */
1310 char *buf; /* input buffer */
1311 struct strpush *strpush; /* for pushing strings at this level */
1312 struct strpush basestrpush; /* so pushing one is fast */
1314 /* Remember last two characters for pungetc. */
1317 /* Number of outstanding calls to pungetc. */
1321 static struct parsefile basepf; /* top level input file */
1322 static struct parsefile *g_parsefile = &basepf; /* current input file */
1323 static char *commandname; /* currently executing command */
1326 /* ============ Message printing */
1329 ash_vmsg(const char *msg, va_list ap)
1331 fprintf(stderr, "%s: ", arg0);
1333 if (strcmp(arg0, commandname))
1334 fprintf(stderr, "%s: ", commandname);
1335 if (!iflag || g_parsefile->pf_fd > 0)
1336 fprintf(stderr, "line %d: ", errlinno);
1338 vfprintf(stderr, msg, ap);
1339 newline_and_flush(stderr);
1343 * Exverror is called to raise the error exception. If the second argument
1344 * is not NULL then error prints an error message using printf style
1345 * formatting. It then raises the error exception.
1347 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1349 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1353 TRACE(("ash_vmsg_and_raise(%d):", cond));
1356 TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
1361 flush_stdout_stderr();
1362 raise_exception(cond);
1366 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1368 ash_msg_and_raise_error(const char *msg, ...)
1375 ash_vmsg_and_raise(EXERROR, msg, ap);
1381 * 'fmt' must be a string literal.
1383 #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": "STRERROR_FMT, ##__VA_ARGS__ STRERROR_ERRNO)
1385 static void raise_error_syntax(const char *) NORETURN;
1387 raise_error_syntax(const char *msg)
1389 errlinno = g_parsefile->linno;
1390 ash_msg_and_raise_error("syntax error: %s", msg);
1394 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1396 ash_msg_and_raise(int cond, const char *msg, ...)
1401 ash_vmsg_and_raise(cond, msg, ap);
1407 * error/warning routines for external builtins
1410 ash_msg(const char *fmt, ...)
1420 * Return a string describing an error. The returned string may be a
1421 * pointer to a static buffer that will be overwritten on the next call.
1422 * Action describes the operation that got the error.
1425 errmsg(int e, const char *em)
1427 if (e == ENOENT || e == ENOTDIR) {
1434 /* ============ Memory allocation */
1437 /* I consider these wrappers nearly useless:
1438 * ok, they return you to nearest exception handler, but
1439 * how much memory do you leak in the process, making
1440 * memory starvation worse?
1443 ckrealloc(void * p, size_t nbytes)
1445 p = realloc(p, nbytes);
1447 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1452 ckmalloc(size_t nbytes)
1454 return ckrealloc(NULL, nbytes);
1458 ckzalloc(size_t nbytes)
1460 return memset(ckmalloc(nbytes), 0, nbytes);
1464 ckstrdup(const char *s)
1466 char *p = strdup(s);
1468 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1472 /* Using bbox equivalents. They exit if out of memory */
1473 # define ckrealloc xrealloc
1474 # define ckmalloc xmalloc
1475 # define ckzalloc xzalloc
1476 # define ckstrdup xstrdup
1480 * It appears that grabstackstr() will barf with such alignments
1481 * because stalloc() will return a string allocated in a new stackblock.
1483 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1485 /* Most machines require the value returned from malloc to be aligned
1486 * in some way. The following macro will get this right
1487 * on many machines. */
1488 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1489 /* Minimum size of a block */
1490 MINSIZE = SHELL_ALIGN(504),
1493 struct stack_block {
1494 struct stack_block *prev;
1495 char space[MINSIZE];
1499 struct stack_block *stackp;
1505 struct globals_memstack {
1506 struct stack_block *g_stackp; // = &stackbase;
1507 char *g_stacknxt; // = stackbase.space;
1508 char *sstrend; // = stackbase.space + MINSIZE;
1509 size_t g_stacknleft; // = MINSIZE;
1510 struct stack_block stackbase;
1512 extern struct globals_memstack *BB_GLOBAL_CONST ash_ptr_to_globals_memstack;
1513 #define G_memstack (*ash_ptr_to_globals_memstack)
1514 #define g_stackp (G_memstack.g_stackp )
1515 #define g_stacknxt (G_memstack.g_stacknxt )
1516 #define sstrend (G_memstack.sstrend )
1517 #define g_stacknleft (G_memstack.g_stacknleft)
1518 #define stackbase (G_memstack.stackbase )
1519 #define INIT_G_memstack() do { \
1520 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1522 g_stackp = &stackbase; \
1523 g_stacknxt = stackbase.space; \
1524 g_stacknleft = MINSIZE; \
1525 sstrend = stackbase.space + MINSIZE; \
1529 #define stackblock() ((void *)g_stacknxt)
1530 #define stackblocksize() g_stacknleft
1533 * Parse trees for commands are allocated in lifo order, so we use a stack
1534 * to make this more efficient, and also to avoid all sorts of exception
1535 * handling code to handle interrupts in the middle of a parse.
1537 * The size 504 was chosen because the Ultrix malloc handles that size
1541 stalloc(size_t nbytes)
1546 aligned = SHELL_ALIGN(nbytes);
1547 if (aligned > g_stacknleft) {
1550 struct stack_block *sp;
1552 blocksize = aligned;
1553 if (blocksize < MINSIZE)
1554 blocksize = MINSIZE;
1555 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1556 if (len < blocksize)
1557 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1560 sp->prev = g_stackp;
1561 g_stacknxt = sp->space;
1562 g_stacknleft = blocksize;
1563 sstrend = g_stacknxt + blocksize;
1568 g_stacknxt += aligned;
1569 g_stacknleft -= aligned;
1574 stzalloc(size_t nbytes)
1576 return memset(stalloc(nbytes), 0, nbytes);
1583 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1584 write(STDERR_FILENO, "stunalloc\n", 10);
1588 g_stacknleft += g_stacknxt - (char *)p;
1593 * Like strdup but works with the ash stack.
1596 sstrdup(const char *p)
1598 size_t len = strlen(p) + 1;
1599 return memcpy(stalloc(len), p, len);
1602 static ALWAYS_INLINE void
1603 grabstackblock(size_t len)
1609 pushstackmark(struct stackmark *mark, size_t len)
1611 mark->stackp = g_stackp;
1612 mark->stacknxt = g_stacknxt;
1613 mark->stacknleft = g_stacknleft;
1614 grabstackblock(len);
1618 setstackmark(struct stackmark *mark)
1620 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1624 popstackmark(struct stackmark *mark)
1626 struct stack_block *sp;
1632 while (g_stackp != mark->stackp) {
1634 g_stackp = sp->prev;
1637 g_stacknxt = mark->stacknxt;
1638 g_stacknleft = mark->stacknleft;
1639 sstrend = mark->stacknxt + mark->stacknleft;
1644 * When the parser reads in a string, it wants to stick the string on the
1645 * stack and only adjust the stack pointer when it knows how big the
1646 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1647 * of space on top of the stack and stackblocklen returns the length of
1648 * this block. Growstackblock will grow this space by at least one byte,
1649 * possibly moving it (like realloc). Grabstackblock actually allocates the
1650 * part of the block that has been used.
1653 growstackblock(void)
1657 newlen = g_stacknleft * 2;
1658 if (newlen < g_stacknleft)
1659 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1663 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1664 struct stack_block *sp;
1665 struct stack_block *prevstackp;
1670 prevstackp = sp->prev;
1671 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1672 sp = ckrealloc(sp, grosslen);
1673 sp->prev = prevstackp;
1675 g_stacknxt = sp->space;
1676 g_stacknleft = newlen;
1677 sstrend = sp->space + newlen;
1680 char *oldspace = g_stacknxt;
1681 size_t oldlen = g_stacknleft;
1682 char *p = stalloc(newlen);
1684 /* free the space we just allocated */
1685 g_stacknxt = memcpy(p, oldspace, oldlen);
1686 g_stacknleft += newlen;
1691 * The following routines are somewhat easier to use than the above.
1692 * The user declares a variable of type STACKSTR, which may be declared
1693 * to be a register. The macro STARTSTACKSTR initializes things. Then
1694 * the user uses the macro STPUTC to add characters to the string. In
1695 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1696 * grown as necessary. When the user is done, she can just leave the
1697 * string there and refer to it using stackblock(). Or she can allocate
1698 * the space for it using grabstackstr(). If it is necessary to allow
1699 * someone else to use the stack temporarily and then continue to grow
1700 * the string, the user should use grabstack to allocate the space, and
1701 * then call ungrabstr(p) to return to the previous mode of operation.
1703 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1704 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1705 * is space for at least one character.
1710 size_t len = stackblocksize();
1712 return (char *)stackblock() + len;
1716 * Called from CHECKSTRSPACE.
1719 makestrspace(size_t newlen, char *p)
1721 size_t len = p - g_stacknxt;
1727 size = stackblocksize();
1729 if (nleft >= newlen)
1733 return (char *)stackblock() + len;
1737 stack_nputstr(const char *s, size_t n, char *p)
1739 p = makestrspace(n, p);
1740 p = (char *)mempcpy(p, s, n);
1745 stack_putstr(const char *s, char *p)
1747 return stack_nputstr(s, strlen(s), p);
1751 _STPUTC(int c, char *p)
1759 #define STARTSTACKSTR(p) ((p) = stackblock())
1760 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1761 #define CHECKSTRSPACE(n, p) do { \
1764 size_t m = sstrend - q; \
1766 (p) = makestrspace(l, q); \
1768 #define USTPUTC(c, p) (*(p)++ = (c))
1769 #define STACKSTRNUL(p) do { \
1770 if ((p) == sstrend) \
1771 (p) = growstackstr(); \
1774 #define STUNPUTC(p) (--(p))
1775 #define STTOPC(p) ((p)[-1])
1776 #define STADJUST(amount, p) ((p) += (amount))
1778 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1779 #define ungrabstackstr(s, p) stunalloc(s)
1780 #define stackstrend() ((void *)sstrend)
1783 /* ============ String helpers */
1786 * prefix -- see if pfx is a prefix of string.
1789 prefix(const char *string, const char *pfx)
1792 if (*pfx++ != *string++)
1795 return (char *) string;
1799 * Check for a valid number. This should be elsewhere.
1802 is_number(const char *p)
1807 } while (*++p != '\0');
1812 * Convert a string of digits to an integer, printing an error message on
1816 number(const char *s)
1819 ash_msg_and_raise_error(msg_illnum, s);
1824 * Produce a single quoted string suitable as input to the shell.
1825 * The return string is allocated on the stack.
1828 single_quote(const char *s)
1838 len = strchrnul(s, '\'') - s;
1840 q = p = makestrspace(len + 3, p);
1843 q = (char *)mempcpy(q, s, len);
1852 do len++; while (*++s == '\'');
1854 q = p = makestrspace(len + 3, p);
1857 q = (char *)mempcpy(q, s - len, len);
1865 return stackblock();
1869 * Produce a possibly single quoted string suitable as input to the shell.
1870 * If quoting was done, the return string is allocated on the stack,
1871 * otherwise a pointer to the original string is returned.
1874 maybe_single_quote(const char *s)
1879 /* Assuming ACSII */
1880 /* quote ctrl_chars space !"#$%&'()* */
1884 if (*p >= ';' && *p <= '?')
1893 /* quote {|}~ DEL and high bytes */
1896 /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
1897 /* TODO: maybe avoid quoting % */
1903 return single_quote(s);
1907 /* ============ nextopt */
1909 static char **argptr; /* argument list for builtin commands */
1910 static char *optionarg; /* set by nextopt (like getopt) */
1911 static char *optptr; /* used by nextopt */
1914 * XXX - should get rid of. Have all builtins use getopt(3).
1915 * The library getopt must have the BSD extension static variable
1916 * "optreset", otherwise it can't be used within the shell safely.
1918 * Standard option processing (a la getopt) for builtin routines.
1919 * The only argument that is passed to nextopt is the option string;
1920 * the other arguments are unnecessary. It returns the character,
1921 * or '\0' on end of input.
1924 nextopt(const char *optstring)
1931 if (p == NULL || *p == '\0') {
1932 /* We ate entire "-param", take next one */
1938 if (*++p == '\0') /* just "-" ? */
1941 if (LONE_DASH(p)) /* "--" ? */
1943 /* p => next "-param" */
1945 /* p => some option char in the middle of a "-param" */
1947 for (q = optstring; *q != c;) {
1949 ash_msg_and_raise_error("illegal option -%c", c);
1957 ash_msg_and_raise_error("no arg for -%c option", c);
1967 /* ============ Shell variables */
1970 int nparam; /* # of positional parameters (without $0) */
1971 #if ENABLE_ASH_GETOPTS
1972 int optind; /* next parameter to be processed by getopts */
1973 int optoff; /* used by getopts */
1975 unsigned char malloced; /* if parameter list dynamically allocated */
1976 char **p; /* parameter list */
1980 * Free the list of positional parameters.
1983 freeparam(volatile struct shparam *param)
1985 if (param->malloced) {
1987 ap = ap1 = param->p;
1994 #if ENABLE_ASH_GETOPTS
1995 static void FAST_FUNC getoptsreset(const char *value);
1999 struct var *next; /* next entry in hash list */
2000 int flags; /* flags are defined above */
2001 const char *var_text; /* name=value */
2002 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
2003 /* the variable gets set/unset */
2007 struct localvar *next; /* next local variable in list */
2008 struct var *vp; /* the variable that was made local */
2009 int flags; /* saved flags */
2010 const char *text; /* saved text */
2014 #define VEXPORT 0x01 /* variable is exported */
2015 #define VREADONLY 0x02 /* variable cannot be modified */
2016 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
2017 #define VTEXTFIXED 0x08 /* text is statically allocated */
2018 #define VSTACK 0x10 /* text is allocated on the stack */
2019 #define VUNSET 0x20 /* the variable is not set */
2020 #define VNOFUNC 0x40 /* don't call the callback function */
2021 #define VNOSET 0x80 /* do not set variable - just readonly test */
2022 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
2023 #if ENABLE_ASH_RANDOM_SUPPORT
2024 # define VDYNAMIC 0x200 /* dynamic variable */
2030 /* Need to be before varinit_data[] */
2031 #if ENABLE_LOCALE_SUPPORT
2032 static void FAST_FUNC
2033 change_lc_all(const char *value)
2035 if (value && *value != '\0')
2036 setlocale(LC_ALL, value);
2038 static void FAST_FUNC
2039 change_lc_ctype(const char *value)
2041 if (value && *value != '\0')
2042 setlocale(LC_CTYPE, value);
2046 static void chkmail(void);
2047 static void changemail(const char *var_value) FAST_FUNC;
2049 # define chkmail() ((void)0)
2051 static void changepath(const char *) FAST_FUNC;
2052 #if ENABLE_ASH_RANDOM_SUPPORT
2053 static void change_random(const char *) FAST_FUNC;
2056 static const struct {
2058 const char *var_text;
2059 void (*var_func)(const char *) FAST_FUNC;
2060 } varinit_data[] = {
2062 * Note: VEXPORT would not work correctly here for NOFORK applets:
2063 * some environment strings may be constant.
2065 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
2067 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
2068 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
2070 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
2071 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
2072 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
2073 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
2074 #if ENABLE_ASH_GETOPTS
2075 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
2077 { VSTRFIXED|VTEXTFIXED , NULL /* inited to linenovar */, NULL },
2078 #if ENABLE_ASH_RANDOM_SUPPORT
2079 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
2081 #if ENABLE_LOCALE_SUPPORT
2082 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
2083 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
2085 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
2086 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
2092 struct globals_var {
2093 struct shparam shellparam; /* $@ current positional parameters */
2094 struct redirtab *redirlist;
2095 int preverrout_fd; /* stderr fd: usually 2, unless redirect moved it */
2096 struct var *vartab[VTABSIZE];
2097 struct var varinit[ARRAY_SIZE(varinit_data)];
2099 char linenovar[sizeof("LINENO=") + sizeof(int)*3];
2101 extern struct globals_var *BB_GLOBAL_CONST ash_ptr_to_globals_var;
2102 #define G_var (*ash_ptr_to_globals_var)
2103 #define shellparam (G_var.shellparam )
2104 //#define redirlist (G_var.redirlist )
2105 #define preverrout_fd (G_var.preverrout_fd)
2106 #define vartab (G_var.vartab )
2107 #define varinit (G_var.varinit )
2108 #define lineno (G_var.lineno )
2109 #define linenovar (G_var.linenovar )
2110 #define vifs varinit[0]
2112 # define vmail (&vifs)[1]
2113 # define vmpath (&vmail)[1]
2114 # define vpath (&vmpath)[1]
2116 # define vpath (&vifs)[1]
2118 #define vps1 (&vpath)[1]
2119 #define vps2 (&vps1)[1]
2120 #define vps4 (&vps2)[1]
2121 #if ENABLE_ASH_GETOPTS
2122 # define voptind (&vps4)[1]
2123 # define vlineno (&voptind)[1]
2124 # if ENABLE_ASH_RANDOM_SUPPORT
2125 # define vrandom (&vlineno)[1]
2128 # define vlineno (&vps4)[1]
2129 # if ENABLE_ASH_RANDOM_SUPPORT
2130 # define vrandom (&vlineno)[1]
2133 #define INIT_G_var() do { \
2135 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
2137 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
2138 varinit[i].flags = varinit_data[i].flags; \
2139 varinit[i].var_text = varinit_data[i].var_text; \
2140 varinit[i].var_func = varinit_data[i].var_func; \
2142 strcpy(linenovar, "LINENO="); \
2143 vlineno.var_text = linenovar; \
2147 * The following macros access the values of the above variables.
2148 * They have to skip over the name. They return the null string
2149 * for unset variables.
2151 #define ifsval() (vifs.var_text + 4)
2152 #define ifsset() ((vifs.flags & VUNSET) == 0)
2154 # define mailval() (vmail.var_text + 5)
2155 # define mpathval() (vmpath.var_text + 9)
2156 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2158 #define pathval() (vpath.var_text + 5)
2159 #define ps1val() (vps1.var_text + 4)
2160 #define ps2val() (vps2.var_text + 4)
2161 #define ps4val() (vps4.var_text + 4)
2162 #if ENABLE_ASH_GETOPTS
2163 # define optindval() (voptind.var_text + 7)
2166 #if ENABLE_ASH_GETOPTS
2167 static void FAST_FUNC
2168 getoptsreset(const char *value)
2170 shellparam.optind = 1;
2171 if (is_number(value))
2172 shellparam.optind = number(value) ?: 1;
2173 shellparam.optoff = -1;
2178 * Compares two strings up to the first = or '\0'. The first
2179 * string must be terminated by '='; the second may be terminated by
2180 * either '=' or '\0'.
2183 varcmp(const char *p, const char *q)
2187 while ((c = *p) == (d = *q)) {
2188 if (c == '\0' || c == '=')
2202 * Find the appropriate entry in the hash table from the name.
2204 static struct var **
2205 hashvar(const char *p)
2209 hashval = ((unsigned char) *p) << 4;
2210 while (*p && *p != '=')
2211 hashval += (unsigned char) *p++;
2212 return &vartab[hashval % VTABSIZE];
2216 vpcmp(const void *a, const void *b)
2218 return varcmp(*(const char **)a, *(const char **)b);
2222 * This routine initializes the builtin variables.
2232 * PS1 depends on uid
2234 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2235 vps1.var_text = "PS1=\\w \\$ ";
2238 vps1.var_text = "PS1=# ";
2241 end = vp + ARRAY_SIZE(varinit);
2243 vpp = hashvar(vp->var_text);
2246 } while (++vp < end);
2249 static struct var **
2250 findvar(struct var **vpp, const char *name)
2252 for (; *vpp; vpp = &(*vpp)->next) {
2253 if (varcmp((*vpp)->var_text, name) == 0) {
2261 * Find the value of a variable. Returns NULL if not set.
2263 static const char* FAST_FUNC
2264 lookupvar(const char *name)
2268 v = *findvar(hashvar(name), name);
2270 #if ENABLE_ASH_RANDOM_SUPPORT
2272 * Dynamic variables are implemented roughly the same way they are
2273 * in bash. Namely, they're "special" so long as they aren't unset.
2274 * As soon as they're unset, they're no longer dynamic, and dynamic
2275 * lookup will no longer happen at that point. -- PFM.
2277 if (v->flags & VDYNAMIC)
2280 if (!(v->flags & VUNSET)) {
2281 if (v == &vlineno && v->var_text == linenovar) {
2282 fmtstr(linenovar+7, sizeof(linenovar)-7, "%d", lineno);
2284 return var_end(v->var_text);
2290 #if ENABLE_UNICODE_SUPPORT
2292 reinit_unicode_for_ash(void)
2294 /* Unicode support should be activated even if LANG is set
2295 * _during_ shell execution, not only if it was set when
2296 * shell was started. Therefore, re-check LANG every time:
2298 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2299 || ENABLE_UNICODE_USING_LOCALE
2301 const char *s = lookupvar("LC_ALL");
2302 if (!s) s = lookupvar("LC_CTYPE");
2303 if (!s) s = lookupvar("LANG");
2308 # define reinit_unicode_for_ash() ((void)0)
2312 * Search the environment of a builtin command.
2314 static ALWAYS_INLINE const char *
2315 bltinlookup(const char *name)
2317 return lookupvar(name);
2321 * Same as setvar except that the variable and value are passed in
2322 * the first argument as name=value. Since the first argument will
2323 * be actually stored in the table, it should not be a string that
2325 * Called with interrupts off.
2328 setvareq(char *s, int flags)
2330 struct var *vp, **vpp;
2333 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2334 vpp = findvar(vpp, s);
2337 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2340 if (flags & VNOSAVE)
2344 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2350 if (vp->var_func && !(flags & VNOFUNC))
2351 vp->var_func(var_end(s));
2353 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2354 free((char*)vp->var_text);
2356 if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
2360 if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
2365 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2367 /* variable s is not found */
2370 if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
2372 vp = ckzalloc(sizeof(*vp));
2374 /*vp->func = NULL; - ckzalloc did it */
2377 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2387 * Set the value of a variable. The flags argument is ored with the
2388 * flags of the variable. If val is NULL, the variable is unset.
2391 setvar(const char *name, const char *val, int flags)
2400 q = endofname(name);
2401 p = strchrnul(q, '=');
2403 if (!namelen || p != q)
2404 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2409 vallen = strlen(val);
2413 nameeq = ckzalloc(namelen + vallen + 2);
2414 p = mempcpy(nameeq, name, namelen);
2417 memcpy(p, val, vallen);
2419 vp = setvareq(nameeq, flags | VNOSAVE);
2425 static void FAST_FUNC
2426 setvar0(const char *name, const char *val)
2428 setvar(name, val, 0);
2432 * Unset the specified variable.
2435 unsetvar(const char *s)
2441 * Process a linked list of variable assignments.
2444 listsetvar(struct strlist *list_set_var, int flags)
2446 struct strlist *lp = list_set_var;
2452 setvareq(lp->text, flags);
2459 * Generate a list of variables satisfying the given conditions.
2461 #if !ENABLE_FEATURE_SH_NOFORK
2462 # define listvars(on, off, lp, end) listvars(on, off, end)
2465 listvars(int on, int off, struct strlist *lp, char ***end)
2476 for (vp = *vpp; vp; vp = vp->next) {
2477 if ((vp->flags & mask) == on) {
2478 #if ENABLE_FEATURE_SH_NOFORK
2479 /* If variable with the same name is both
2480 * exported and temporarily set for a command:
2483 * then "ZVAR=6" will be both in vartab and
2484 * lp lists. Do not pass it twice to printenv.
2486 struct strlist *lp1 = lp;
2488 if (strcmp(lp1->text, vp->var_text) == 0)
2493 if (ep == stackstrend())
2494 ep = growstackstr();
2495 *ep++ = (char*)vp->var_text;
2496 #if ENABLE_FEATURE_SH_NOFORK
2501 } while (++vpp < vartab + VTABSIZE);
2503 #if ENABLE_FEATURE_SH_NOFORK
2505 if (ep == stackstrend())
2506 ep = growstackstr();
2512 if (ep == stackstrend())
2513 ep = growstackstr();
2517 return grabstackstr(ep);
2521 /* ============ Path search helper
2523 * The variable path (passed by reference) should be set to the start
2524 * of the path before the first call; path_advance will update
2525 * this value as it proceeds. Successive calls to path_advance will return
2526 * the possible path expansions in sequence. If an option (indicated by
2527 * a percent sign) appears in the path entry then the global variable
2528 * pathopt will be set to point to it; otherwise pathopt will be set to
2531 static const char *pathopt; /* set by path_advance */
2534 path_advance(const char **path, const char *name)
2544 for (p = start; *p && *p != ':' && *p != '%'; p++)
2546 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2547 while (stackblocksize() < len)
2551 q = mempcpy(q, start, p - start);
2558 while (*p && *p != ':')
2565 return stalloc(len);
2569 /* ============ Prompt */
2571 static smallint doprompt; /* if set, prompt the user */
2572 static smallint needprompt; /* true if interactive and at start of line */
2574 #if ENABLE_FEATURE_EDITING
2575 static line_input_t *line_input_state;
2576 static const char *cmdedit_prompt;
2578 putprompt(const char *s)
2580 if (ENABLE_ASH_EXPAND_PRMT) {
2581 free((char*)cmdedit_prompt);
2582 cmdedit_prompt = ckstrdup(s);
2589 putprompt(const char *s)
2595 /* expandstr() needs parsing machinery, so it is far away ahead... */
2596 static const char *expandstr(const char *ps, int syntax_type);
2597 /* Values for syntax param */
2598 #define BASESYNTAX 0 /* not in quotes */
2599 #define DQSYNTAX 1 /* in double quotes */
2600 #define SQSYNTAX 2 /* in single quotes */
2601 #define ARISYNTAX 3 /* in arithmetic */
2602 #if ENABLE_ASH_EXPAND_PRMT
2603 # define PSSYNTAX 4 /* prompt. never passed to SIT() */
2605 /* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
2608 * called by editline -- any expansions to the prompt should be added here.
2611 setprompt_if(smallint do_set, int whichprompt)
2614 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2621 switch (whichprompt) {
2631 #if ENABLE_ASH_EXPAND_PRMT
2632 pushstackmark(&smark, stackblocksize());
2633 putprompt(expandstr(prompt, PSSYNTAX));
2634 popstackmark(&smark);
2641 /* ============ The cd and pwd commands */
2643 #define CD_PHYSICAL 1
2653 while ((i = nextopt("LP")) != '\0') {
2655 flags ^= CD_PHYSICAL;
2664 * Update curdir (the name of the current directory) in response to a
2668 updatepwd(const char *dir)
2675 cdcomppath = sstrdup(dir);
2678 if (curdir == nullstr)
2680 new = stack_putstr(curdir, new);
2682 new = makestrspace(strlen(dir) + 2, new);
2683 lim = (char *)stackblock() + 1;
2687 if (new > lim && *lim == '/')
2692 if (dir[1] == '/' && dir[2] != '/') {
2698 p = strtok(cdcomppath, "/");
2702 if (p[1] == '.' && p[2] == '\0') {
2714 new = stack_putstr(p, new);
2717 p = strtok(NULL, "/");
2722 return stackblock();
2726 * Find out what the current directory is. If we already know the current
2727 * directory, this routine returns immediately.
2732 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2733 return dir ? dir : nullstr;
2737 setpwd(const char *val, int setold)
2741 oldcur = dir = curdir;
2744 setvar("OLDPWD", oldcur, VEXPORT);
2747 if (physdir != nullstr) {
2748 if (physdir != oldcur)
2752 if (oldcur == val || !val) {
2758 dir = ckstrdup(val);
2759 if (oldcur != dir && oldcur != nullstr) {
2764 setvar("PWD", dir, VEXPORT);
2767 static void hashcd(void);
2770 * Actually do the chdir. We also call hashcd to let other routines
2771 * know that the current directory has changed.
2774 docd(const char *dest, int flags)
2776 const char *dir = NULL;
2779 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2782 if (!(flags & CD_PHYSICAL)) {
2783 dir = updatepwd(dest);
2797 static int FAST_FUNC
2798 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2810 dest = bltinlookup("HOME");
2811 else if (LONE_DASH(dest)) {
2812 dest = bltinlookup("OLDPWD");
2834 path = bltinlookup("CDPATH");
2837 p = path_advance(&path, dest);
2838 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2842 if (!docd(p, flags))
2853 ash_msg_and_raise_perror("can't cd to %s", dest);
2856 if (flags & CD_PRINT)
2857 out1fmt("%s\n", curdir);
2861 static int FAST_FUNC
2862 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2865 const char *dir = curdir;
2869 if (physdir == nullstr)
2873 out1fmt("%s\n", dir);
2878 /* ============ ... */
2881 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2883 /* Syntax classes */
2884 #define CWORD 0 /* character is nothing special */
2885 #define CNL 1 /* newline character */
2886 #define CBACK 2 /* a backslash character */
2887 #define CSQUOTE 3 /* single quote */
2888 #define CDQUOTE 4 /* double quote */
2889 #define CENDQUOTE 5 /* a terminating quote */
2890 #define CBQUOTE 6 /* backwards single quote */
2891 #define CVAR 7 /* a dollar sign */
2892 #define CENDVAR 8 /* a '}' character */
2893 #define CLP 9 /* a left paren in arithmetic */
2894 #define CRP 10 /* a right paren in arithmetic */
2895 #define CENDFILE 11 /* end of file */
2896 #define CCTL 12 /* like CWORD, except it must be escaped */
2897 #define CSPCL 13 /* these terminate a word */
2898 #define CIGN 14 /* character should be ignored */
2901 #if ENABLE_ASH_ALIAS
2905 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2907 #if ENABLE_FEATURE_SH_MATH
2908 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2910 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2912 static const uint16_t S_I_T[] ALIGN2 = {
2913 #if ENABLE_ASH_ALIAS
2914 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2916 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2917 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2918 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2919 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2920 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2921 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2922 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2923 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2924 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2925 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2926 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2927 #if !USE_SIT_FUNCTION
2928 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2929 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2930 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2934 /* Constants below must match table above */
2936 #if ENABLE_ASH_ALIAS
2937 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2939 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2940 CNL_CNL_CNL_CNL , /* 2 */
2941 CWORD_CCTL_CCTL_CWORD , /* 3 */
2942 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2943 CVAR_CVAR_CWORD_CVAR , /* 5 */
2944 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2945 CSPCL_CWORD_CWORD_CLP , /* 7 */
2946 CSPCL_CWORD_CWORD_CRP , /* 8 */
2947 CBACK_CBACK_CCTL_CBACK , /* 9 */
2948 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2949 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2950 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2951 CWORD_CWORD_CWORD_CWORD , /* 13 */
2952 CCTL_CCTL_CCTL_CCTL , /* 14 */
2955 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2956 * caller must ensure proper cast on it if c is *char_ptr!
2958 #if USE_SIT_FUNCTION
2961 SIT(int c, int syntax)
2963 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2964 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2966 * This causes '/' to be prepended with CTLESC in dquoted string,
2967 * making "./file"* treated incorrectly because we feed
2968 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2969 * The "homegrown" glob implementation is okay with that,
2970 * but glibc one isn't. With '/' always treated as CWORD,
2973 # if ENABLE_ASH_ALIAS
2974 static const uint8_t syntax_index_table[] ALIGN1 = {
2975 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2976 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2977 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2981 static const uint8_t syntax_index_table[] ALIGN1 = {
2982 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2983 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2984 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2993 # if ENABLE_ASH_ALIAS
2999 /* Cast is purely for paranoia here,
3000 * just in case someone passed signed char to us */
3001 if ((unsigned char)c >= CTL_FIRST
3002 && (unsigned char)c <= CTL_LAST
3006 s = strchrnul(spec_symbls, c);
3009 indx = syntax_index_table[s - spec_symbls];
3011 return (S_I_T[indx] >> (syntax*4)) & 0xf;
3014 #else /* !USE_SIT_FUNCTION */
3016 static const uint8_t syntax_index_table[] ALIGN1 = {
3017 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
3018 /* 0 */ CWORD_CWORD_CWORD_CWORD,
3019 /* 1 */ CWORD_CWORD_CWORD_CWORD,
3020 /* 2 */ CWORD_CWORD_CWORD_CWORD,
3021 /* 3 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 4 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 5 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 6 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 7 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 8 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
3028 /* 10 "\n" */ CNL_CNL_CNL_CNL,
3029 /* 11 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 12 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 13 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 14 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 15 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 16 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 17 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 18 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 19 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 20 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 21 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 22 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 23 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 24 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 25 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 26 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 27 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 28 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 29 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 30 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 31 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
3051 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
3052 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
3053 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
3054 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
3055 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
3056 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
3057 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
3058 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
3059 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
3060 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
3061 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
3062 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
3063 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
3064 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
3065 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
3066 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
3067 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
3068 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
3069 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
3070 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
3071 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
3072 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
3073 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
3074 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
3075 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
3076 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
3077 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
3078 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
3079 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
3080 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
3081 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
3082 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
3083 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
3084 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
3085 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
3086 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
3087 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
3088 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
3089 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
3090 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
3091 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
3092 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
3093 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
3094 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
3095 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
3096 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
3097 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
3098 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
3099 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
3100 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
3101 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
3102 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
3103 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
3104 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
3105 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
3106 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
3107 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
3108 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
3109 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
3110 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
3111 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
3112 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
3113 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
3114 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
3115 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
3116 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
3117 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
3118 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
3119 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
3120 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
3121 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
3122 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
3123 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
3124 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
3125 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
3126 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
3127 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
3128 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
3129 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
3130 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3131 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3132 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3133 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3134 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3135 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3136 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3137 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3138 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3139 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3140 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3141 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3142 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3143 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3144 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3145 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3146 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
3147 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
3148 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
3149 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
3150 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
3151 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
3152 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
3153 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3154 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3155 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3156 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3157 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3158 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3159 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3160 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3161 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3162 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3163 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3164 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3165 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3166 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3167 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3168 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3169 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3170 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3171 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3172 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3173 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3174 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3175 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3176 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3177 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3178 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3179 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3180 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3181 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3182 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3183 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3184 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3185 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3186 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3187 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3188 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3189 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3190 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3191 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3192 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3193 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3194 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3195 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3196 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3197 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3198 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3199 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3200 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3201 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3202 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3203 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3204 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3205 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3206 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3207 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3208 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3209 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3210 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3211 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3212 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3213 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3214 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3215 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3216 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3217 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3218 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3219 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3220 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3221 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3222 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3223 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3224 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3225 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3226 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3227 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3228 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3229 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3230 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3231 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3232 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3233 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3234 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3235 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3236 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3237 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3238 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3239 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3240 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3241 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3242 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3243 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3244 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3245 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3246 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3247 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3248 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3249 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3250 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3251 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3252 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3253 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3254 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3255 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3256 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3257 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3258 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3259 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3260 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3261 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3262 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3263 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3264 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3265 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3266 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3267 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3268 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3269 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3270 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3271 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3272 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3273 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3274 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3275 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3276 # if ENABLE_ASH_ALIAS
3277 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3282 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3283 #else /* debug version, caught one signed char bug */
3284 # define SIT(c, syntax) \
3286 if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
3287 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3288 if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
3289 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3290 ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
3294 #endif /* !USE_SIT_FUNCTION */
3297 /* ============ Alias handling */
3299 #if ENABLE_ASH_ALIAS
3301 #define ALIASINUSE 1
3312 static struct alias **atab; // [ATABSIZE];
3313 #define INIT_G_alias() do { \
3314 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3318 static struct alias **
3319 __lookupalias(const char *name)
3321 unsigned int hashval;
3328 ch = (unsigned char)*p;
3332 ch = (unsigned char)*++p;
3334 app = &atab[hashval % ATABSIZE];
3336 for (; *app; app = &(*app)->next) {
3337 if (strcmp(name, (*app)->name) == 0) {
3345 static struct alias *
3346 lookupalias(const char *name, int check)
3348 struct alias *ap = *__lookupalias(name);
3350 if (check && ap && (ap->flag & ALIASINUSE))
3355 static struct alias *
3356 freealias(struct alias *ap)
3360 if (ap->flag & ALIASINUSE) {
3361 ap->flag |= ALIASDEAD;
3373 setalias(const char *name, const char *val)
3375 struct alias *ap, **app;
3377 app = __lookupalias(name);
3381 if (!(ap->flag & ALIASINUSE)) {
3384 ap->val = ckstrdup(val);
3385 ap->flag &= ~ALIASDEAD;
3388 ap = ckzalloc(sizeof(struct alias));
3389 ap->name = ckstrdup(name);
3390 ap->val = ckstrdup(val);
3391 /*ap->flag = 0; - ckzalloc did it */
3392 /*ap->next = NULL;*/
3399 unalias(const char *name)
3403 app = __lookupalias(name);
3407 *app = freealias(*app);
3418 struct alias *ap, **app;
3422 for (i = 0; i < ATABSIZE; i++) {
3424 for (ap = *app; ap; ap = *app) {
3425 *app = freealias(*app);
3435 printalias(const struct alias *ap)
3437 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3441 * TODO - sort output
3443 static int FAST_FUNC
3444 aliascmd(int argc UNUSED_PARAM, char **argv)
3453 for (i = 0; i < ATABSIZE; i++) {
3454 for (ap = atab[i]; ap; ap = ap->next) {
3460 while ((n = *++argv) != NULL) {
3461 v = strchr(n+1, '=');
3462 if (v == NULL) { /* n+1: funny ksh stuff */
3463 ap = *__lookupalias(n);
3465 fprintf(stderr, "%s: %s not found\n", "alias", n);
3478 static int FAST_FUNC
3479 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3483 while (nextopt("a") != '\0') {
3487 for (i = 0; *argptr; argptr++) {
3488 if (unalias(*argptr)) {
3489 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3497 #endif /* ASH_ALIAS */
3500 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3503 #define FORK_NOJOB 2
3505 /* mode flags for showjob(s) */
3506 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3507 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3508 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3509 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3512 * A job structure contains information about a job. A job is either a
3513 * single process or a set of processes contained in a pipeline. In the
3514 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3518 pid_t ps_pid; /* process id */
3519 int ps_status; /* last process status from wait() */
3520 char *ps_cmd; /* text of command being run */
3524 struct procstat ps0; /* status of process */
3525 struct procstat *ps; /* status or processes when more than one */
3527 int stopstatus; /* status of a stopped job */
3529 unsigned nprocs; /* number of processes */
3531 #define JOBRUNNING 0 /* at least one proc running */
3532 #define JOBSTOPPED 1 /* all procs are stopped */
3533 #define JOBDONE 2 /* all procs are completed */
3537 sigint: 1, /* job was killed by SIGINT */
3538 jobctl: 1, /* job running under job control */
3540 waited: 1, /* true if this entry has been waited for */
3541 used: 1, /* true if this entry is in used */
3542 changed: 1; /* true if status has changed */
3543 struct job *prev_job; /* previous job */
3546 static struct job *makejob(/*union node *,*/ int);
3547 static int forkshell(struct job *, union node *, int);
3548 static int waitforjob(struct job *);
3551 enum { doing_jobctl = 0 };
3552 #define setjobctl(on) do {} while (0)
3554 static smallint doing_jobctl; //references:8
3555 static void setjobctl(int);
3562 ignoresig(int signo)
3564 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3565 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3566 /* No, need to do it */
3567 signal(signo, SIG_IGN);
3569 sigmode[signo - 1] = S_HARD_IGN;
3573 * Only one usage site - in setsignal()
3576 signal_handler(int signo)
3578 if (signo == SIGCHLD) {
3584 gotsig[signo - 1] = 1;
3585 pending_sig = signo;
3587 if (signo == SIGINT && !trap[SIGINT]) {
3588 if (!suppress_int) {
3590 raise_interrupt(); /* does not return */
3597 * Set the signal handler for the specified signal. The routine figures
3598 * out what it should be set to.
3601 setsignal(int signo)
3604 char cur_act, new_act;
3605 struct sigaction act;
3609 if (t != NULL) { /* trap for this sig is set */
3611 if (t[0] == '\0') /* trap is "": ignore this sig */
3615 if (rootshell && new_act == S_DFL) {
3618 if (iflag || minusc || sflag == 0)
3627 * "In all cases, bash ignores SIGQUIT. Non-builtin
3628 * commands run by bash have signal handlers
3629 * set to the values inherited by the shell
3630 * from its parent". */
3646 /* if !rootshell, we reset SIGQUIT to DFL,
3647 * whereas we have to restore it to what shell got on entry.
3648 * This is handled by the fact that if signal was IGNored on entry,
3649 * then cur_act is S_HARD_IGN and we never change its sigaction
3653 if (signo == SIGCHLD)
3656 t = &sigmode[signo - 1];
3659 /* current setting is not yet known */
3660 if (sigaction(signo, NULL, &act)) {
3661 /* pretend it worked; maybe we should give a warning,
3662 * but other shells don't. We don't alter sigmode,
3663 * so we retry every time.
3664 * btw, in Linux it never fails. --vda */
3667 if (act.sa_handler == SIG_IGN) {
3668 cur_act = S_HARD_IGN;
3670 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3672 cur_act = S_IGN; /* don't hard ignore these */
3675 if (act.sa_handler == SIG_DFL && new_act == S_DFL) {
3676 /* installing SIG_DFL over SIG_DFL is a no-op */
3677 /* saves one sigaction call in each "sh -c SCRIPT" invocation */
3682 if (cur_act == S_HARD_IGN || cur_act == new_act)
3687 act.sa_handler = SIG_DFL;
3690 act.sa_handler = signal_handler;
3693 act.sa_handler = SIG_IGN;
3696 /* flags and mask matter only if !DFL and !IGN, but we do it
3697 * for all cases for more deterministic behavior:
3699 act.sa_flags = 0; //TODO: why not SA_RESTART?
3700 sigfillset(&act.sa_mask);
3702 sigaction_set(signo, &act);
3705 /* mode flags for set_curjob */
3706 #define CUR_DELETE 2
3707 #define CUR_RUNNING 1
3708 #define CUR_STOPPED 0
3711 /* pgrp of shell on invocation */
3712 static int initialpgrp; //references:2
3713 static int ttyfd = -1; //5
3716 static struct job *jobtab; //5
3718 static unsigned njobs; //4
3720 static struct job *curjob; //lots
3721 /* number of presumed living untracked jobs */
3722 static int jobless; //4
3725 /* Bash has a feature: it restores termios after a successful wait for
3726 * a foreground job which had at least one stopped or sigkilled member.
3727 * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
3728 * properly restoring tty state. Should we do this too?
3729 * A reproducer: ^Z an interactive python:
3732 * Python 2.7.12 (...)
3734 * { python leaves tty in -icanon -echo state. We do survive that... }
3735 * [1]+ Stopped python
3736 * { ...however, next program (python #2) does not survive it well: }
3738 * Python 2.7.12 (...)
3739 * >>> Traceback (most recent call last):
3740 * { above, I typed "qwerty<CR>", but -echo state is still in effect }
3741 * File "<stdin>", line 1, in <module>
3742 * NameError: name 'qwerty' is not defined
3744 * The implementation below is modeled on bash code and seems to work.
3745 * However, I'm not sure we should do this. For one: what if I'd fg
3746 * the stopped python instead? It'll be confused by "restored" tty state.
3748 static struct termios shell_tty_info;
3752 if (rootshell && ttyfd >= 0)
3753 tcgetattr(ttyfd, &shell_tty_info);
3758 /* if (rootshell) - caller ensures this */
3760 tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
3763 job_signal_status(struct job *jp)
3767 struct procstat *ps = jp->ps;
3768 for (i = 0; i < jp->nprocs; i++) {
3769 status = ps[i].ps_status;
3770 if (WIFSIGNALED(status) || WIFSTOPPED(status))
3776 restore_tty_if_stopped_or_signaled(struct job *jp)
3778 //TODO: check what happens if we come from waitforjob() in expbackq()
3780 int s = job_signal_status(jp);
3781 if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
3786 # define get_tty_state() ((void)0)
3787 # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
3791 set_curjob(struct job *jp, unsigned mode)
3794 struct job **jpp, **curp;
3796 /* first remove from list */
3797 jpp = curp = &curjob;
3802 jpp = &jp1->prev_job;
3804 *jpp = jp1->prev_job;
3806 /* Then re-insert in correct position */
3814 /* job being deleted */
3817 /* newly created job or backgrounded job,
3818 * put after all stopped jobs.
3823 if (!jp1 || jp1->state != JOBSTOPPED)
3826 jpp = &jp1->prev_job;
3832 /* newly stopped job - becomes curjob */
3833 jp->prev_job = *jpp;
3841 jobno(const struct job *jp)
3843 return jp - jobtab + 1;
3848 * Convert a job name to a job structure.
3851 #define getjob(name, getctl) getjob(name)
3854 getjob(const char *name, int getctl)
3858 const char *err_msg = "%s: no such job";
3862 char *(*match)(const char *, const char *);
3877 if (c == '+' || c == '%') {
3879 err_msg = "No current job";
3885 err_msg = "No previous job";
3895 if (num > 0 && num <= njobs) {
3896 jp = jobtab + num - 1;
3911 if (match(jp->ps[0].ps_cmd, p)) {
3915 err_msg = "%s: ambiguous";
3925 err_msg = "job %s not created under job control";
3926 if (getctl && jp->jobctl == 0)
3931 ash_msg_and_raise_error(err_msg, name);
3935 * Mark a job structure as unused.
3938 freejob(struct job *jp)
3940 struct procstat *ps;
3944 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3945 if (ps->ps_cmd != nullstr)
3948 if (jp->ps != &jp->ps0)
3951 set_curjob(jp, CUR_DELETE);
3957 xtcsetpgrp(int fd, pid_t pgrp)
3959 if (tcsetpgrp(fd, pgrp))
3960 ash_msg_and_raise_perror("can't set tty process group");
3964 * Turn job control on and off.
3966 * Note: This code assumes that the third arg to ioctl is a character
3967 * pointer, which is true on Berkeley systems but not System V. Since
3968 * System V doesn't have job control yet, this isn't a problem now.
3970 * Called with interrupts off.
3978 if (on == doing_jobctl || rootshell == 0)
3982 ofd = fd = open(_PATH_TTY, O_RDWR);
3984 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3985 * That sometimes helps to acquire controlling tty.
3986 * Obviously, a workaround for bugs when someone
3987 * failed to provide a controlling tty to bash! :) */
3993 /* fd is a tty at this point */
3994 fd = fcntl(fd, F_DUPFD_CLOEXEC, 10);
3995 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
3998 goto out; /* F_DUPFD failed */
3999 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
4000 close_on_exec_on(fd);
4001 while (1) { /* while we are in the background */
4002 pgrp = tcgetpgrp(fd);
4005 ash_msg("can't access tty; job control turned off");
4009 if (pgrp == getpgrp())
4020 xtcsetpgrp(fd, pgrp);
4022 /* turning job control off */
4025 /* was xtcsetpgrp, but this can make exiting ash
4026 * loop forever if pty is already deleted */
4027 tcsetpgrp(fd, pgrp);
4041 static int FAST_FUNC
4042 killcmd(int argc, char **argv)
4044 if (argv[1] && strcmp(argv[1], "-l") != 0) {
4047 if (argv[i][0] == '%') {
4049 * "kill %N" - job kill
4050 * Converting to pgrp / pid kill
4056 jp = getjob(argv[i], 0);
4058 * In jobs started under job control, we signal
4059 * entire process group by kill -PGRP_ID.
4060 * This happens, f.e., in interactive shell.
4062 * Otherwise, we signal each child via
4063 * kill PID1 PID2 PID3.
4065 * sh -c 'sleep 1|sleep 1 & kill %1'
4066 * sh -c 'true|sleep 2 & sleep 1; kill %1'
4067 * sh -c 'true|sleep 1 & sleep 2; kill %1'
4069 n = jp->nprocs; /* can't be 0 (I hope) */
4072 dst = alloca(n * sizeof(int)*4);
4074 for (j = 0; j < n; j++) {
4075 struct procstat *ps = &jp->ps[j];
4076 /* Skip non-running and not-stopped members
4077 * (i.e. dead members) of the job
4079 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
4082 * kill_main has matching code to expect
4083 * leading space. Needed to not confuse
4084 * negative pids with "kill -SIGNAL_NO" syntax
4086 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
4090 } while (argv[++i]);
4092 return kill_main(argc, argv);
4096 showpipe(struct job *jp /*, FILE *out*/)
4098 struct procstat *ps;
4099 struct procstat *psend;
4101 psend = jp->ps + jp->nprocs;
4102 for (ps = jp->ps + 1; ps < psend; ps++)
4103 printf(" | %s", ps->ps_cmd);
4104 newline_and_flush(stdout);
4105 flush_stdout_stderr();
4110 restartjob(struct job *jp, int mode)
4112 struct procstat *ps;
4118 if (jp->state == JOBDONE)
4120 jp->state = JOBRUNNING;
4121 pgid = jp->ps[0].ps_pid;
4122 if (mode == FORK_FG) {
4124 xtcsetpgrp(ttyfd, pgid);
4126 killpg(pgid, SIGCONT);
4130 if (WIFSTOPPED(ps->ps_status)) {
4136 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
4141 static int FAST_FUNC
4142 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
4148 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
4152 jp = getjob(*argv, 1);
4153 if (mode == FORK_BG) {
4154 set_curjob(jp, CUR_RUNNING);
4155 printf("[%d] ", jobno(jp));
4157 out1str(jp->ps[0].ps_cmd);
4158 showpipe(jp /*, stdout*/);
4159 retval = restartjob(jp, mode);
4160 } while (*argv && *++argv);
4166 sprint_status48(char *s, int status, int sigonly)
4172 if (!WIFEXITED(status)) {
4174 if (WIFSTOPPED(status))
4175 st = WSTOPSIG(status);
4178 st = WTERMSIG(status);
4180 if (st == SIGINT || st == SIGPIPE)
4183 if (WIFSTOPPED(status))
4188 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
4189 col = fmtstr(s, 32, strsignal(st));
4190 if (WCOREDUMP(status)) {
4191 strcpy(s + col, " (core dumped)");
4192 col += sizeof(" (core dumped)")-1;
4194 } else if (!sigonly) {
4195 st = WEXITSTATUS(status);
4196 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
4203 wait_block_or_sig(int *status)
4210 /* Poll all children for changes in their state */
4212 /* if job control is active, accept stopped processes too */
4213 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
4215 break; /* Error (e.g. EINTR, ECHILD) or pid */
4217 /* Children exist, but none are ready. Sleep until interesting signal */
4220 sigprocmask2(SIG_SETMASK, &mask); /* mask is updated */
4221 while (!got_sigchld && !pending_sig)
4223 sigprocmask(SIG_SETMASK, &mask, NULL);
4224 #else /* unsafe: a signal can set pending_sig after check, but before pause() */
4225 while (!got_sigchld && !pending_sig)
4229 /* If it was SIGCHLD, poll children again */
4230 } while (got_sigchld);
4235 #define DOWAIT_NONBLOCK 0
4236 #define DOWAIT_BLOCK 1
4237 #define DOWAIT_BLOCK_OR_SIG 2
4240 dowait(int block, struct job *job)
4245 struct job *thisjob = NULL;
4247 TRACE(("dowait(0x%x) called\n", block));
4249 /* It's wrong to call waitpid() outside of INT_OFF region:
4250 * signal can arrive just after syscall return and handler can
4251 * longjmp away, losing stop/exit notification processing.
4252 * Thus, for "jobs" builtin, and for waiting for a fg job,
4253 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
4255 * However, for "wait" builtin it is wrong to simply call waitpid()
4256 * in INT_OFF region: "wait" needs to wait for any running job
4257 * to change state, but should exit on any trap too.
4258 * In INT_OFF region, a signal just before syscall entry can set
4259 * pending_sig variables, but we can't check them, and we would
4260 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
4262 * Because of this, we run inside INT_OFF, but use a special routine
4263 * which combines waitpid() and sigsuspend().
4264 * This is the reason why we need to have a handler for SIGCHLD:
4265 * SIG_DFL handler does not wake sigsuspend().
4268 if (block == DOWAIT_BLOCK_OR_SIG) {
4269 pid = wait_block_or_sig(&status);
4272 if (block == DOWAIT_NONBLOCK)
4273 wait_flags = WNOHANG;
4274 /* if job control is active, accept stopped processes too */
4276 wait_flags |= WUNTRACED;
4277 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4278 pid = waitpid(-1, &status, wait_flags);
4280 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4281 pid, status, errno, strerror(errno)));
4286 for (jp = curjob; jp; jp = jp->prev_job) {
4288 struct procstat *ps;
4289 struct procstat *psend;
4290 if (jp->state == JOBDONE)
4294 psend = ps + jp->nprocs;
4296 if (ps->ps_pid == pid) {
4297 TRACE(("Job %d: changing status of proc %d "
4298 "from 0x%x to 0x%x\n",
4299 jobno(jp), pid, ps->ps_status, status));
4300 ps->ps_status = status;
4303 if (ps->ps_status == -1)
4304 jobstate = JOBRUNNING;
4306 if (jobstate == JOBRUNNING)
4308 if (WIFSTOPPED(ps->ps_status)) {
4309 jp->stopstatus = ps->ps_status;
4310 jobstate = JOBSTOPPED;
4313 } while (++ps < psend);
4317 /* Found the job where one of its processes changed its state.
4318 * Is there at least one live and running process in this job? */
4319 if (jobstate != JOBRUNNING) {
4320 /* No. All live processes in the job are stopped
4321 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4323 thisjob->changed = 1;
4324 if (thisjob->state != jobstate) {
4325 TRACE(("Job %d: changing state from %d to %d\n",
4326 jobno(thisjob), thisjob->state, jobstate));
4327 thisjob->state = jobstate;
4329 if (jobstate == JOBSTOPPED)
4330 set_curjob(thisjob, CUR_STOPPED);
4336 /* The process wasn't found in job list */
4338 if (!WIFSTOPPED(status))
4344 if (thisjob && thisjob == job) {
4348 len = sprint_status48(s, status, 1);
4360 showjob(struct job *jp, int mode)
4362 struct procstat *ps;
4363 struct procstat *psend;
4366 char s[16 + 16 + 48];
4367 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4371 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4372 /* just output process (group) id of pipeline */
4373 fprintf(out, "%d\n", ps->ps_pid);
4377 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4382 else if (curjob && jp == curjob->prev_job)
4385 if (mode & SHOW_PIDS)
4386 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4388 psend = ps + jp->nprocs;
4390 if (jp->state == JOBRUNNING) {
4391 strcpy(s + col, "Running");
4392 col += sizeof("Running") - 1;
4394 int status = psend[-1].ps_status;
4395 if (jp->state == JOBSTOPPED)
4396 status = jp->stopstatus;
4397 col += sprint_status48(s + col, status, 0);
4399 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4401 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4402 * or prints several "PID | <cmdN>" lines,
4403 * depending on SHOW_PIDS bit.
4404 * We do not print status of individual processes
4405 * between PID and <cmdN>. bash does it, but not very well:
4406 * first line shows overall job status, not process status,
4407 * making it impossible to know 1st process status.
4411 /* for each process */
4414 if (mode & SHOW_PIDS)
4415 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4417 fprintf(out, "%s%*c%s%s",
4419 33 - col >= 0 ? 33 - col : 0, ' ',
4420 ps == jp->ps ? "" : "| ",
4423 } while (++ps != psend);
4424 newline_and_flush(out);
4428 if (jp->state == JOBDONE) {
4429 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4435 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4436 * statuses have changed since the last call to showjobs.
4443 TRACE(("showjobs(0x%x) called\n", mode));
4445 /* Handle all finished jobs */
4446 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4449 for (jp = curjob; jp; jp = jp->prev_job) {
4450 if (!(mode & SHOW_CHANGED) || jp->changed) {
4456 static int FAST_FUNC
4457 jobscmd(int argc UNUSED_PARAM, char **argv)
4462 while ((m = nextopt("lp")) != '\0') {
4466 mode |= SHOW_ONLY_PGID;
4472 showjob(getjob(*argv, 0), mode);
4482 /* Called only on finished or stopped jobs (no members are running) */
4484 getstatus(struct job *job)
4488 struct procstat *ps;
4490 /* Fetch last member's status */
4491 ps = job->ps + job->nprocs - 1;
4492 status = ps->ps_status;
4494 /* "set -o pipefail" mode: use last _nonzero_ status */
4495 while (status == 0 && --ps >= job->ps)
4496 status = ps->ps_status;
4499 retval = WEXITSTATUS(status);
4500 if (!WIFEXITED(status)) {
4502 retval = WSTOPSIG(status);
4503 if (!WIFSTOPPED(status))
4506 /* XXX: limits number of signals */
4507 retval = WTERMSIG(status);
4509 if (retval == SIGINT)
4515 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4516 jobno(job), job->nprocs, status, retval));
4520 static int FAST_FUNC
4521 waitcmd(int argc UNUSED_PARAM, char **argv)
4532 /* wait for all jobs */
4536 if (!jp) /* no running procs */
4538 if (jp->state == JOBRUNNING)
4544 * "When bash is waiting for an asynchronous command via
4545 * the wait builtin, the reception of a signal for which a trap
4546 * has been set will cause the wait builtin to return immediately
4547 * with an exit status greater than 128, immediately after which
4548 * the trap is executed."
4550 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4551 /* if child sends us a signal *and immediately exits*,
4552 * dowait() returns pid > 0. Check this case,
4553 * not "if (dowait() < 0)"!
4562 if (**argv != '%') {
4563 pid_t pid = number(*argv);
4568 if (job->ps[job->nprocs - 1].ps_pid == pid)
4570 job = job->prev_job;
4573 job = getjob(*argv, 0);
4575 /* loop until process terminated or stopped */
4576 while (job->state == JOBRUNNING) {
4577 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4582 retval = getstatus(job);
4589 retval = 128 + pending_sig;
4598 struct job *jp, *jq;
4600 len = njobs * sizeof(*jp);
4602 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4604 offset = (char *)jp - (char *)jq;
4606 /* Relocate pointers */
4609 jq = (struct job *)((char *)jq + l);
4613 #define joff(p) ((struct job *)((char *)(p) + l))
4614 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4615 if (joff(jp)->ps == &jq->ps0)
4616 jmove(joff(jp)->ps);
4617 if (joff(jp)->prev_job)
4618 jmove(joff(jp)->prev_job);
4628 jp = (struct job *)((char *)jp + len);
4632 } while (--jq >= jp);
4637 * Return a new job structure.
4638 * Called with interrupts off.
4641 makejob(/*union node *node,*/ int nprocs)
4646 for (i = njobs, jp = jobtab; ; jp++) {
4653 if (jp->state != JOBDONE || !jp->waited)
4662 memset(jp, 0, sizeof(*jp));
4664 /* jp->jobctl is a bitfield.
4665 * "jp->jobctl |= doing_jobctl" likely to give awful code */
4669 jp->prev_job = curjob;
4674 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4676 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4683 * Return a string identifying a command (to be printed by the
4686 static char *cmdnextc;
4689 cmdputs(const char *s)
4691 static const char vstype[VSTYPE + 1][3] = {
4692 "", "}", "-", "+", "?", "=",
4693 "%", "%%", "#", "##"
4694 IF_BASH_SUBSTR(, ":")
4695 IF_BASH_PATTERN_SUBST(, "/", "//")
4698 const char *p, *str;
4702 unsigned char subtype = 0;
4706 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4708 while ((c = *p++) != '\0') {
4716 if ((subtype & VSTYPE) == VSLENGTH)
4722 str = "\"}" + !(quoted & 1);
4729 #if ENABLE_FEATURE_SH_MATH
4744 if ((subtype & VSTYPE) != VSNORMAL)
4746 str = vstype[subtype & VSTYPE];
4747 if (subtype & VSNUL)
4756 /* These can only happen inside quotes */
4762 // [1]+ Done true ${\$} <<=== BUG: ${\$} is not a valid way to write $$ (${$} would be ok)
4773 while ((c = *str++) != '\0') {
4776 } /* while *p++ not NUL */
4779 USTPUTC('"', nextc);
4785 /* cmdtxt() and cmdlist() call each other */
4786 static void cmdtxt(union node *n);
4789 cmdlist(union node *np, int sep)
4791 for (; np; np = np->narg.next) {
4795 if (sep && np->narg.next)
4801 cmdtxt(union node *n)
4804 struct nodelist *lp;
4815 lp = n->npipe.cmdlist;
4833 cmdtxt(n->nbinary.ch1);
4849 cmdtxt(n->nif.test);
4851 if (n->nif.elsepart) {
4852 cmdtxt(n->nif.ifpart);
4854 n = n->nif.elsepart;
4872 cmdtxt(n->nbinary.ch1);
4882 cmdputs(n->nfor.var);
4884 cmdlist(n->nfor.args, 1);
4889 cmdputs(n->ndefun.text);
4893 cmdlist(n->ncmd.args, 1);
4894 cmdlist(n->ncmd.redirect, 0);
4907 cmdputs(n->ncase.expr->narg.text);
4909 for (np = n->ncase.cases; np; np = np->nclist.next) {
4910 cmdtxt(np->nclist.pattern);
4912 cmdtxt(np->nclist.body);
4926 #if BASH_REDIR_OUTPUT
4941 cmdputs(utoa(n->nfile.fd));
4943 if (n->type == NTOFD || n->type == NFROMFD) {
4944 if (n->ndup.dupfd >= 0)
4945 cmdputs(utoa(n->ndup.dupfd));
4956 commandtext(union node *n)
4960 STARTSTACKSTR(cmdnextc);
4962 name = stackblock();
4963 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4964 return ckstrdup(name);
4969 * Fork off a subshell. If we are doing job control, give the subshell its
4970 * own process group. Jp is a job structure that the job is to be added to.
4971 * N is the command that will be evaluated by the child. Both jp and n may
4972 * be NULL. The mode parameter can be one of the following:
4973 * FORK_FG - Fork off a foreground process.
4974 * FORK_BG - Fork off a background process.
4975 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4976 * process group even if job control is on.
4978 * When job control is turned off, background processes have their standard
4979 * input redirected to /dev/null (except for the second and later processes
4982 * Called with interrupts off.
4985 * Clear traps on a fork.
4993 for (tp = trap; tp < &trap[NSIG]; tp++) {
4994 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4995 if (trap_ptr == trap)
4997 /* else: it "belongs" to trap_ptr vector, don't free */
4999 if ((tp - trap) != 0)
5000 setsignal(tp - trap);
5007 /* Lives far away from here, needed for forkchild */
5008 static void closescript(void);
5010 /* Called after fork(), in child */
5011 /* jp and n are NULL when called by openhere() for heredoc support */
5012 static NOINLINE void
5013 forkchild(struct job *jp, union node *n, int mode)
5017 TRACE(("Child shell %d\n", getpid()));
5021 /* man bash: "Non-builtin commands run by bash have signal handlers
5022 * set to the values inherited by the shell from its parent".
5023 * Do we do it correctly? */
5027 if (mode == FORK_NOJOB /* is it `xxx` ? */
5028 && n && n->type == NCMD /* is it single cmd? */
5029 /* && n->ncmd.args->type == NARG - always true? */
5030 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
5031 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
5032 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
5034 TRACE(("Trap hack\n"));
5035 /* Awful hack for `trap` or $(trap).
5037 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
5038 * contains an example where "trap" is executed in a subshell:
5040 * save_traps=$(trap)
5042 * eval "$save_traps"
5044 * Standard does not say that "trap" in subshell shall print
5045 * parent shell's traps. It only says that its output
5046 * must have suitable form, but then, in the above example
5047 * (which is not supposed to be normative), it implies that.
5049 * bash (and probably other shell) does implement it
5050 * (traps are reset to defaults, but "trap" still shows them),
5051 * but as a result, "trap" logic is hopelessly messed up:
5054 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
5055 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
5056 * # true | trap <--- trap is in subshell - no output (ditto)
5057 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
5058 * trap -- 'echo Ho' SIGWINCH
5059 * # echo `(trap)` <--- in subshell in subshell - output
5060 * trap -- 'echo Ho' SIGWINCH
5061 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
5062 * trap -- 'echo Ho' SIGWINCH
5064 * The rules when to forget and when to not forget traps
5065 * get really complex and nonsensical.
5067 * Our solution: ONLY bare $(trap) or `trap` is special.
5069 /* Save trap handler strings for trap builtin to print */
5070 trap_ptr = xmemdup(trap, sizeof(trap));
5071 /* Fall through into clearing traps */
5075 /* do job control only in root shell */
5077 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
5080 if (jp->nprocs == 0)
5083 pgrp = jp->ps[0].ps_pid;
5084 /* this can fail because we are doing it in the parent also */
5086 if (mode == FORK_FG)
5087 xtcsetpgrp(ttyfd, pgrp);
5092 if (mode == FORK_BG) {
5093 /* man bash: "When job control is not in effect,
5094 * asynchronous commands ignore SIGINT and SIGQUIT" */
5097 if (jp->nprocs == 0) {
5099 if (open(bb_dev_null, O_RDONLY) != 0)
5100 ash_msg_and_raise_perror("can't open '%s'", bb_dev_null);
5104 if (iflag) { /* why if iflag only? */
5109 * "In all cases, bash ignores SIGQUIT. Non-builtin
5110 * commands run by bash have signal handlers
5111 * set to the values inherited by the shell
5113 * Take care of the second rule: */
5117 if (n && n->type == NCMD
5118 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
5120 TRACE(("Job hack\n"));
5121 /* "jobs": we do not want to clear job list for it,
5122 * instead we remove only _its_ own_ job from job list.
5123 * This makes "jobs .... | cat" more useful.
5129 for (jp = curjob; jp; jp = jp->prev_job)
5134 /* Called after fork(), in parent */
5136 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
5139 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
5141 TRACE(("In parent shell: child = %d\n", pid));
5143 /* jp is NULL when called by openhere() for heredoc support */
5144 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
5150 if (mode != FORK_NOJOB && jp->jobctl) {
5153 if (jp->nprocs == 0)
5156 pgrp = jp->ps[0].ps_pid;
5157 /* This can fail because we are doing it in the child also */
5161 if (mode == FORK_BG) {
5162 backgndpid = pid; /* set $! */
5163 set_curjob(jp, CUR_RUNNING);
5166 struct procstat *ps = &jp->ps[jp->nprocs++];
5169 ps->ps_cmd = nullstr;
5171 if (doing_jobctl && n)
5172 ps->ps_cmd = commandtext(n);
5177 /* jp and n are NULL when called by openhere() for heredoc support */
5179 forkshell(struct job *jp, union node *n, int mode)
5183 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
5186 TRACE(("Fork failed, errno=%d", errno));
5189 ash_msg_and_raise_perror("can't fork");
5192 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
5193 forkchild(jp, n, mode);
5195 forkparent(jp, n, mode, pid);
5201 * Wait for job to finish.
5203 * Under job control we have the problem that while a child process
5204 * is running interrupts generated by the user are sent to the child
5205 * but not to the shell. This means that an infinite loop started by
5206 * an interactive user may be hard to kill. With job control turned off,
5207 * an interactive user may place an interactive program inside a loop.
5208 * If the interactive program catches interrupts, the user doesn't want
5209 * these interrupts to also abort the loop. The approach we take here
5210 * is to have the shell ignore interrupt signals while waiting for a
5211 * foreground process to terminate, and then send itself an interrupt
5212 * signal if the child process was terminated by an interrupt signal.
5213 * Unfortunately, some programs want to do a bit of cleanup and then
5214 * exit on interrupt; unless these processes terminate themselves by
5215 * sending a signal to themselves (instead of calling exit) they will
5216 * confuse this approach.
5218 * Called with interrupts off.
5221 waitforjob(struct job *jp)
5225 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
5228 while (jp->state == JOBRUNNING) {
5229 /* In non-interactive shells, we _can_ get
5230 * a keyboard signal here and be EINTRed,
5231 * but we just loop back, waiting for command to complete.
5234 * "If bash is waiting for a command to complete and receives
5235 * a signal for which a trap has been set, the trap
5236 * will not be executed until the command completes."
5238 * Reality is that even if trap is not set, bash
5239 * will not act on the signal until command completes.
5240 * Try this. sleep5intoff.c:
5241 * #include <signal.h>
5242 * #include <unistd.h>
5245 * sigemptyset(&set);
5246 * sigaddset(&set, SIGINT);
5247 * sigaddset(&set, SIGQUIT);
5248 * sigprocmask(SIG_BLOCK, &set, NULL);
5252 * $ bash -c './sleep5intoff; echo hi'
5253 * ^C^C^C^C <--- pressing ^C once a second
5255 * $ bash -c './sleep5intoff; echo hi'
5256 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
5259 dowait(DOWAIT_BLOCK, jp);
5266 xtcsetpgrp(ttyfd, rootpid);
5267 restore_tty_if_stopped_or_signaled(jp);
5270 * This is truly gross.
5271 * If we're doing job control, then we did a TIOCSPGRP which
5272 * caused us (the shell) to no longer be in the controlling
5273 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
5274 * intuit from the subprocess exit status whether a SIGINT
5275 * occurred, and if so interrupt ourselves. Yuck. - mycroft
5277 if (jp->sigint) /* TODO: do the same with all signals */
5278 raise(SIGINT); /* ... by raise(jp->sig) instead? */
5280 if (jp->state == JOBDONE)
5287 * return 1 if there are stopped jobs, otherwise 0
5299 if (jp && jp->state == JOBSTOPPED) {
5300 out2str("You have stopped jobs.\n");
5310 * Code for dealing with input/output redirection.
5315 #define EMPTY -2 /* marks an unused slot in redirtab */
5316 #define CLOSED -1 /* marks a slot of previously-closed fd */
5319 * Handle here documents. Normally we fork off a process to write the
5320 * data to a pipe. If the document is short, we can stuff the data in
5321 * the pipe without forking.
5323 /* openhere needs this forward reference */
5324 static void expandhere(union node *arg, int fd);
5326 openhere(union node *redir)
5332 ash_msg_and_raise_perror("can't create pipe");
5333 if (redir->type == NHERE) {
5334 len = strlen(redir->nhere.doc->narg.text);
5335 if (len <= PIPE_BUF) {
5336 full_write(pip[1], redir->nhere.doc->narg.text, len);
5340 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5343 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5344 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5345 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5346 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5347 signal(SIGPIPE, SIG_DFL);
5348 if (redir->type == NHERE)
5349 full_write(pip[1], redir->nhere.doc->narg.text, len);
5351 expandhere(redir->nhere.doc, pip[1]);
5352 _exit(EXIT_SUCCESS);
5360 openredirect(union node *redir)
5366 switch (redir->nfile.type) {
5367 /* Can't happen, our single caller does this itself */
5373 return openhere(redir);
5376 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5377 * allocated space. Do it only when we know it is safe.
5379 fname = redir->nfile.expfname;
5381 switch (redir->nfile.type) {
5387 f = open(fname, O_RDONLY);
5392 f = open(fname, O_RDWR|O_CREAT, 0666);
5397 #if BASH_REDIR_OUTPUT
5400 /* Take care of noclobber mode. */
5402 if (stat(fname, &sb) < 0) {
5403 f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5406 } else if (!S_ISREG(sb.st_mode)) {
5407 f = open(fname, O_WRONLY, 0666);
5410 if (!fstat(f, &sb) && S_ISREG(sb.st_mode)) {
5423 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5428 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5436 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5438 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5442 * Copy a file descriptor to be >= 10. Throws exception on error.
5450 newfd = fcntl(from, F_DUPFD_CLOEXEC, 10);
5451 err = newfd < 0 ? errno : 0;
5454 ash_msg_and_raise_perror("%d", from);
5456 if (F_DUPFD_CLOEXEC == F_DUPFD)
5457 close_on_exec_on(newfd);
5463 dup2_or_raise(int from, int to)
5467 newfd = (from != to) ? dup2(from, to) : to;
5469 /* Happens when source fd is not open: try "echo >&99" */
5470 ash_msg_and_raise_perror("%d", from);
5475 dup_CLOEXEC(int fd, int avoid_fd)
5479 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
5481 if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
5482 close_on_exec_on(newfd);
5483 } else { /* newfd < 0 */
5492 xdup_CLOEXEC_and_close(int fd, int avoid_fd)
5496 newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
5502 /* fd was not open? */
5505 ash_msg_and_raise_perror("%d", newfd);
5507 if (F_DUPFD_CLOEXEC == F_DUPFD)
5508 close_on_exec_on(newfd);
5513 /* Struct def and variable are moved down to the first usage site */
5519 struct redirtab *next;
5521 struct squirrel two_fd[];
5523 #define redirlist (G_var.redirlist)
5526 add_squirrel_closed(struct redirtab *sq, int fd)
5533 for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
5534 /* If we collide with an already moved fd... */
5535 if (fd == sq->two_fd[i].orig_fd) {
5537 * "echo 3>FILE 3>&- 3>FILE"
5538 * "echo 3>&- 3>FILE"
5539 * No need for last redirect to insert
5540 * another "need to close 3" indicator.
5542 TRACE(("redirect_fd %d: already moved or closed\n", fd));
5546 TRACE(("redirect_fd %d: previous fd was closed\n", fd));
5547 sq->two_fd[i].orig_fd = fd;
5548 sq->two_fd[i].moved_to = CLOSED;
5552 save_fd_on_redirect(int fd, int avoid_fd, struct redirtab *sq)
5556 if (avoid_fd < 9) /* the important case here is that it can be -1 */
5561 /* Testcase: "ls -l /proc/$$/fd 10>&-" should work */
5562 ttyfd = xdup_CLOEXEC_and_close(ttyfd, avoid_fd);
5563 TRACE(("redirect_fd %d: matches ttyfd, moving it to %d\n", fd, ttyfd));
5564 return 1; /* "we closed fd" */
5567 /* Are we called from redirect(0)? E.g. redirect
5568 * in a forked child. No need to save fds,
5569 * we aren't going to use them anymore, ok to trash.
5574 /* If this one of script's fds? */
5576 struct parsefile *pf = g_parsefile;
5578 /* We skip fd == 0 case because of the following:
5579 * $ ash # running ash interactively
5581 * and in script.sh: "exec 9>&0".
5582 * Even though top-level pf_fd _is_ 0,
5583 * it's still ok to use it: "read" builtin uses it,
5584 * why should we cripple "exec" builtin?
5586 if (fd == pf->pf_fd) {
5587 pf->pf_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
5588 return 1; /* "we closed fd" */
5594 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
5596 /* First: do we collide with some already moved fds? */
5597 for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
5598 /* If we collide with an already moved fd... */
5599 if (fd == sq->two_fd[i].moved_to) {
5600 new_fd = dup_CLOEXEC(fd, avoid_fd);
5601 sq->two_fd[i].moved_to = new_fd;
5602 TRACE(("redirect_fd %d: already busy, moving to %d\n", fd, new_fd));
5603 if (new_fd < 0) /* what? */
5605 return 0; /* "we did not close fd" */
5607 if (fd == sq->two_fd[i].orig_fd) {
5608 /* Example: echo Hello >/dev/null 1>&2 */
5609 TRACE(("redirect_fd %d: already moved\n", fd));
5610 return 0; /* "we did not close fd" */
5614 /* If this fd is open, we move and remember it; if it's closed, new_fd = CLOSED (-1) */
5615 new_fd = dup_CLOEXEC(fd, avoid_fd);
5616 TRACE(("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, new_fd));
5620 /* new_fd = CLOSED; - already is -1 */
5622 sq->two_fd[i].moved_to = new_fd;
5623 sq->two_fd[i].orig_fd = fd;
5625 /* if we move stderr, let "set -x" code know */
5626 if (fd == preverrout_fd)
5627 preverrout_fd = new_fd;
5629 return 0; /* "we did not close fd" */
5633 internally_opened_fd(int fd, struct redirtab *sq)
5640 /* If this one of script's fds? */
5642 struct parsefile *pf = g_parsefile;
5644 if (fd == pf->pf_fd)
5650 if (sq) for (i = 0; i < sq->pair_count && sq->two_fd[i].orig_fd != EMPTY; i++) {
5651 if (fd == sq->two_fd[i].moved_to)
5658 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5659 * old file descriptors are stashed away so that the redirection can be
5660 * undone by calling popredir.
5662 /* flags passed to redirect */
5663 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5665 redirect(union node *redir, int flags)
5667 struct redirtab *sv;
5674 if (flags & REDIR_PUSH)
5682 fd = redir->nfile.fd;
5683 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5684 //bb_error_msg("doing %d > %d", fd, newfd);
5685 newfd = redir->ndup.dupfd;
5688 newfd = openredirect(redir); /* always >= 0 */
5690 /* open() gave us precisely the fd we wanted.
5691 * This means that this fd was not busy
5692 * (not opened to anywhere).
5693 * Remember to close it on restore:
5695 add_squirrel_closed(sv, fd);
5704 /* if "N>FILE": move newfd to fd */
5705 /* if "N>&M": dup newfd to fd */
5706 /* if "N>&-": close fd (newfd is -1) */
5708 IF_BASH_REDIR_OUTPUT(redirect_more:)
5710 closed = save_fd_on_redirect(fd, /*avoid:*/ newfd, sv);
5712 /* "N>&-" means "close me" */
5714 /* ^^^ optimization: saving may already
5715 * have closed it. If not... */
5719 /* if newfd is a script fd or saved fd, simulate EBADF */
5720 if (internally_opened_fd(newfd, sv)) {
5722 ash_msg_and_raise_perror("%d", newfd);
5724 dup2_or_raise(newfd, fd);
5725 if (close_fd >= 0) /* "N>FILE" or ">&FILE" or heredoc? */
5727 #if BASH_REDIR_OUTPUT
5728 if (redir->nfile.type == NTO2 && fd == 1) {
5729 /* ">&FILE". we already redirected to 1, now copy 1 to 2 */
5737 } while ((redir = redir->nfile.next) != NULL);
5740 //dash:#define REDIR_SAVEFD2 03 /* set preverrout */
5741 #define REDIR_SAVEFD2 0
5742 // dash has a bug: since REDIR_SAVEFD2=3 and REDIR_PUSH=1, this test
5743 // triggers for pure REDIR_PUSH too. Thus, this is done almost always,
5744 // not only for calls with flags containing REDIR_SAVEFD2.
5745 // We do this unconditionally (see save_fd_on_redirect()).
5746 //if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5747 // preverrout_fd = copied_fd2;
5751 redirectsafe(union node *redir, int flags)
5754 volatile int saveint;
5755 struct jmploc *volatile savehandler = exception_handler;
5756 struct jmploc jmploc;
5759 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5760 err = setjmp(jmploc.loc); /* was = setjmp(jmploc.loc) * 2; */
5762 exception_handler = &jmploc;
5763 redirect(redir, flags);
5765 exception_handler = savehandler;
5766 if (err && exception_type != EXERROR)
5767 longjmp(exception_handler->loc, 1);
5768 RESTORE_INT(saveint);
5772 static struct redirtab*
5773 pushredir(union node *redir)
5775 struct redirtab *sv;
5784 #if BASH_REDIR_OUTPUT
5785 if (redir->nfile.type == NTO2)
5788 redir = redir->nfile.next;
5791 sv = ckzalloc(sizeof(*sv) + i * sizeof(sv->two_fd[0]));
5794 sv->two_fd[i].orig_fd = sv->two_fd[i].moved_to = EMPTY;
5795 sv->next = redirlist;
5801 * Undo the effects of the last redirection.
5806 struct redirtab *rp;
5809 if (redirlist == NULL)
5813 for (i = 0; i < rp->pair_count; i++) {
5814 int fd = rp->two_fd[i].orig_fd;
5815 int copy = rp->two_fd[i].moved_to;
5816 if (copy == CLOSED) {
5821 if (copy != EMPTY) {
5824 dup2_or_raise(copy, fd);
5829 redirlist = rp->next;
5835 unwindredir(struct redirtab *stop)
5837 while (redirlist != stop)
5838 popredir(/*drop:*/ 0);
5842 /* ============ Routines to expand arguments to commands
5844 * We have to deal with backquotes, shell variables, and file metacharacters.
5847 #if ENABLE_FEATURE_SH_MATH
5849 ash_arith(const char *s)
5851 arith_state_t math_state;
5854 math_state.lookupvar = lookupvar;
5855 math_state.setvar = setvar0;
5856 //math_state.endofname = endofname;
5859 result = arith(&math_state, s);
5860 if (math_state.errmsg)
5861 ash_msg_and_raise_error(math_state.errmsg);
5868 # if ENABLE_FEATURE_SH_MATH
5869 static int substr_atoi(const char *s)
5871 arith_t t = ash_arith(s);
5872 if (sizeof(t) > sizeof(int)) {
5873 /* clamp very large or very large negative nums for ${v:N:M}:
5874 * else "${v:0:0x100000001}" would work as "${v:0:1}"
5884 # define substr_atoi(s) number(s)
5891 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5892 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5893 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5894 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5895 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5896 * POSIX says for this case:
5897 * Pathname expansion shall not be performed on the word by a
5898 * non-interactive shell; an interactive shell may perform it, but shall
5899 * do so only when the expansion would result in one word.
5900 * Currently, our code complies to the above rule by never globbing
5901 * redirection filenames.
5902 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5903 * (this means that on a typical Linux distro, bash almost always
5904 * performs globbing, and thus diverges from what we do).
5906 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5907 #define EXP_VARTILDE2 0x20 /* expand tildes after colons only */
5908 #define EXP_WORD 0x40 /* expand word in parameter expansion */
5909 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5913 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5914 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5915 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5916 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5918 /* Add CTLESC when necessary. */
5919 #define QUOTES_ESC (EXP_FULL | EXP_CASE)
5920 /* Do not skip NUL characters. */
5921 #define QUOTES_KEEPNUL EXP_TILDE
5924 * Structure specifying which parts of the string should be searched
5925 * for IFS characters.
5928 struct ifsregion *next; /* next region in list */
5929 int begoff; /* offset of start of region */
5930 int endoff; /* offset of end of region */
5931 int nulonly; /* search for nul bytes only */
5935 struct strlist *list;
5936 struct strlist **lastp;
5939 /* output of current string */
5940 static char *expdest;
5941 /* list of back quote expressions */
5942 static struct nodelist *argbackq;
5943 /* first struct in list of ifs regions */
5944 static struct ifsregion ifsfirst;
5945 /* last struct in list */
5946 static struct ifsregion *ifslastp;
5947 /* holds expanded arg list */
5948 static struct arglist exparg;
5952 * cvtnum() is used even if math support is off (to prepare $? values and such).
5959 /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
5960 len = sizeof(arith_t) * 3;
5961 /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
5962 if (sizeof(arith_t) < 4) len += 2;
5964 expdest = makestrspace(len, expdest);
5965 len = fmtstr(expdest, len, ARITH_FMT, num);
5966 STADJUST(len, expdest);
5971 * Break the argument string into pieces based upon IFS and add the
5972 * strings to the argument list. The regions of the string to be
5973 * searched for IFS characters have been stored by recordregion.
5976 ifsbreakup(char *string, struct arglist *arglist)
5978 struct ifsregion *ifsp;
5983 const char *ifs, *realifs;
5988 if (ifslastp != NULL) {
5991 realifs = ifsset() ? ifsval() : defifs;
5996 p = string + ifsp->begoff;
5998 nulonly = ifsp->nulonly;
5999 ifs = nulonly ? nullstr : realifs;
6001 while (p < string + ifsp->endoff) {
6003 if ((unsigned char)*p == CTLESC)
6005 if (!strchr(ifs, *p)) {
6009 if (!(afternul || nulonly))
6010 ifsspc = (strchr(defifs, *p) != NULL);
6011 /* Ignore IFS whitespace at start */
6012 if (q == start && ifsspc) {
6018 sp = stzalloc(sizeof(*sp));
6020 *arglist->lastp = sp;
6021 arglist->lastp = &sp->next;
6025 if (p >= string + ifsp->endoff) {
6029 if ((unsigned char)*p == CTLESC)
6031 if (strchr(ifs, *p) == NULL) {
6035 if (strchr(defifs, *p) == NULL) {
6050 } while (ifsp != NULL);
6059 sp = stzalloc(sizeof(*sp));
6061 *arglist->lastp = sp;
6062 arglist->lastp = &sp->next;
6068 struct ifsregion *p = ifsfirst.next;
6075 struct ifsregion *ifsp;
6080 ifsfirst.next = NULL;
6087 esclen(const char *start, const char *p)
6091 while (p > start && (unsigned char)*--p == CTLESC) {
6098 * Remove any CTLESC characters from a string.
6100 #if !BASH_PATTERN_SUBST
6101 #define rmescapes(str, flag, slash_position) \
6102 rmescapes(str, flag)
6105 rmescapes(char *str, int flag, int *slash_position)
6107 static const char qchars[] ALIGN1 = {
6108 IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
6111 unsigned protect_against_glob;
6114 p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash_position));
6120 if (flag & RMESCAPE_ALLOC) {
6121 size_t len = p - str;
6122 size_t fulllen = len + strlen(p) + 1;
6124 if (flag & RMESCAPE_GROW) {
6125 int strloc = str - (char *)stackblock();
6126 r = makestrspace(fulllen, expdest);
6127 /* p and str may be invalidated by makestrspace */
6128 str = (char *)stackblock() + strloc;
6130 } else if (flag & RMESCAPE_HEAP) {
6131 r = ckmalloc(fulllen);
6133 r = stalloc(fulllen);
6137 q = (char *)mempcpy(q, str, len);
6141 globbing = flag & RMESCAPE_GLOB;
6142 protect_against_glob = globbing;
6144 if ((unsigned char)*p == CTLQUOTEMARK) {
6145 // Note: protect_against_glob only affect whether
6146 // CTLESC,<ch> gets converted to <ch> or to \<ch>
6148 protect_against_glob = globbing;
6152 /* naked back slash */
6153 protect_against_glob = 0;
6156 if ((unsigned char)*p == CTLESC) {
6160 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
6162 if (protect_against_glob) {
6164 * We used to trust glob() and fnmatch() to eat
6165 * superfluous escapes (\z where z has no
6166 * special meaning anyway). But this causes
6167 * bugs such as string of one greek letter rho
6168 * (unicode-encoded as two bytes "cf,81")
6169 * getting encoded as "cf,CTLESC,81"
6170 * and here, converted to "cf,\,81" -
6171 * which does not go well with some flavors
6172 * of fnmatch() in unicode locales
6173 * (for example, glibc <= 2.22).
6175 * Lets add "\" only on the chars which need it.
6176 * Testcases for less obvious chars are shown.
6181 || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
6182 || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
6183 || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
6184 || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
6185 /* Some libc support [^negate], that's why "^" also needs love */
6186 || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
6192 #if BASH_PATTERN_SUBST
6193 else if (slash_position && p == str + *slash_position) {
6194 /* stop handling globbing */
6196 *slash_position = q - r;
6197 slash_position = NULL;
6200 protect_against_glob = globbing;
6205 if (flag & RMESCAPE_GROW) {
6207 STADJUST(q - r + 1, expdest);
6211 #define pmatch(a, b) !fnmatch((a), (b), 0)
6214 * Prepare a pattern for a expmeta (internal glob(3)) call.
6216 * Returns an stalloced string.
6219 preglob(const char *pattern, int flag)
6221 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB, NULL);
6225 * Put a string on the stack.
6228 memtodest(const char *p, size_t len, int syntax, int quotes)
6235 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
6238 unsigned char c = *p++;
6240 if (quotes & QUOTES_ESC) {
6241 int n = SIT(c, syntax);
6243 || (syntax != BASESYNTAX && n == CBACK)
6248 } else if (!(quotes & QUOTES_KEEPNUL))
6257 strtodest(const char *p, int syntax, int quotes)
6259 size_t len = strlen(p);
6260 memtodest(p, len, syntax, quotes);
6265 * Record the fact that we have to scan this region of the
6266 * string for IFS characters.
6269 recordregion(int start, int end, int nulonly)
6271 struct ifsregion *ifsp;
6273 if (ifslastp == NULL) {
6277 ifsp = ckzalloc(sizeof(*ifsp));
6278 /*ifsp->next = NULL; - ckzalloc did it */
6279 ifslastp->next = ifsp;
6283 ifslastp->begoff = start;
6284 ifslastp->endoff = end;
6285 ifslastp->nulonly = nulonly;
6289 removerecordregions(int endoff)
6291 if (ifslastp == NULL)
6294 if (ifsfirst.endoff > endoff) {
6295 while (ifsfirst.next) {
6296 struct ifsregion *ifsp;
6298 ifsp = ifsfirst.next->next;
6299 free(ifsfirst.next);
6300 ifsfirst.next = ifsp;
6303 if (ifsfirst.begoff > endoff) {
6306 ifslastp = &ifsfirst;
6307 ifsfirst.endoff = endoff;
6312 ifslastp = &ifsfirst;
6313 while (ifslastp->next && ifslastp->next->begoff < endoff)
6314 ifslastp = ifslastp->next;
6315 while (ifslastp->next) {
6316 struct ifsregion *ifsp;
6318 ifsp = ifslastp->next->next;
6319 free(ifslastp->next);
6320 ifslastp->next = ifsp;
6323 if (ifslastp->endoff > endoff)
6324 ifslastp->endoff = endoff;
6328 exptilde(char *startp, char *p, int flags)
6334 int quotes = flags & QUOTES_ESC;
6338 while ((c = *++p) != '\0') {
6345 if (flags & EXP_VARTILDE)
6355 if (*name == '\0') {
6356 home = lookupvar("HOME");
6358 pw = getpwnam(name);
6363 if (!home || !*home)
6366 strtodest(home, SQSYNTAX, quotes);
6374 * Execute a command inside back quotes. If it's a builtin command, we
6375 * want to save its output in a block obtained from malloc. Otherwise
6376 * we fork off a subprocess and get the output of the command via a pipe.
6377 * Should be called with interrupts off.
6379 struct backcmd { /* result of evalbackcmd */
6380 int fd; /* file descriptor to read from */
6381 int nleft; /* number of chars in buffer */
6382 char *buf; /* buffer */
6383 struct job *jp; /* job structure for command */
6386 /* These forward decls are needed to use "eval" code for backticks handling: */
6387 /* flags in argument to evaltree */
6388 #define EV_EXIT 01 /* exit after evaluating tree */
6389 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
6390 static int evaltree(union node *, int);
6392 /* An evaltree() which is known to never return.
6393 * Used to use an alias:
6394 * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
6395 * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
6397 static ALWAYS_INLINE NORETURN void
6398 evaltreenr(union node *n, int flags)
6401 bb_unreachable(abort());
6405 static void FAST_FUNC
6406 evalbackcmd(union node *n, struct backcmd *result)
6420 ash_msg_and_raise_perror("can't create pipe");
6421 jp = makejob(/*n,*/ 1);
6422 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6428 dup2_or_raise(pip[1], 1);
6431 /* TODO: eflag clearing makes the following not abort:
6432 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6433 * which is what bash does (unless it is in POSIX mode).
6434 * dash deleted "eflag = 0" line in the commit
6435 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6436 * [EVAL] Don't clear eflag in evalbackcmd
6437 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6441 evaltreenr(n, EV_EXIT);
6446 result->fd = pip[0];
6450 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6451 result->fd, result->buf, result->nleft, result->jp));
6455 * Expand stuff in backwards quotes.
6458 expbackq(union node *cmd, int flag)
6466 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6467 struct stackmark smark;
6470 startloc = expdest - (char *)stackblock();
6471 pushstackmark(&smark, startloc);
6472 evalbackcmd(cmd, &in);
6473 popstackmark(&smark);
6480 memtodest(p, i, syntax, flag & QUOTES_ESC);
6484 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6485 TRACE(("expbackq: read returns %d\n", i));
6494 back_exitstatus = waitforjob(in.jp);
6498 /* Eat all trailing newlines */
6500 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6504 if (!(flag & EXP_QUOTED))
6505 recordregion(startloc, dest - (char *)stackblock(), 0);
6506 TRACE(("evalbackq: size:%d:'%.*s'\n",
6507 (int)((dest - (char *)stackblock()) - startloc),
6508 (int)((dest - (char *)stackblock()) - startloc),
6509 stackblock() + startloc));
6512 #if ENABLE_FEATURE_SH_MATH
6514 * Expand arithmetic expression. Backup to start of expression,
6515 * evaluate, place result in (backed up) result, adjust string position.
6527 * This routine is slightly over-complicated for
6528 * efficiency. Next we scan backwards looking for the
6529 * start of arithmetic.
6531 start = stackblock();
6538 while ((unsigned char)*p != CTLARI) {
6542 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6547 esc = esclen(start, p);
6557 removerecordregions(begoff);
6561 if (flag & QUOTES_ESC)
6562 rmescapes(p + 1, 0, NULL);
6564 len = cvtnum(ash_arith(p + 1));
6566 if (!(flag & EXP_QUOTED))
6567 recordregion(begoff, begoff + len, 0);
6571 /* argstr needs it */
6572 static char *evalvar(char *p, int flags);
6575 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6576 * characters to allow for further processing. Otherwise treat
6577 * $@ like $* since no splitting will be performed.
6580 argstr(char *p, int flags)
6582 static const char spclchars[] ALIGN1 = {
6590 #if ENABLE_FEATURE_SH_MATH
6595 const char *reject = spclchars;
6596 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6601 if (!(flags & EXP_VARTILDE)) {
6603 } else if (flags & EXP_VARTILDE2) {
6608 if (flags & EXP_TILDE) {
6611 flags &= ~EXP_TILDE;
6615 p = exptilde(p, q, flags);
6618 startloc = expdest - (char *)stackblock();
6622 length += strcspn(p + length, reject);
6626 IF_FEATURE_SH_MATH(|| c == CTLENDARI)
6628 /* c == '=' || c == ':' || c == CTLENDARI */
6634 expdest = stack_nputstr(p, length, expdest);
6635 newloc = expdest - (char *)stackblock();
6636 if (breakall && !inquotes && newloc > startloc) {
6637 recordregion(startloc, newloc, 0);
6648 if (flags & EXP_VARTILDE2) {
6652 flags |= EXP_VARTILDE2;
6657 * sort of a hack - expand tildes in variable
6658 * assignments (after the first '=' and after ':'s).
6667 case CTLENDVAR: /* ??? */
6670 /* "$@" syntax adherence hack */
6671 if (!inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6672 p = evalvar(p + 1, flags | EXP_QUOTED) + 1;
6675 inquotes ^= EXP_QUOTED;
6677 if (flags & QUOTES_ESC) {
6688 TRACE(("argstr: evalvar('%s')\n", p));
6689 p = evalvar(p, flags | inquotes);
6690 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6693 expbackq(argbackq->n, flags | inquotes);
6694 argbackq = argbackq->next;
6696 #if ENABLE_FEATURE_SH_MATH
6699 expari(flags | inquotes);
6708 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6709 char *pattern, int quotes, int zero)
6718 const char *s = loc2;
6725 match = pmatch(pattern, s);
6730 if (quotes && (unsigned char)*loc == CTLESC)
6739 scanright(char *startp, char *rmesc, char *rmescend,
6740 char *pattern, int quotes, int match_at_start)
6742 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6743 int try2optimize = match_at_start;
6749 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6750 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6751 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6753 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6754 * and on each iteration they go back two/one char until they reach the beginning.
6755 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6757 /* TODO: document in what other circumstances we are called. */
6759 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6762 const char *s = loc2;
6763 if (match_at_start) {
6767 match = pmatch(pattern, s);
6768 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6772 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6774 /* Maybe we can optimize this:
6775 * if pattern ends with unescaped *, we can avoid checking
6776 * shorter strings: if "foo*" doesn't match "raw_value_of_v",
6777 * it won't match truncated "raw_value_of_" strings too.
6779 unsigned plen = strlen(pattern);
6780 /* Does it end with "*"? */
6781 if (plen != 0 && pattern[--plen] == '*') {
6782 /* "xxxx*" is not escaped */
6783 /* "xxx\*" is escaped */
6784 /* "xx\\*" is not escaped */
6785 /* "x\\\*" is escaped */
6787 while (plen != 0 && pattern[--plen] == '\\')
6790 break; /* ends with unescaped "*" */
6798 esc = esclen(startp, loc);
6809 static void varunset(const char *, const char *, const char *, int) NORETURN;
6811 varunset(const char *end, const char *var, const char *umsg, int varflags)
6817 msg = "parameter not set";
6819 if ((unsigned char)*end == CTLENDVAR) {
6820 if (varflags & VSNUL)
6826 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6830 subevalvar(char *p, char *varname, int strloc, int subtype,
6831 int startloc, int varflags, int flag)
6833 struct nodelist *saveargbackq = argbackq;
6834 int quotes = flag & QUOTES_ESC;
6837 char *rmesc, *rmescend;
6839 int amount, resetloc;
6841 IF_BASH_PATTERN_SUBST(int workloc;)
6842 IF_BASH_PATTERN_SUBST(int slash_pos;)
6843 IF_BASH_PATTERN_SUBST(char *repl;)
6845 char *(*scan)(char*, char*, char*, char*, int, int);
6847 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6848 // p, varname, strloc, subtype, startloc, varflags, quotes);
6850 #if BASH_PATTERN_SUBST
6851 /* For "${v/pattern/repl}", we must find the delimiter _before_
6852 * argstr() call expands possible variable references in pattern:
6853 * think about "v=a; a=a/; echo ${v/$a/r}" case.
6856 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6857 /* Find '/' and replace with NUL */
6859 /* The pattern can't be empty.
6860 * IOW: if the first char after "${v//" is a slash,
6861 * it does not terminate the pattern - it's the first char of the pattern:
6862 * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
6863 * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
6868 if (*repl == '\0') {
6876 /* Handle escaped slashes, e.g. "${v/\//_}" (they are CTLESC'ed by this point) */
6877 if ((unsigned char)*repl == CTLESC && repl[1])
6883 argstr_flags = EXP_TILDE;
6884 if (subtype != VSASSIGN
6885 && subtype != VSQUESTION
6887 && subtype != VSSUBSTR
6890 /* EXP_CASE keeps CTLESC's */
6891 argstr_flags = EXP_TILDE | EXP_CASE;
6893 argstr(p, argstr_flags);
6894 //bb_error_msg("str0:'%s'", (char *)stackblock() + strloc);
6895 #if BASH_PATTERN_SUBST
6898 slash_pos = expdest - ((char *)stackblock() + strloc);
6899 STPUTC('/', expdest);
6900 //bb_error_msg("repl+1:'%s'", repl + 1);
6901 argstr(repl + 1, EXP_TILDE); /* EXP_TILDE: echo "${v/x/~}" expands ~ ! */
6905 STPUTC('\0', expdest);
6906 argbackq = saveargbackq;
6907 startp = (char *)stackblock() + startloc;
6908 //bb_error_msg("str1:'%s'", (char *)stackblock() + strloc);
6912 setvar0(varname, startp);
6913 amount = startp - expdest;
6914 STADJUST(amount, expdest);
6918 varunset(p, varname, startp, varflags);
6923 int pos, len, orig_len;
6926 loc = str = stackblock() + strloc;
6928 /* Read POS in ${var:POS:LEN} */
6929 colon = strchr(loc, ':');
6930 if (colon) *colon = '\0';
6931 pos = substr_atoi(loc);
6932 if (colon) *colon = ':';
6934 /* Read LEN in ${var:POS:LEN} */
6935 len = str - startp - 1;
6936 /* *loc != '\0', guaranteed by parser */
6939 /* Adjust the length by the number of escapes */
6940 for (ptr = startp; ptr < (str - 1); ptr++) {
6941 if ((unsigned char)*ptr == CTLESC) {
6948 if (*loc++ == ':') {
6950 len = substr_atoi(loc);
6952 /* Skip POS in ${var:POS:LEN} */
6954 while (*loc && *loc != ':')
6957 len = substr_atoi(loc);
6960 /* ${VAR:$((-n)):l} starts n chars from the end */
6961 pos = orig_len + pos;
6963 if ((unsigned)pos >= orig_len) {
6964 /* apart from obvious ${VAR:999999:l},
6965 * covers ${VAR:$((-9999999)):l} - result is ""
6972 /* ${VAR:N:-M} sets LEN to strlen()-M */
6973 len = (orig_len - pos) + len;
6975 if ((unsigned)len > (orig_len - pos))
6976 len = orig_len - pos;
6978 for (str = startp; pos; str++, pos--) {
6979 if (quotes && (unsigned char)*str == CTLESC)
6982 for (loc = startp; len; len--) {
6983 if (quotes && (unsigned char)*str == CTLESC)
6988 amount = loc - expdest;
6989 STADJUST(amount, expdest);
6992 #endif /* BASH_SUBSTR */
6995 resetloc = expdest - (char *)stackblock();
6997 #if BASH_PATTERN_SUBST
7000 /* We'll comeback here if we grow the stack while handling
7001 * a VSREPLACE or VSREPLACEALL, since our pointers into the
7002 * stack will need rebasing, and we'll need to remove our work
7008 amount = expdest - ((char *)stackblock() + resetloc);
7009 STADJUST(-amount, expdest);
7010 startp = (char *)stackblock() + startloc;
7013 rmescend = (char *)stackblock() + strloc;
7014 //bb_error_msg("str7:'%s'", rmescend);
7016 //TODO: how to handle slash_pos here if string changes (shortens?)
7017 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW, NULL);
7018 if (rmesc != startp) {
7020 startp = (char *)stackblock() + startloc;
7024 str = (char *)stackblock() + strloc;
7026 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
7027 * The result is a_\_z_c (not a\_\_z_c)!
7029 * The search pattern and replace string treat backslashes differently!
7030 * "&slash_pos" causes rmescapes() to work differently on the pattern
7031 * and string. It's only used on the first call.
7033 //bb_error_msg("str8:'%s' slash_pos:%d", str, slash_pos);
7034 rmescapes(str, RMESCAPE_GLOB,
7035 repl ? NULL : (slash_pos < 0 ? NULL : &slash_pos)
7038 #if BASH_PATTERN_SUBST
7039 workloc = expdest - (char *)stackblock();
7040 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
7045 //bb_error_msg("str9:'%s' slash_pos:%d", str, slash_pos);
7047 if (slash_pos >= 0) {
7048 repl = str + slash_pos;
7052 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
7054 /* If there's no pattern to match, return the expansion unmolested */
7063 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
7064 //bb_error_msg("scanright('%s'):'%s'", str, loc);
7066 /* No match, advance */
7067 char *restart_detect = stackblock();
7069 STPUTC(*idx, expdest);
7070 if (quotes && (unsigned char)*idx == CTLESC) {
7073 STPUTC(*idx, expdest);
7075 if (stackblock() != restart_detect)
7080 /* continue; - prone to quadratic behavior, smarter code: */
7083 if (str[0] == '*') {
7084 /* Pattern is "*foo". If "*foo" does not match "long_string",
7085 * it would never match "ong_string" etc, no point in trying.
7092 if (subtype == VSREPLACEALL) {
7094 if (quotes && (unsigned char)*idx == CTLESC)
7103 //bb_error_msg("repl:'%s'", repl);
7104 for (loc = (char*)repl; *loc; loc++) {
7105 char *restart_detect = stackblock();
7106 if (quotes && *loc == '\\') {
7107 STPUTC(CTLESC, expdest);
7110 STPUTC(*loc, expdest);
7111 if (stackblock() != restart_detect)
7116 if (subtype == VSREPLACE) {
7117 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
7119 char *restart_detect = stackblock();
7120 STPUTC(*idx, expdest);
7121 if (stackblock() != restart_detect)
7130 /* We've put the replaced text into a buffer at workloc, now
7131 * move it to the right place and adjust the stack.
7133 STPUTC('\0', expdest);
7134 startp = (char *)stackblock() + startloc;
7135 memmove(startp, (char *)stackblock() + workloc, len + 1);
7136 //bb_error_msg("startp:'%s'", startp);
7137 amount = expdest - (startp + len);
7138 STADJUST(-amount, expdest);
7141 #endif /* BASH_PATTERN_SUBST */
7143 subtype -= VSTRIMRIGHT;
7145 if (subtype < 0 || subtype > 7)
7148 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
7149 zero = subtype >> 1;
7150 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
7151 scan = (subtype & 1) ^ zero ? scanleft : scanright;
7153 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
7156 memmove(startp, loc, str - loc);
7157 loc = startp + (str - loc) - 1;
7160 amount = loc - expdest;
7161 STADJUST(amount, expdest);
7167 * Add the value of a specialized variable to the stack string.
7168 * name parameter (examples):
7169 * ash -c 'echo $1' name:'1='
7170 * ash -c 'echo $qwe' name:'qwe='
7171 * ash -c 'echo $$' name:'$='
7172 * ash -c 'echo ${$}' name:'$='
7173 * ash -c 'echo ${$##q}' name:'$=q'
7174 * ash -c 'echo ${#$}' name:'$='
7175 * note: examples with bad shell syntax:
7176 * ash -c 'echo ${#$1}' name:'$=1'
7177 * ash -c 'echo ${#1#}' name:'1=#'
7179 static NOINLINE ssize_t
7180 varvalue(char *name, int varflags, int flags, int quoted)
7187 int subtype = varflags & VSTYPE;
7188 int discard = subtype == VSPLUS || subtype == VSLENGTH;
7189 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
7192 sep = (flags & EXP_FULL) << CHAR_BIT;
7193 syntax = quoted ? DQSYNTAX : BASESYNTAX;
7203 num = shellparam.nparam;
7211 goto check_1char_name;
7213 expdest = makestrspace(NOPTS, expdest);
7214 for (i = NOPTS - 1; i >= 0; i--) {
7215 if (optlist[i] && optletters(i)) {
7216 USTPUTC(optletters(i), expdest);
7222 /* handles cases similar to ${#$1} */
7223 if (name[2] != '\0')
7224 raise_error_syntax("bad substitution");
7236 /* We will set c to 0 or ~0 depending on whether
7237 * we're doing field splitting. We won't do field
7238 * splitting if either we're quoted or sep is zero.
7240 * Instead of testing (quoted || !sep) the following
7241 * trick optimises away any branches by using the
7242 * fact that EXP_QUOTED (which is the only bit that
7243 * can be set in quoted) is the same as EXP_FULL <<
7244 * CHAR_BIT (which is the only bit that can be set
7247 #if EXP_QUOTED >> CHAR_BIT != EXP_FULL
7248 #error The following two lines expect EXP_QUOTED == EXP_FULL << CHAR_BIT
7250 c = !((quoted | ~sep) & EXP_QUOTED) - 1;
7252 sep |= ifsset() ? (unsigned char)(c & ifsval()[0]) : ' ';
7258 while ((p = *ap++) != NULL) {
7259 len += strtodest(p, syntax, quotes);
7263 memtodest(&sepc, 1, syntax, quotes);
7278 num = atoi(name); /* number(name) fails on ${N#str} etc */
7279 if (num < 0 || num > shellparam.nparam)
7281 p = num ? shellparam.p[num - 1] : arg0;
7284 /* NB: name has form "VAR=..." */
7285 p = lookupvar(name);
7290 len = strtodest(p, syntax, quotes);
7291 #if ENABLE_UNICODE_SUPPORT
7292 if (subtype == VSLENGTH && len > 0) {
7293 reinit_unicode_for_ash();
7294 if (unicode_status == UNICODE_ON) {
7295 STADJUST(-len, expdest);
7297 len = unicode_strlen(p);
7305 STADJUST(-len, expdest);
7310 * Expand a variable, and return a pointer to the next character in the
7314 evalvar(char *p, int flag)
7324 varflags = (unsigned char) *p++;
7325 subtype = varflags & VSTYPE;
7328 raise_error_syntax("bad substitution");
7330 quoted = flag & EXP_QUOTED;
7332 startloc = expdest - (char *)stackblock();
7333 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
7336 varlen = varvalue(var, varflags, flag, quoted);
7337 if (varflags & VSNUL)
7340 if (subtype == VSPLUS) {
7341 varlen = -1 - varlen;
7345 if (subtype == VSMINUS) {
7350 flag | EXP_TILDE | EXP_WORD
7357 if (subtype == VSASSIGN || subtype == VSQUESTION) {
7361 subevalvar(p, var, 0, subtype, startloc, varflags,
7362 flag & ~QUOTES_ESC);
7365 * Remove any recorded regions beyond
7368 removerecordregions(startloc);
7372 if (varlen < 0 && uflag)
7373 varunset(p, var, 0, 0);
7375 if (subtype == VSLENGTH) {
7376 cvtnum(varlen > 0 ? varlen : 0);
7380 if (subtype == VSNORMAL) {
7383 quoted = *var == '@' && shellparam.nparam;
7387 recordregion(startloc, expdest - (char *)stackblock(), quoted);
7396 case VSTRIMRIGHTMAX:
7400 #if BASH_PATTERN_SUBST
7412 * Terminate the string and start recording the pattern
7415 STPUTC('\0', expdest);
7416 patloc = expdest - (char *)stackblock();
7417 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
7418 startloc, varflags, flag)) {
7419 int amount = expdest - (
7420 (char *)stackblock() + patloc - 1
7422 STADJUST(-amount, expdest);
7424 /* Remove any recorded regions beyond start of variable */
7425 removerecordregions(startloc);
7430 if (subtype != VSNORMAL) { /* skip to end of alternative */
7433 unsigned char c = *p++;
7436 else if (c == CTLBACKQ) {
7438 argbackq = argbackq->next;
7439 } else if (c == CTLVAR) {
7440 if ((*p++ & VSTYPE) != VSNORMAL)
7442 } else if (c == CTLENDVAR) {
7452 * Add a file name to the list.
7455 addfname(const char *name)
7459 sp = stzalloc(sizeof(*sp));
7460 sp->text = sstrdup(name);
7462 exparg.lastp = &sp->next;
7465 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7467 hasmeta(const char *p)
7469 static const char chars[] ALIGN1 = {
7470 '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
7474 p = strpbrk(p, chars);
7477 switch ((unsigned char)*p) {
7481 if ((unsigned char)*p == CTLQUOTEMARK)
7483 if ((unsigned char)*p == CTLESC)
7485 if (*p == '\0') /* huh? */
7496 if (!strchr(p + 1, ']')) {
7497 /* It's not a properly closed [] pattern,
7498 * but other metas may follow. Continue checking.
7499 * my[file* _is_ globbed by bash
7500 * and matches filenames like "my[file1".
7516 /* If we want to use glob() from libc... */
7517 #if !ENABLE_ASH_INTERNAL_GLOB
7519 /* Add the result of glob() to the list */
7521 addglob(const glob_t *pglob)
7523 char **p = pglob->gl_pathv;
7530 expandmeta(struct strlist *str /*, int flag*/)
7532 /* TODO - EXP_REDIR */
7542 if (!hasmeta(str->text))
7546 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7547 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7548 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7550 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7551 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7552 // Which means you need to unescape the string, right? Not so fast:
7553 // if there _is_ a file named "file\?" (with backslash), it is returned
7554 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7555 // You DON'T KNOW by looking at the result whether you need to unescape it.
7557 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7558 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7559 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7560 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7561 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7562 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7563 i = glob(p, 0, NULL, &pglob);
7564 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7569 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7570 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7571 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7583 *exparg.lastp = str;
7584 rmescapes(str->text, 0, NULL);
7585 exparg.lastp = &str->next;
7587 default: /* GLOB_NOSPACE */
7590 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7597 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7600 * Do metacharacter (i.e. *, ?, [...]) expansion.
7602 typedef struct exp_t {
7607 expmeta(exp_t *exp, char *name, unsigned name_len, unsigned expdir_len)
7609 #define expdir exp->dir
7610 #define expdir_max exp->dir_max
7611 char *enddir = expdir + expdir_len;
7626 for (p = name; esc = 0, *p; p += esc + 1) {
7627 if (*p == '*' || *p == '?')
7629 else if (*p == '[') {
7636 if (*q == '/' || *q == '\0')
7644 if (*p == '\\' && p[1])
7646 if (p[esc] == '/') {
7649 start = p + esc + 1;
7653 if (metaflag == 0) { /* we've reached the end of the file name */
7658 if (*p == '\\' && p[1])
7662 if (lstat(expdir, &statb) == 0)
7670 if (*p == '\\' && p[1])
7673 } while (p < start);
7677 expdir_len = enddir - cp;
7683 if (*endname == 0) {
7690 name_len -= endname - name;
7697 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7698 if (dp->d_name[0] == '.' && !matchdot)
7700 if (pmatch(start, dp->d_name)) {
7702 strcpy(enddir, dp->d_name);
7708 p = stpcpy(enddir, dp->d_name);
7711 offset = p - expdir + 1;
7712 len = offset + name_len + NAME_MAX;
7713 if (len > expdir_max) {
7715 expdir = ckrealloc(expdir, len);
7719 expmeta(exp, endname, name_len, offset);
7720 enddir = expdir + expdir_len;
7726 endname[-esc - 1] = esc ? '\\' : '/';
7731 static struct strlist *
7732 msort(struct strlist *list, int len)
7734 struct strlist *p, *q = NULL;
7735 struct strlist **lpp;
7743 for (n = half; --n >= 0;) {
7747 q->next = NULL; /* terminate first half of list */
7748 q = msort(list, half); /* sort first half of list */
7749 p = msort(p, len - half); /* sort second half */
7752 #if ENABLE_LOCALE_SUPPORT
7753 if (strcoll(p->text, q->text) < 0)
7755 if (strcmp(p->text, q->text) < 0)
7779 * Sort the results of file name expansion. It calculates the number of
7780 * strings to sort and then calls msort (short for merge sort) to do the
7783 static struct strlist *
7784 expsort(struct strlist *str)
7790 for (sp = str; sp; sp = sp->next)
7792 return msort(str, len);
7796 expandmeta(struct strlist *str /*, int flag*/)
7798 /* TODO - EXP_REDIR */
7802 struct strlist **savelastp;
7809 if (!hasmeta(str->text))
7811 savelastp = exparg.lastp;
7814 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7816 exp.dir_max = len + PATH_MAX;
7817 exp.dir = ckmalloc(exp.dir_max);
7819 expmeta(&exp, p, len, 0);
7824 if (exparg.lastp == savelastp) {
7829 *exparg.lastp = str;
7830 rmescapes(str->text, 0, NULL);
7831 exparg.lastp = &str->next;
7833 *exparg.lastp = NULL;
7834 *savelastp = sp = expsort(*savelastp);
7835 while (sp->next != NULL)
7837 exparg.lastp = &sp->next;
7842 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7845 * Perform variable substitution and command substitution on an argument,
7846 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7847 * perform splitting and file name expansion. When arglist is NULL, perform
7848 * here document expansion.
7851 expandarg(union node *arg, struct arglist *arglist, int flag)
7856 argbackq = arg->narg.backquote;
7857 STARTSTACKSTR(expdest);
7858 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7859 argstr(arg->narg.text, flag);
7860 p = _STPUTC('\0', expdest);
7862 if (arglist == NULL) {
7863 /* here document expanded */
7866 p = grabstackstr(p);
7867 TRACE(("expandarg: p:'%s'\n", p));
7868 exparg.lastp = &exparg.list;
7872 if (flag & EXP_FULL) {
7873 ifsbreakup(p, &exparg);
7874 *exparg.lastp = NULL;
7875 exparg.lastp = &exparg.list;
7876 expandmeta(exparg.list /*, flag*/);
7878 sp = stzalloc(sizeof(*sp));
7881 exparg.lastp = &sp->next;
7883 *exparg.lastp = NULL;
7885 *arglist->lastp = exparg.list;
7886 arglist->lastp = exparg.lastp;
7894 * Expand shell variables and backquotes inside a here document.
7897 expandhere(union node *arg, int fd)
7899 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7900 full_write(fd, stackblock(), expdest - (char *)stackblock());
7904 * Returns true if the pattern matches the string.
7907 patmatch(char *pattern, const char *string)
7909 char *p = preglob(pattern, 0);
7910 int r = pmatch(p, string);
7911 //bb_error_msg("!fnmatch(pattern:'%s',str:'%s',0):%d", p, string, r);
7916 * See if a pattern matches in a case statement.
7919 casematch(union node *pattern, char *val)
7921 struct stackmark smark;
7924 setstackmark(&smark);
7925 argbackq = pattern->narg.backquote;
7926 STARTSTACKSTR(expdest);
7927 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
7928 STACKSTRNUL(expdest);
7930 result = patmatch(stackblock(), val);
7931 popstackmark(&smark);
7936 /* ============ find_command */
7940 int (*builtin)(int, char **) FAST_FUNC;
7941 /* unsigned flags; */
7943 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7944 /* "regular" builtins always take precedence over commands,
7945 * regardless of PATH=....%builtin... position */
7946 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7947 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7950 smallint cmdtype; /* CMDxxx */
7953 /* index >= 0 for commands without path (slashes) */
7954 /* (TODO: what exactly does the value mean? PATH position?) */
7955 /* index == -1 for commands with slashes */
7956 /* index == (-2 - applet_no) for NOFORK applets */
7957 const struct builtincmd *cmd;
7958 struct funcnode *func;
7961 /* values of cmdtype */
7962 #define CMDUNKNOWN -1 /* no entry in table for command */
7963 #define CMDNORMAL 0 /* command is an executable program */
7964 #define CMDFUNCTION 1 /* command is a shell function */
7965 #define CMDBUILTIN 2 /* command is a shell builtin */
7967 /* action to find_command() */
7968 #define DO_ERR 0x01 /* prints errors */
7969 #define DO_ABS 0x02 /* checks absolute paths */
7970 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7971 #define DO_ALTPATH 0x08 /* using alternate path */
7972 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7974 static void find_command(char *, struct cmdentry *, int, const char *);
7977 /* ============ Hashing commands */
7980 * When commands are first encountered, they are entered in a hash table.
7981 * This ensures that a full path search will not have to be done for them
7982 * on each invocation.
7984 * We should investigate converting to a linear search, even though that
7985 * would make the command name "hash" a misnomer.
7989 struct tblentry *next; /* next entry in hash chain */
7990 union param param; /* definition of builtin function */
7991 smallint cmdtype; /* CMDxxx */
7992 char rehash; /* if set, cd done since entry created */
7993 char cmdname[1]; /* name of command */
7996 static struct tblentry **cmdtable;
7997 #define INIT_G_cmdtable() do { \
7998 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
8001 static int builtinloc = -1; /* index in path of %builtin, or -1 */
8005 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
8007 #if ENABLE_FEATURE_SH_STANDALONE
8008 if (applet_no >= 0) {
8009 if (APPLET_IS_NOEXEC(applet_no)) {
8013 popredir(/*drop:*/ 1);
8014 run_noexec_applet_and_exit(applet_no, cmd, argv);
8016 /* re-exec ourselves with the new arguments */
8017 execve(bb_busybox_exec_path, argv, envp);
8018 /* If they called chroot or otherwise made the binary no longer
8019 * executable, fall through */
8026 execve(cmd, argv, envp);
8027 } while (errno == EINTR);
8029 execve(cmd, argv, envp);
8032 if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
8033 /* Run "cmd" as a shell script:
8034 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
8035 * "If the execve() function fails with ENOEXEC, the shell
8036 * shall execute a command equivalent to having a shell invoked
8037 * with the command name as its first operand,
8038 * with any remaining arguments passed to the new shell"
8040 * That is, do not use $SHELL, user's shell, or /bin/sh;
8041 * just call ourselves.
8043 * Note that bash reads ~80 chars of the file, and if it sees
8044 * a zero byte before it sees newline, it doesn't try to
8045 * interpret it, but fails with "cannot execute binary file"
8046 * message and exit code 126. For one, this prevents attempts
8047 * to interpret foreign ELF binaries as shell scripts.
8049 argv[0] = (char*) cmd;
8050 cmd = bb_busybox_exec_path;
8051 /* NB: this is only possible because all callers of shellexec()
8052 * ensure that the argv[-1] slot exists!
8055 argv[0] = (char*) "ash";
8061 * Exec a program. Never returns. If you change this routine, you may
8062 * have to change the find_command routine as well.
8063 * argv[-1] must exist and be writable! See tryexec() for why.
8065 static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
8066 static void shellexec(char *prog, char **argv, const char *path, int idx)
8072 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
8074 envp = listvars(VEXPORT, VUNSET, /*strlist:*/ NULL, /*end:*/ NULL);
8075 if (strchr(prog, '/') != NULL
8076 #if ENABLE_FEATURE_SH_STANDALONE
8077 || (applet_no = find_applet_by_name(prog)) >= 0
8080 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
8081 if (applet_no >= 0) {
8082 /* We tried execing ourself, but it didn't work.
8083 * Maybe /proc/self/exe doesn't exist?
8092 while ((cmdname = path_advance(&path, prog)) != NULL) {
8093 if (--idx < 0 && pathopt == NULL) {
8094 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
8095 if (errno != ENOENT && errno != ENOTDIR)
8102 /* Map to POSIX errors */
8114 exitstatus = exerrno;
8115 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
8116 prog, e, suppress_int));
8117 ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
8122 printentry(struct tblentry *cmdp)
8128 idx = cmdp->param.index;
8131 name = path_advance(&path, cmdp->cmdname);
8133 } while (--idx >= 0);
8134 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
8138 * Clear out command entries. The argument specifies the first entry in
8139 * PATH which has changed.
8142 clearcmdentry(int firstchange)
8144 struct tblentry **tblp;
8145 struct tblentry **pp;
8146 struct tblentry *cmdp;
8149 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
8151 while ((cmdp = *pp) != NULL) {
8152 if ((cmdp->cmdtype == CMDNORMAL &&
8153 cmdp->param.index >= firstchange)
8154 || (cmdp->cmdtype == CMDBUILTIN &&
8155 builtinloc >= firstchange)
8168 * Locate a command in the command hash table. If "add" is nonzero,
8169 * add the command to the table if it is not already present. The
8170 * variable "lastcmdentry" is set to point to the address of the link
8171 * pointing to the entry, so that delete_cmd_entry can delete the
8174 * Interrupts must be off if called with add != 0.
8176 static struct tblentry **lastcmdentry;
8178 static struct tblentry *
8179 cmdlookup(const char *name, int add)
8181 unsigned int hashval;
8183 struct tblentry *cmdp;
8184 struct tblentry **pp;
8187 hashval = (unsigned char)*p << 4;
8189 hashval += (unsigned char)*p++;
8191 pp = &cmdtable[hashval % CMDTABLESIZE];
8192 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8193 if (strcmp(cmdp->cmdname, name) == 0)
8197 if (add && cmdp == NULL) {
8198 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
8200 /* + 1 - already done because
8201 * tblentry::cmdname is char[1] */);
8202 /*cmdp->next = NULL; - ckzalloc did it */
8203 cmdp->cmdtype = CMDUNKNOWN;
8204 strcpy(cmdp->cmdname, name);
8211 * Delete the command entry returned on the last lookup.
8214 delete_cmd_entry(void)
8216 struct tblentry *cmdp;
8219 cmdp = *lastcmdentry;
8220 *lastcmdentry = cmdp->next;
8221 if (cmdp->cmdtype == CMDFUNCTION)
8222 freefunc(cmdp->param.func);
8228 * Add a new command entry, replacing any existing command entry for
8229 * the same name - except special builtins.
8232 addcmdentry(char *name, struct cmdentry *entry)
8234 struct tblentry *cmdp;
8236 cmdp = cmdlookup(name, 1);
8237 if (cmdp->cmdtype == CMDFUNCTION) {
8238 freefunc(cmdp->param.func);
8240 cmdp->cmdtype = entry->cmdtype;
8241 cmdp->param = entry->u;
8245 static int FAST_FUNC
8246 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8248 struct tblentry **pp;
8249 struct tblentry *cmdp;
8251 struct cmdentry entry;
8254 if (nextopt("r") != '\0') {
8259 if (*argptr == NULL) {
8260 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8261 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8262 if (cmdp->cmdtype == CMDNORMAL)
8270 while ((name = *argptr) != NULL) {
8271 cmdp = cmdlookup(name, 0);
8273 && (cmdp->cmdtype == CMDNORMAL
8274 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
8278 find_command(name, &entry, DO_ERR, pathval());
8279 if (entry.cmdtype == CMDUNKNOWN)
8287 * Called when a cd is done. Marks all commands so the next time they
8288 * are executed they will be rehashed.
8293 struct tblentry **pp;
8294 struct tblentry *cmdp;
8296 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8297 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8298 if (cmdp->cmdtype == CMDNORMAL
8299 || (cmdp->cmdtype == CMDBUILTIN
8300 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
8310 * Fix command hash table when PATH changed.
8311 * Called before PATH is changed. The argument is the new value of PATH;
8312 * pathval() still returns the old value at this point.
8313 * Called with interrupts off.
8315 static void FAST_FUNC
8316 changepath(const char *new)
8324 firstchange = 9999; /* assume no change */
8330 if ((*old == '\0' && *new == ':')
8331 || (*old == ':' && *new == '\0')
8335 old = new; /* ignore subsequent differences */
8339 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
8346 if (builtinloc < 0 && idx_bltin >= 0)
8347 builtinloc = idx_bltin; /* zap builtins */
8348 if (builtinloc >= 0 && idx_bltin < 0)
8350 clearcmdentry(firstchange);
8351 builtinloc = idx_bltin;
8387 typedef smallint token_id_t;
8389 /* Nth bit indicates if token marks the end of a list */
8392 /* 0 */ | (1u << TEOF)
8393 /* 1 */ | (0u << TNL)
8394 /* 2 */ | (0u << TREDIR)
8395 /* 3 */ | (0u << TWORD)
8396 /* 4 */ | (0u << TSEMI)
8397 /* 5 */ | (0u << TBACKGND)
8398 /* 6 */ | (0u << TAND)
8399 /* 7 */ | (0u << TOR)
8400 /* 8 */ | (0u << TPIPE)
8401 /* 9 */ | (0u << TLP)
8402 /* 10 */ | (1u << TRP)
8403 /* 11 */ | (1u << TENDCASE)
8404 /* 12 */ | (1u << TENDBQUOTE)
8405 /* 13 */ | (0u << TNOT)
8406 /* 14 */ | (0u << TCASE)
8407 /* 15 */ | (1u << TDO)
8408 /* 16 */ | (1u << TDONE)
8409 /* 17 */ | (1u << TELIF)
8410 /* 18 */ | (1u << TELSE)
8411 /* 19 */ | (1u << TESAC)
8412 /* 20 */ | (1u << TFI)
8413 /* 21 */ | (0u << TFOR)
8415 /* 22 */ | (0u << TFUNCTION)
8417 /* 23 */ | (0u << TIF)
8418 /* 24 */ | (0u << TIN)
8419 /* 25 */ | (1u << TTHEN)
8420 /* 26 */ | (0u << TUNTIL)
8421 /* 27 */ | (0u << TWHILE)
8422 /* 28 */ | (0u << TBEGIN)
8423 /* 29 */ | (1u << TEND)
8424 , /* thus far 29 bits used */
8427 static const char *const tokname_array[] = {
8441 #define KWDOFFSET 13
8442 /* the following are keywords */
8464 /* Wrapper around strcmp for qsort/bsearch/... */
8466 pstrcmp(const void *a, const void *b)
8468 return strcmp((char*)a, *(char**)b);
8471 static const char *const *
8472 findkwd(const char *s)
8474 return bsearch(s, tokname_array + KWDOFFSET,
8475 ARRAY_SIZE(tokname_array) - KWDOFFSET,
8476 sizeof(tokname_array[0]), pstrcmp);
8480 * Locate and print what a word is...
8483 describe_command(char *command, const char *path, int describe_command_verbose)
8485 struct cmdentry entry;
8486 #if ENABLE_ASH_ALIAS
8487 const struct alias *ap;
8490 path = path ? path : pathval();
8492 if (describe_command_verbose) {
8496 /* First look at the keywords */
8497 if (findkwd(command)) {
8498 out1str(describe_command_verbose ? " is a shell keyword" : command);
8502 #if ENABLE_ASH_ALIAS
8503 /* Then look at the aliases */
8504 ap = lookupalias(command, 0);
8506 if (!describe_command_verbose) {
8511 out1fmt(" is an alias for %s", ap->val);
8516 find_command(command, &entry, DO_ABS, path);
8518 switch (entry.cmdtype) {
8520 int j = entry.u.index;
8526 p = path_advance(&path, command);
8530 if (describe_command_verbose) {
8531 out1fmt(" is %s", p);
8539 if (describe_command_verbose) {
8540 /*out1str(" is a shell function");*/
8541 out1str(" is a function"); /* bash says this */
8548 if (describe_command_verbose) {
8549 out1fmt(" is a %sshell builtin",
8550 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8551 "special " : nullstr
8559 if (describe_command_verbose) {
8560 out1str(": not found\n");
8569 static int FAST_FUNC
8570 typecmd(int argc UNUSED_PARAM, char **argv)
8576 /* type -p ... ? (we don't bother checking for 'p') */
8577 if (argv[1] && argv[1][0] == '-') {
8582 err |= describe_command(argv[i++], NULL, verbose);
8587 #if ENABLE_ASH_CMDCMD
8588 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8590 parse_command_args(char **argv, const char **path)
8603 if (c == '-' && !*cp) {
8611 *path = bb_default_path;
8614 /* run 'typecmd' for other options */
8623 static int FAST_FUNC
8624 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8632 const char *path = NULL;
8634 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8635 * never reaches this function.
8638 while ((c = nextopt("pvV")) != '\0')
8640 verify |= VERIFY_VERBOSE;
8642 /*verify |= VERIFY_BRIEF*/;
8648 path = bb_default_path;
8650 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8652 if (/*verify && */ cmd)
8653 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8660 /*static int funcblocksize; // size of structures in function */
8661 /*static int funcstringsize; // size of strings in node */
8662 static void *funcblock; /* block to allocate function from */
8663 static char *funcstring_end; /* end of block to allocate strings from */
8665 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8666 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8667 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8668 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8669 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8670 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8671 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8672 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8673 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8674 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8675 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8676 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8677 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8678 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8679 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8680 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8681 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8682 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8683 #if BASH_REDIR_OUTPUT
8684 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8686 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8687 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8688 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8689 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8690 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8691 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8692 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8693 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8694 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8697 static int calcsize(int funcblocksize, union node *n);
8700 sizenodelist(int funcblocksize, struct nodelist *lp)
8703 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8704 funcblocksize = calcsize(funcblocksize, lp->n);
8707 return funcblocksize;
8711 calcsize(int funcblocksize, union node *n)
8714 return funcblocksize;
8715 funcblocksize += nodesize[n->type];
8718 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8719 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8720 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8723 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8728 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8729 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8736 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8737 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8740 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8741 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8742 funcblocksize = calcsize(funcblocksize, n->nif.test);
8745 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8746 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8747 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8750 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8751 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8754 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8755 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8756 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8759 funcblocksize = calcsize(funcblocksize, n->ndefun.body);
8760 funcblocksize += SHELL_ALIGN(strlen(n->ndefun.text) + 1);
8763 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8764 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8765 funcblocksize = calcsize(funcblocksize, n->narg.next);
8768 #if BASH_REDIR_OUTPUT
8775 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8776 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8780 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8781 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8785 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8786 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8789 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8792 return funcblocksize;
8796 nodeckstrdup(char *s)
8798 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8799 return strcpy(funcstring_end, s);
8802 static union node *copynode(union node *);
8804 static struct nodelist *
8805 copynodelist(struct nodelist *lp)
8807 struct nodelist *start;
8808 struct nodelist **lpp;
8813 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8814 (*lpp)->n = copynode(lp->n);
8816 lpp = &(*lpp)->next;
8823 copynode(union node *n)
8830 funcblock = (char *) funcblock + nodesize[n->type];
8834 new->ncmd.redirect = copynode(n->ncmd.redirect);
8835 new->ncmd.args = copynode(n->ncmd.args);
8836 new->ncmd.assign = copynode(n->ncmd.assign);
8837 new->ncmd.linno = n->ncmd.linno;
8840 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8841 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8846 new->nredir.redirect = copynode(n->nredir.redirect);
8847 new->nredir.n = copynode(n->nredir.n);
8848 new->nredir.linno = n->nredir.linno;
8855 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8856 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8859 new->nif.elsepart = copynode(n->nif.elsepart);
8860 new->nif.ifpart = copynode(n->nif.ifpart);
8861 new->nif.test = copynode(n->nif.test);
8864 new->nfor.var = nodeckstrdup(n->nfor.var);
8865 new->nfor.body = copynode(n->nfor.body);
8866 new->nfor.args = copynode(n->nfor.args);
8867 new->nfor.linno = n->nfor.linno;
8870 new->ncase.cases = copynode(n->ncase.cases);
8871 new->ncase.expr = copynode(n->ncase.expr);
8872 new->ncase.linno = n->ncase.linno;
8875 new->nclist.body = copynode(n->nclist.body);
8876 new->nclist.pattern = copynode(n->nclist.pattern);
8877 new->nclist.next = copynode(n->nclist.next);
8880 new->ndefun.body = copynode(n->ndefun.body);
8881 new->ndefun.text = nodeckstrdup(n->ndefun.text);
8882 new->ndefun.linno = n->ndefun.linno;
8885 new->narg.backquote = copynodelist(n->narg.backquote);
8886 new->narg.text = nodeckstrdup(n->narg.text);
8887 new->narg.next = copynode(n->narg.next);
8890 #if BASH_REDIR_OUTPUT
8897 new->nfile.fname = copynode(n->nfile.fname);
8898 new->nfile.fd = n->nfile.fd;
8899 new->nfile.next = copynode(n->nfile.next);
8903 new->ndup.vname = copynode(n->ndup.vname);
8904 new->ndup.dupfd = n->ndup.dupfd;
8905 new->ndup.fd = n->ndup.fd;
8906 new->ndup.next = copynode(n->ndup.next);
8910 new->nhere.doc = copynode(n->nhere.doc);
8911 new->nhere.fd = n->nhere.fd;
8912 new->nhere.next = copynode(n->nhere.next);
8915 new->nnot.com = copynode(n->nnot.com);
8918 new->type = n->type;
8923 * Make a copy of a parse tree.
8925 static struct funcnode *
8926 copyfunc(union node *n)
8931 /*funcstringsize = 0;*/
8932 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8933 f = ckzalloc(blocksize /* + funcstringsize */);
8934 funcblock = (char *) f + offsetof(struct funcnode, n);
8935 funcstring_end = (char *) f + blocksize;
8937 /* f->count = 0; - ckzalloc did it */
8942 * Define a shell function.
8945 defun(union node *func)
8947 struct cmdentry entry;
8950 entry.cmdtype = CMDFUNCTION;
8951 entry.u.func = copyfunc(func);
8952 addcmdentry(func->ndefun.text, &entry);
8956 /* Reasons for skipping commands (see comment on breakcmd routine) */
8957 #define SKIPBREAK (1 << 0)
8958 #define SKIPCONT (1 << 1)
8959 #define SKIPFUNC (1 << 2)
8960 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8961 static int skipcount; /* number of levels to skip */
8962 static int loopnest; /* current loop nesting level */
8963 static int funcline; /* starting line number of current function, or 0 if not in a function */
8965 /* Forward decl way out to parsing code - dotrap needs it */
8966 static int evalstring(char *s, int flags);
8968 /* Called to execute a trap.
8969 * Single callsite - at the end of evaltree().
8970 * If we return non-zero, evaltree raises EXEXIT exception.
8972 * Perhaps we should avoid entering new trap handlers
8973 * while we are executing a trap handler. [is it a TODO?]
8980 uint8_t last_status;
8985 last_status = exitstatus;
8989 TRACE(("dotrap entered\n"));
8990 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
9002 /* non-trapped SIGINT is handled separately by raise_interrupt,
9003 * don't upset it by resetting gotsig[SIGINT-1] */
9004 if (sig == SIGINT && !p)
9007 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
9013 exitstatus = last_status;
9014 TRACE(("dotrap returns\n"));
9017 /* forward declarations - evaluation is fairly recursive business... */
9018 static int evalloop(union node *, int);
9019 static int evalfor(union node *, int);
9020 static int evalcase(union node *, int);
9021 static int evalsubshell(union node *, int);
9022 static void expredir(union node *);
9023 static int evalpipe(union node *, int);
9024 static int evalcommand(union node *, int);
9025 static int evalbltin(const struct builtincmd *, int, char **, int);
9026 static void prehash(union node *);
9029 * Evaluate a parse tree. The value is left in the global variable
9033 evaltree(union node *n, int flags)
9036 int (*evalfn)(union node *, int);
9040 TRACE(("evaltree(NULL) called\n"));
9043 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
9050 out1fmt("Node type = %d\n", n->type);
9055 status = !evaltree(n->nnot.com, EV_TESTED);
9058 errlinno = lineno = n->nredir.linno;
9060 lineno -= funcline - 1;
9061 expredir(n->nredir.redirect);
9062 pushredir(n->nredir.redirect);
9063 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
9065 status = evaltree(n->nredir.n, flags & EV_TESTED);
9067 if (n->nredir.redirect)
9068 popredir(/*drop:*/ 0);
9071 evalfn = evalcommand;
9073 if (eflag && !(flags & EV_TESTED))
9085 evalfn = evalsubshell;
9098 #error NAND + 1 != NOR
9100 #if NOR + 1 != NSEMI
9101 #error NOR + 1 != NSEMI
9103 unsigned is_or = n->type - NAND;
9106 (flags | ((is_or >> 1) - 1)) & EV_TESTED
9108 if ((!status) == is_or || evalskip)
9114 status = evalfn(n, flags);
9118 status = evaltree(n->nif.test, EV_TESTED);
9125 if (n->nif.elsepart) {
9126 n = n->nif.elsepart;
9133 /* Not necessary. To test it:
9134 * "false; f() { qwerty; }; echo $?" should print 0.
9138 exitstatus = status;
9142 /* Order of checks below is important:
9143 * signal handlers trigger before exit caused by "set -e".
9147 if (checkexit & status)
9148 raise_exception(EXEXIT);
9149 if (flags & EV_EXIT)
9150 raise_exception(EXEXIT);
9152 TRACE(("leaving evaltree (no interrupts)\n"));
9159 int skip = evalskip;
9166 if (--skipcount <= 0) {
9177 evalloop(union node *n, int flags)
9188 i = evaltree(n->nbinary.ch1, EV_TESTED);
9190 if (skip == SKIPFUNC)
9194 if (n->type != NWHILE)
9198 status = evaltree(n->nbinary.ch2, flags);
9200 } while (!(skip & ~SKIPCONT));
9207 evalfor(union node *n, int flags)
9209 struct arglist arglist;
9212 struct stackmark smark;
9215 errlinno = lineno = n->ncase.linno;
9217 lineno -= funcline - 1;
9219 setstackmark(&smark);
9220 arglist.list = NULL;
9221 arglist.lastp = &arglist.list;
9222 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
9223 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9225 *arglist.lastp = NULL;
9229 for (sp = arglist.list; sp; sp = sp->next) {
9230 setvar0(n->nfor.var, sp->text);
9231 status = evaltree(n->nfor.body, flags);
9232 if (skiploop() & ~SKIPCONT)
9236 popstackmark(&smark);
9242 evalcase(union node *n, int flags)
9246 struct arglist arglist;
9247 struct stackmark smark;
9250 errlinno = lineno = n->ncase.linno;
9252 lineno -= funcline - 1;
9254 setstackmark(&smark);
9255 arglist.list = NULL;
9256 arglist.lastp = &arglist.list;
9257 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
9258 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
9259 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
9260 if (casematch(patp, arglist.list->text)) {
9261 /* Ensure body is non-empty as otherwise
9262 * EV_EXIT may prevent us from setting the
9265 if (evalskip == 0 && cp->nclist.body) {
9266 status = evaltree(cp->nclist.body, flags);
9273 popstackmark(&smark);
9279 * Kick off a subshell to evaluate a tree.
9282 evalsubshell(union node *n, int flags)
9285 int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
9288 errlinno = lineno = n->nredir.linno;
9290 lineno -= funcline - 1;
9292 expredir(n->nredir.redirect);
9293 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
9296 if (backgnd == FORK_FG)
9298 jp = makejob(/*n,*/ 1);
9299 if (forkshell(jp, n, backgnd) == 0) {
9304 flags &= ~EV_TESTED;
9306 redirect(n->nredir.redirect, 0);
9307 evaltreenr(n->nredir.n, flags);
9312 if (backgnd == FORK_FG)
9313 status = waitforjob(jp);
9319 * Compute the names of the files in a redirection list.
9321 static void fixredir(union node *, const char *, int);
9323 expredir(union node *n)
9327 for (redir = n; redir; redir = redir->nfile.next) {
9331 fn.lastp = &fn.list;
9332 switch (redir->type) {
9336 #if BASH_REDIR_OUTPUT
9341 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
9342 TRACE(("expredir expanded to '%s'\n", fn.list->text));
9343 #if BASH_REDIR_OUTPUT
9347 // By the design of stack allocator, the loop of this kind:
9348 // while true; do while true; do break; done </dev/null; done
9349 // will look like a memory leak: ash plans to free expfname's
9350 // of "/dev/null" as soon as it finishes running the loop
9351 // (in this case, never).
9352 // This "fix" is wrong:
9353 if (redir->nfile.expfname)
9354 stunalloc(redir->nfile.expfname);
9355 // It results in corrupted state of stacked allocations.
9357 redir->nfile.expfname = fn.list->text;
9360 case NTOFD: /* >& */
9361 if (redir->ndup.vname) {
9362 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
9363 if (fn.list == NULL)
9364 ash_msg_and_raise_error("redir error");
9365 #if BASH_REDIR_OUTPUT
9366 //FIXME: we used expandarg with different args!
9367 if (!isdigit_str9(fn.list->text)) {
9368 /* >&file, not >&fd */
9369 if (redir->nfile.fd != 1) /* 123>&file - BAD */
9370 ash_msg_and_raise_error("redir error");
9372 goto store_expfname;
9375 fixredir(redir, fn.list->text, 1);
9383 * Evaluate a pipeline. All the processes in the pipeline are children
9384 * of the process creating the pipeline. (This differs from some versions
9385 * of the shell, which make the last process in a pipeline the parent
9389 evalpipe(union node *n, int flags)
9392 struct nodelist *lp;
9398 TRACE(("evalpipe(0x%lx) called\n", (long)n));
9400 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
9404 if (n->npipe.pipe_backgnd == 0)
9406 jp = makejob(/*n,*/ pipelen);
9408 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
9412 if (pipe(pip) < 0) {
9414 ash_msg_and_raise_perror("can't create pipe");
9417 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
9431 evaltreenr(lp->n, flags);
9438 /* Don't want to trigger debugging */
9442 if (n->npipe.pipe_backgnd == 0) {
9443 status = waitforjob(jp);
9444 TRACE(("evalpipe: job done exit status %d\n", status));
9452 * Controls whether the shell is interactive or not.
9455 setinteractive(int on)
9457 static smallint is_interactive;
9459 if (++on == is_interactive)
9461 is_interactive = on;
9465 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9466 if (is_interactive > 1) {
9467 /* Looks like they want an interactive shell */
9468 static smallint did_banner;
9471 /* note: ash and hush share this string */
9472 out1fmt("\n\n%s %s\n"
9473 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
9476 "built-in shell (ash)"
9490 setinteractive(iflag);
9492 #if ENABLE_FEATURE_EDITING_VI
9494 line_input_state->flags |= VI_MODE;
9496 line_input_state->flags &= ~VI_MODE;
9498 viflag = 0; /* forcibly keep the option off */
9502 struct localvar_list {
9503 struct localvar_list *next;
9504 struct localvar *lv;
9507 static struct localvar_list *localvar_stack;
9510 * Called after a function returns.
9511 * Interrupts must be off.
9514 poplocalvars(int keep)
9516 struct localvar_list *ll;
9517 struct localvar *lvp, *next;
9521 ll = localvar_stack;
9522 localvar_stack = ll->next;
9527 while ((lvp = next) != NULL) {
9530 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9532 int bits = VSTRFIXED;
9534 if (lvp->flags != VUNSET) {
9535 if (vp->var_text == lvp->text)
9537 else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
9538 free((char*)lvp->text);
9542 vp->flags |= (lvp->flags & bits);
9545 (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
9546 unsetvar(vp->var_text);
9547 } else if (vp == NULL) { /* $- saved */
9548 memcpy(optlist, lvp->text, sizeof(optlist));
9549 free((char*)lvp->text);
9551 } else if (lvp->flags == VUNSET) {
9552 vp->flags &= ~(VSTRFIXED|VREADONLY);
9553 unsetvar(vp->var_text);
9556 vp->var_func(var_end(lvp->text));
9557 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9558 free((char*)vp->var_text);
9559 vp->flags = lvp->flags;
9560 vp->var_text = lvp->text;
9568 * Create a new localvar environment.
9570 static struct localvar_list *
9573 struct localvar_list *ll;
9576 ll = ckzalloc(sizeof(*ll));
9577 /*ll->lv = NULL; - zalloc did it */
9578 ll->next = localvar_stack;
9579 localvar_stack = ll;
9586 unwindlocalvars(struct localvar_list *stop)
9588 while (localvar_stack != stop)
9593 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9595 volatile struct shparam saveparam;
9596 struct jmploc *volatile savehandler;
9597 struct jmploc jmploc;
9601 saveparam = shellparam;
9602 savefuncline = funcline;
9603 savehandler = exception_handler;
9604 e = setjmp(jmploc.loc);
9609 exception_handler = &jmploc;
9610 shellparam.malloced = 0;
9612 funcline = func->n.ndefun.linno;
9614 shellparam.nparam = argc - 1;
9615 shellparam.p = argv + 1;
9616 #if ENABLE_ASH_GETOPTS
9617 shellparam.optind = 1;
9618 shellparam.optoff = -1;
9620 evaltree(func->n.ndefun.body, flags & EV_TESTED);
9623 funcline = savefuncline;
9625 freeparam(&shellparam);
9626 shellparam = saveparam;
9627 exception_handler = savehandler;
9629 evalskip &= ~SKIPFUNC;
9634 * Make a variable a local variable. When a variable is made local, it's
9635 * value and flags are saved in a localvar structure. The saved values
9636 * will be restored when the shell function returns. We handle the name
9637 * "-" as a special case: it makes changes to "set +-options" local
9638 * (options will be restored on return from the function).
9643 struct localvar *lvp;
9646 char *eq = strchr(name, '=');
9649 /* Cater for duplicate "local". Examples:
9650 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9651 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9653 lvp = localvar_stack->lv;
9655 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9659 * it's a duplicate "local VAR" declaration, do nothing
9666 lvp = ckzalloc(sizeof(*lvp));
9667 if (LONE_DASH(name)) {
9669 p = ckmalloc(sizeof(optlist));
9670 lvp->text = memcpy(p, optlist, sizeof(optlist));
9673 vpp = hashvar(name);
9674 vp = *findvar(vpp, name);
9676 /* variable did not exist yet */
9678 vp = setvareq(name, VSTRFIXED);
9680 vp = setvar(name, NULL, VSTRFIXED);
9681 lvp->flags = VUNSET;
9683 lvp->text = vp->var_text;
9684 lvp->flags = vp->flags;
9685 /* make sure neither "struct var" nor string gets freed
9686 * during (un)setting:
9688 vp->flags |= VSTRFIXED|VTEXTFIXED;
9692 /* "local VAR" unsets VAR: */
9693 setvar0(name, NULL);
9697 lvp->next = localvar_stack->lv;
9698 localvar_stack->lv = lvp;
9704 * The "local" command.
9706 static int FAST_FUNC
9707 localcmd(int argc UNUSED_PARAM, char **argv)
9711 if (!localvar_stack)
9712 ash_msg_and_raise_error("not in a function");
9715 while ((name = *argv++) != NULL) {
9721 static int FAST_FUNC
9722 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9727 static int FAST_FUNC
9728 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9733 static int FAST_FUNC
9734 execcmd(int argc UNUSED_PARAM, char **argv)
9737 while (nextopt("a:") != '\0')
9738 /* nextopt() sets optionarg to "-a ARGV0" */;
9744 iflag = 0; /* exit on error */
9747 /* We should set up signals for "exec CMD"
9748 * the same way as for "CMD" without "exec".
9749 * But optschanged->setinteractive->setsignal
9750 * still thought we are a root shell. Therefore, for example,
9751 * SIGQUIT is still set to IGN. Fix it:
9755 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9756 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9757 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9761 argv[0] = optionarg;
9762 shellexec(prog, argv, pathval(), 0);
9769 * The return command.
9771 static int FAST_FUNC
9772 returncmd(int argc UNUSED_PARAM, char **argv)
9775 * If called outside a function, do what ksh does;
9776 * skip the rest of the file.
9778 evalskip = SKIPFUNC;
9779 return argv[1] ? number(argv[1]) : exitstatus;
9782 /* Forward declarations for builtintab[] */
9783 static int breakcmd(int, char **) FAST_FUNC;
9784 static int dotcmd(int, char **) FAST_FUNC;
9785 static int evalcmd(int, char **, int) FAST_FUNC;
9786 static int exitcmd(int, char **) FAST_FUNC;
9787 static int exportcmd(int, char **) FAST_FUNC;
9788 #if ENABLE_ASH_GETOPTS
9789 static int getoptscmd(int, char **) FAST_FUNC;
9792 static int helpcmd(int, char **) FAST_FUNC;
9795 static int historycmd(int, char **) FAST_FUNC;
9797 #if ENABLE_FEATURE_SH_MATH
9798 static int letcmd(int, char **) FAST_FUNC;
9800 static int readcmd(int, char **) FAST_FUNC;
9801 static int setcmd(int, char **) FAST_FUNC;
9802 static int shiftcmd(int, char **) FAST_FUNC;
9803 static int timescmd(int, char **) FAST_FUNC;
9804 static int trapcmd(int, char **) FAST_FUNC;
9805 static int umaskcmd(int, char **) FAST_FUNC;
9806 static int unsetcmd(int, char **) FAST_FUNC;
9807 static int ulimitcmd(int, char **) FAST_FUNC;
9809 #define BUILTIN_NOSPEC "0"
9810 #define BUILTIN_SPECIAL "1"
9811 #define BUILTIN_REGULAR "2"
9812 #define BUILTIN_SPEC_REG "3"
9813 #define BUILTIN_ASSIGN "4"
9814 #define BUILTIN_SPEC_ASSG "5"
9815 #define BUILTIN_REG_ASSG "6"
9816 #define BUILTIN_SPEC_REG_ASSG "7"
9818 /* Stubs for calling non-FAST_FUNC's */
9820 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9822 #if ENABLE_ASH_PRINTF
9823 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9825 #if ENABLE_ASH_TEST || BASH_TEST2
9826 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9829 /* Keep these in proper order since it is searched via bsearch() */
9830 static const struct builtincmd builtintab[] = {
9831 { BUILTIN_SPEC_REG "." , dotcmd },
9832 { BUILTIN_SPEC_REG ":" , truecmd },
9834 { BUILTIN_REGULAR "[" , testcmd },
9837 { BUILTIN_REGULAR "[[" , testcmd },
9839 #if ENABLE_ASH_ALIAS
9840 { BUILTIN_REG_ASSG "alias" , aliascmd },
9843 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9845 { BUILTIN_SPEC_REG "break" , breakcmd },
9846 { BUILTIN_REGULAR "cd" , cdcmd },
9847 { BUILTIN_NOSPEC "chdir" , cdcmd },
9848 #if ENABLE_ASH_CMDCMD
9849 { BUILTIN_REGULAR "command" , commandcmd },
9851 { BUILTIN_SPEC_REG "continue", breakcmd },
9853 { BUILTIN_REGULAR "echo" , echocmd },
9855 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9856 { BUILTIN_SPEC_REG "exec" , execcmd },
9857 { BUILTIN_SPEC_REG "exit" , exitcmd },
9858 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9859 { BUILTIN_REGULAR "false" , falsecmd },
9861 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9863 #if ENABLE_ASH_GETOPTS
9864 { BUILTIN_REGULAR "getopts" , getoptscmd },
9866 { BUILTIN_NOSPEC "hash" , hashcmd },
9868 { BUILTIN_NOSPEC "help" , helpcmd },
9871 { BUILTIN_NOSPEC "history" , historycmd },
9874 { BUILTIN_REGULAR "jobs" , jobscmd },
9875 { BUILTIN_REGULAR "kill" , killcmd },
9877 #if ENABLE_FEATURE_SH_MATH
9878 { BUILTIN_NOSPEC "let" , letcmd },
9880 { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
9881 #if ENABLE_ASH_PRINTF
9882 { BUILTIN_REGULAR "printf" , printfcmd },
9884 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9885 { BUILTIN_REGULAR "read" , readcmd },
9886 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9887 { BUILTIN_SPEC_REG "return" , returncmd },
9888 { BUILTIN_SPEC_REG "set" , setcmd },
9889 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9891 { BUILTIN_SPEC_REG "source" , dotcmd },
9894 { BUILTIN_REGULAR "test" , testcmd },
9896 { BUILTIN_SPEC_REG "times" , timescmd },
9897 { BUILTIN_SPEC_REG "trap" , trapcmd },
9898 { BUILTIN_REGULAR "true" , truecmd },
9899 { BUILTIN_NOSPEC "type" , typecmd },
9900 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9901 { BUILTIN_REGULAR "umask" , umaskcmd },
9902 #if ENABLE_ASH_ALIAS
9903 { BUILTIN_REGULAR "unalias" , unaliascmd },
9905 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9906 { BUILTIN_REGULAR "wait" , waitcmd },
9909 /* Should match the above table! */
9910 #define COMMANDCMD (builtintab + \
9912 /* [ */ 1 * ENABLE_ASH_TEST + \
9913 /* [[ */ 1 * BASH_TEST2 + \
9914 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9915 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9916 /* break cd cddir */ 3)
9917 #define EVALCMD (COMMANDCMD + \
9918 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9919 /* continue */ 1 + \
9920 /* echo */ 1 * ENABLE_ASH_ECHO + \
9922 #define EXECCMD (EVALCMD + \
9926 * Search the table of builtin commands.
9929 pstrcmp1(const void *a, const void *b)
9931 return strcmp((char*)a, *(char**)b + 1);
9933 static struct builtincmd *
9934 find_builtin(const char *name)
9936 struct builtincmd *bp;
9939 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9946 * Execute a simple command.
9948 static void unwindfiles(struct parsefile *stop);
9950 isassignment(const char *p)
9952 const char *q = endofname(p);
9957 static int FAST_FUNC
9958 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9960 /* Preserve exitstatus of a previous possible redirection
9961 * as POSIX mandates */
9962 return back_exitstatus;
9965 evalcommand(union node *cmd, int flags)
9967 static const struct builtincmd null_bltin = {
9968 "\0\0", bltincmd /* why three NULs? */
9970 struct localvar_list *localvar_stop;
9971 struct parsefile *file_stop;
9972 struct redirtab *redir_stop;
9973 struct stackmark smark;
9975 struct arglist arglist;
9976 struct arglist varlist;
9979 const struct strlist *sp;
9980 struct cmdentry cmdentry;
9987 smallint cmd_is_exec;
9989 errlinno = lineno = cmd->ncmd.linno;
9991 lineno -= funcline - 1;
9993 /* First expand the arguments. */
9994 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9995 setstackmark(&smark);
9996 localvar_stop = pushlocalvars();
9997 file_stop = g_parsefile;
9998 back_exitstatus = 0;
10000 cmdentry.cmdtype = CMDBUILTIN;
10001 cmdentry.u.cmd = &null_bltin;
10002 varlist.lastp = &varlist.list;
10003 *varlist.lastp = NULL;
10004 arglist.lastp = &arglist.list;
10005 *arglist.lastp = NULL;
10008 if (cmd->ncmd.args) {
10009 struct builtincmd *bcmd;
10010 smallint pseudovarflag;
10012 bcmd = find_builtin(cmd->ncmd.args->narg.text);
10013 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
10015 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
10016 struct strlist **spp;
10018 spp = arglist.lastp;
10019 if (pseudovarflag && isassignment(argp->narg.text))
10020 expandarg(argp, &arglist, EXP_VARTILDE);
10022 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
10024 for (sp = *spp; sp; sp = sp->next)
10029 /* Reserve one extra spot at the front for shellexec. */
10030 nargv = stalloc(sizeof(char *) * (argc + 2));
10032 for (sp = arglist.list; sp; sp = sp->next) {
10033 TRACE(("evalcommand arg: %s\n", sp->text));
10034 *nargv++ = sp->text;
10039 if (iflag && funcline == 0 && argc > 0)
10040 lastarg = nargv[-1];
10042 expredir(cmd->ncmd.redirect);
10043 redir_stop = pushredir(cmd->ncmd.redirect);
10045 if (BASH_XTRACEFD && xflag) {
10046 /* NB: bash closes fd == $BASH_XTRACEFD when it is changed.
10047 * we do not emulate this. We only use its value.
10049 const char *xtracefd = lookupvar("BASH_XTRACEFD");
10050 if (xtracefd && is_number(xtracefd))
10051 preverrout_fd = atoi(xtracefd);
10054 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
10056 path = vpath.var_text;
10057 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
10058 struct strlist **spp;
10061 spp = varlist.lastp;
10062 expandarg(argp, &varlist, EXP_VARTILDE);
10064 mklocal((*spp)->text);
10067 * Modify the command lookup path, if a PATH= assignment
10071 if (varcmp(p, path) == 0)
10075 /* Print the command if xflag is set. */
10077 const char *pfx = "";
10079 fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
10083 char *varval = sp->text;
10084 char *eq = strchrnul(varval, '=');
10087 fdprintf(preverrout_fd, "%s%.*s%s",
10089 (int)(eq - varval), varval,
10090 maybe_single_quote(eq)
10098 fdprintf(preverrout_fd, "%s%s",
10100 /* always quote if matches reserved word: */
10102 ? single_quote(sp->text)
10103 : maybe_single_quote(sp->text)
10108 safe_write(preverrout_fd, "\n", 1);
10114 /* Now locate the command. */
10116 int cmd_flag = DO_ERR;
10117 #if ENABLE_ASH_CMDCMD
10118 const char *oldpath = path + 5;
10122 find_command(argv[0], &cmdentry, cmd_flag, path);
10123 if (cmdentry.cmdtype == CMDUNKNOWN) {
10124 flush_stdout_stderr();
10129 /* implement bltin and command here */
10130 if (cmdentry.cmdtype != CMDBUILTIN)
10133 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
10134 if (cmdentry.u.cmd == EXECCMD)
10136 #if ENABLE_ASH_CMDCMD
10137 if (cmdentry.u.cmd == COMMANDCMD) {
10139 nargv = parse_command_args(argv, &path);
10142 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
10143 * nargv => "PROG". path is updated if -p.
10145 argc -= nargv - argv;
10147 cmd_flag |= DO_NOFUNC;
10156 exitstatus = status;
10158 /* We have a redirection error. */
10160 raise_exception(EXERROR);
10165 /* Execute the command. */
10166 switch (cmdentry.cmdtype) {
10169 #if ENABLE_FEATURE_SH_STANDALONE \
10170 && ENABLE_FEATURE_SH_NOFORK \
10172 /* (1) BUG: if variables are set, we need to fork, or save/restore them
10173 * around run_nofork_applet() call.
10174 * (2) Should this check also be done in forkshell()?
10175 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
10177 /* find_command() encodes applet_no as (-2 - applet_no) */
10178 int applet_no = (- cmdentry.u.index - 2);
10179 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
10183 sv_environ = environ;
10184 environ = listvars(VEXPORT, VUNSET, varlist.list, /*end:*/ NULL);
10186 * Run <applet>_main().
10187 * Signals (^C) can't interrupt here.
10188 * Otherwise we can mangle stdio or malloc internal state.
10189 * This makes applets which can run for a long time
10190 * and/or wait for user input ineligible for NOFORK:
10191 * for example, "yes" or "rm" (rm -i waits for input).
10193 status = run_nofork_applet(applet_no, argv);
10194 environ = sv_environ;
10196 * Try enabling NOFORK for "yes" applet.
10197 * ^C _will_ stop it (write returns EINTR),
10198 * but this causes stdout FILE to be stuck
10199 * and needing clearerr(). What if other applets
10200 * also can get EINTRs? Do we need to switch
10201 * our signals to SA_RESTART?
10203 /*clearerr(stdout);*/
10208 /* Can we avoid forking? For example, very last command
10209 * in a script or a subshell does not need forking,
10210 * we can just exec it.
10212 if (!(flags & EV_EXIT) || may_have_traps) {
10213 /* No, forking off a child is necessary */
10216 jp = makejob(/*cmd,*/ 1);
10217 if (forkshell(jp, cmd, FORK_FG) != 0) {
10219 status = waitforjob(jp);
10221 TRACE(("forked child exited with %d\n", status));
10226 /* fall through to exec'ing external program */
10228 listsetvar(varlist.list, VEXPORT|VSTACK);
10229 shellexec(argv[0], argv, path, cmdentry.u.index);
10233 if (spclbltin > 0 || argc == 0) {
10235 if (cmd_is_exec && argc > 1)
10236 listsetvar(varlist.list, VEXPORT);
10239 /* Tight loop with builtins only:
10240 * "while kill -0 $child; do true; done"
10241 * will never exit even if $child died, unless we do this
10242 * to reap the zombie and make kill detect that it's gone: */
10243 dowait(DOWAIT_NONBLOCK, NULL);
10245 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
10246 if (exception_type == EXERROR && spclbltin <= 0) {
10251 longjmp(exception_handler->loc, 1);
10256 /* See above for the rationale */
10257 dowait(DOWAIT_NONBLOCK, NULL);
10258 if (evalfun(cmdentry.u.func, argc, argv, flags))
10261 status = exitstatus;
10266 if (cmd->ncmd.redirect)
10267 popredir(/*drop:*/ cmd_is_exec);
10268 unwindredir(redir_stop);
10269 unwindfiles(file_stop);
10270 unwindlocalvars(localvar_stop);
10272 /* dsl: I think this is intended to be used to support
10273 * '_' in 'vi' command mode during line editing...
10274 * However I implemented that within libedit itself.
10276 setvar0("_", lastarg);
10278 popstackmark(&smark);
10284 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
10286 char *volatile savecmdname;
10287 struct jmploc *volatile savehandler;
10288 struct jmploc jmploc;
10292 savecmdname = commandname;
10293 savehandler = exception_handler;
10294 i = setjmp(jmploc.loc);
10297 exception_handler = &jmploc;
10298 commandname = argv[0];
10300 optptr = NULL; /* initialize nextopt */
10301 if (cmd == EVALCMD)
10302 status = evalcmd(argc, argv, flags);
10304 status = (*cmd->builtin)(argc, argv);
10305 flush_stdout_stderr();
10306 status |= ferror(stdout);
10307 exitstatus = status;
10310 commandname = savecmdname;
10311 exception_handler = savehandler;
10317 goodname(const char *p)
10319 return endofname(p)[0] == '\0';
10324 * Search for a command. This is called before we fork so that the
10325 * location of the command will be available in the parent as well as
10326 * the child. The check for "goodname" is an overly conservative
10327 * check that the name will not be subject to expansion.
10330 prehash(union node *n)
10332 struct cmdentry entry;
10334 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
10335 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
10339 /* ============ Builtin commands
10341 * Builtin commands whose functions are closely tied to evaluation
10342 * are implemented here.
10346 * Handle break and continue commands. Break, continue, and return are
10347 * all handled by setting the evalskip flag. The evaluation routines
10348 * above all check this flag, and if it is set they start skipping
10349 * commands rather than executing them. The variable skipcount is
10350 * the number of loops to break/continue, or the number of function
10351 * levels to return. (The latter is always 1.) It should probably
10352 * be an error to break out of more loops than exist, but it isn't
10353 * in the standard shell so we don't make it one here.
10355 static int FAST_FUNC
10356 breakcmd(int argc UNUSED_PARAM, char **argv)
10358 int n = argv[1] ? number(argv[1]) : 1;
10361 ash_msg_and_raise_error(msg_illnum, argv[1]);
10365 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
10373 * This implements the input routines used by the parser.
10377 INPUT_PUSH_FILE = 1,
10378 INPUT_NOFILE_OK = 2,
10381 static smallint checkkwd;
10382 /* values of checkkwd variable */
10383 #define CHKALIAS 0x1
10386 #define CHKEOFMARK 0x8
10389 * Push a string back onto the input at this current parsefile level.
10390 * We handle aliases this way.
10392 #if !ENABLE_ASH_ALIAS
10393 #define pushstring(s, ap) pushstring(s)
10396 pushstring(char *s, struct alias *ap)
10398 struct strpush *sp;
10403 if (g_parsefile->strpush) {
10404 sp = ckzalloc(sizeof(*sp));
10405 sp->prev = g_parsefile->strpush;
10407 sp = &(g_parsefile->basestrpush);
10409 g_parsefile->strpush = sp;
10410 sp->prev_string = g_parsefile->next_to_pgetc;
10411 sp->prev_left_in_line = g_parsefile->left_in_line;
10412 sp->unget = g_parsefile->unget;
10413 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
10414 #if ENABLE_ASH_ALIAS
10417 ap->flag |= ALIASINUSE;
10421 g_parsefile->next_to_pgetc = s;
10422 g_parsefile->left_in_line = len;
10423 g_parsefile->unget = 0;
10430 struct strpush *sp = g_parsefile->strpush;
10433 #if ENABLE_ASH_ALIAS
10435 if (g_parsefile->next_to_pgetc[-1] == ' '
10436 || g_parsefile->next_to_pgetc[-1] == '\t'
10438 checkkwd |= CHKALIAS;
10440 if (sp->string != sp->ap->val) {
10443 sp->ap->flag &= ~ALIASINUSE;
10444 if (sp->ap->flag & ALIASDEAD) {
10445 unalias(sp->ap->name);
10449 g_parsefile->next_to_pgetc = sp->prev_string;
10450 g_parsefile->left_in_line = sp->prev_left_in_line;
10451 g_parsefile->unget = sp->unget;
10452 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
10453 g_parsefile->strpush = sp->prev;
10454 if (sp != &(g_parsefile->basestrpush))
10463 char *buf = g_parsefile->buf;
10465 g_parsefile->next_to_pgetc = buf;
10466 #if ENABLE_FEATURE_EDITING
10468 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
10469 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10471 # if ENABLE_ASH_IDLE_TIMEOUT
10474 const char *tmout_var = lookupvar("TMOUT");
10476 timeout = atoi(tmout_var) * 1000;
10481 line_input_state->timeout = timeout;
10483 # if ENABLE_FEATURE_TAB_COMPLETION
10484 line_input_state->path_lookup = pathval();
10486 reinit_unicode_for_ash();
10487 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ);
10489 /* ^C pressed, "convert" to SIGINT */
10490 write(STDOUT_FILENO, "^C", 2);
10491 if (trap[SIGINT]) {
10497 exitstatus = 128 + SIGINT;
10503 /* Ctrl+D pressed */
10506 # if ENABLE_ASH_IDLE_TIMEOUT
10507 else if (errno == EAGAIN && timeout > 0) {
10508 puts("\007timed out waiting for input: auto-logout");
10515 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10518 #if 0 /* disabled: nonblock_immune_read() handles this problem */
10520 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
10521 int flags = fcntl(0, F_GETFL);
10522 if (flags >= 0 && (flags & O_NONBLOCK)) {
10523 flags &= ~O_NONBLOCK;
10524 if (fcntl(0, F_SETFL, flags) >= 0) {
10525 out2str("sh: turning off NDELAY mode\n");
10536 * Refill the input buffer and return the next input character:
10538 * 1) If a string was pushed back on the input, pop it;
10539 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
10540 * or we are reading from a string so we can't refill the buffer,
10542 * 3) If there is more stuff in this buffer, use it else call read to fill it.
10543 * 4) Process input up to the next newline, deleting nul characters.
10545 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
10546 #define pgetc_debug(...) ((void)0)
10547 static int pgetc(void);
10554 if (g_parsefile->strpush) {
10555 #if ENABLE_ASH_ALIAS
10556 if (g_parsefile->left_in_line == -1
10557 && g_parsefile->strpush->ap
10558 && g_parsefile->next_to_pgetc[-1] != ' '
10559 && g_parsefile->next_to_pgetc[-1] != '\t'
10561 pgetc_debug("preadbuffer PEOA");
10568 /* on both branches above g_parsefile->left_in_line < 0.
10569 * "pgetc" needs refilling.
10572 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
10573 * pungetc() may increment it a few times.
10574 * Assuming it won't increment it to less than -90.
10576 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
10577 pgetc_debug("preadbuffer PEOF1");
10578 /* even in failure keep left_in_line and next_to_pgetc
10579 * in lock step, for correct multi-layer pungetc.
10580 * left_in_line was decremented before preadbuffer(),
10581 * must inc next_to_pgetc: */
10582 g_parsefile->next_to_pgetc++;
10586 more = g_parsefile->left_in_buffer;
10588 flush_stdout_stderr();
10592 /* don't try reading again */
10593 g_parsefile->left_in_line = -99;
10594 pgetc_debug("preadbuffer PEOF2");
10595 g_parsefile->next_to_pgetc++;
10600 /* Find out where's the end of line.
10601 * Set g_parsefile->left_in_line
10602 * and g_parsefile->left_in_buffer acordingly.
10603 * NUL chars are deleted.
10605 q = g_parsefile->next_to_pgetc;
10613 memmove(q, q + 1, more);
10617 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10623 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10624 if (g_parsefile->left_in_line < 0)
10629 g_parsefile->left_in_buffer = more;
10634 out2str(g_parsefile->next_to_pgetc);
10638 pgetc_debug("preadbuffer at %d:%p'%s'",
10639 g_parsefile->left_in_line,
10640 g_parsefile->next_to_pgetc,
10641 g_parsefile->next_to_pgetc);
10642 return (unsigned char)*g_parsefile->next_to_pgetc++;
10648 g_parsefile->linno++;
10649 setprompt_if(doprompt, 2);
10654 g_parsefile->linno++;
10655 needprompt = doprompt;
10663 pgetc_debug("pgetc at %d:%p'%s'",
10664 g_parsefile->left_in_line,
10665 g_parsefile->next_to_pgetc,
10666 g_parsefile->next_to_pgetc);
10667 if (g_parsefile->unget)
10668 return g_parsefile->lastc[--g_parsefile->unget];
10670 if (--g_parsefile->left_in_line >= 0)
10671 c = (unsigned char)*g_parsefile->next_to_pgetc++;
10675 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10676 g_parsefile->lastc[0] = c;
10681 #if ENABLE_ASH_ALIAS
10683 pgetc_without_PEOA(void)
10687 pgetc_debug("pgetc at %d:%p'%s'",
10688 g_parsefile->left_in_line,
10689 g_parsefile->next_to_pgetc,
10690 g_parsefile->next_to_pgetc);
10692 } while (c == PEOA);
10696 # define pgetc_without_PEOA() pgetc()
10700 * Undo a call to pgetc. Only two characters may be pushed back.
10701 * PEOF may be pushed back.
10706 g_parsefile->unget++;
10709 /* This one eats backslash+newline */
10715 while ((c = pgetc()) == '\\') {
10716 if (pgetc() != '\n') {
10729 uint8_t innerdq :1;
10730 uint8_t varpushed :1;
10731 uint8_t dblquote :1;
10732 int varnest; /* levels of variables expansion */
10733 int dqvarnest; /* levels of variables expansion within double quotes */
10734 int parenlevel; /* levels of parens in arithmetic */
10735 struct synstack *prev;
10736 struct synstack *next;
10740 synstack_push(struct synstack **stack, struct synstack *next, int syntax)
10742 memset(next, 0, sizeof(*next));
10743 next->syntax = syntax;
10744 next->next = *stack;
10745 (*stack)->prev = next;
10749 static ALWAYS_INLINE void
10750 synstack_pop(struct synstack **stack)
10752 *stack = (*stack)->next;
10756 * To handle the "." command, a stack of input files is used. Pushfile
10757 * adds a new entry to the stack and popfile restores the previous level.
10762 struct parsefile *pf;
10764 pf = ckzalloc(sizeof(*pf));
10765 pf->prev = g_parsefile;
10767 /*pf->strpush = NULL; - ckzalloc did it */
10768 /*pf->basestrpush.prev = NULL;*/
10776 struct parsefile *pf = g_parsefile;
10782 if (pf->pf_fd >= 0)
10785 while (pf->strpush)
10787 g_parsefile = pf->prev;
10793 unwindfiles(struct parsefile *stop)
10795 while (g_parsefile != stop)
10800 * Return to top level.
10805 unwindfiles(&basepf);
10809 * Close the file(s) that the shell is reading commands from. Called
10810 * after a fork is done.
10816 if (g_parsefile->pf_fd > 0) {
10817 close(g_parsefile->pf_fd);
10818 g_parsefile->pf_fd = 0;
10823 * Like setinputfile, but takes an open file descriptor. Call this with
10827 setinputfd(int fd, int push)
10831 g_parsefile->buf = NULL;
10833 g_parsefile->pf_fd = fd;
10834 if (g_parsefile->buf == NULL)
10835 g_parsefile->buf = ckmalloc(IBUFSIZ);
10836 g_parsefile->left_in_buffer = 0;
10837 g_parsefile->left_in_line = 0;
10838 g_parsefile->linno = 1;
10842 * Set the input to take input from a file. If push is set, push the
10843 * old input onto the stack first.
10846 setinputfile(const char *fname, int flags)
10851 fd = open(fname, O_RDONLY | O_CLOEXEC);
10853 if (flags & INPUT_NOFILE_OK)
10856 ash_msg_and_raise_perror("can't open '%s'", fname);
10860 else if (O_CLOEXEC == 0) /* old libc */
10861 close_on_exec_on(fd);
10863 setinputfd(fd, flags & INPUT_PUSH_FILE);
10870 * Like setinputfile, but takes input from a string.
10873 setinputstring(char *string)
10877 g_parsefile->next_to_pgetc = string;
10878 g_parsefile->left_in_line = strlen(string);
10879 g_parsefile->buf = NULL;
10880 g_parsefile->linno = 1;
10886 * Routines to check for mail.
10889 #if ENABLE_ASH_MAIL
10891 /* Hash of mtimes of mailboxes */
10892 static unsigned mailtime_hash;
10893 /* Set if MAIL or MAILPATH is changed. */
10894 static smallint mail_var_path_changed;
10897 * Print appropriate message(s) if mail has arrived.
10898 * If mail_var_path_changed is set,
10899 * then the value of MAIL has mail_var_path_changed,
10900 * so we just update the values.
10909 struct stackmark smark;
10912 setstackmark(&smark);
10913 mpath = mpathset() ? mpathval() : mailval();
10916 p = path_advance(&mpath, nullstr);
10921 for (q = p; *q; q++)
10927 q[-1] = '\0'; /* delete trailing '/' */
10928 if (stat(p, &statb) < 0) {
10931 /* Very simplistic "hash": just a sum of all mtimes */
10932 new_hash += (unsigned)statb.st_mtime;
10934 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10935 if (mailtime_hash != 0)
10936 out2str("you have mail\n");
10937 mailtime_hash = new_hash;
10939 mail_var_path_changed = 0;
10940 popstackmark(&smark);
10943 static void FAST_FUNC
10944 changemail(const char *val UNUSED_PARAM)
10946 mail_var_path_changed = 1;
10949 #endif /* ASH_MAIL */
10952 /* ============ ??? */
10955 * Set the shell parameters.
10958 setparam(char **argv)
10964 for (nparam = 0; argv[nparam]; nparam++)
10966 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10968 *ap++ = ckstrdup(*argv++);
10971 freeparam(&shellparam);
10972 shellparam.malloced = 1;
10973 shellparam.nparam = nparam;
10974 shellparam.p = newparam;
10975 #if ENABLE_ASH_GETOPTS
10976 shellparam.optind = 1;
10977 shellparam.optoff = -1;
10982 * Process shell options. The global variable argptr contains a pointer
10983 * to the argument list; we advance it past the options.
10985 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10986 * For a non-interactive shell, an error condition encountered
10987 * by a special built-in ... shall cause the shell to write a diagnostic message
10988 * to standard error and exit as shown in the following table:
10989 * Error Special Built-In
10991 * Utility syntax error (option or operand error) Shall exit
10993 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10994 * we see that bash does not do that (set "finishes" with error code 1 instead,
10995 * and shell continues), and people rely on this behavior!
10997 * set -o barfoo 2>/dev/null
11000 * Oh well. Let's mimic that.
11003 plus_minus_o(char *name, int val)
11008 for (i = 0; i < NOPTS; i++) {
11009 if (strcmp(name, optnames(i)) == 0) {
11014 ash_msg("illegal option %co %s", val ? '-' : '+', name);
11017 for (i = 0; i < NOPTS; i++) {
11019 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
11021 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
11027 setoption(int flag, int val)
11031 for (i = 0; i < NOPTS; i++) {
11032 if (optletters(i) == flag) {
11037 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
11041 options(int cmdline, int *login_sh)
11049 while ((p = *argptr) != NULL) {
11051 if (c != '-' && c != '+')
11054 val = 0; /* val = 0 if c == '+' */
11057 if (p[0] == '\0' || LONE_DASH(p)) {
11059 /* "-" means turn off -x and -v */
11062 /* "--" means reset params */
11063 else if (*argptr == NULL)
11066 break; /* "-" or "--" terminates options */
11069 /* first char was + or - */
11070 while ((c = *p++) != '\0') {
11071 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
11072 if (c == 'c' && cmdline) {
11073 minusc = p; /* command is after shell args */
11074 } else if (c == 'o') {
11075 if (plus_minus_o(*argptr, val)) {
11076 /* it already printed err message */
11077 return 1; /* error */
11081 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
11084 /* bash does not accept +-login, we also won't */
11085 } else if (cmdline && val && (c == '-')) { /* long options */
11086 if (strcmp(p, "login") == 0) {
11100 * The shift builtin command.
11102 static int FAST_FUNC
11103 shiftcmd(int argc UNUSED_PARAM, char **argv)
11110 n = number(argv[1]);
11111 if (n > shellparam.nparam)
11114 shellparam.nparam -= n;
11115 for (ap1 = shellparam.p; --n >= 0; ap1++) {
11116 if (shellparam.malloced)
11119 ap2 = shellparam.p;
11120 while ((*ap2++ = *ap1++) != NULL)
11122 #if ENABLE_ASH_GETOPTS
11123 shellparam.optind = 1;
11124 shellparam.optoff = -1;
11131 * POSIX requires that 'set' (but not export or readonly) output the
11132 * variables in lexicographic order - by the locale's collating order (sigh).
11133 * Maybe we could keep them in an ordered balanced binary tree
11134 * instead of hashed lists.
11135 * For now just roll 'em through qsort for printing...
11138 showvars(const char *sep_prefix, int on, int off)
11141 char **ep, **epend;
11143 ep = listvars(on, off, /*strlist:*/ NULL, &epend);
11144 qsort(ep, epend - ep, sizeof(char *), vpcmp);
11146 sep = *sep_prefix ? " " : sep_prefix;
11148 for (; ep < epend; ep++) {
11152 p = endofname(*ep);
11153 /* Used to have simple "p = strchrnul(*ep, '=')" here instead, but this
11154 * makes "export -p" to have output not suitable for "eval":
11156 * os.environ["test-test"]="test"
11157 * if os.fork() == 0:
11158 * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
11159 * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ])
11163 q = single_quote(++p);
11164 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
11170 * The set command builtin.
11172 static int FAST_FUNC
11173 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
11178 return showvars(nullstr, 0, VUNSET);
11181 retval = options(/*cmdline:*/ 0, NULL);
11182 if (retval == 0) { /* if no parse error... */
11184 if (*argptr != NULL) {
11192 #if ENABLE_ASH_RANDOM_SUPPORT
11193 static void FAST_FUNC
11194 change_random(const char *value)
11198 if (value == NULL) {
11199 /* "get", generate */
11200 t = next_random(&random_gen);
11201 /* set without recursion */
11202 setvar(vrandom.var_text, utoa(t), VNOFUNC);
11203 vrandom.flags &= ~VNOFUNC;
11206 t = strtoul(value, NULL, 10);
11207 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
11212 #if ENABLE_ASH_GETOPTS
11214 getopts(char *optstr, char *optvar, char **optfirst)
11221 int ind = shellparam.optind;
11222 int off = shellparam.optoff;
11226 shellparam.optind = -1;
11227 optnext = optfirst + ind - 1;
11229 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
11232 p = optnext[-1] + off;
11233 if (p == NULL || *p == '\0') {
11234 /* Current word is done, advance */
11236 if (p == NULL || *p != '-' || *++p == '\0') {
11238 unsetvar("OPTARG");
11244 if (LONE_DASH(p)) /* check for "--" */
11249 for (q = optstr; *q != c;) {
11251 /* OPTERR is a bashism */
11252 const char *cp = lookupvar("OPTERR");
11253 if ((cp && LONE_CHAR(cp, '0'))
11254 || (optstr[0] == ':')
11257 /*sbuf[1] = '\0'; - already is */
11258 setvar0("OPTARG", sbuf);
11260 fprintf(stderr, "Illegal option -%c\n", c);
11261 unsetvar("OPTARG");
11271 if (*p == '\0' && (p = *optnext) == NULL) {
11272 /* OPTERR is a bashism */
11273 const char *cp = lookupvar("OPTERR");
11274 if ((cp && LONE_CHAR(cp, '0'))
11275 || (optstr[0] == ':')
11278 /*sbuf[1] = '\0'; - already is */
11279 setvar0("OPTARG", sbuf);
11282 fprintf(stderr, "No arg for -%c option\n", c);
11283 unsetvar("OPTARG");
11291 setvar0("OPTARG", p);
11294 setvar0("OPTARG", nullstr);
11296 ind = optnext - optfirst + 1;
11297 setvar("OPTIND", itoa(ind), VNOFUNC);
11299 /*sbuf[1] = '\0'; - already is */
11300 setvar0(optvar, sbuf);
11302 shellparam.optoff = p ? p - *(optnext - 1) : -1;
11303 shellparam.optind = ind;
11309 * The getopts builtin. Shellparam.optnext points to the next argument
11310 * to be processed. Shellparam.optptr points to the next character to
11311 * be processed in the current argument. If shellparam.optnext is NULL,
11312 * then it's the first time getopts has been called.
11314 static int FAST_FUNC
11315 getoptscmd(int argc, char **argv)
11320 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
11322 optbase = shellparam.p;
11323 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
11324 shellparam.optind = 1;
11325 shellparam.optoff = -1;
11328 optbase = &argv[3];
11329 if ((unsigned)shellparam.optind > argc - 2) {
11330 shellparam.optind = 1;
11331 shellparam.optoff = -1;
11335 return getopts(argv[1], argv[2], optbase);
11337 #endif /* ASH_GETOPTS */
11340 /* ============ Shell parser */
11343 struct heredoc *next; /* next here document in list */
11344 union node *here; /* redirection node */
11345 char *eofmark; /* string indicating end of input */
11346 smallint striptabs; /* if set, strip leading tabs */
11349 static smallint tokpushback; /* last token pushed back */
11350 static smallint quoteflag; /* set if (part of) last token was quoted */
11351 static token_id_t lasttoken; /* last token read (integer id Txxx) */
11352 static struct heredoc *heredoclist; /* list of here documents to read */
11353 static char *wordtext; /* text of last word returned by readtoken */
11354 static struct nodelist *backquotelist;
11355 static union node *redirnode;
11356 static struct heredoc *heredoc;
11358 static const char *
11359 tokname(char *buf, int tok)
11362 return tokname_array[tok];
11363 sprintf(buf, "\"%s\"", tokname_array[tok]);
11367 /* raise_error_unexpected_syntax:
11368 * Called when an unexpected token is read during the parse. The argument
11369 * is the token that is expected, or -1 if more than one type of token can
11370 * occur at this point.
11372 static void raise_error_unexpected_syntax(int) NORETURN;
11374 raise_error_unexpected_syntax(int token)
11380 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
11382 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
11383 raise_error_syntax(msg);
11387 /* parsing is heavily cross-recursive, need these forward decls */
11388 static union node *andor(void);
11389 static union node *pipeline(void);
11390 static union node *parse_command(void);
11391 static void parseheredoc(void);
11392 static int peektoken(void);
11393 static int readtoken(void);
11395 static union node *
11398 union node *n1, *n2, *n3;
11403 switch (peektoken()) {
11411 if (!n1 && (nlflag & 1))
11417 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11418 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
11424 if (tok == TBACKGND) {
11425 if (n2->type == NPIPE) {
11426 n2->npipe.pipe_backgnd = 1;
11428 if (n2->type != NREDIR) {
11429 n3 = stzalloc(sizeof(struct nredir));
11431 /*n3->nredir.redirect = NULL; - stzalloc did it */
11434 n2->type = NBACKGND;
11440 n3 = stzalloc(sizeof(struct nbinary));
11442 n3->nbinary.ch1 = n1;
11443 n3->nbinary.ch2 = n2;
11456 raise_error_unexpected_syntax(-1);
11463 static union node *
11466 union node *n1, *n2, *n3;
11474 } else if (t == TOR) {
11480 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11482 n3 = stzalloc(sizeof(struct nbinary));
11484 n3->nbinary.ch1 = n1;
11485 n3->nbinary.ch2 = n2;
11490 static union node *
11493 union node *n1, *n2, *pipenode;
11494 struct nodelist *lp, *prev;
11498 TRACE(("pipeline: entered\n"));
11499 if (readtoken() == TNOT) {
11501 checkkwd = CHKKWD | CHKALIAS;
11504 n1 = parse_command();
11505 if (readtoken() == TPIPE) {
11506 pipenode = stzalloc(sizeof(struct npipe));
11507 pipenode->type = NPIPE;
11508 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
11509 lp = stzalloc(sizeof(struct nodelist));
11510 pipenode->npipe.cmdlist = lp;
11514 lp = stzalloc(sizeof(struct nodelist));
11515 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11516 lp->n = parse_command();
11518 } while (readtoken() == TPIPE);
11524 n2 = stzalloc(sizeof(struct nnot));
11532 static union node *
11537 n = stzalloc(sizeof(struct narg));
11539 /*n->narg.next = NULL; - stzalloc did it */
11540 n->narg.text = wordtext;
11541 n->narg.backquote = backquotelist;
11546 fixredir(union node *n, const char *text, int err)
11550 TRACE(("Fix redir %s %d\n", text, err));
11552 n->ndup.vname = NULL;
11554 fd = bb_strtou(text, NULL, 10);
11555 if (!errno && fd >= 0)
11556 n->ndup.dupfd = fd;
11557 else if (LONE_DASH(text))
11558 n->ndup.dupfd = -1;
11561 raise_error_syntax("bad fd number");
11562 n->ndup.vname = makename();
11569 union node *n = redirnode;
11571 if (n->type == NHERE)
11572 checkkwd = CHKEOFMARK;
11573 if (readtoken() != TWORD)
11574 raise_error_unexpected_syntax(-1);
11575 if (n->type == NHERE) {
11576 struct heredoc *here = heredoc;
11579 if (quoteflag == 0)
11581 TRACE(("Here document %d\n", n->type));
11582 rmescapes(wordtext, 0, NULL);
11583 here->eofmark = wordtext;
11585 if (heredoclist == NULL)
11586 heredoclist = here;
11588 for (p = heredoclist; p->next; p = p->next)
11592 } else if (n->type == NTOFD || n->type == NFROMFD) {
11593 fixredir(n, wordtext, 0);
11595 n->nfile.fname = makename();
11599 static union node *
11602 union node *args, **app;
11603 union node *n = NULL;
11604 union node *vars, **vpp;
11605 union node **rpp, *redir;
11609 smallint double_brackets_flag = 0;
11611 IF_BASH_FUNCTION(smallint function_flag = 0;)
11620 savecheckkwd = CHKALIAS;
11621 savelinno = g_parsefile->linno;
11624 checkkwd = savecheckkwd;
11629 if (peektoken() != TWORD)
11630 raise_error_unexpected_syntax(TWORD);
11635 case TAND: /* "&&" */
11636 case TOR: /* "||" */
11637 if (!double_brackets_flag) {
11641 wordtext = (char *) (t == TAND ? "-a" : "-o");
11644 n = stzalloc(sizeof(struct narg));
11646 /*n->narg.next = NULL; - stzalloc did it */
11647 n->narg.text = wordtext;
11649 if (strcmp("[[", wordtext) == 0)
11650 double_brackets_flag = 1;
11651 else if (strcmp("]]", wordtext) == 0)
11652 double_brackets_flag = 0;
11654 n->narg.backquote = backquotelist;
11655 if (savecheckkwd && isassignment(wordtext)) {
11657 vpp = &n->narg.next;
11660 app = &n->narg.next;
11664 if (function_flag) {
11665 checkkwd = CHKNL | CHKKWD;
11666 switch (peektoken()) {
11679 if (strcmp("[[", wordtext) == 0)
11684 raise_error_unexpected_syntax(-1);
11690 *rpp = n = redirnode;
11691 rpp = &n->nfile.next;
11692 parsefname(); /* read name of redirection file */
11695 IF_BASH_FUNCTION(do_func:)
11696 if (args && app == &args->narg.next
11699 struct builtincmd *bcmd;
11702 /* We have a function */
11703 if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
11704 raise_error_unexpected_syntax(TRP);
11705 name = n->narg.text;
11706 if (!goodname(name)
11707 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11709 raise_error_syntax("bad function name");
11712 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11713 n->ndefun.text = n->narg.text;
11714 n->ndefun.linno = g_parsefile->linno;
11715 n->ndefun.body = parse_command();
11718 IF_BASH_FUNCTION(function_flag = 0;)
11729 n = stzalloc(sizeof(struct ncmd));
11732 n->ncmd.linno = savelinno;
11733 n->ncmd.args = args;
11734 n->ncmd.assign = vars;
11735 n->ncmd.redirect = redir;
11739 static union node *
11740 parse_command(void)
11742 union node *n1, *n2;
11743 union node *ap, **app;
11744 union node *cp, **cpp;
11745 union node *redir, **rpp;
11753 savelinno = g_parsefile->linno;
11755 switch (readtoken()) {
11757 raise_error_unexpected_syntax(-1);
11760 n1 = stzalloc(sizeof(struct nif));
11762 n1->nif.test = list(0);
11763 if (readtoken() != TTHEN)
11764 raise_error_unexpected_syntax(TTHEN);
11765 n1->nif.ifpart = list(0);
11767 while (readtoken() == TELIF) {
11768 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11769 n2 = n2->nif.elsepart;
11771 n2->nif.test = list(0);
11772 if (readtoken() != TTHEN)
11773 raise_error_unexpected_syntax(TTHEN);
11774 n2->nif.ifpart = list(0);
11776 if (lasttoken == TELSE)
11777 n2->nif.elsepart = list(0);
11779 n2->nif.elsepart = NULL;
11787 n1 = stzalloc(sizeof(struct nbinary));
11788 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11789 n1->nbinary.ch1 = list(0);
11792 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11793 got == TWORD ? wordtext : ""));
11794 raise_error_unexpected_syntax(TDO);
11796 n1->nbinary.ch2 = list(0);
11801 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11802 raise_error_syntax("bad for loop variable");
11803 n1 = stzalloc(sizeof(struct nfor));
11805 n1->nfor.linno = savelinno;
11806 n1->nfor.var = wordtext;
11807 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11808 if (readtoken() == TIN) {
11810 while (readtoken() == TWORD) {
11811 n2 = stzalloc(sizeof(struct narg));
11813 /*n2->narg.next = NULL; - stzalloc did it */
11814 n2->narg.text = wordtext;
11815 n2->narg.backquote = backquotelist;
11817 app = &n2->narg.next;
11820 n1->nfor.args = ap;
11821 if (lasttoken != TNL && lasttoken != TSEMI)
11822 raise_error_unexpected_syntax(-1);
11824 n2 = stzalloc(sizeof(struct narg));
11826 /*n2->narg.next = NULL; - stzalloc did it */
11827 n2->narg.text = (char *)dolatstr;
11828 /*n2->narg.backquote = NULL;*/
11829 n1->nfor.args = n2;
11831 * Newline or semicolon here is optional (but note
11832 * that the original Bourne shell only allowed NL).
11834 if (lasttoken != TSEMI)
11837 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11838 if (readtoken() != TDO)
11839 raise_error_unexpected_syntax(TDO);
11840 n1->nfor.body = list(0);
11844 n1 = stzalloc(sizeof(struct ncase));
11846 n1->ncase.linno = savelinno;
11847 if (readtoken() != TWORD)
11848 raise_error_unexpected_syntax(TWORD);
11849 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11851 /*n2->narg.next = NULL; - stzalloc did it */
11852 n2->narg.text = wordtext;
11853 n2->narg.backquote = backquotelist;
11854 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11855 if (readtoken() != TIN)
11856 raise_error_unexpected_syntax(TIN);
11857 cpp = &n1->ncase.cases;
11859 checkkwd = CHKNL | CHKKWD;
11861 while (t != TESAC) {
11862 if (lasttoken == TLP)
11864 *cpp = cp = stzalloc(sizeof(struct nclist));
11866 app = &cp->nclist.pattern;
11868 *app = ap = stzalloc(sizeof(struct narg));
11870 /*ap->narg.next = NULL; - stzalloc did it */
11871 ap->narg.text = wordtext;
11872 ap->narg.backquote = backquotelist;
11873 if (readtoken() != TPIPE)
11875 app = &ap->narg.next;
11878 //ap->narg.next = NULL;
11879 if (lasttoken != TRP)
11880 raise_error_unexpected_syntax(TRP);
11881 cp->nclist.body = list(2);
11883 cpp = &cp->nclist.next;
11885 checkkwd = CHKNL | CHKKWD;
11889 raise_error_unexpected_syntax(TENDCASE);
11896 n1 = stzalloc(sizeof(struct nredir));
11897 n1->type = NSUBSHELL;
11898 n1->nredir.linno = savelinno;
11899 n1->nredir.n = list(0);
11900 /*n1->nredir.redirect = NULL; - stzalloc did it */
11907 IF_BASH_FUNCTION(case TFUNCTION:)
11911 return simplecmd();
11914 if (readtoken() != t)
11915 raise_error_unexpected_syntax(t);
11918 /* Now check for redirection which may follow command */
11919 checkkwd = CHKKWD | CHKALIAS;
11921 while (readtoken() == TREDIR) {
11922 *rpp = n2 = redirnode;
11923 rpp = &n2->nfile.next;
11929 if (n1->type != NSUBSHELL) {
11930 n2 = stzalloc(sizeof(struct nredir));
11932 n2->nredir.linno = savelinno;
11936 n1->nredir.redirect = redir;
11941 #if BASH_DOLLAR_SQUOTE
11943 decode_dollar_squote(void)
11945 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11951 p = strchr(C_escapes, c);
11956 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11960 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11962 } else if (c == 'x') { /* \xHH */
11966 } while (isxdigit(c) && --cnt);
11968 if (cnt == 3) { /* \x but next char is "bad" */
11972 } else { /* simple seq like \\ or \t */
11977 c = bb_process_escape_sequence((void*)&p);
11978 } else { /* unrecognized "\z": print both chars unless ' or " */
11979 if (c != '\'' && c != '"') {
11981 c |= 0x100; /* "please encode \, then me" */
11988 /* Used by expandstr to get here-doc like behaviour. */
11989 #define FAKEEOFMARK ((char*)(uintptr_t)1)
11991 static ALWAYS_INLINE int
11992 realeofmark(const char *eofmark)
11994 return eofmark && eofmark != FAKEEOFMARK;
11998 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11999 * is not NULL, read a here document. In the latter case, eofmark is the
12000 * word which marks the end of the document and striptabs is true if
12001 * leading tabs should be stripped from the document. The argument c
12002 * is the first character of the input token or document.
12004 * Because C does not have internal subroutines, I have simulated them
12005 * using goto's to implement the subroutine linkage. The following macros
12006 * will run code that appears at the end of readtoken1.
12008 #define CHECKEND() {goto checkend; checkend_return:;}
12009 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
12010 #define PARSESUB() {goto parsesub; parsesub_return:;}
12011 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
12012 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
12013 #define PARSEARITH() {goto parsearith; parsearith_return:;}
12015 readtoken1(int c, int syntax, char *eofmark, int striptabs)
12017 /* NB: syntax parameter fits into smallint */
12018 /* c parameter is an unsigned char or PEOF or PEOA */
12021 struct nodelist *bqlist;
12024 smallint pssyntax; /* we are expanding a prompt string */
12025 IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
12027 struct synstack synbase = { };
12028 struct synstack *synstack = &synbase;
12030 #if ENABLE_ASH_EXPAND_PRMT
12031 pssyntax = (syntax == PSSYNTAX);
12035 pssyntax = 0; /* constant */
12037 synstack->syntax = syntax;
12039 if (syntax == DQSYNTAX)
12040 synstack->dblquote = 1;
12044 STARTSTACKSTR(out);
12046 /* For each line, until end of word */
12047 CHECKEND(); /* set c to PEOF if at end of here document */
12048 for (;;) { /* until end of line or end of word */
12049 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
12050 switch (SIT(c, synstack->syntax)) {
12051 case CNL: /* '\n' */
12052 if (synstack->syntax == BASESYNTAX
12053 && !synstack->varnest
12055 goto endword; /* exit outer loop */
12060 goto loop; /* continue outer loop */
12065 #if BASH_DOLLAR_SQUOTE
12066 if (c == '\\' && bash_dollar_squote) {
12067 c = decode_dollar_squote();
12069 /* skip $'\000', $'\x00' (like bash) */
12073 /* Unknown escape. Encode as '\z' */
12074 c = (unsigned char)c;
12075 if (eofmark == NULL || synstack->dblquote)
12076 USTPUTC(CTLESC, out);
12077 USTPUTC('\\', out);
12081 if (!eofmark || synstack->dblquote || synstack->varnest)
12082 USTPUTC(CTLESC, out);
12085 case CBACK: /* backslash */
12086 c = pgetc_without_PEOA();
12088 USTPUTC(CTLESC, out);
12089 USTPUTC('\\', out);
12091 } else if (c == '\n') {
12094 if (pssyntax && c == '$') {
12095 USTPUTC(CTLESC, out);
12096 USTPUTC('\\', out);
12098 /* Backslash is retained if we are in "str"
12099 * and next char isn't dquote-special.
12101 if (synstack->dblquote
12105 && (c != '"' || (eofmark != NULL && !synstack->varnest))
12106 && (c != '}' || !synstack->varnest)
12108 USTPUTC(CTLESC, out); /* protect '\' from glob */
12109 USTPUTC('\\', out);
12111 USTPUTC(CTLESC, out);
12117 synstack->syntax = SQSYNTAX;
12119 if (eofmark == NULL) {
12120 USTPUTC(CTLQUOTEMARK, out);
12124 synstack->syntax = DQSYNTAX;
12125 synstack->dblquote = 1;
12127 if (synstack->varnest)
12128 synstack->innerdq ^= 1;
12131 IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
12132 if (eofmark != NULL && synstack->varnest == 0) {
12137 if (synstack->dqvarnest == 0) {
12138 synstack->syntax = BASESYNTAX;
12139 synstack->dblquote = 0;
12148 case CVAR: /* '$' */
12149 PARSESUB(); /* parse substitution */
12151 case CENDVAR: /* '}' */
12152 if (!synstack->innerdq && synstack->varnest > 0) {
12153 if (!--synstack->varnest && synstack->varpushed)
12154 synstack_pop(&synstack);
12155 else if (synstack->dqvarnest > 0)
12156 synstack->dqvarnest--;
12161 #if ENABLE_FEATURE_SH_MATH
12162 case CLP: /* '(' in arithmetic */
12163 synstack->parenlevel++;
12166 case CRP: /* ')' in arithmetic */
12167 if (synstack->parenlevel > 0) {
12168 synstack->parenlevel--;
12170 if (pgetc_eatbnl() == ')') {
12172 synstack_pop(&synstack);
12175 * unbalanced parens
12176 * (don't 2nd guess - no error)
12184 case CBQUOTE: /* '`' */
12185 if (checkkwd & CHKEOFMARK) {
12194 goto endword; /* exit outer loop */
12198 if (synstack->varnest == 0) {
12199 #if BASH_REDIR_OUTPUT
12201 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
12202 if (pgetc() == '>')
12203 c = 0x100 + '>'; /* flag &> */
12207 goto endword; /* exit outer loop */
12209 IF_ASH_ALIAS(if (c != PEOA))
12216 #if ENABLE_FEATURE_SH_MATH
12217 if (synstack->syntax == ARISYNTAX)
12218 raise_error_syntax("missing '))'");
12220 if (synstack->syntax != BASESYNTAX && eofmark == NULL)
12221 raise_error_syntax("unterminated quoted string");
12222 if (synstack->varnest != 0) {
12224 raise_error_syntax("missing '}'");
12226 USTPUTC('\0', out);
12227 len = out - (char *)stackblock();
12228 out = stackblock();
12229 if (eofmark == NULL) {
12230 if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
12233 if (isdigit_str9(out)) {
12234 PARSEREDIR(); /* passed as params: out, c */
12235 lasttoken = TREDIR;
12238 /* else: non-number X seen, interpret it
12239 * as "NNNX>file" = "NNNX >file" */
12243 quoteflag = quotef;
12244 backquotelist = bqlist;
12245 grabstackblock(len);
12249 /* end of readtoken routine */
12252 * Check to see whether we are at the end of the here document. When this
12253 * is called, c is set to the first character of the next input line. If
12254 * we are at the end of the here document, this routine sets the c to PEOF.
12257 if (realeofmark(eofmark)) {
12261 #if ENABLE_ASH_ALIAS
12263 c = pgetc_without_PEOA();
12266 while (c == '\t') {
12267 c = pgetc_without_PEOA();
12271 markloc = out - (char *)stackblock();
12272 for (p = eofmark; STPUTC(c, out), *p; p++) {
12276 c = pgetc_without_PEOA();
12279 if (c == '\n' || c == PEOF) {
12281 g_parsefile->linno++;
12282 needprompt = doprompt;
12287 p = (char *)stackblock() + markloc + 1;
12288 len_here = out - p;
12291 len_here -= (c >= PEOF);
12297 str = alloca(len_here + 1);
12298 *(char *)mempcpy(str, p, len_here) = '\0';
12300 pushstring(str, NULL);
12305 STADJUST((char *)stackblock() + markloc - out, out);
12307 goto checkend_return;
12311 * Parse a redirection operator. The variable "out" points to a string
12312 * specifying the fd to be redirected. The variable "c" contains the
12313 * first character of the redirection operator.
12316 /* out is already checked to be a valid number or "" */
12317 int fd = (*out == '\0' ? -1 : atoi(out));
12320 np = stzalloc(sizeof(struct nfile));
12323 c = pgetc_eatbnl();
12325 np->type = NAPPEND;
12327 np->type = NCLOBBER;
12330 /* it also can be NTO2 (>&file), but we can't figure it out yet */
12336 #if BASH_REDIR_OUTPUT
12337 else if (c == 0x100 + '>') { /* this flags &> redirection */
12339 pgetc(); /* this is '>', no need to check */
12343 else { /* c == '<' */
12344 /*np->nfile.fd = 0; - stzalloc did it */
12345 c = pgetc_eatbnl();
12348 if (sizeof(struct nfile) != sizeof(struct nhere)) {
12349 np = stzalloc(sizeof(struct nhere));
12350 /*np->nfile.fd = 0; - stzalloc did it */
12353 heredoc = stzalloc(sizeof(struct heredoc));
12354 heredoc->here = np;
12355 c = pgetc_eatbnl();
12357 heredoc->striptabs = 1;
12359 /*heredoc->striptabs = 0; - stzalloc did it */
12365 np->type = NFROMFD;
12369 np->type = NFROMTO;
12381 goto parseredir_return;
12385 * Parse a substitution. At this point, we have read the dollar sign
12386 * and nothing else.
12389 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
12390 * (assuming ascii char codes, as the original implementation did) */
12391 #define is_special(c) \
12392 (((unsigned)(c) - 33 < 32) \
12393 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
12395 unsigned char subtype;
12398 c = pgetc_eatbnl();
12399 if ((checkkwd & CHKEOFMARK)
12400 || c > 255 /* PEOA or PEOF */
12401 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
12403 #if BASH_DOLLAR_SQUOTE
12404 if (synstack->syntax != DQSYNTAX && c == '\'')
12405 bash_dollar_squote = 1;
12410 } else if (c == '(') {
12411 /* $(command) or $((arith)) */
12412 if (pgetc_eatbnl() == '(') {
12413 #if ENABLE_FEATURE_SH_MATH
12416 raise_error_syntax("support for $((arith)) is disabled");
12423 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
12424 smalluint newsyn = synstack->syntax;
12426 USTPUTC(CTLVAR, out);
12427 typeloc = out - (char *)stackblock();
12429 subtype = VSNORMAL;
12431 c = pgetc_eatbnl();
12436 /* $[{[#]]NAME[}] */
12439 c = pgetc_eatbnl();
12440 } while (is_in_name(c));
12441 } else if (isdigit(c)) {
12442 /* $[{[#]]NUM[}] */
12445 c = pgetc_eatbnl();
12446 } while (isdigit(c));
12447 } else if (c != '}') {
12448 /* $[{[#]]<specialchar>[}] */
12451 c = pgetc_eatbnl();
12452 if (!subtype && cc == '#') {
12453 subtype = VSLENGTH;
12454 if (c == '_' || isalnum(c))
12457 c = pgetc_eatbnl();
12458 if (cc == '}' || c != '}') {
12466 if (!is_special(cc)) {
12467 if (subtype == VSLENGTH)
12476 if (c != '}' && subtype == VSLENGTH) {
12477 /* ${#VAR didn't end with } */
12481 if (subtype == 0) {
12482 static const char types[] ALIGN1 = "}-+?=";
12483 /* ${VAR...} but not $VAR or ${#VAR} */
12484 /* c == first char after VAR */
12489 c = pgetc_eatbnl();
12491 /* This check is only needed to not misinterpret
12492 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
12495 if (!strchr(types, c)) {
12496 subtype = VSSUBSTR;
12498 break; /* "goto badsub" is bigger (!) */
12504 const char *p = strchr(types, c);
12507 subtype |= p - types + VSNORMAL;
12512 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
12513 c = pgetc_eatbnl();
12519 newsyn = BASESYNTAX;
12521 #if BASH_PATTERN_SUBST
12523 /* ${v/[/]pattern/repl} */
12524 //TODO: encode pattern and repl separately.
12525 // Currently cases like: v=1;echo ${v/$((1/1))/ONE}
12526 // are broken (should print "ONE")
12527 subtype = VSREPLACE;
12528 newsyn = BASESYNTAX;
12529 c = pgetc_eatbnl();
12532 subtype++; /* VSREPLACEALL */
12541 if (newsyn == ARISYNTAX)
12544 if ((newsyn != synstack->syntax || synstack->innerdq)
12545 && subtype != VSNORMAL
12547 synstack_push(&synstack,
12548 synstack->prev ?: alloca(sizeof(*synstack)),
12551 synstack->varpushed = 1;
12552 synstack->dblquote = newsyn != BASESYNTAX;
12555 ((unsigned char *)stackblock())[typeloc] = subtype;
12556 if (subtype != VSNORMAL) {
12557 synstack->varnest++;
12558 if (synstack->dblquote)
12559 synstack->dqvarnest++;
12563 goto parsesub_return;
12567 * Called to parse command substitutions. Newstyle is set if the command
12568 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
12569 * list of commands (passed by reference), and savelen is the number of
12570 * characters on the top of the stack which must be preserved.
12573 struct nodelist **nlpp;
12577 smallint saveprompt = 0;
12580 savelen = out - (char *)stackblock();
12583 * FIXME: this can allocate very large block on stack and SEGV.
12585 * echo "..<100kbytes>..`true` $(true) `true` ..."
12586 * allocates 100kb for every command subst. With about
12587 * a hundred command substitutions stack overflows.
12588 * With larger prepended string, SEGV happens sooner.
12590 str = alloca(savelen);
12591 memcpy(str, stackblock(), savelen);
12595 /* We must read until the closing backquote, giving special
12596 * treatment to some slashes, and then push the string and
12597 * reread it as input, interpreting it normally.
12603 STARTSTACKSTR(pout);
12607 setprompt_if(needprompt, 2);
12608 pc = pgetc_eatbnl();
12614 pc = pgetc(); /* or pgetc_eatbnl()? why (example)? */
12615 if (pc != '\\' && pc != '`' && pc != '$'
12616 && (!synstack->dblquote || pc != '"')
12618 STPUTC('\\', pout);
12620 if (pc <= 255 /* not PEOA or PEOF */) {
12626 IF_ASH_ALIAS(case PEOA:)
12627 raise_error_syntax("EOF in backquote substitution");
12639 STPUTC('\0', pout);
12640 psavelen = pout - (char *)stackblock();
12641 if (psavelen > 0) {
12642 pstr = grabstackstr(pout);
12643 setinputstring(pstr);
12648 nlpp = &(*nlpp)->next;
12649 *nlpp = stzalloc(sizeof(**nlpp));
12650 /* (*nlpp)->next = NULL; - stzalloc did it */
12653 saveprompt = doprompt;
12660 doprompt = saveprompt;
12661 else if (readtoken() != TRP)
12662 raise_error_unexpected_syntax(TRP);
12667 * Start reading from old file again, ignoring any pushed back
12668 * tokens left from the backquote parsing
12673 while (stackblocksize() <= savelen)
12675 STARTSTACKSTR(out);
12677 memcpy(out, str, savelen);
12678 STADJUST(savelen, out);
12680 USTPUTC(CTLBACKQ, out);
12682 goto parsebackq_oldreturn;
12683 goto parsebackq_newreturn;
12686 #if ENABLE_FEATURE_SH_MATH
12688 * Parse an arithmetic expansion (indicate start of one and set state)
12692 synstack_push(&synstack,
12693 synstack->prev ?: alloca(sizeof(*synstack)),
12695 synstack->dblquote = 1;
12696 USTPUTC(CTLARI, out);
12697 goto parsearith_return;
12700 } /* end of readtoken */
12703 * Read the next input token.
12704 * If the token is a word, we set backquotelist to the list of cmds in
12705 * backquotes. We set quoteflag to true if any part of the word was
12707 * If the token is TREDIR, then we set redirnode to a structure containing
12710 * [Change comment: here documents and internal procedures]
12711 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12712 * word parsing code into a separate routine. In this case, readtoken
12713 * doesn't need to have any internal procedures, but parseword does.
12714 * We could also make parseoperator in essence the main routine, and
12715 * have parseword (readtoken1?) handle both words and redirection.]
12717 #define NEW_xxreadtoken
12718 #ifdef NEW_xxreadtoken
12719 /* singles must be first! */
12720 static const char xxreadtoken_chars[7] ALIGN1 = {
12721 '\n', '(', ')', /* singles */
12722 '&', '|', ';', /* doubles */
12726 #define xxreadtoken_singles 3
12727 #define xxreadtoken_doubles 3
12729 static const char xxreadtoken_tokens[] ALIGN1 = {
12730 TNL, TLP, TRP, /* only single occurrence allowed */
12731 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12732 TEOF, /* corresponds to trailing nul */
12733 TAND, TOR, TENDCASE /* if double occurrence */
12745 setprompt_if(needprompt, 2);
12746 for (;;) { /* until token or start of word found */
12747 c = pgetc_eatbnl();
12748 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12752 while ((c = pgetc()) != '\n' && c != PEOF)
12755 } else if (c == '\\') {
12756 break; /* return readtoken1(...) */
12760 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12766 p = strchr(xxreadtoken_chars, c);
12768 break; /* return readtoken1(...) */
12770 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12771 int cc = pgetc_eatbnl();
12772 if (cc == c) { /* double occurrence? */
12773 p += xxreadtoken_doubles + 1;
12776 #if BASH_REDIR_OUTPUT
12777 if (c == '&' && cc == '>') /* &> */
12778 break; /* return readtoken1(...) */
12783 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12788 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12790 #else /* old xxreadtoken */
12791 #define RETURN(token) return lasttoken = token
12801 setprompt_if(needprompt, 2);
12802 for (;;) { /* until token or start of word found */
12803 c = pgetc_eatbnl();
12805 case ' ': case '\t':
12806 IF_ASH_ALIAS(case PEOA:)
12809 while ((c = pgetc()) != '\n' && c != PEOF)
12819 if (pgetc_eatbnl() == '&')
12824 if (pgetc_eatbnl() == '|')
12829 if (pgetc_eatbnl() == ';')
12840 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12843 #endif /* old xxreadtoken */
12849 int kwd = checkkwd;
12851 smallint alreadyseen = tokpushback;
12854 #if ENABLE_ASH_ALIAS
12870 if (t != TWORD || quoteflag) {
12875 * check for keywords
12877 if (kwd & CHKKWD) {
12878 const char *const *pp;
12880 pp = findkwd(wordtext);
12882 lasttoken = t = pp - tokname_array;
12883 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12888 if (checkkwd & CHKALIAS) {
12889 #if ENABLE_ASH_ALIAS
12891 ap = lookupalias(wordtext, 1);
12894 pushstring(ap->val, ap);
12904 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12906 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12922 * Read and parse a command. Returns NODE_EOF on end of file.
12923 * (NULL is a valid parse tree indicating a blank line.)
12925 static union node *
12926 parsecmd(int interact)
12931 doprompt = interact;
12932 setprompt_if(doprompt, doprompt);
12938 * Input any here documents.
12943 struct heredoc *here;
12946 here = heredoclist;
12947 heredoclist = NULL;
12951 setprompt_if(needprompt, 2);
12952 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12953 here->eofmark, here->striptabs);
12954 n = stzalloc(sizeof(struct narg));
12955 n->narg.type = NARG;
12956 /*n->narg.next = NULL; - stzalloc did it */
12957 n->narg.text = wordtext;
12958 n->narg.backquote = backquotelist;
12959 here->here->nhere.doc = n;
12965 static const char *
12966 expandstr(const char *ps, int syntax_type)
12971 /* XXX Fix (char *) cast. */
12972 setinputstring((char *)ps);
12974 saveprompt = doprompt;
12977 /* readtoken1() might die horribly.
12978 * Try a prompt with syntactically wrong command:
12979 * PS1='$(date "+%H:%M:%S) > '
12982 volatile int saveint;
12983 struct jmploc *volatile savehandler = exception_handler;
12984 struct jmploc jmploc;
12986 if (setjmp(jmploc.loc) == 0) {
12987 exception_handler = &jmploc;
12988 readtoken1(pgetc(), syntax_type, FAKEEOFMARK, 0);
12990 exception_handler = savehandler;
12991 RESTORE_INT(saveint);
12994 doprompt = saveprompt;
12998 n.narg.type = NARG;
12999 n.narg.next = NULL;
13000 n.narg.text = wordtext;
13001 n.narg.backquote = backquotelist;
13003 expandarg(&n, NULL, EXP_QUOTED);
13004 return stackblock();
13010 return tokpushback && lasttoken == TEOF;
13014 * Execute a command or commands contained in a string.
13017 evalstring(char *s, int flags)
13019 struct jmploc *volatile savehandler;
13020 struct jmploc jmploc;
13024 struct stackmark smark;
13029 setstackmark(&smark);
13032 /* On exception inside execution loop, we must popfile().
13033 * Try interactively:
13035 * command eval "a=b" # throws "is read only" error
13036 * "command BLTIN" is not supposed to abort (even in non-interactive use).
13037 * But if we skip popfile(), we hit EOF in eval's string, and exit.
13039 savehandler = exception_handler;
13040 ex = setjmp(jmploc.loc);
13043 exception_handler = &jmploc;
13045 while ((n = parsecmd(0)) != NODE_EOF) {
13048 i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
13051 popstackmark(&smark);
13056 popstackmark(&smark);
13060 exception_handler = savehandler;
13062 longjmp(exception_handler->loc, ex);
13068 * The eval command.
13070 static int FAST_FUNC
13071 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
13080 STARTSTACKSTR(concat);
13082 concat = stack_putstr(p, concat);
13086 STPUTC(' ', concat);
13088 STPUTC('\0', concat);
13089 p = grabstackstr(concat);
13091 return evalstring(p, flags & EV_TESTED);
13097 * Read and execute commands.
13098 * "Top" is nonzero for the top level command loop;
13099 * it turns on prompting if the shell is interactive.
13105 struct stackmark smark;
13110 TRACE(("cmdloop(%d) called\n", top));
13114 setstackmark(&smark);
13117 showjobs(SHOW_CHANGED|SHOW_STDERR);
13120 if (iflag && top) {
13124 n = parsecmd(inter);
13126 if (DEBUG > 2 && debug && (n != NODE_EOF))
13129 if (n == NODE_EOF) {
13130 if (!top || numeof >= 50)
13132 if (!stoppedjobs()) {
13135 out2str("\nUse \"exit\" to leave shell.\n");
13138 } else if (nflag == 0) {
13141 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
13144 i = evaltree(n, 0);
13148 popstackmark(&smark);
13152 evalskip &= ~SKIPFUNC;
13160 * Take commands from a file. To be compatible we should do a path
13161 * search for the file, which is necessary to find sub-commands.
13164 find_dot_file(char *name)
13167 const char *path = pathval();
13170 /* don't try this for absolute or relative paths */
13171 if (strchr(name, '/'))
13174 while ((fullname = path_advance(&path, name)) != NULL) {
13175 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
13177 * Don't bother freeing here, since it will
13178 * be freed by the caller.
13182 if (fullname != name)
13183 stunalloc(fullname);
13185 /* not found in PATH */
13187 #if ENABLE_ASH_BASH_SOURCE_CURDIR
13190 ash_msg_and_raise_error("%s: not found", name);
13195 static int FAST_FUNC
13196 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
13198 /* "false; . empty_file; echo $?" should print 0, not 1: */
13202 char *args_need_save;
13203 volatile struct shparam saveparam;
13206 // struct strlist *sp;
13207 // for (sp = cmdenviron; sp; sp = sp->next)
13208 // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
13210 nextopt(nullstr); /* handle possible "--" */
13214 /* bash says: "bash: .: filename argument required" */
13215 return 2; /* bash compat */
13218 /* This aborts if file isn't found, which is POSIXly correct.
13219 * bash returns exitcode 1 instead.
13221 fullname = find_dot_file(argv[0]);
13223 args_need_save = argv[0];
13224 if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
13226 saveparam = shellparam;
13227 shellparam.malloced = 0;
13231 shellparam.nparam = argc;
13232 shellparam.p = argv;
13235 /* This aborts if file can't be opened, which is POSIXly correct.
13236 * bash returns exitcode 1 instead.
13238 setinputfile(fullname, INPUT_PUSH_FILE);
13239 commandname = fullname;
13240 status = cmdloop(0);
13243 if (args_need_save) {
13244 freeparam(&shellparam);
13245 shellparam = saveparam;
13251 static int FAST_FUNC
13252 exitcmd(int argc UNUSED_PARAM, char **argv)
13257 exitstatus = number(argv[1]);
13258 raise_exception(EXEXIT);
13263 * Read a file containing shell functions.
13266 readcmdfile(char *name)
13268 setinputfile(name, INPUT_PUSH_FILE);
13274 /* ============ find_command inplementation */
13277 * Resolve a command name. If you change this routine, you may have to
13278 * change the shellexec routine as well.
13281 find_command(char *name, struct cmdentry *entry, int act, const char *path)
13283 struct tblentry *cmdp;
13290 struct builtincmd *bcmd;
13292 /* If name contains a slash, don't use PATH or hash table */
13293 if (strchr(name, '/') != NULL) {
13294 entry->u.index = -1;
13295 if (act & DO_ABS) {
13296 while (stat(name, &statb) < 0) {
13298 if (errno == EINTR)
13301 entry->cmdtype = CMDUNKNOWN;
13305 entry->cmdtype = CMDNORMAL;
13309 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
13311 updatetbl = (path == pathval());
13314 if (strstr(path, "%builtin") != NULL)
13315 act |= DO_ALTBLTIN;
13318 /* If name is in the table, check answer will be ok */
13319 cmdp = cmdlookup(name, 0);
13320 if (cmdp != NULL) {
13323 switch (cmdp->cmdtype) {
13341 } else if (cmdp->rehash == 0)
13342 /* if not invalidated by cd, we're done */
13346 /* If %builtin not in path, check for builtin next */
13347 bcmd = find_builtin(name);
13349 if (IS_BUILTIN_REGULAR(bcmd))
13350 goto builtin_success;
13351 if (act & DO_ALTPATH) {
13352 if (!(act & DO_ALTBLTIN))
13353 goto builtin_success;
13354 } else if (builtinloc <= 0) {
13355 goto builtin_success;
13359 #if ENABLE_FEATURE_SH_STANDALONE
13361 int applet_no = find_applet_by_name(name);
13362 if (applet_no >= 0) {
13363 entry->cmdtype = CMDNORMAL;
13364 entry->u.index = -2 - applet_no;
13370 /* We have to search path. */
13371 prev = -1; /* where to start */
13372 if (cmdp && cmdp->rehash) { /* doing a rehash */
13373 if (cmdp->cmdtype == CMDBUILTIN)
13376 prev = cmdp->param.index;
13382 while ((fullname = path_advance(&path, name)) != NULL) {
13383 stunalloc(fullname);
13384 /* NB: code below will still use fullname
13385 * despite it being "unallocated" */
13388 if (prefix(pathopt, "builtin")) {
13390 goto builtin_success;
13393 if ((act & DO_NOFUNC)
13394 || !prefix(pathopt, "func")
13395 ) { /* ignore unimplemented options */
13399 /* if rehash, don't redo absolute path names */
13400 if (fullname[0] == '/' && idx <= prev) {
13403 TRACE(("searchexec \"%s\": no change\n", name));
13406 while (stat(fullname, &statb) < 0) {
13408 if (errno == EINTR)
13411 if (errno != ENOENT && errno != ENOTDIR)
13415 e = EACCES; /* if we fail, this will be the error */
13416 if (!S_ISREG(statb.st_mode))
13418 if (pathopt) { /* this is a %func directory */
13419 stalloc(strlen(fullname) + 1);
13420 /* NB: stalloc will return space pointed by fullname
13421 * (because we don't have any intervening allocations
13422 * between stunalloc above and this stalloc) */
13423 readcmdfile(fullname);
13424 cmdp = cmdlookup(name, 0);
13425 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
13426 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
13427 stunalloc(fullname);
13430 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
13432 entry->cmdtype = CMDNORMAL;
13433 entry->u.index = idx;
13437 cmdp = cmdlookup(name, 1);
13438 cmdp->cmdtype = CMDNORMAL;
13439 cmdp->param.index = idx;
13444 /* We failed. If there was an entry for this command, delete it */
13445 if (cmdp && updatetbl)
13446 delete_cmd_entry();
13447 if (act & DO_ERR) {
13448 #if ENABLE_ASH_BASH_NOT_FOUND_HOOK
13449 struct tblentry *hookp = cmdlookup("command_not_found_handle", 0);
13450 if (hookp && hookp->cmdtype == CMDFUNCTION) {
13452 argv[0] = (char*) "command_not_found_handle";
13455 evalfun(hookp->param.func, 2, argv, 0);
13456 entry->cmdtype = CMDUNKNOWN;
13460 ash_msg("%s: %s", name, errmsg(e, "not found"));
13462 entry->cmdtype = CMDUNKNOWN;
13467 entry->cmdtype = CMDBUILTIN;
13468 entry->u.cmd = bcmd;
13472 cmdp = cmdlookup(name, 1);
13473 cmdp->cmdtype = CMDBUILTIN;
13474 cmdp->param.cmd = bcmd;
13478 entry->cmdtype = cmdp->cmdtype;
13479 entry->u = cmdp->param;
13484 * The trap builtin.
13486 static int FAST_FUNC
13487 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13491 int signo, exitcode;
13496 for (signo = 0; signo < NSIG; signo++) {
13497 char *tr = trap_ptr[signo];
13499 /* note: bash adds "SIG", but only if invoked
13500 * as "bash". If called as "sh", or if set -o posix,
13501 * then it prints short signal names.
13502 * We are printing short names: */
13503 out1fmt("trap -- %s %s\n",
13505 get_signame(signo));
13506 /* trap_ptr != trap only if we are in special-cased `trap` code.
13507 * In this case, we will exit very soon, no need to free(). */
13508 /* if (trap_ptr != trap && tp[0]) */
13513 if (trap_ptr != trap) {
13521 /* Why the second check?
13522 * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
13523 * In this case, NUM is signal no, not an action.
13526 if (ap[1] && !is_number(ap[0]))
13531 signo = get_signum(*ap);
13533 /* Mimic bash message exactly */
13534 ash_msg("%s: invalid signal specification", *ap);
13540 if (LONE_DASH(action))
13543 if (action[0]) /* not NULL and not "" and not "-" */
13544 may_have_traps = 1;
13545 action = ckstrdup(action);
13549 trap[signo] = action;
13560 /* ============ Builtins */
13562 #if ENABLE_ASH_HELP
13563 static int FAST_FUNC
13564 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13570 "Built-in commands:\n"
13571 "------------------\n");
13572 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
13573 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
13574 builtintab[i].name + 1);
13580 # if ENABLE_FEATURE_SH_STANDALONE
13582 const char *a = applet_names;
13584 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
13589 while (*a++ != '\0')
13594 newline_and_flush(stdout);
13595 return EXIT_SUCCESS;
13600 static int FAST_FUNC
13601 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13603 show_history(line_input_state);
13604 return EXIT_SUCCESS;
13609 * The export and readonly commands.
13611 static int FAST_FUNC
13612 exportcmd(int argc UNUSED_PARAM, char **argv)
13622 /* "readonly" in bash accepts, but ignores -n.
13623 * We do the same: it saves a conditional in nextopt's param.
13626 while ((opt = nextopt("np")) != '\0') {
13628 flag_off = VEXPORT;
13631 if (argv[0][0] == 'r') {
13633 flag_off = 0; /* readonly ignores -n */
13635 flag_off = ~flag_off;
13637 /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
13643 p = strchr(name, '=');
13647 vp = *findvar(hashvar(name), name);
13649 vp->flags = ((vp->flags | flag) & flag_off);
13653 setvar(name, p, (flag & flag_off));
13654 } while ((name = *++aptr) != NULL);
13659 /* No arguments. Show the list of exported or readonly vars.
13662 showvars(argv[0], flag, 0);
13667 * Delete a function if it exists.
13670 unsetfunc(const char *name)
13672 struct tblentry *cmdp;
13674 cmdp = cmdlookup(name, 0);
13675 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
13676 delete_cmd_entry();
13680 * The unset builtin command. We unset the function before we unset the
13681 * variable to allow a function to be unset when there is a readonly variable
13682 * with the same name.
13684 static int FAST_FUNC
13685 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13691 while ((i = nextopt("vf")) != 0) {
13695 for (ap = argptr; *ap; ap++) {
13706 static const unsigned char timescmd_str[] ALIGN1 = {
13707 ' ', offsetof(struct tms, tms_utime),
13708 '\n', offsetof(struct tms, tms_stime),
13709 ' ', offsetof(struct tms, tms_cutime),
13710 '\n', offsetof(struct tms, tms_cstime),
13713 static int FAST_FUNC
13714 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13717 const unsigned char *p;
13720 clk_tck = bb_clk_tck();
13725 unsigned sec, frac;
13727 t = *(clock_t *)(((char *) &buf) + p[1]);
13729 frac = t % clk_tck;
13730 out1fmt("%um%u.%03us%c",
13731 sec / 60, sec % 60,
13732 (frac * 1000) / clk_tck,
13740 #if ENABLE_FEATURE_SH_MATH
13742 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13743 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13745 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13747 static int FAST_FUNC
13748 letcmd(int argc UNUSED_PARAM, char **argv)
13754 ash_msg_and_raise_error("expression expected");
13756 i = ash_arith(*argv);
13764 * The read builtin. Options:
13765 * -r Do not interpret '\' specially
13766 * -s Turn off echo (tty only)
13767 * -n NCHARS Read NCHARS max
13768 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13769 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13770 * -u FD Read from given FD instead of fd 0
13771 * -d DELIM End on DELIM char, not newline
13772 * This uses unbuffered input, which may be avoidable in some cases.
13773 * TODO: bash also has:
13774 * -a ARRAY Read into array[0],[1],etc
13775 * -e Use line editing (tty only)
13777 static int FAST_FUNC
13778 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13780 struct builtin_read_params params;
13784 memset(¶ms, 0, sizeof(params));
13786 while ((i = nextopt("p:u:rt:n:sd:")) != '\0') {
13789 params.opt_p = optionarg;
13792 params.opt_n = optionarg;
13795 params.read_flags |= BUILTIN_READ_SILENT;
13798 params.opt_t = optionarg;
13801 params.read_flags |= BUILTIN_READ_RAW;
13804 params.opt_u = optionarg;
13808 params.opt_d = optionarg;
13816 params.argv = argptr;
13817 params.setvar = setvar0;
13818 params.ifs = bltinlookup("IFS"); /* can be NULL */
13820 /* "read -s" needs to save/restore termios, can't allow ^C
13821 * to jump out of it.
13825 r = shell_builtin_read(¶ms);
13828 if ((uintptr_t)r == 1 && errno == EINTR) {
13829 /* To get SIGCHLD: sleep 1 & read x; echo $x
13830 * Correct behavior is to not exit "read"
13832 if (pending_sig == 0)
13836 if ((uintptr_t)r > 1)
13837 ash_msg_and_raise_error(r);
13839 return (uintptr_t)r;
13842 static int FAST_FUNC
13843 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13845 static const char permuser[3] ALIGN1 = "ogu";
13848 int symbolic_mode = 0;
13850 while (nextopt("S") != '\0') {
13859 if (*argptr == NULL) {
13860 if (symbolic_mode) {
13861 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13868 *p++ = permuser[i];
13870 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13871 if (!(mask & 0400)) *p++ = 'r';
13872 if (!(mask & 0200)) *p++ = 'w';
13873 if (!(mask & 0100)) *p++ = 'x';
13881 out1fmt("%04o\n", mask);
13884 char *modestr = *argptr;
13885 /* numeric umasks are taken as-is */
13886 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13887 if (!isdigit(modestr[0]))
13889 mask = bb_parse_mode(modestr, mask);
13890 if ((unsigned)mask > 0777) {
13891 ash_msg_and_raise_error("illegal mode: %s", modestr);
13893 if (!isdigit(modestr[0]))
13900 static int FAST_FUNC
13901 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13903 return shell_builtin_ulimit(argv);
13906 /* ============ main() and helpers */
13909 * Called to exit the shell.
13918 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13919 save_history(line_input_state);
13921 status = exitstatus;
13922 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13923 if (setjmp(loc.loc)) {
13924 if (exception_type == EXEXIT)
13925 status = exitstatus;
13928 exception_handler = &loc;
13934 /*free(p); - we'll exit soon */
13937 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13938 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13941 flush_stdout_stderr();
13946 /* Don't inline: conserve stack of caller from having our locals too */
13947 static NOINLINE void
13950 /* we will never free this */
13951 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13954 sigmode[SIGCHLD - 1] = S_DFL; /* ensure we install handler even if it is SIG_IGNed */
13955 setsignal(SIGCHLD);
13957 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13958 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13960 signal(SIGHUP, SIG_DFL);
13967 for (envp = environ; envp && *envp; envp++) {
13969 * p = endofname(*envp);
13970 * if (p != *envp && *p == '=') {
13971 * here to weed out badly-named variables, but this breaks
13972 * scenarios where people do want them passed to children:
13974 * os.environ["test-test"]="test"
13975 * if os.fork() == 0:
13976 * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
13977 * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ]) # breaks this
13979 if (strchr(*envp, '=')) {
13980 setvareq(*envp, VEXPORT|VTEXTFIXED);
13984 setvareq((char*)defifsvar, VTEXTFIXED);
13985 setvareq((char*)defoptindvar, VTEXTFIXED);
13987 setvar0("PPID", utoa(getppid()));
13989 p = lookupvar("SHLVL");
13990 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13992 #if BASH_HOSTNAME_VAR
13993 if (!lookupvar("HOSTNAME")) {
13994 struct utsname uts;
13996 setvar0("HOSTNAME", uts.nodename);
13999 p = lookupvar("PWD");
14001 struct stat st1, st2;
14002 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
14003 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
14013 //usage:#define ash_trivial_usage
14014 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
14015 //usage:#define ash_full_usage "\n\n"
14016 //usage: "Unix shell interpreter"
14019 * Process the shell command line arguments.
14022 procargs(char **argv)
14025 const char *xminusc;
14030 login_sh = xargv[0] && xargv[0][0] == '-';
14031 #if NUM_SCRIPTS > 0
14036 /* if (xargv[0]) - mmm, this is always true! */
14039 for (i = 0; i < NOPTS; i++)
14041 if (options(/*cmdline:*/ 1, &login_sh)) {
14042 /* it already printed err message */
14043 raise_exception(EXERROR);
14047 if (*xargv == NULL) {
14049 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
14052 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
14056 for (i = 0; i < NOPTS; i++)
14057 if (optlist[i] == 2)
14062 /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
14067 } else if (!sflag) {
14068 setinputfile(*xargv, 0);
14071 commandname = arg0;
14074 shellparam.p = xargv;
14075 #if ENABLE_ASH_GETOPTS
14076 shellparam.optind = 1;
14077 shellparam.optoff = -1;
14079 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
14081 shellparam.nparam++;
14090 * Read /etc/profile, ~/.profile, $ENV.
14093 read_profile(const char *name)
14095 name = expandstr(name, DQSYNTAX);
14096 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
14103 * This routine is called when an error or an interrupt occurs in an
14104 * interactive shell and control is returned to the main command loop.
14105 * (In dash, this function is auto-generated by build machinery).
14114 /* from expand.c: */
14117 /* from input.c: */
14118 g_parsefile->left_in_buffer = 0;
14119 g_parsefile->left_in_line = 0; /* clear input buffer */
14122 /* from redir.c: */
14126 unwindlocalvars(NULL);
14130 static short profile_buf[16384];
14131 extern int etext();
14135 * Main routine. We initialize things, parse the arguments, execute
14136 * profiles if we're a login shell, and then call cmdloop to execute
14137 * commands. The setjmp call sets up the location to jump to when an
14138 * exception occurs. When an exception occurs the variable "state"
14139 * is used to figure out how far we had gotten.
14141 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
14142 #if NUM_SCRIPTS > 0
14143 int ash_main(int argc, char **argv)
14145 int ash_main(int argc UNUSED_PARAM, char **argv)
14147 /* note: 'argc' is used only if embedded scripts are enabled */
14149 volatile smallint state;
14150 struct jmploc jmploc;
14151 struct stackmark smark;
14154 /* Initialize global data */
14158 #if ENABLE_ASH_ALIAS
14164 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
14167 #if ENABLE_FEATURE_EDITING
14168 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
14171 if (setjmp(jmploc.loc)) {
14177 e = exception_type;
14179 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
14183 newline_and_flush(stderr);
14186 popstackmark(&smark);
14187 FORCE_INT_ON; /* enable interrupts */
14196 exception_handler = &jmploc;
14197 rootpid = getpid();
14200 setstackmark(&smark);
14202 #if NUM_SCRIPTS > 0
14204 /* Non-NULL minusc tells procargs that an embedded script is being run */
14205 minusc = get_script_content(-argc - 1);
14207 login_sh = procargs(argv);
14209 TRACE(("Shell args: "));
14210 trace_puts_args(argv);
14217 read_profile("/etc/profile");
14220 hp = lookupvar("HOME");
14222 read_profile("$HOME/.profile");
14228 getuid() == geteuid() && getgid() == getegid() &&
14232 const char *shinit = lookupvar("ENV");
14233 if (shinit != NULL && *shinit != '\0')
14234 read_profile(shinit);
14236 popstackmark(&smark);
14240 /* evalstring pushes parsefile stack.
14241 * Ensure we don't falsely claim that 0 (stdin)
14242 * is one of stacked source fds.
14243 * Testcase: ash -c 'exec 1>&0' must not complain. */
14244 // if (!sflag) g_parsefile->pf_fd = -1;
14245 // ^^ not necessary since now we special-case fd 0
14246 // in save_fd_on_redirect()
14247 evalstring(minusc, sflag ? 0 : EV_EXIT);
14250 if (sflag || minusc == NULL) {
14251 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
14253 const char *hp = lookupvar("HISTFILE");
14255 hp = lookupvar("HOME");
14258 hp = concat_path_file(hp, ".ash_history");
14259 setvar0("HISTFILE", hp);
14262 hp = lookupvar("HISTFILE");
14266 line_input_state->hist_file = hp;
14267 # if ENABLE_FEATURE_SH_HISTFILESIZE
14268 hp = lookupvar("HISTFILESIZE");
14269 line_input_state->max_history = size_from_HISTFILESIZE(hp);
14273 state4: /* XXX ??? - why isn't this before the "if" statement */
14281 extern void _mcleanup(void);
14285 TRACE(("End of main reached\n"));
14292 * Copyright (c) 1989, 1991, 1993, 1994
14293 * The Regents of the University of California. All rights reserved.
14295 * This code is derived from software contributed to Berkeley by
14296 * Kenneth Almquist.
14298 * Redistribution and use in source and binary forms, with or without
14299 * modification, are permitted provided that the following conditions
14301 * 1. Redistributions of source code must retain the above copyright
14302 * notice, this list of conditions and the following disclaimer.
14303 * 2. Redistributions in binary form must reproduce the above copyright
14304 * notice, this list of conditions and the following disclaimer in the
14305 * documentation and/or other materials provided with the distribution.
14306 * 3. Neither the name of the University nor the names of its contributors
14307 * may be used to endorse or promote products derived from this software
14308 * without specific prior written permission.
14310 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
14311 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
14312 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
14313 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
14314 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
14315 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
14316 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
14317 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
14318 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
14319 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF