1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * This code is derived from software contributed to Berkeley by
8 * Original BSD copyright notice is retained at the end of this file.
10 * Copyright (c) 1989, 1991, 1993, 1994
11 * The Regents of the University of California. All rights reserved.
13 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
14 * was re-ported from NetBSD and debianized.
16 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
19 //config: bool "ash (77 kb)"
21 //config: depends on !NOMMU
23 //config: The most complete and most pedantically correct shell included with
24 //config: busybox. This shell is actually a derivative of the Debian 'dash'
25 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
26 //config: (written by Kenneth Almquist) from NetBSD.
28 //config:# ash options
29 //config:# note: Don't remove !NOMMU part in the next line; it would break
30 //config:# menuconfig's indenting.
31 //config:if !NOMMU && (ASH || SH_IS_ASH || BASH_IS_ASH)
33 //config:config ASH_OPTIMIZE_FOR_SIZE
34 //config: bool "Optimize for size instead of speed"
36 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
38 //config:config ASH_INTERNAL_GLOB
39 //config: bool "Use internal glob() implementation"
40 //config: default y # Y is bigger, but because of uclibc glob() bug, let Y be default for now
41 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
43 //config: Do not use glob() function from libc, use internal implementation.
44 //config: Use this if you are getting "glob.h: No such file or directory"
45 //config: or similar build errors.
46 //config: Note that as of now (2017-01), uclibc and musl glob() both have bugs
47 //config: which would break ash if you select N here.
49 //config:config ASH_BASH_COMPAT
50 //config: bool "bash-compatible extensions"
52 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
54 //config:config ASH_JOB_CONTROL
55 //config: bool "Job control"
57 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
59 //config:config ASH_ALIAS
60 //config: bool "Alias support"
62 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
64 //config:config ASH_RANDOM_SUPPORT
65 //config: bool "Pseudorandom generator and $RANDOM variable"
67 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
69 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
70 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
71 //config: You can reset the generator by using a specified start value.
72 //config: After "unset RANDOM" the generator will switch off and this
73 //config: variable will no longer have special treatment.
75 //config:config ASH_EXPAND_PRMT
76 //config: bool "Expand prompt string"
78 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
80 //config: $PS# may contain volatile content, such as backquote commands.
81 //config: This option recreates the prompt string from the environment
82 //config: variable each time it is displayed.
84 //config:config ASH_IDLE_TIMEOUT
85 //config: bool "Idle timeout variable $TMOUT"
87 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
89 //config: Enable bash-like auto-logout after $TMOUT seconds of idle time.
91 //config:config ASH_MAIL
92 //config: bool "Check for new mail in interactive shell"
94 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
96 //config: Enable "check for new mail" function:
97 //config: if set, $MAIL file and $MAILPATH list of files
98 //config: are checked for mtime changes, and "you have mail"
99 //config: message is printed if change is detected.
101 //config:config ASH_ECHO
102 //config: bool "echo builtin"
104 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
106 //config:config ASH_PRINTF
107 //config: bool "printf builtin"
109 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
111 //config:config ASH_TEST
112 //config: bool "test builtin"
114 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
116 //config:config ASH_HELP
117 //config: bool "help builtin"
119 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
121 //config:config ASH_GETOPTS
122 //config: bool "getopts builtin"
124 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
126 //config:config ASH_CMDCMD
127 //config: bool "command builtin"
129 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
131 //config: Enable support for the 'command' builtin, which allows
132 //config: you to run the specified command or builtin,
133 //config: even when there is a function with the same name.
135 //config:endif # ash options
137 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
138 // APPLET_ODDNAME:name main location suid_type help
139 //applet:IF_SH_IS_ASH( APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
140 //applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
142 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
143 //kbuild:lib-$(CONFIG_SH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
144 //kbuild:lib-$(CONFIG_BASH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
145 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
148 * DEBUG=1 to compile in debugging ('set -o debug' turns on)
149 * DEBUG=2 to compile in and turn on debugging.
150 * When debugging is on ("set -o debug" was executed, or DEBUG=2),
151 * debugging info is written to ./trace, quit signal generates core dump.
154 /* Tweak debug output verbosity here */
158 #define DEBUG_INTONOFF 0
162 #define JOBS ENABLE_ASH_JOB_CONTROL
166 #include <sys/times.h>
167 #include <sys/utsname.h> /* for setting $HOSTNAME */
168 #include "busybox.h" /* for applet_names */
170 /* So far, all bash compat is controlled by one config option */
171 /* Separate defines document which part of code implements what */
172 /* function keyword */
173 #define BASH_FUNCTION ENABLE_ASH_BASH_COMPAT
174 #define IF_BASH_FUNCTION IF_ASH_BASH_COMPAT
176 #define BASH_REDIR_OUTPUT ENABLE_ASH_BASH_COMPAT
177 #define IF_BASH_REDIR_OUTPUT IF_ASH_BASH_COMPAT
179 #define BASH_DOLLAR_SQUOTE ENABLE_ASH_BASH_COMPAT
180 #define IF_BASH_DOLLAR_SQUOTE IF_ASH_BASH_COMPAT
181 #define BASH_PATTERN_SUBST ENABLE_ASH_BASH_COMPAT
182 #define IF_BASH_PATTERN_SUBST IF_ASH_BASH_COMPAT
183 #define BASH_SUBSTR ENABLE_ASH_BASH_COMPAT
184 #define IF_BASH_SUBSTR IF_ASH_BASH_COMPAT
186 #define BASH_TEST2 (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)
187 #define BASH_SOURCE ENABLE_ASH_BASH_COMPAT
188 #define BASH_PIPEFAIL ENABLE_ASH_BASH_COMPAT
189 #define BASH_HOSTNAME_VAR ENABLE_ASH_BASH_COMPAT
190 #define BASH_SHLVL_VAR ENABLE_ASH_BASH_COMPAT
192 #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
193 /* Bionic at least up to version 24 has no glob() */
194 # undef ENABLE_ASH_INTERNAL_GLOB
195 # define ENABLE_ASH_INTERNAL_GLOB 1
198 #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
199 # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
200 # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
201 # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
202 # error glob() should unbackslash them and match. uClibc does not unbackslash,
203 # error fails to match dirname, subsequently not expanding <pattern> in it.
205 // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
206 // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
209 #if !ENABLE_ASH_INTERNAL_GLOB
214 #include "shell_common.h"
215 #if ENABLE_FEATURE_SH_MATH
218 typedef long arith_t;
219 # define ARITH_FMT "%ld"
221 #if ENABLE_ASH_RANDOM_SUPPORT
224 # define CLEAR_RANDOM_T(rnd) ((void)0)
227 #include "NUM_APPLETS.h"
229 /* STANDALONE does not make sense, and won't compile */
230 # undef CONFIG_FEATURE_SH_STANDALONE
231 # undef ENABLE_FEATURE_SH_STANDALONE
232 # undef IF_FEATURE_SH_STANDALONE
233 # undef IF_NOT_FEATURE_SH_STANDALONE
234 # define ENABLE_FEATURE_SH_STANDALONE 0
235 # define IF_FEATURE_SH_STANDALONE(...)
236 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
240 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
244 # error "Do not even bother, ash will not run on NOMMU machine"
248 /* ============ Hash table sizes. Configurable. */
252 #define CMDTABLESIZE 31 /* should be prime */
255 /* ============ Shell options */
257 static const char *const optletters_optnames[] = {
281 #define optletters(n) optletters_optnames[n][0]
282 #define optnames(n) (optletters_optnames[n] + 1)
284 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
287 /* ============ Misc data */
289 #define msg_illnum "Illegal number: %s"
292 * We enclose jmp_buf in a structure so that we can declare pointers to
293 * jump locations. The global variable handler contains the location to
294 * jump to when an exception occurs, and the global variable exception_type
295 * contains a code identifying the exception. To implement nested
296 * exception handlers, the user should save the value of handler on entry
297 * to an inner scope, set handler to point to a jmploc structure for the
298 * inner scope, and restore handler on exit from the scope.
304 struct globals_misc {
305 uint8_t exitstatus; /* exit status of last command */
306 uint8_t back_exitstatus;/* exit status of backquoted command */
307 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
308 int rootpid; /* pid of main shell */
309 /* shell level: 0 for the main shell, 1 for its children, and so on */
311 #define rootshell (!shlvl)
312 char *minusc; /* argument to -c option */
314 char *curdir; // = nullstr; /* current working directory */
315 char *physdir; // = nullstr; /* physical working directory */
317 char *arg0; /* value of $0 */
319 struct jmploc *exception_handler;
321 volatile int suppress_int; /* counter */
322 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
323 volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
324 volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
325 smallint exception_type; /* kind of exception (0..5) */
327 #define EXINT 0 /* SIGINT received */
328 #define EXERROR 1 /* a generic error */
329 #define EXEXIT 4 /* exit the shell */
332 char nullstr[1]; /* zero length string */
335 #define eflag optlist[0]
336 #define fflag optlist[1]
337 #define Iflag optlist[2]
338 #define iflag optlist[3]
339 #define mflag optlist[4]
340 #define nflag optlist[5]
341 #define sflag optlist[6]
342 #define xflag optlist[7]
343 #define vflag optlist[8]
344 #define Cflag optlist[9]
345 #define aflag optlist[10]
346 #define bflag optlist[11]
347 #define uflag optlist[12]
348 #define viflag optlist[13]
350 # define pipefail optlist[14]
355 # define nolog optlist[14 + BASH_PIPEFAIL]
356 # define debug optlist[15 + BASH_PIPEFAIL]
359 /* trap handler commands */
361 * Sigmode records the current value of the signal handlers for the various
362 * modes. A value of zero means that the current handler is not known.
363 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
365 char sigmode[NSIG - 1];
366 #define S_DFL 1 /* default signal handling (SIG_DFL) */
367 #define S_CATCH 2 /* signal is caught */
368 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
369 #define S_HARD_IGN 4 /* signal is ignored permanently */
371 /* indicates specified signal received */
372 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
373 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
375 char **trap_ptr; /* used only by "trap hack" */
377 /* Rarely referenced stuff */
378 #if ENABLE_ASH_RANDOM_SUPPORT
381 pid_t backgndpid; /* pid of last background process */
383 extern struct globals_misc *const ash_ptr_to_globals_misc;
384 #define G_misc (*ash_ptr_to_globals_misc)
385 #define exitstatus (G_misc.exitstatus )
386 #define back_exitstatus (G_misc.back_exitstatus )
387 #define job_warning (G_misc.job_warning)
388 #define rootpid (G_misc.rootpid )
389 #define shlvl (G_misc.shlvl )
390 #define minusc (G_misc.minusc )
391 #define curdir (G_misc.curdir )
392 #define physdir (G_misc.physdir )
393 #define arg0 (G_misc.arg0 )
394 #define exception_handler (G_misc.exception_handler)
395 #define exception_type (G_misc.exception_type )
396 #define suppress_int (G_misc.suppress_int )
397 #define pending_int (G_misc.pending_int )
398 #define got_sigchld (G_misc.got_sigchld )
399 #define pending_sig (G_misc.pending_sig )
400 #define isloginsh (G_misc.isloginsh )
401 #define nullstr (G_misc.nullstr )
402 #define optlist (G_misc.optlist )
403 #define sigmode (G_misc.sigmode )
404 #define gotsig (G_misc.gotsig )
405 #define may_have_traps (G_misc.may_have_traps )
406 #define trap (G_misc.trap )
407 #define trap_ptr (G_misc.trap_ptr )
408 #define random_gen (G_misc.random_gen )
409 #define backgndpid (G_misc.backgndpid )
410 #define INIT_G_misc() do { \
411 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
419 /* ============ DEBUG */
421 static void trace_printf(const char *fmt, ...);
422 static void trace_vprintf(const char *fmt, va_list va);
423 # define TRACE(param) trace_printf param
424 # define TRACEV(param) trace_vprintf param
425 # define close(fd) do { \
427 if (close(dfd) < 0) \
428 bb_error_msg("bug on %d: closing %d(0x%x)", \
429 __LINE__, dfd, dfd); \
432 # define TRACE(param)
433 # define TRACEV(param)
437 /* ============ Utility functions */
438 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
439 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
442 isdigit_str9(const char *str)
444 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
445 while (--maxlen && isdigit(*str))
447 return (*str == '\0');
451 var_end(const char *var)
460 /* ============ Interrupts / exceptions */
462 static void exitshell(void) NORETURN;
465 * These macros allow the user to suspend the handling of interrupt signals
466 * over a period of time. This is similar to SIGHOLD or to sigblock, but
467 * much more efficient and portable. (But hacking the kernel is so much
468 * more fun than worrying about efficiency and portability. :-))
471 # define INT_OFF do { \
472 TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
477 # define INT_OFF do { \
484 * Called to raise an exception. Since C doesn't include exceptions, we
485 * just do a longjmp to the exception handler. The type of exception is
486 * stored in the global variable "exception_type".
488 static void raise_exception(int) NORETURN;
490 raise_exception(int e)
493 if (exception_handler == NULL)
498 longjmp(exception_handler->loc, 1);
501 #define raise_exception(e) do { \
502 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
503 raise_exception(e); \
508 * Called when a SIGINT is received. (If the user specifies
509 * that SIGINT is to be trapped or ignored using the trap builtin, then
510 * this routine is not called.) Suppressint is nonzero when interrupts
511 * are held using the INT_OFF macro. (The test for iflag is just
512 * defensive programming.)
514 static void raise_interrupt(void) NORETURN;
516 raise_interrupt(void)
519 /* Signal is not automatically unmasked after it is raised,
520 * do it ourself - unmask all signals */
521 sigprocmask_allsigs(SIG_UNBLOCK);
522 /* pending_sig = 0; - now done in signal_handler() */
524 if (!(rootshell && iflag)) {
525 /* Kill ourself with SIGINT */
526 signal(SIGINT, SIG_DFL);
529 /* bash: ^C even on empty command line sets $? */
530 exitstatus = SIGINT + 128;
531 raise_exception(EXINT);
535 #define raise_interrupt() do { \
536 TRACE(("raising interrupt on line %d\n", __LINE__)); \
541 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
545 if (--suppress_int == 0 && pending_int) {
550 # define INT_ON do { \
551 TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
555 # define INT_ON int_on()
557 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
565 #define FORCE_INT_ON force_int_on()
567 #define SAVE_INT(v) ((v) = suppress_int)
569 #define RESTORE_INT(v) do { \
571 suppress_int = (v); \
572 if (suppress_int == 0 && pending_int) \
577 /* ============ Stdout/stderr output */
580 outstr(const char *p, FILE *file)
588 flush_stdout_stderr(void)
595 /* Was called outcslow(c,FILE*), but c was always '\n' */
597 newline_and_flush(FILE *dest)
605 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
607 out1fmt(const char *fmt, ...)
614 r = vprintf(fmt, ap);
620 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
622 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
629 ret = vsnprintf(outbuf, length, fmt, ap);
636 out1str(const char *p)
642 out2str(const char *p)
645 flush_stdout_stderr();
649 /* ============ Parser structures */
651 /* control characters in argument strings */
652 #define CTL_FIRST CTLESC
653 #define CTLESC ((unsigned char)'\201') /* escape next character */
654 #define CTLVAR ((unsigned char)'\202') /* variable defn */
655 #define CTLENDVAR ((unsigned char)'\203')
656 #define CTLBACKQ ((unsigned char)'\204')
657 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
658 #define CTLENDARI ((unsigned char)'\207')
659 #define CTLQUOTEMARK ((unsigned char)'\210')
660 #define CTL_LAST CTLQUOTEMARK
662 /* variable substitution byte (follows CTLVAR) */
663 #define VSTYPE 0x0f /* type of variable substitution */
664 #define VSNUL 0x10 /* colon--treat the empty string as unset */
666 /* values of VSTYPE field */
667 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
668 #define VSMINUS 0x2 /* ${var-text} */
669 #define VSPLUS 0x3 /* ${var+text} */
670 #define VSQUESTION 0x4 /* ${var?message} */
671 #define VSASSIGN 0x5 /* ${var=text} */
672 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
673 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
674 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
675 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
676 #define VSLENGTH 0xa /* ${#var} */
678 #define VSSUBSTR 0xc /* ${var:position:length} */
680 #if BASH_PATTERN_SUBST
681 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
682 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
685 static const char dolatstr[] ALIGN1 = {
686 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
688 #define DOLATSTRLEN 6
707 #if BASH_REDIR_OUTPUT
724 smallint type; /* Nxxxx */
727 union node *redirect;
732 smallint pipe_backgnd;
733 struct nodelist *cmdlist;
739 union node *redirect;
752 union node *elsepart;
779 struct nodelist *backquote;
782 /* nfile and ndup layout must match!
783 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
784 * that it is actually NTO2 (>&file), and change its type.
801 char *_unused_expfname;
820 struct nredir nredir;
821 struct nbinary nbinary;
825 struct nclist nclist;
834 * NODE_EOF is returned by parsecmd when it encounters an end of file.
835 * It must be distinct from NULL.
837 #define NODE_EOF ((union node *) -1L)
840 struct nodelist *next;
853 freefunc(struct funcnode *f)
855 if (f && --f->count < 0)
860 /* ============ Debugging output */
864 static FILE *tracefile;
867 trace_printf(const char *fmt, ...)
874 fprintf(tracefile, "%u ", (int) time(NULL));
876 fprintf(tracefile, "[%u] ", (int) getpid());
878 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
880 vfprintf(tracefile, fmt, va);
885 trace_vprintf(const char *fmt, va_list va)
889 vfprintf(tracefile, fmt, va);
890 fprintf(tracefile, "\n");
894 trace_puts(const char *s)
902 trace_puts_quoted(char *s)
909 putc('"', tracefile);
910 for (p = s; *p; p++) {
911 switch ((unsigned char)*p) {
912 case '\n': c = 'n'; goto backslash;
913 case '\t': c = 't'; goto backslash;
914 case '\r': c = 'r'; goto backslash;
915 case '\"': c = '\"'; goto backslash;
916 case '\\': c = '\\'; goto backslash;
917 case CTLESC: c = 'e'; goto backslash;
918 case CTLVAR: c = 'v'; goto backslash;
919 case CTLBACKQ: c = 'q'; goto backslash;
921 putc('\\', tracefile);
925 if (*p >= ' ' && *p <= '~')
928 putc('\\', tracefile);
929 putc((*p >> 6) & 03, tracefile);
930 putc((*p >> 3) & 07, tracefile);
931 putc(*p & 07, tracefile);
936 putc('"', tracefile);
940 trace_puts_args(char **ap)
947 trace_puts_quoted(*ap);
949 putc('\n', tracefile);
952 putc(' ', tracefile);
967 /* leave open because libedit might be using it */
970 strcpy(s, "./trace");
972 if (!freopen(s, "a", tracefile)) {
973 fprintf(stderr, "Can't re-open %s\n", s);
978 tracefile = fopen(s, "a");
979 if (tracefile == NULL) {
980 fprintf(stderr, "Can't open %s\n", s);
986 flags = fcntl(fileno(tracefile), F_GETFL);
988 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
990 setlinebuf(tracefile);
991 fputs("\nTracing started.\n", tracefile);
995 indent(int amount, char *pfx, FILE *fp)
999 for (i = 0; i < amount; i++) {
1000 if (pfx && i == amount - 1)
1006 /* little circular references here... */
1007 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
1010 sharg(union node *arg, FILE *fp)
1013 struct nodelist *bqlist;
1014 unsigned char subtype;
1016 if (arg->type != NARG) {
1017 out1fmt("<node type %d>\n", arg->type);
1020 bqlist = arg->narg.backquote;
1021 for (p = arg->narg.text; *p; p++) {
1022 switch ((unsigned char)*p) {
1031 if (subtype == VSLENGTH)
1039 if (subtype & VSNUL)
1042 switch (subtype & VSTYPE) {
1068 case VSTRIMRIGHTMAX:
1075 out1fmt("<subtype %d>", subtype);
1084 shtree(bqlist->n, -1, NULL, fp);
1095 shcmd(union node *cmd, FILE *fp)
1103 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1109 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1113 switch (np->nfile.type) {
1114 case NTO: s = ">>"+1; dftfd = 1; break;
1115 case NCLOBBER: s = ">|"; dftfd = 1; break;
1116 case NAPPEND: s = ">>"; dftfd = 1; break;
1117 #if BASH_REDIR_OUTPUT
1120 case NTOFD: s = ">&"; dftfd = 1; break;
1121 case NFROM: s = "<"; break;
1122 case NFROMFD: s = "<&"; break;
1123 case NFROMTO: s = "<>"; break;
1124 default: s = "*error*"; break;
1126 if (np->nfile.fd != dftfd)
1127 fprintf(fp, "%d", np->nfile.fd);
1129 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1130 fprintf(fp, "%d", np->ndup.dupfd);
1132 sharg(np->nfile.fname, fp);
1139 shtree(union node *n, int ind, char *pfx, FILE *fp)
1141 struct nodelist *lp;
1147 indent(ind, pfx, fp);
1149 if (n == NODE_EOF) {
1164 shtree(n->nbinary.ch1, ind, NULL, fp);
1167 shtree(n->nbinary.ch2, ind, NULL, fp);
1175 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1176 shtree(lp->n, 0, NULL, fp);
1180 if (n->npipe.pipe_backgnd)
1186 fprintf(fp, "<node type %d>", n->type);
1194 showtree(union node *n)
1196 trace_puts("showtree called\n");
1197 shtree(n, 1, NULL, stderr);
1203 /* ============ Parser data */
1206 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1209 struct strlist *next;
1216 struct strpush *prev; /* preceding string on stack */
1218 int prev_left_in_line;
1219 #if ENABLE_ASH_ALIAS
1220 struct alias *ap; /* if push was associated with an alias */
1222 char *string; /* remember the string since it may change */
1224 /* Remember last two characters for pungetc. */
1227 /* Number of outstanding calls to pungetc. */
1232 struct parsefile *prev; /* preceding file on stack */
1233 int linno; /* current line */
1234 int pf_fd; /* file descriptor (or -1 if string) */
1235 int left_in_line; /* number of chars left in this line */
1236 int left_in_buffer; /* number of chars left in this buffer past the line */
1237 char *next_to_pgetc; /* next char in buffer */
1238 char *buf; /* input buffer */
1239 struct strpush *strpush; /* for pushing strings at this level */
1240 struct strpush basestrpush; /* so pushing one is fast */
1242 /* Remember last two characters for pungetc. */
1245 /* Number of outstanding calls to pungetc. */
1249 static struct parsefile basepf; /* top level input file */
1250 static struct parsefile *g_parsefile = &basepf; /* current input file */
1251 static int startlinno; /* line # where last token started */
1252 static char *commandname; /* currently executing command */
1255 /* ============ Message printing */
1258 ash_vmsg(const char *msg, va_list ap)
1260 fprintf(stderr, "%s: ", arg0);
1262 if (strcmp(arg0, commandname))
1263 fprintf(stderr, "%s: ", commandname);
1264 if (!iflag || g_parsefile->pf_fd > 0)
1265 fprintf(stderr, "line %d: ", startlinno);
1267 vfprintf(stderr, msg, ap);
1268 newline_and_flush(stderr);
1272 * Exverror is called to raise the error exception. If the second argument
1273 * is not NULL then error prints an error message using printf style
1274 * formatting. It then raises the error exception.
1276 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1278 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1282 TRACE(("ash_vmsg_and_raise(%d):", cond));
1285 TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
1290 flush_stdout_stderr();
1291 raise_exception(cond);
1295 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1297 ash_msg_and_raise_error(const char *msg, ...)
1304 ash_vmsg_and_raise(EXERROR, msg, ap);
1310 * Use '%m' to append error string on platforms that support it, '%s' and
1311 * strerror() on those that don't.
1313 * 'fmt' must be a string literal.
1315 #ifdef HAVE_PRINTF_PERCENTM
1316 #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": %m", ##__VA_ARGS__)
1318 #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": %s", ##__VA_ARGS__, strerror(errno))
1321 static void raise_error_syntax(const char *) NORETURN;
1323 raise_error_syntax(const char *msg)
1325 ash_msg_and_raise_error("syntax error: %s", msg);
1329 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1331 ash_msg_and_raise(int cond, const char *msg, ...)
1336 ash_vmsg_and_raise(cond, msg, ap);
1342 * error/warning routines for external builtins
1345 ash_msg(const char *fmt, ...)
1355 * Return a string describing an error. The returned string may be a
1356 * pointer to a static buffer that will be overwritten on the next call.
1357 * Action describes the operation that got the error.
1360 errmsg(int e, const char *em)
1362 if (e == ENOENT || e == ENOTDIR) {
1369 /* ============ Memory allocation */
1372 /* I consider these wrappers nearly useless:
1373 * ok, they return you to nearest exception handler, but
1374 * how much memory do you leak in the process, making
1375 * memory starvation worse?
1378 ckrealloc(void * p, size_t nbytes)
1380 p = realloc(p, nbytes);
1382 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1387 ckmalloc(size_t nbytes)
1389 return ckrealloc(NULL, nbytes);
1393 ckzalloc(size_t nbytes)
1395 return memset(ckmalloc(nbytes), 0, nbytes);
1399 ckstrdup(const char *s)
1401 char *p = strdup(s);
1403 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1407 /* Using bbox equivalents. They exit if out of memory */
1408 # define ckrealloc xrealloc
1409 # define ckmalloc xmalloc
1410 # define ckzalloc xzalloc
1411 # define ckstrdup xstrdup
1415 * It appears that grabstackstr() will barf with such alignments
1416 * because stalloc() will return a string allocated in a new stackblock.
1418 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1420 /* Most machines require the value returned from malloc to be aligned
1421 * in some way. The following macro will get this right
1422 * on many machines. */
1423 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1424 /* Minimum size of a block */
1425 MINSIZE = SHELL_ALIGN(504),
1428 struct stack_block {
1429 struct stack_block *prev;
1430 char space[MINSIZE];
1434 struct stack_block *stackp;
1440 struct globals_memstack {
1441 struct stack_block *g_stackp; // = &stackbase;
1442 char *g_stacknxt; // = stackbase.space;
1443 char *sstrend; // = stackbase.space + MINSIZE;
1444 size_t g_stacknleft; // = MINSIZE;
1445 struct stack_block stackbase;
1447 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1448 #define G_memstack (*ash_ptr_to_globals_memstack)
1449 #define g_stackp (G_memstack.g_stackp )
1450 #define g_stacknxt (G_memstack.g_stacknxt )
1451 #define sstrend (G_memstack.sstrend )
1452 #define g_stacknleft (G_memstack.g_stacknleft)
1453 #define stackbase (G_memstack.stackbase )
1454 #define INIT_G_memstack() do { \
1455 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1457 g_stackp = &stackbase; \
1458 g_stacknxt = stackbase.space; \
1459 g_stacknleft = MINSIZE; \
1460 sstrend = stackbase.space + MINSIZE; \
1464 #define stackblock() ((void *)g_stacknxt)
1465 #define stackblocksize() g_stacknleft
1468 * Parse trees for commands are allocated in lifo order, so we use a stack
1469 * to make this more efficient, and also to avoid all sorts of exception
1470 * handling code to handle interrupts in the middle of a parse.
1472 * The size 504 was chosen because the Ultrix malloc handles that size
1476 stalloc(size_t nbytes)
1481 aligned = SHELL_ALIGN(nbytes);
1482 if (aligned > g_stacknleft) {
1485 struct stack_block *sp;
1487 blocksize = aligned;
1488 if (blocksize < MINSIZE)
1489 blocksize = MINSIZE;
1490 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1491 if (len < blocksize)
1492 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1495 sp->prev = g_stackp;
1496 g_stacknxt = sp->space;
1497 g_stacknleft = blocksize;
1498 sstrend = g_stacknxt + blocksize;
1503 g_stacknxt += aligned;
1504 g_stacknleft -= aligned;
1509 stzalloc(size_t nbytes)
1511 return memset(stalloc(nbytes), 0, nbytes);
1518 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1519 write(STDERR_FILENO, "stunalloc\n", 10);
1523 g_stacknleft += g_stacknxt - (char *)p;
1528 * Like strdup but works with the ash stack.
1531 sstrdup(const char *p)
1533 size_t len = strlen(p) + 1;
1534 return memcpy(stalloc(len), p, len);
1538 grabstackblock(size_t len)
1544 pushstackmark(struct stackmark *mark, size_t len)
1546 mark->stackp = g_stackp;
1547 mark->stacknxt = g_stacknxt;
1548 mark->stacknleft = g_stacknleft;
1549 grabstackblock(len);
1553 setstackmark(struct stackmark *mark)
1555 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1559 popstackmark(struct stackmark *mark)
1561 struct stack_block *sp;
1567 while (g_stackp != mark->stackp) {
1569 g_stackp = sp->prev;
1572 g_stacknxt = mark->stacknxt;
1573 g_stacknleft = mark->stacknleft;
1574 sstrend = mark->stacknxt + mark->stacknleft;
1579 * When the parser reads in a string, it wants to stick the string on the
1580 * stack and only adjust the stack pointer when it knows how big the
1581 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1582 * of space on top of the stack and stackblocklen returns the length of
1583 * this block. Growstackblock will grow this space by at least one byte,
1584 * possibly moving it (like realloc). Grabstackblock actually allocates the
1585 * part of the block that has been used.
1588 growstackblock(void)
1592 newlen = g_stacknleft * 2;
1593 if (newlen < g_stacknleft)
1594 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1598 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1599 struct stack_block *sp;
1600 struct stack_block *prevstackp;
1605 prevstackp = sp->prev;
1606 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1607 sp = ckrealloc(sp, grosslen);
1608 sp->prev = prevstackp;
1610 g_stacknxt = sp->space;
1611 g_stacknleft = newlen;
1612 sstrend = sp->space + newlen;
1615 char *oldspace = g_stacknxt;
1616 size_t oldlen = g_stacknleft;
1617 char *p = stalloc(newlen);
1619 /* free the space we just allocated */
1620 g_stacknxt = memcpy(p, oldspace, oldlen);
1621 g_stacknleft += newlen;
1626 * The following routines are somewhat easier to use than the above.
1627 * The user declares a variable of type STACKSTR, which may be declared
1628 * to be a register. The macro STARTSTACKSTR initializes things. Then
1629 * the user uses the macro STPUTC to add characters to the string. In
1630 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1631 * grown as necessary. When the user is done, she can just leave the
1632 * string there and refer to it using stackblock(). Or she can allocate
1633 * the space for it using grabstackstr(). If it is necessary to allow
1634 * someone else to use the stack temporarily and then continue to grow
1635 * the string, the user should use grabstack to allocate the space, and
1636 * then call ungrabstr(p) to return to the previous mode of operation.
1638 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1639 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1640 * is space for at least one character.
1645 size_t len = stackblocksize();
1647 return (char *)stackblock() + len;
1651 * Called from CHECKSTRSPACE.
1654 makestrspace(size_t newlen, char *p)
1656 size_t len = p - g_stacknxt;
1662 size = stackblocksize();
1664 if (nleft >= newlen)
1668 return (char *)stackblock() + len;
1672 stack_nputstr(const char *s, size_t n, char *p)
1674 p = makestrspace(n, p);
1675 p = (char *)mempcpy(p, s, n);
1680 stack_putstr(const char *s, char *p)
1682 return stack_nputstr(s, strlen(s), p);
1686 _STPUTC(int c, char *p)
1694 #define STARTSTACKSTR(p) ((p) = stackblock())
1695 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1696 #define CHECKSTRSPACE(n, p) do { \
1699 size_t m = sstrend - q; \
1701 (p) = makestrspace(l, q); \
1703 #define USTPUTC(c, p) (*(p)++ = (c))
1704 #define STACKSTRNUL(p) do { \
1705 if ((p) == sstrend) \
1706 (p) = growstackstr(); \
1709 #define STUNPUTC(p) (--(p))
1710 #define STTOPC(p) ((p)[-1])
1711 #define STADJUST(amount, p) ((p) += (amount))
1713 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1714 #define ungrabstackstr(s, p) stunalloc(s)
1715 #define stackstrend() ((void *)sstrend)
1718 /* ============ String helpers */
1721 * prefix -- see if pfx is a prefix of string.
1724 prefix(const char *string, const char *pfx)
1727 if (*pfx++ != *string++)
1730 return (char *) string;
1734 * Check for a valid number. This should be elsewhere.
1737 is_number(const char *p)
1742 } while (*++p != '\0');
1747 * Convert a string of digits to an integer, printing an error message on
1751 number(const char *s)
1754 ash_msg_and_raise_error(msg_illnum, s);
1759 * Produce a single quoted string suitable as input to the shell.
1760 * The return string is allocated on the stack.
1763 single_quote(const char *s)
1773 len = strchrnul(s, '\'') - s;
1775 q = p = makestrspace(len + 3, p);
1778 q = (char *)mempcpy(q, s, len);
1787 do len++; while (*++s == '\'');
1789 q = p = makestrspace(len + 3, p);
1792 q = (char *)mempcpy(q, s - len, len);
1800 return stackblock();
1804 * Produce a possibly single quoted string suitable as input to the shell.
1805 * If quoting was done, the return string is allocated on the stack,
1806 * otherwise a pointer to the original string is returned.
1809 maybe_single_quote(const char *s)
1814 /* Assuming ACSII */
1815 /* quote ctrl_chars space !"#$%&'()* */
1819 if (*p >= ';' && *p <= '?')
1828 /* quote {|}~ DEL and high bytes */
1831 /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
1832 /* TODO: maybe avoid quoting % */
1838 return single_quote(s);
1842 /* ============ nextopt */
1844 static char **argptr; /* argument list for builtin commands */
1845 static char *optionarg; /* set by nextopt (like getopt) */
1846 static char *optptr; /* used by nextopt */
1849 * XXX - should get rid of. Have all builtins use getopt(3).
1850 * The library getopt must have the BSD extension static variable
1851 * "optreset", otherwise it can't be used within the shell safely.
1853 * Standard option processing (a la getopt) for builtin routines.
1854 * The only argument that is passed to nextopt is the option string;
1855 * the other arguments are unnecessary. It returns the character,
1856 * or '\0' on end of input.
1859 nextopt(const char *optstring)
1866 if (p == NULL || *p == '\0') {
1867 /* We ate entire "-param", take next one */
1873 if (*++p == '\0') /* just "-" ? */
1876 if (LONE_DASH(p)) /* "--" ? */
1878 /* p => next "-param" */
1880 /* p => some option char in the middle of a "-param" */
1882 for (q = optstring; *q != c;) {
1884 ash_msg_and_raise_error("illegal option -%c", c);
1892 ash_msg_and_raise_error("no arg for -%c option", c);
1902 /* ============ Shell variables */
1905 * The parsefile structure pointed to by the global variable parsefile
1906 * contains information about the current file being read.
1909 int nparam; /* # of positional parameters (without $0) */
1910 #if ENABLE_ASH_GETOPTS
1911 int optind; /* next parameter to be processed by getopts */
1912 int optoff; /* used by getopts */
1914 unsigned char malloced; /* if parameter list dynamically allocated */
1915 char **p; /* parameter list */
1919 * Free the list of positional parameters.
1922 freeparam(volatile struct shparam *param)
1924 if (param->malloced) {
1926 ap = ap1 = param->p;
1933 #if ENABLE_ASH_GETOPTS
1934 static void FAST_FUNC getoptsreset(const char *value);
1938 struct var *next; /* next entry in hash list */
1939 int flags; /* flags are defined above */
1940 const char *var_text; /* name=value */
1941 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1942 /* the variable gets set/unset */
1946 struct localvar *next; /* next local variable in list */
1947 struct var *vp; /* the variable that was made local */
1948 int flags; /* saved flags */
1949 const char *text; /* saved text */
1953 #define VEXPORT 0x01 /* variable is exported */
1954 #define VREADONLY 0x02 /* variable cannot be modified */
1955 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1956 #define VTEXTFIXED 0x08 /* text is statically allocated */
1957 #define VSTACK 0x10 /* text is allocated on the stack */
1958 #define VUNSET 0x20 /* the variable is not set */
1959 #define VNOFUNC 0x40 /* don't call the callback function */
1960 #define VNOSET 0x80 /* do not set variable - just readonly test */
1961 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1962 #if ENABLE_ASH_RANDOM_SUPPORT
1963 # define VDYNAMIC 0x200 /* dynamic variable */
1969 /* Need to be before varinit_data[] */
1970 #if ENABLE_LOCALE_SUPPORT
1971 static void FAST_FUNC
1972 change_lc_all(const char *value)
1974 if (value && *value != '\0')
1975 setlocale(LC_ALL, value);
1977 static void FAST_FUNC
1978 change_lc_ctype(const char *value)
1980 if (value && *value != '\0')
1981 setlocale(LC_CTYPE, value);
1985 static void chkmail(void);
1986 static void changemail(const char *var_value) FAST_FUNC;
1988 # define chkmail() ((void)0)
1990 static void changepath(const char *) FAST_FUNC;
1991 #if ENABLE_ASH_RANDOM_SUPPORT
1992 static void change_random(const char *) FAST_FUNC;
1995 static const struct {
1997 const char *var_text;
1998 void (*var_func)(const char *) FAST_FUNC;
1999 } varinit_data[] = {
2001 * Note: VEXPORT would not work correctly here for NOFORK applets:
2002 * some environment strings may be constant.
2004 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
2006 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
2007 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
2009 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
2010 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
2011 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
2012 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
2013 #if ENABLE_ASH_GETOPTS
2014 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
2016 #if ENABLE_ASH_RANDOM_SUPPORT
2017 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
2019 #if ENABLE_LOCALE_SUPPORT
2020 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
2021 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
2023 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
2024 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
2030 struct globals_var {
2031 struct shparam shellparam; /* $@ current positional parameters */
2032 struct redirtab *redirlist;
2033 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
2034 struct var *vartab[VTABSIZE];
2035 struct var varinit[ARRAY_SIZE(varinit_data)];
2037 extern struct globals_var *const ash_ptr_to_globals_var;
2038 #define G_var (*ash_ptr_to_globals_var)
2039 #define shellparam (G_var.shellparam )
2040 //#define redirlist (G_var.redirlist )
2041 #define preverrout_fd (G_var.preverrout_fd)
2042 #define vartab (G_var.vartab )
2043 #define varinit (G_var.varinit )
2044 #define INIT_G_var() do { \
2046 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
2048 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
2049 varinit[i].flags = varinit_data[i].flags; \
2050 varinit[i].var_text = varinit_data[i].var_text; \
2051 varinit[i].var_func = varinit_data[i].var_func; \
2055 #define vifs varinit[0]
2057 # define vmail (&vifs)[1]
2058 # define vmpath (&vmail)[1]
2059 # define vpath (&vmpath)[1]
2061 # define vpath (&vifs)[1]
2063 #define vps1 (&vpath)[1]
2064 #define vps2 (&vps1)[1]
2065 #define vps4 (&vps2)[1]
2066 #if ENABLE_ASH_GETOPTS
2067 # define voptind (&vps4)[1]
2068 # if ENABLE_ASH_RANDOM_SUPPORT
2069 # define vrandom (&voptind)[1]
2072 # if ENABLE_ASH_RANDOM_SUPPORT
2073 # define vrandom (&vps4)[1]
2078 * The following macros access the values of the above variables.
2079 * They have to skip over the name. They return the null string
2080 * for unset variables.
2082 #define ifsval() (vifs.var_text + 4)
2083 #define ifsset() ((vifs.flags & VUNSET) == 0)
2085 # define mailval() (vmail.var_text + 5)
2086 # define mpathval() (vmpath.var_text + 9)
2087 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2089 #define pathval() (vpath.var_text + 5)
2090 #define ps1val() (vps1.var_text + 4)
2091 #define ps2val() (vps2.var_text + 4)
2092 #define ps4val() (vps4.var_text + 4)
2093 #if ENABLE_ASH_GETOPTS
2094 # define optindval() (voptind.var_text + 7)
2097 #if ENABLE_ASH_GETOPTS
2098 static void FAST_FUNC
2099 getoptsreset(const char *value)
2101 shellparam.optind = number(value) ?: 1;
2102 shellparam.optoff = -1;
2107 * Compares two strings up to the first = or '\0'. The first
2108 * string must be terminated by '='; the second may be terminated by
2109 * either '=' or '\0'.
2112 varcmp(const char *p, const char *q)
2116 while ((c = *p) == (d = *q)) {
2117 if (c == '\0' || c == '=')
2131 * Find the appropriate entry in the hash table from the name.
2133 static struct var **
2134 hashvar(const char *p)
2138 hashval = ((unsigned char) *p) << 4;
2139 while (*p && *p != '=')
2140 hashval += (unsigned char) *p++;
2141 return &vartab[hashval % VTABSIZE];
2145 vpcmp(const void *a, const void *b)
2147 return varcmp(*(const char **)a, *(const char **)b);
2151 * This routine initializes the builtin variables.
2161 * PS1 depends on uid
2163 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2164 vps1.var_text = "PS1=\\w \\$ ";
2167 vps1.var_text = "PS1=# ";
2170 end = vp + ARRAY_SIZE(varinit);
2172 vpp = hashvar(vp->var_text);
2175 } while (++vp < end);
2178 static struct var **
2179 findvar(struct var **vpp, const char *name)
2181 for (; *vpp; vpp = &(*vpp)->next) {
2182 if (varcmp((*vpp)->var_text, name) == 0) {
2190 * Find the value of a variable. Returns NULL if not set.
2192 static const char* FAST_FUNC
2193 lookupvar(const char *name)
2197 v = *findvar(hashvar(name), name);
2199 #if ENABLE_ASH_RANDOM_SUPPORT
2201 * Dynamic variables are implemented roughly the same way they are
2202 * in bash. Namely, they're "special" so long as they aren't unset.
2203 * As soon as they're unset, they're no longer dynamic, and dynamic
2204 * lookup will no longer happen at that point. -- PFM.
2206 if (v->flags & VDYNAMIC)
2209 if (!(v->flags & VUNSET))
2210 return var_end(v->var_text);
2215 #if ENABLE_UNICODE_SUPPORT
2217 reinit_unicode_for_ash(void)
2219 /* Unicode support should be activated even if LANG is set
2220 * _during_ shell execution, not only if it was set when
2221 * shell was started. Therefore, re-check LANG every time:
2223 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2224 || ENABLE_UNICODE_USING_LOCALE
2226 const char *s = lookupvar("LC_ALL");
2227 if (!s) s = lookupvar("LC_CTYPE");
2228 if (!s) s = lookupvar("LANG");
2233 # define reinit_unicode_for_ash() ((void)0)
2237 * Search the environment of a builtin command.
2239 static ALWAYS_INLINE const char *
2240 bltinlookup(const char *name)
2242 return lookupvar(name);
2246 * Same as setvar except that the variable and value are passed in
2247 * the first argument as name=value. Since the first argument will
2248 * be actually stored in the table, it should not be a string that
2250 * Called with interrupts off.
2253 setvareq(char *s, int flags)
2255 struct var *vp, **vpp;
2258 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2259 vpp = findvar(vpp, s);
2262 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2265 if (flags & VNOSAVE)
2269 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2275 if (vp->var_func && !(flags & VNOFUNC))
2276 vp->var_func(var_end(s));
2278 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2279 free((char*)vp->var_text);
2281 if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
2285 if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
2290 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2292 /* variable s is not found */
2295 if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
2297 vp = ckzalloc(sizeof(*vp));
2299 /*vp->func = NULL; - ckzalloc did it */
2302 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2312 * Set the value of a variable. The flags argument is ored with the
2313 * flags of the variable. If val is NULL, the variable is unset.
2316 setvar(const char *name, const char *val, int flags)
2325 q = endofname(name);
2326 p = strchrnul(q, '=');
2328 if (!namelen || p != q)
2329 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2334 vallen = strlen(val);
2338 nameeq = ckmalloc(namelen + vallen + 2);
2339 p = mempcpy(nameeq, name, namelen);
2342 p = mempcpy(p, val, vallen);
2345 vp = setvareq(nameeq, flags | VNOSAVE);
2351 static void FAST_FUNC
2352 setvar0(const char *name, const char *val)
2354 setvar(name, val, 0);
2358 * Unset the specified variable.
2361 unsetvar(const char *s)
2367 * Process a linked list of variable assignments.
2370 listsetvar(struct strlist *list_set_var, int flags)
2372 struct strlist *lp = list_set_var;
2378 setvareq(lp->text, flags);
2385 * Generate a list of variables satisfying the given conditions.
2388 listvars(int on, int off, char ***end)
2399 for (vp = *vpp; vp; vp = vp->next) {
2400 if ((vp->flags & mask) == on) {
2401 if (ep == stackstrend())
2402 ep = growstackstr();
2403 *ep++ = (char*)vp->var_text;
2406 } while (++vpp < vartab + VTABSIZE);
2407 if (ep == stackstrend())
2408 ep = growstackstr();
2412 return grabstackstr(ep);
2416 /* ============ Path search helper
2418 * The variable path (passed by reference) should be set to the start
2419 * of the path before the first call; path_advance will update
2420 * this value as it proceeds. Successive calls to path_advance will return
2421 * the possible path expansions in sequence. If an option (indicated by
2422 * a percent sign) appears in the path entry then the global variable
2423 * pathopt will be set to point to it; otherwise pathopt will be set to
2426 static const char *pathopt; /* set by path_advance */
2429 path_advance(const char **path, const char *name)
2439 for (p = start; *p && *p != ':' && *p != '%'; p++)
2441 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2442 while (stackblocksize() < len)
2446 q = mempcpy(q, start, p - start);
2453 while (*p && *p != ':')
2460 return stalloc(len);
2464 /* ============ Prompt */
2466 static smallint doprompt; /* if set, prompt the user */
2467 static smallint needprompt; /* true if interactive and at start of line */
2469 #if ENABLE_FEATURE_EDITING
2470 static line_input_t *line_input_state;
2471 static const char *cmdedit_prompt;
2473 putprompt(const char *s)
2475 if (ENABLE_ASH_EXPAND_PRMT) {
2476 free((char*)cmdedit_prompt);
2477 cmdedit_prompt = ckstrdup(s);
2484 putprompt(const char *s)
2490 /* expandstr() needs parsing machinery, so it is far away ahead... */
2491 static const char *expandstr(const char *ps, int syntax_type);
2492 /* Values for syntax param */
2493 #define BASESYNTAX 0 /* not in quotes */
2494 #define DQSYNTAX 1 /* in double quotes */
2495 #define SQSYNTAX 2 /* in single quotes */
2496 #define ARISYNTAX 3 /* in arithmetic */
2497 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2498 /* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
2501 * called by editline -- any expansions to the prompt should be added here.
2504 setprompt_if(smallint do_set, int whichprompt)
2507 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2514 switch (whichprompt) {
2524 #if ENABLE_ASH_EXPAND_PRMT
2525 pushstackmark(&smark, stackblocksize());
2526 putprompt(expandstr(prompt, PSSYNTAX));
2527 popstackmark(&smark);
2534 /* ============ The cd and pwd commands */
2536 #define CD_PHYSICAL 1
2546 while ((i = nextopt("LP")) != '\0') {
2548 flags ^= CD_PHYSICAL;
2557 * Update curdir (the name of the current directory) in response to a
2561 updatepwd(const char *dir)
2568 cdcomppath = sstrdup(dir);
2571 if (curdir == nullstr)
2573 new = stack_putstr(curdir, new);
2575 new = makestrspace(strlen(dir) + 2, new);
2576 lim = (char *)stackblock() + 1;
2580 if (new > lim && *lim == '/')
2585 if (dir[1] == '/' && dir[2] != '/') {
2591 p = strtok(cdcomppath, "/");
2595 if (p[1] == '.' && p[2] == '\0') {
2607 new = stack_putstr(p, new);
2610 p = strtok(NULL, "/");
2615 return stackblock();
2619 * Find out what the current directory is. If we already know the current
2620 * directory, this routine returns immediately.
2625 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2626 return dir ? dir : nullstr;
2630 setpwd(const char *val, int setold)
2634 oldcur = dir = curdir;
2637 setvar("OLDPWD", oldcur, VEXPORT);
2640 if (physdir != nullstr) {
2641 if (physdir != oldcur)
2645 if (oldcur == val || !val) {
2651 dir = ckstrdup(val);
2652 if (oldcur != dir && oldcur != nullstr) {
2657 setvar("PWD", dir, VEXPORT);
2660 static void hashcd(void);
2663 * Actually do the chdir. We also call hashcd to let other routines
2664 * know that the current directory has changed.
2667 docd(const char *dest, int flags)
2669 const char *dir = NULL;
2672 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2675 if (!(flags & CD_PHYSICAL)) {
2676 dir = updatepwd(dest);
2690 static int FAST_FUNC
2691 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2703 dest = bltinlookup("HOME");
2704 else if (LONE_DASH(dest)) {
2705 dest = bltinlookup("OLDPWD");
2727 path = bltinlookup("CDPATH");
2730 p = path_advance(&path, dest);
2731 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2735 if (!docd(p, flags))
2746 ash_msg_and_raise_error("can't cd to %s", dest);
2749 if (flags & CD_PRINT)
2750 out1fmt("%s\n", curdir);
2754 static int FAST_FUNC
2755 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2758 const char *dir = curdir;
2762 if (physdir == nullstr)
2766 out1fmt("%s\n", dir);
2771 /* ============ ... */
2774 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2776 /* Syntax classes */
2777 #define CWORD 0 /* character is nothing special */
2778 #define CNL 1 /* newline character */
2779 #define CBACK 2 /* a backslash character */
2780 #define CSQUOTE 3 /* single quote */
2781 #define CDQUOTE 4 /* double quote */
2782 #define CENDQUOTE 5 /* a terminating quote */
2783 #define CBQUOTE 6 /* backwards single quote */
2784 #define CVAR 7 /* a dollar sign */
2785 #define CENDVAR 8 /* a '}' character */
2786 #define CLP 9 /* a left paren in arithmetic */
2787 #define CRP 10 /* a right paren in arithmetic */
2788 #define CENDFILE 11 /* end of file */
2789 #define CCTL 12 /* like CWORD, except it must be escaped */
2790 #define CSPCL 13 /* these terminate a word */
2791 #define CIGN 14 /* character should be ignored */
2794 #if ENABLE_ASH_ALIAS
2798 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2800 #if ENABLE_FEATURE_SH_MATH
2801 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2803 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2805 static const uint16_t S_I_T[] ALIGN2 = {
2806 #if ENABLE_ASH_ALIAS
2807 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2809 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2810 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2811 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2812 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2813 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2814 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2815 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2816 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2817 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2818 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2819 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2820 #if !USE_SIT_FUNCTION
2821 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2822 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2823 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2827 /* Constants below must match table above */
2829 #if ENABLE_ASH_ALIAS
2830 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2832 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2833 CNL_CNL_CNL_CNL , /* 2 */
2834 CWORD_CCTL_CCTL_CWORD , /* 3 */
2835 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2836 CVAR_CVAR_CWORD_CVAR , /* 5 */
2837 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2838 CSPCL_CWORD_CWORD_CLP , /* 7 */
2839 CSPCL_CWORD_CWORD_CRP , /* 8 */
2840 CBACK_CBACK_CCTL_CBACK , /* 9 */
2841 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2842 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2843 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2844 CWORD_CWORD_CWORD_CWORD , /* 13 */
2845 CCTL_CCTL_CCTL_CCTL , /* 14 */
2848 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2849 * caller must ensure proper cast on it if c is *char_ptr!
2851 #if USE_SIT_FUNCTION
2854 SIT(int c, int syntax)
2856 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2857 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2859 * This causes '/' to be prepended with CTLESC in dquoted string,
2860 * making "./file"* treated incorrectly because we feed
2861 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2862 * The "homegrown" glob implementation is okay with that,
2863 * but glibc one isn't. With '/' always treated as CWORD,
2866 # if ENABLE_ASH_ALIAS
2867 static const uint8_t syntax_index_table[] ALIGN1 = {
2868 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2869 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2870 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2874 static const uint8_t syntax_index_table[] ALIGN1 = {
2875 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2876 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2877 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2886 # if ENABLE_ASH_ALIAS
2892 /* Cast is purely for paranoia here,
2893 * just in case someone passed signed char to us */
2894 if ((unsigned char)c >= CTL_FIRST
2895 && (unsigned char)c <= CTL_LAST
2899 s = strchrnul(spec_symbls, c);
2902 indx = syntax_index_table[s - spec_symbls];
2904 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2907 #else /* !USE_SIT_FUNCTION */
2909 static const uint8_t syntax_index_table[] ALIGN1 = {
2910 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2911 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2921 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2922 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2944 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2945 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2946 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2948 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2950 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2951 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2952 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2953 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2954 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2956 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2957 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2958 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2959 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2971 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2972 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2973 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2974 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2975 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2976 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2993 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
3004 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
3005 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
3006 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
3007 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
3008 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
3009 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
3010 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
3011 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
3012 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
3013 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
3014 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
3015 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
3016 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
3017 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
3018 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
3019 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
3020 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
3021 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
3022 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
3023 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3024 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3025 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3026 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3027 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3028 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3029 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3030 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3031 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3032 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3033 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3034 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3035 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3036 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3037 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3038 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3039 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
3040 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
3042 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
3043 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
3044 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
3045 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
3046 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3047 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3048 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3049 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3113 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3114 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3115 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3116 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3117 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3118 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3119 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3120 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3121 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3122 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3123 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3124 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3125 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3126 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3127 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3128 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3129 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3130 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3131 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3132 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3133 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3134 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3135 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3136 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3137 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3138 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3139 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3140 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3141 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3142 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3143 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3144 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3145 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3146 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3147 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3148 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3149 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3150 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3151 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3152 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3153 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3154 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3155 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3156 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3157 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3158 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3159 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3160 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3161 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3162 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3163 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3164 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3165 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3166 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3167 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3168 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3169 # if ENABLE_ASH_ALIAS
3170 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3175 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3176 #else /* debug version, caught one signed char bug */
3177 # define SIT(c, syntax) \
3179 if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
3180 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3181 if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
3182 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3183 ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
3187 #endif /* !USE_SIT_FUNCTION */
3190 /* ============ Alias handling */
3192 #if ENABLE_ASH_ALIAS
3194 #define ALIASINUSE 1
3205 static struct alias **atab; // [ATABSIZE];
3206 #define INIT_G_alias() do { \
3207 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3211 static struct alias **
3212 __lookupalias(const char *name)
3214 unsigned int hashval;
3221 ch = (unsigned char)*p;
3225 ch = (unsigned char)*++p;
3227 app = &atab[hashval % ATABSIZE];
3229 for (; *app; app = &(*app)->next) {
3230 if (strcmp(name, (*app)->name) == 0) {
3238 static struct alias *
3239 lookupalias(const char *name, int check)
3241 struct alias *ap = *__lookupalias(name);
3243 if (check && ap && (ap->flag & ALIASINUSE))
3248 static struct alias *
3249 freealias(struct alias *ap)
3253 if (ap->flag & ALIASINUSE) {
3254 ap->flag |= ALIASDEAD;
3266 setalias(const char *name, const char *val)
3268 struct alias *ap, **app;
3270 app = __lookupalias(name);
3274 if (!(ap->flag & ALIASINUSE)) {
3277 ap->val = ckstrdup(val);
3278 ap->flag &= ~ALIASDEAD;
3281 ap = ckzalloc(sizeof(struct alias));
3282 ap->name = ckstrdup(name);
3283 ap->val = ckstrdup(val);
3284 /*ap->flag = 0; - ckzalloc did it */
3285 /*ap->next = NULL;*/
3292 unalias(const char *name)
3296 app = __lookupalias(name);
3300 *app = freealias(*app);
3311 struct alias *ap, **app;
3315 for (i = 0; i < ATABSIZE; i++) {
3317 for (ap = *app; ap; ap = *app) {
3318 *app = freealias(*app);
3328 printalias(const struct alias *ap)
3330 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3334 * TODO - sort output
3336 static int FAST_FUNC
3337 aliascmd(int argc UNUSED_PARAM, char **argv)
3346 for (i = 0; i < ATABSIZE; i++) {
3347 for (ap = atab[i]; ap; ap = ap->next) {
3353 while ((n = *++argv) != NULL) {
3354 v = strchr(n+1, '=');
3355 if (v == NULL) { /* n+1: funny ksh stuff */
3356 ap = *__lookupalias(n);
3358 fprintf(stderr, "%s: %s not found\n", "alias", n);
3371 static int FAST_FUNC
3372 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3376 while (nextopt("a") != '\0') {
3380 for (i = 0; *argptr; argptr++) {
3381 if (unalias(*argptr)) {
3382 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3390 #endif /* ASH_ALIAS */
3393 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3396 #define FORK_NOJOB 2
3398 /* mode flags for showjob(s) */
3399 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3400 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3401 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3402 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3405 * A job structure contains information about a job. A job is either a
3406 * single process or a set of processes contained in a pipeline. In the
3407 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3411 pid_t ps_pid; /* process id */
3412 int ps_status; /* last process status from wait() */
3413 char *ps_cmd; /* text of command being run */
3417 struct procstat ps0; /* status of process */
3418 struct procstat *ps; /* status or processes when more than one */
3420 int stopstatus; /* status of a stopped job */
3422 unsigned nprocs; /* number of processes */
3424 #define JOBRUNNING 0 /* at least one proc running */
3425 #define JOBSTOPPED 1 /* all procs are stopped */
3426 #define JOBDONE 2 /* all procs are completed */
3430 sigint: 1, /* job was killed by SIGINT */
3431 jobctl: 1, /* job running under job control */
3433 waited: 1, /* true if this entry has been waited for */
3434 used: 1, /* true if this entry is in used */
3435 changed: 1; /* true if status has changed */
3436 struct job *prev_job; /* previous job */
3439 static struct job *makejob(/*union node *,*/ int);
3440 static int forkshell(struct job *, union node *, int);
3441 static int waitforjob(struct job *);
3444 enum { doing_jobctl = 0 };
3445 #define setjobctl(on) do {} while (0)
3447 static smallint doing_jobctl; //references:8
3448 static void setjobctl(int);
3455 ignoresig(int signo)
3457 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3458 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3459 /* No, need to do it */
3460 signal(signo, SIG_IGN);
3462 sigmode[signo - 1] = S_HARD_IGN;
3466 * Only one usage site - in setsignal()
3469 signal_handler(int signo)
3471 if (signo == SIGCHLD) {
3477 gotsig[signo - 1] = 1;
3478 pending_sig = signo;
3480 if (signo == SIGINT && !trap[SIGINT]) {
3481 if (!suppress_int) {
3483 raise_interrupt(); /* does not return */
3490 * Set the signal handler for the specified signal. The routine figures
3491 * out what it should be set to.
3494 setsignal(int signo)
3497 char cur_act, new_act;
3498 struct sigaction act;
3502 if (t != NULL) { /* trap for this sig is set */
3504 if (t[0] == '\0') /* trap is "": ignore this sig */
3508 if (rootshell && new_act == S_DFL) {
3511 if (iflag || minusc || sflag == 0)
3520 * "In all cases, bash ignores SIGQUIT. Non-builtin
3521 * commands run by bash have signal handlers
3522 * set to the values inherited by the shell
3523 * from its parent". */
3539 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3540 //whereas we have to restore it to what shell got on entry
3541 //from the parent. See comment above
3543 if (signo == SIGCHLD)
3546 t = &sigmode[signo - 1];
3549 /* current setting is not yet known */
3550 if (sigaction(signo, NULL, &act)) {
3551 /* pretend it worked; maybe we should give a warning,
3552 * but other shells don't. We don't alter sigmode,
3553 * so we retry every time.
3554 * btw, in Linux it never fails. --vda */
3557 if (act.sa_handler == SIG_IGN) {
3558 cur_act = S_HARD_IGN;
3560 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3562 cur_act = S_IGN; /* don't hard ignore these */
3566 if (cur_act == S_HARD_IGN || cur_act == new_act)
3569 act.sa_handler = SIG_DFL;
3572 act.sa_handler = signal_handler;
3575 act.sa_handler = SIG_IGN;
3579 /* flags and mask matter only if !DFL and !IGN, but we do it
3580 * for all cases for more deterministic behavior:
3583 sigfillset(&act.sa_mask);
3585 sigaction_set(signo, &act);
3590 /* mode flags for set_curjob */
3591 #define CUR_DELETE 2
3592 #define CUR_RUNNING 1
3593 #define CUR_STOPPED 0
3596 /* pgrp of shell on invocation */
3597 static int initialpgrp; //references:2
3598 static int ttyfd = -1; //5
3601 static struct job *jobtab; //5
3603 static unsigned njobs; //4
3605 static struct job *curjob; //lots
3606 /* number of presumed living untracked jobs */
3607 static int jobless; //4
3610 /* Bash has a feature: it restores termios after a successful wait for
3611 * a foreground job which had at least one stopped or sigkilled member.
3612 * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
3613 * properly restoring tty state. Should we do this too?
3614 * A reproducer: ^Z an interactive python:
3617 * Python 2.7.12 (...)
3619 * { python leaves tty in -icanon -echo state. We do survive that... }
3620 * [1]+ Stopped python
3621 * { ...however, next program (python #2) does not survive it well: }
3623 * Python 2.7.12 (...)
3624 * >>> Traceback (most recent call last):
3625 * { above, I typed "qwerty<CR>", but -echo state is still in effect }
3626 * File "<stdin>", line 1, in <module>
3627 * NameError: name 'qwerty' is not defined
3629 * The implementation below is modeled on bash code and seems to work.
3630 * However, I'm not sure we should do this. For one: what if I'd fg
3631 * the stopped python instead? It'll be confused by "restored" tty state.
3633 static struct termios shell_tty_info;
3637 if (rootshell && ttyfd >= 0)
3638 tcgetattr(ttyfd, &shell_tty_info);
3643 /* if (rootshell) - caller ensures this */
3645 tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
3648 job_signal_status(struct job *jp)
3652 struct procstat *ps = jp->ps;
3653 for (i = 0; i < jp->nprocs; i++) {
3654 status = ps[i].ps_status;
3655 if (WIFSIGNALED(status) || WIFSTOPPED(status))
3661 restore_tty_if_stopped_or_signaled(struct job *jp)
3663 //TODO: check what happens if we come from waitforjob() in expbackq()
3665 int s = job_signal_status(jp);
3666 if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
3671 # define get_tty_state() ((void)0)
3672 # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
3676 set_curjob(struct job *jp, unsigned mode)
3679 struct job **jpp, **curp;
3681 /* first remove from list */
3682 jpp = curp = &curjob;
3687 jpp = &jp1->prev_job;
3689 *jpp = jp1->prev_job;
3691 /* Then re-insert in correct position */
3699 /* job being deleted */
3702 /* newly created job or backgrounded job,
3703 * put after all stopped jobs.
3708 if (!jp1 || jp1->state != JOBSTOPPED)
3711 jpp = &jp1->prev_job;
3717 /* newly stopped job - becomes curjob */
3718 jp->prev_job = *jpp;
3726 jobno(const struct job *jp)
3728 return jp - jobtab + 1;
3733 * Convert a job name to a job structure.
3736 #define getjob(name, getctl) getjob(name)
3739 getjob(const char *name, int getctl)
3743 const char *err_msg = "%s: no such job";
3747 char *(*match)(const char *, const char *);
3762 if (c == '+' || c == '%') {
3764 err_msg = "No current job";
3770 err_msg = "No previous job";
3780 if (num > 0 && num <= njobs) {
3781 jp = jobtab + num - 1;
3796 if (match(jp->ps[0].ps_cmd, p)) {
3800 err_msg = "%s: ambiguous";
3810 err_msg = "job %s not created under job control";
3811 if (getctl && jp->jobctl == 0)
3816 ash_msg_and_raise_error(err_msg, name);
3820 * Mark a job structure as unused.
3823 freejob(struct job *jp)
3825 struct procstat *ps;
3829 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3830 if (ps->ps_cmd != nullstr)
3833 if (jp->ps != &jp->ps0)
3836 set_curjob(jp, CUR_DELETE);
3842 xtcsetpgrp(int fd, pid_t pgrp)
3844 if (tcsetpgrp(fd, pgrp))
3845 ash_msg_and_raise_perror("can't set tty process group");
3849 * Turn job control on and off.
3851 * Note: This code assumes that the third arg to ioctl is a character
3852 * pointer, which is true on Berkeley systems but not System V. Since
3853 * System V doesn't have job control yet, this isn't a problem now.
3855 * Called with interrupts off.
3863 if (on == doing_jobctl || rootshell == 0)
3867 ofd = fd = open(_PATH_TTY, O_RDWR);
3869 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3870 * That sometimes helps to acquire controlling tty.
3871 * Obviously, a workaround for bugs when someone
3872 * failed to provide a controlling tty to bash! :) */
3878 /* fd is a tty at this point */
3879 fd = fcntl(fd, F_DUPFD, 10);
3880 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
3883 goto out; /* F_DUPFD failed */
3884 close_on_exec_on(fd);
3885 while (1) { /* while we are in the background */
3886 pgrp = tcgetpgrp(fd);
3889 ash_msg("can't access tty; job control turned off");
3893 if (pgrp == getpgrp())
3904 xtcsetpgrp(fd, pgrp);
3906 /* turning job control off */
3909 /* was xtcsetpgrp, but this can make exiting ash
3910 * loop forever if pty is already deleted */
3911 tcsetpgrp(fd, pgrp);
3925 static int FAST_FUNC
3926 killcmd(int argc, char **argv)
3928 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3931 if (argv[i][0] == '%') {
3933 * "kill %N" - job kill
3934 * Converting to pgrp / pid kill
3940 jp = getjob(argv[i], 0);
3942 * In jobs started under job control, we signal
3943 * entire process group by kill -PGRP_ID.
3944 * This happens, f.e., in interactive shell.
3946 * Otherwise, we signal each child via
3947 * kill PID1 PID2 PID3.
3949 * sh -c 'sleep 1|sleep 1 & kill %1'
3950 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3951 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3953 n = jp->nprocs; /* can't be 0 (I hope) */
3956 dst = alloca(n * sizeof(int)*4);
3958 for (j = 0; j < n; j++) {
3959 struct procstat *ps = &jp->ps[j];
3960 /* Skip non-running and not-stopped members
3961 * (i.e. dead members) of the job
3963 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3966 * kill_main has matching code to expect
3967 * leading space. Needed to not confuse
3968 * negative pids with "kill -SIGNAL_NO" syntax
3970 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3974 } while (argv[++i]);
3976 return kill_main(argc, argv);
3980 showpipe(struct job *jp /*, FILE *out*/)
3982 struct procstat *ps;
3983 struct procstat *psend;
3985 psend = jp->ps + jp->nprocs;
3986 for (ps = jp->ps + 1; ps < psend; ps++)
3987 printf(" | %s", ps->ps_cmd);
3988 newline_and_flush(stdout);
3989 flush_stdout_stderr();
3994 restartjob(struct job *jp, int mode)
3996 struct procstat *ps;
4002 if (jp->state == JOBDONE)
4004 jp->state = JOBRUNNING;
4005 pgid = jp->ps[0].ps_pid;
4006 if (mode == FORK_FG) {
4008 xtcsetpgrp(ttyfd, pgid);
4010 killpg(pgid, SIGCONT);
4014 if (WIFSTOPPED(ps->ps_status)) {
4020 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
4025 static int FAST_FUNC
4026 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
4032 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
4036 jp = getjob(*argv, 1);
4037 if (mode == FORK_BG) {
4038 set_curjob(jp, CUR_RUNNING);
4039 printf("[%d] ", jobno(jp));
4041 out1str(jp->ps[0].ps_cmd);
4042 showpipe(jp /*, stdout*/);
4043 retval = restartjob(jp, mode);
4044 } while (*argv && *++argv);
4050 sprint_status48(char *s, int status, int sigonly)
4056 if (!WIFEXITED(status)) {
4058 if (WIFSTOPPED(status))
4059 st = WSTOPSIG(status);
4062 st = WTERMSIG(status);
4064 if (st == SIGINT || st == SIGPIPE)
4067 if (WIFSTOPPED(status))
4072 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
4073 col = fmtstr(s, 32, strsignal(st));
4074 if (WCOREDUMP(status)) {
4075 strcpy(s + col, " (core dumped)");
4076 col += sizeof(" (core dumped)")-1;
4078 } else if (!sigonly) {
4079 st = WEXITSTATUS(status);
4080 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
4087 wait_block_or_sig(int *status)
4094 /* Poll all children for changes in their state */
4096 /* if job control is active, accept stopped processes too */
4097 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
4099 break; /* Error (e.g. EINTR, ECHILD) or pid */
4101 /* Children exist, but none are ready. Sleep until interesting signal */
4104 sigprocmask(SIG_SETMASK, &mask, &mask);
4105 while (!got_sigchld && !pending_sig)
4107 sigprocmask(SIG_SETMASK, &mask, NULL);
4108 #else /* unsafe: a signal can set pending_sig after check, but before pause() */
4109 while (!got_sigchld && !pending_sig)
4113 /* If it was SIGCHLD, poll children again */
4114 } while (got_sigchld);
4119 #define DOWAIT_NONBLOCK 0
4120 #define DOWAIT_BLOCK 1
4121 #define DOWAIT_BLOCK_OR_SIG 2
4124 dowait(int block, struct job *job)
4129 struct job *thisjob = NULL;
4131 TRACE(("dowait(0x%x) called\n", block));
4133 /* It's wrong to call waitpid() outside of INT_OFF region:
4134 * signal can arrive just after syscall return and handler can
4135 * longjmp away, losing stop/exit notification processing.
4136 * Thus, for "jobs" builtin, and for waiting for a fg job,
4137 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
4139 * However, for "wait" builtin it is wrong to simply call waitpid()
4140 * in INT_OFF region: "wait" needs to wait for any running job
4141 * to change state, but should exit on any trap too.
4142 * In INT_OFF region, a signal just before syscall entry can set
4143 * pending_sig variables, but we can't check them, and we would
4144 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
4146 * Because of this, we run inside INT_OFF, but use a special routine
4147 * which combines waitpid() and sigsuspend().
4148 * This is the reason why we need to have a handler for SIGCHLD:
4149 * SIG_DFL handler does not wake sigsuspend().
4152 if (block == DOWAIT_BLOCK_OR_SIG) {
4153 pid = wait_block_or_sig(&status);
4156 if (block == DOWAIT_NONBLOCK)
4157 wait_flags = WNOHANG;
4158 /* if job control is active, accept stopped processes too */
4160 wait_flags |= WUNTRACED;
4161 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4162 pid = waitpid(-1, &status, wait_flags);
4164 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4165 pid, status, errno, strerror(errno)));
4170 for (jp = curjob; jp; jp = jp->prev_job) {
4172 struct procstat *ps;
4173 struct procstat *psend;
4174 if (jp->state == JOBDONE)
4178 psend = ps + jp->nprocs;
4180 if (ps->ps_pid == pid) {
4181 TRACE(("Job %d: changing status of proc %d "
4182 "from 0x%x to 0x%x\n",
4183 jobno(jp), pid, ps->ps_status, status));
4184 ps->ps_status = status;
4187 if (ps->ps_status == -1)
4188 jobstate = JOBRUNNING;
4190 if (jobstate == JOBRUNNING)
4192 if (WIFSTOPPED(ps->ps_status)) {
4193 jp->stopstatus = ps->ps_status;
4194 jobstate = JOBSTOPPED;
4197 } while (++ps < psend);
4201 /* Found the job where one of its processes changed its state.
4202 * Is there at least one live and running process in this job? */
4203 if (jobstate != JOBRUNNING) {
4204 /* No. All live processes in the job are stopped
4205 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4207 thisjob->changed = 1;
4208 if (thisjob->state != jobstate) {
4209 TRACE(("Job %d: changing state from %d to %d\n",
4210 jobno(thisjob), thisjob->state, jobstate));
4211 thisjob->state = jobstate;
4213 if (jobstate == JOBSTOPPED)
4214 set_curjob(thisjob, CUR_STOPPED);
4220 /* The process wasn't found in job list */
4222 if (!WIFSTOPPED(status))
4228 if (thisjob && thisjob == job) {
4232 len = sprint_status48(s, status, 1);
4244 showjob(struct job *jp, int mode)
4246 struct procstat *ps;
4247 struct procstat *psend;
4250 char s[16 + 16 + 48];
4251 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4255 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4256 /* just output process (group) id of pipeline */
4257 fprintf(out, "%d\n", ps->ps_pid);
4261 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4266 else if (curjob && jp == curjob->prev_job)
4269 if (mode & SHOW_PIDS)
4270 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4272 psend = ps + jp->nprocs;
4274 if (jp->state == JOBRUNNING) {
4275 strcpy(s + col, "Running");
4276 col += sizeof("Running") - 1;
4278 int status = psend[-1].ps_status;
4279 if (jp->state == JOBSTOPPED)
4280 status = jp->stopstatus;
4281 col += sprint_status48(s + col, status, 0);
4283 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4285 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4286 * or prints several "PID | <cmdN>" lines,
4287 * depending on SHOW_PIDS bit.
4288 * We do not print status of individual processes
4289 * between PID and <cmdN>. bash does it, but not very well:
4290 * first line shows overall job status, not process status,
4291 * making it impossible to know 1st process status.
4295 /* for each process */
4298 if (mode & SHOW_PIDS)
4299 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4301 fprintf(out, "%s%*c%s%s",
4303 33 - col >= 0 ? 33 - col : 0, ' ',
4304 ps == jp->ps ? "" : "| ",
4307 } while (++ps != psend);
4308 newline_and_flush(out);
4312 if (jp->state == JOBDONE) {
4313 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4319 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4320 * statuses have changed since the last call to showjobs.
4327 TRACE(("showjobs(0x%x) called\n", mode));
4329 /* Handle all finished jobs */
4330 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4333 for (jp = curjob; jp; jp = jp->prev_job) {
4334 if (!(mode & SHOW_CHANGED) || jp->changed) {
4340 static int FAST_FUNC
4341 jobscmd(int argc UNUSED_PARAM, char **argv)
4346 while ((m = nextopt("lp")) != '\0') {
4350 mode |= SHOW_ONLY_PGID;
4356 showjob(getjob(*argv, 0), mode);
4366 /* Called only on finished or stopped jobs (no members are running) */
4368 getstatus(struct job *job)
4372 struct procstat *ps;
4374 /* Fetch last member's status */
4375 ps = job->ps + job->nprocs - 1;
4376 status = ps->ps_status;
4378 /* "set -o pipefail" mode: use last _nonzero_ status */
4379 while (status == 0 && --ps >= job->ps)
4380 status = ps->ps_status;
4383 retval = WEXITSTATUS(status);
4384 if (!WIFEXITED(status)) {
4386 retval = WSTOPSIG(status);
4387 if (!WIFSTOPPED(status))
4390 /* XXX: limits number of signals */
4391 retval = WTERMSIG(status);
4393 if (retval == SIGINT)
4399 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4400 jobno(job), job->nprocs, status, retval));
4404 static int FAST_FUNC
4405 waitcmd(int argc UNUSED_PARAM, char **argv)
4416 /* wait for all jobs */
4420 if (!jp) /* no running procs */
4422 if (jp->state == JOBRUNNING)
4428 * "When bash is waiting for an asynchronous command via
4429 * the wait builtin, the reception of a signal for which a trap
4430 * has been set will cause the wait builtin to return immediately
4431 * with an exit status greater than 128, immediately after which
4432 * the trap is executed."
4434 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4435 /* if child sends us a signal *and immediately exits*,
4436 * dowait() returns pid > 0. Check this case,
4437 * not "if (dowait() < 0)"!
4446 if (**argv != '%') {
4447 pid_t pid = number(*argv);
4452 if (job->ps[job->nprocs - 1].ps_pid == pid)
4454 job = job->prev_job;
4457 job = getjob(*argv, 0);
4459 /* loop until process terminated or stopped */
4460 while (job->state == JOBRUNNING) {
4461 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4466 retval = getstatus(job);
4473 retval = 128 + pending_sig;
4482 struct job *jp, *jq;
4484 len = njobs * sizeof(*jp);
4486 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4488 offset = (char *)jp - (char *)jq;
4490 /* Relocate pointers */
4493 jq = (struct job *)((char *)jq + l);
4497 #define joff(p) ((struct job *)((char *)(p) + l))
4498 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4499 if (joff(jp)->ps == &jq->ps0)
4500 jmove(joff(jp)->ps);
4501 if (joff(jp)->prev_job)
4502 jmove(joff(jp)->prev_job);
4512 jp = (struct job *)((char *)jp + len);
4516 } while (--jq >= jp);
4521 * Return a new job structure.
4522 * Called with interrupts off.
4525 makejob(/*union node *node,*/ int nprocs)
4530 for (i = njobs, jp = jobtab; ; jp++) {
4537 if (jp->state != JOBDONE || !jp->waited)
4546 memset(jp, 0, sizeof(*jp));
4548 /* jp->jobctl is a bitfield.
4549 * "jp->jobctl |= doing_jobctl" likely to give awful code */
4553 jp->prev_job = curjob;
4558 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4560 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4567 * Return a string identifying a command (to be printed by the
4570 static char *cmdnextc;
4573 cmdputs(const char *s)
4575 static const char vstype[VSTYPE + 1][3] = {
4576 "", "}", "-", "+", "?", "=",
4577 "%", "%%", "#", "##"
4578 IF_BASH_SUBSTR(, ":")
4579 IF_BASH_PATTERN_SUBST(, "/", "//")
4582 const char *p, *str;
4586 unsigned char subtype = 0;
4590 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4592 while ((c = *p++) != '\0') {
4600 if ((subtype & VSTYPE) == VSLENGTH)
4606 str = "\"}" + !(quoted & 1);
4613 #if ENABLE_FEATURE_SH_MATH
4628 if ((subtype & VSTYPE) != VSNORMAL)
4630 str = vstype[subtype & VSTYPE];
4631 if (subtype & VSNUL)
4640 /* These can only happen inside quotes */
4653 while ((c = *str++) != '\0') {
4656 } /* while *p++ not NUL */
4659 USTPUTC('"', nextc);
4665 /* cmdtxt() and cmdlist() call each other */
4666 static void cmdtxt(union node *n);
4669 cmdlist(union node *np, int sep)
4671 for (; np; np = np->narg.next) {
4675 if (sep && np->narg.next)
4681 cmdtxt(union node *n)
4684 struct nodelist *lp;
4695 lp = n->npipe.cmdlist;
4713 cmdtxt(n->nbinary.ch1);
4729 cmdtxt(n->nif.test);
4731 if (n->nif.elsepart) {
4732 cmdtxt(n->nif.ifpart);
4734 n = n->nif.elsepart;
4752 cmdtxt(n->nbinary.ch1);
4762 cmdputs(n->nfor.var);
4764 cmdlist(n->nfor.args, 1);
4769 cmdputs(n->narg.text);
4773 cmdlist(n->ncmd.args, 1);
4774 cmdlist(n->ncmd.redirect, 0);
4787 cmdputs(n->ncase.expr->narg.text);
4789 for (np = n->ncase.cases; np; np = np->nclist.next) {
4790 cmdtxt(np->nclist.pattern);
4792 cmdtxt(np->nclist.body);
4806 #if BASH_REDIR_OUTPUT
4821 cmdputs(utoa(n->nfile.fd));
4823 if (n->type == NTOFD || n->type == NFROMFD) {
4824 cmdputs(utoa(n->ndup.dupfd));
4833 commandtext(union node *n)
4837 STARTSTACKSTR(cmdnextc);
4839 name = stackblock();
4840 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4841 return ckstrdup(name);
4846 * Fork off a subshell. If we are doing job control, give the subshell its
4847 * own process group. Jp is a job structure that the job is to be added to.
4848 * N is the command that will be evaluated by the child. Both jp and n may
4849 * be NULL. The mode parameter can be one of the following:
4850 * FORK_FG - Fork off a foreground process.
4851 * FORK_BG - Fork off a background process.
4852 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4853 * process group even if job control is on.
4855 * When job control is turned off, background processes have their standard
4856 * input redirected to /dev/null (except for the second and later processes
4859 * Called with interrupts off.
4862 * Clear traps on a fork.
4870 for (tp = trap; tp < &trap[NSIG]; tp++) {
4871 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4872 if (trap_ptr == trap)
4874 /* else: it "belongs" to trap_ptr vector, don't free */
4876 if ((tp - trap) != 0)
4877 setsignal(tp - trap);
4884 /* Lives far away from here, needed for forkchild */
4885 static void closescript(void);
4887 /* Called after fork(), in child */
4888 /* jp and n are NULL when called by openhere() for heredoc support */
4889 static NOINLINE void
4890 forkchild(struct job *jp, union node *n, int mode)
4894 TRACE(("Child shell %d\n", getpid()));
4898 /* man bash: "Non-builtin commands run by bash have signal handlers
4899 * set to the values inherited by the shell from its parent".
4900 * Do we do it correctly? */
4904 if (mode == FORK_NOJOB /* is it `xxx` ? */
4905 && n && n->type == NCMD /* is it single cmd? */
4906 /* && n->ncmd.args->type == NARG - always true? */
4907 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4908 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4909 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4911 TRACE(("Trap hack\n"));
4912 /* Awful hack for `trap` or $(trap).
4914 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4915 * contains an example where "trap" is executed in a subshell:
4917 * save_traps=$(trap)
4919 * eval "$save_traps"
4921 * Standard does not say that "trap" in subshell shall print
4922 * parent shell's traps. It only says that its output
4923 * must have suitable form, but then, in the above example
4924 * (which is not supposed to be normative), it implies that.
4926 * bash (and probably other shell) does implement it
4927 * (traps are reset to defaults, but "trap" still shows them),
4928 * but as a result, "trap" logic is hopelessly messed up:
4931 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4932 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4933 * # true | trap <--- trap is in subshell - no output (ditto)
4934 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4935 * trap -- 'echo Ho' SIGWINCH
4936 * # echo `(trap)` <--- in subshell in subshell - output
4937 * trap -- 'echo Ho' SIGWINCH
4938 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4939 * trap -- 'echo Ho' SIGWINCH
4941 * The rules when to forget and when to not forget traps
4942 * get really complex and nonsensical.
4944 * Our solution: ONLY bare $(trap) or `trap` is special.
4946 /* Save trap handler strings for trap builtin to print */
4947 trap_ptr = xmemdup(trap, sizeof(trap));
4948 /* Fall through into clearing traps */
4952 /* do job control only in root shell */
4954 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4957 if (jp->nprocs == 0)
4960 pgrp = jp->ps[0].ps_pid;
4961 /* this can fail because we are doing it in the parent also */
4963 if (mode == FORK_FG)
4964 xtcsetpgrp(ttyfd, pgrp);
4969 if (mode == FORK_BG) {
4970 /* man bash: "When job control is not in effect,
4971 * asynchronous commands ignore SIGINT and SIGQUIT" */
4974 if (jp->nprocs == 0) {
4976 if (open(bb_dev_null, O_RDONLY) != 0)
4977 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4981 if (iflag) { /* why if iflag only? */
4986 * "In all cases, bash ignores SIGQUIT. Non-builtin
4987 * commands run by bash have signal handlers
4988 * set to the values inherited by the shell
4990 * Take care of the second rule: */
4994 if (n && n->type == NCMD
4995 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4997 TRACE(("Job hack\n"));
4998 /* "jobs": we do not want to clear job list for it,
4999 * instead we remove only _its_ own_ job from job list.
5000 * This makes "jobs .... | cat" more useful.
5006 for (jp = curjob; jp; jp = jp->prev_job)
5011 /* Called after fork(), in parent */
5013 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
5016 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
5018 TRACE(("In parent shell: child = %d\n", pid));
5020 /* jp is NULL when called by openhere() for heredoc support */
5021 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
5027 if (mode != FORK_NOJOB && jp->jobctl) {
5030 if (jp->nprocs == 0)
5033 pgrp = jp->ps[0].ps_pid;
5034 /* This can fail because we are doing it in the child also */
5038 if (mode == FORK_BG) {
5039 backgndpid = pid; /* set $! */
5040 set_curjob(jp, CUR_RUNNING);
5043 struct procstat *ps = &jp->ps[jp->nprocs++];
5046 ps->ps_cmd = nullstr;
5048 if (doing_jobctl && n)
5049 ps->ps_cmd = commandtext(n);
5054 /* jp and n are NULL when called by openhere() for heredoc support */
5056 forkshell(struct job *jp, union node *n, int mode)
5060 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
5063 TRACE(("Fork failed, errno=%d", errno));
5066 ash_msg_and_raise_error("can't fork");
5069 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
5070 forkchild(jp, n, mode);
5072 forkparent(jp, n, mode, pid);
5078 * Wait for job to finish.
5080 * Under job control we have the problem that while a child process
5081 * is running interrupts generated by the user are sent to the child
5082 * but not to the shell. This means that an infinite loop started by
5083 * an interactive user may be hard to kill. With job control turned off,
5084 * an interactive user may place an interactive program inside a loop.
5085 * If the interactive program catches interrupts, the user doesn't want
5086 * these interrupts to also abort the loop. The approach we take here
5087 * is to have the shell ignore interrupt signals while waiting for a
5088 * foreground process to terminate, and then send itself an interrupt
5089 * signal if the child process was terminated by an interrupt signal.
5090 * Unfortunately, some programs want to do a bit of cleanup and then
5091 * exit on interrupt; unless these processes terminate themselves by
5092 * sending a signal to themselves (instead of calling exit) they will
5093 * confuse this approach.
5095 * Called with interrupts off.
5098 waitforjob(struct job *jp)
5102 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
5105 while (jp->state == JOBRUNNING) {
5106 /* In non-interactive shells, we _can_ get
5107 * a keyboard signal here and be EINTRed,
5108 * but we just loop back, waiting for command to complete.
5111 * "If bash is waiting for a command to complete and receives
5112 * a signal for which a trap has been set, the trap
5113 * will not be executed until the command completes."
5115 * Reality is that even if trap is not set, bash
5116 * will not act on the signal until command completes.
5117 * Try this. sleep5intoff.c:
5118 * #include <signal.h>
5119 * #include <unistd.h>
5122 * sigemptyset(&set);
5123 * sigaddset(&set, SIGINT);
5124 * sigaddset(&set, SIGQUIT);
5125 * sigprocmask(SIG_BLOCK, &set, NULL);
5129 * $ bash -c './sleep5intoff; echo hi'
5130 * ^C^C^C^C <--- pressing ^C once a second
5132 * $ bash -c './sleep5intoff; echo hi'
5133 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
5136 dowait(DOWAIT_BLOCK, jp);
5143 xtcsetpgrp(ttyfd, rootpid);
5144 restore_tty_if_stopped_or_signaled(jp);
5147 * This is truly gross.
5148 * If we're doing job control, then we did a TIOCSPGRP which
5149 * caused us (the shell) to no longer be in the controlling
5150 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
5151 * intuit from the subprocess exit status whether a SIGINT
5152 * occurred, and if so interrupt ourselves. Yuck. - mycroft
5154 if (jp->sigint) /* TODO: do the same with all signals */
5155 raise(SIGINT); /* ... by raise(jp->sig) instead? */
5157 if (jp->state == JOBDONE)
5164 * return 1 if there are stopped jobs, otherwise 0
5176 if (jp && jp->state == JOBSTOPPED) {
5177 out2str("You have stopped jobs.\n");
5187 * Code for dealing with input/output redirection.
5192 #define EMPTY -2 /* marks an unused slot in redirtab */
5193 #define CLOSED -3 /* marks a slot of previously-closed fd */
5196 * Handle here documents. Normally we fork off a process to write the
5197 * data to a pipe. If the document is short, we can stuff the data in
5198 * the pipe without forking.
5200 /* openhere needs this forward reference */
5201 static void expandhere(union node *arg, int fd);
5203 openhere(union node *redir)
5209 ash_msg_and_raise_error("pipe call failed");
5210 if (redir->type == NHERE) {
5211 len = strlen(redir->nhere.doc->narg.text);
5212 if (len <= PIPE_BUF) {
5213 full_write(pip[1], redir->nhere.doc->narg.text, len);
5217 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5220 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5221 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5222 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5223 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5224 signal(SIGPIPE, SIG_DFL);
5225 if (redir->type == NHERE)
5226 full_write(pip[1], redir->nhere.doc->narg.text, len);
5228 expandhere(redir->nhere.doc, pip[1]);
5229 _exit(EXIT_SUCCESS);
5237 openredirect(union node *redir)
5243 switch (redir->nfile.type) {
5244 /* Can't happen, our single caller does this itself */
5250 return openhere(redir);
5253 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5254 * allocated space. Do it only when we know it is safe.
5256 fname = redir->nfile.expfname;
5258 switch (redir->nfile.type) {
5264 f = open(fname, O_RDONLY);
5269 f = open(fname, O_RDWR|O_CREAT, 0666);
5274 #if BASH_REDIR_OUTPUT
5277 /* Take care of noclobber mode. */
5279 if (stat(fname, &sb) < 0) {
5280 f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5283 } else if (!S_ISREG(sb.st_mode)) {
5284 f = open(fname, O_WRONLY, 0666);
5287 if (fstat(f, &sb) < 0 && S_ISREG(sb.st_mode)) {
5300 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5305 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5313 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5315 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5319 * Copy a file descriptor to be >= 10. Throws exception on error.
5327 newfd = fcntl(from, F_DUPFD, 10);
5328 err = newfd < 0 ? errno : 0;
5331 ash_msg_and_raise_perror("%d", from);
5333 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5339 dup2_or_raise(int from, int to)
5343 newfd = (from != to) ? dup2(from, to) : to;
5345 /* Happens when source fd is not open: try "echo >&99" */
5346 ash_msg_and_raise_perror("%d", from);
5351 /* Struct def and variable are moved down to the first usage site */
5356 struct redirtab *next;
5358 struct two_fd_t two_fd[];
5360 #define redirlist (G_var.redirlist)
5362 COPYFD_RESTORE = (int)~(INT_MAX),
5366 need_to_remember(struct redirtab *rp, int fd)
5370 if (!rp) /* remembering was not requested */
5373 for (i = 0; i < rp->pair_count; i++) {
5374 if (rp->two_fd[i].orig == fd) {
5375 /* already remembered */
5382 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5384 is_hidden_fd(struct redirtab *rp, int fd)
5387 struct parsefile *pf;
5391 /* Check open scripts' fds */
5394 /* We skip pf_fd == 0 case because of the following case:
5395 * $ ash # running ash interactively
5397 * and in script.sh: "exec 9>&0".
5398 * Even though top-level pf_fd _is_ 0,
5399 * it's still ok to use it: "read" builtin uses it,
5400 * why should we cripple "exec" builtin?
5402 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5410 /* Check saved fds of redirects */
5411 fd |= COPYFD_RESTORE;
5412 for (i = 0; i < rp->pair_count; i++) {
5413 if (rp->two_fd[i].copy == fd) {
5421 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5422 * old file descriptors are stashed away so that the redirection can be
5423 * undone by calling popredir.
5425 /* flags passed to redirect */
5426 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5427 #define REDIR_SAVEFD2 03 /* set preverrout */
5429 redirect(union node *redir, int flags)
5431 struct redirtab *sv;
5436 int copied_fd2 = -1;
5442 if (flags & REDIR_PUSH)
5447 fd = redir->nfile.fd;
5448 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5449 right_fd = redir->ndup.dupfd;
5450 //bb_error_msg("doing %d > %d", fd, right_fd);
5451 /* redirect from/to same file descriptor? */
5454 /* "echo >&10" and 10 is a fd opened to a sh script? */
5455 if (is_hidden_fd(sv, right_fd)) {
5456 errno = EBADF; /* as if it is closed */
5457 ash_msg_and_raise_perror("%d", right_fd);
5461 newfd = openredirect(redir); /* always >= 0 */
5463 /* Descriptor wasn't open before redirect.
5464 * Mark it for close in the future */
5465 if (need_to_remember(sv, fd)) {
5466 goto remember_to_close;
5471 #if BASH_REDIR_OUTPUT
5474 if (need_to_remember(sv, fd)) {
5475 /* Copy old descriptor */
5476 /* Careful to not accidentally "save"
5477 * to the same fd as right side fd in N>&M */
5478 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5479 #if defined(F_DUPFD_CLOEXEC)
5480 i = fcntl(fd, F_DUPFD_CLOEXEC, minfd);
5482 i = fcntl(fd, F_DUPFD, minfd);
5487 /* Strange error (e.g. "too many files" EMFILE?) */
5491 ash_msg_and_raise_perror("%d", fd);
5494 /* EBADF: it is not open - good, remember to close it */
5497 } else { /* fd is open, save its copy */
5498 #if !defined(F_DUPFD_CLOEXEC)
5499 fcntl(i, F_SETFD, FD_CLOEXEC);
5501 /* "exec fd>&-" should not close fds
5502 * which point to script file(s).
5503 * Force them to be restored afterwards */
5504 if (is_hidden_fd(sv, fd))
5505 i |= COPYFD_RESTORE;
5509 sv->two_fd[sv_pos].orig = fd;
5510 sv->two_fd[sv_pos].copy = i;
5514 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5515 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5516 /* Don't want to trigger debugging */
5520 dup2_or_raise(redir->ndup.dupfd, fd);
5522 } else if (fd != newfd) { /* move newfd to fd */
5523 dup2_or_raise(newfd, fd);
5524 #if BASH_REDIR_OUTPUT
5525 if (!(redir->nfile.type == NTO2 && fd == 2))
5529 #if BASH_REDIR_OUTPUT
5530 if (redir->nfile.type == NTO2 && fd == 1) {
5531 /* We already redirected it to fd 1, now copy it to 2 */
5537 } while ((redir = redir->nfile.next) != NULL);
5540 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5541 preverrout_fd = copied_fd2;
5545 redirectsafe(union node *redir, int flags)
5548 volatile int saveint;
5549 struct jmploc *volatile savehandler = exception_handler;
5550 struct jmploc jmploc;
5553 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5554 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5556 exception_handler = &jmploc;
5557 redirect(redir, flags);
5559 exception_handler = savehandler;
5560 if (err && exception_type != EXERROR)
5561 longjmp(exception_handler->loc, 1);
5562 RESTORE_INT(saveint);
5566 static struct redirtab*
5567 pushredir(union node *redir)
5569 struct redirtab *sv;
5578 #if BASH_REDIR_OUTPUT
5579 if (redir->nfile.type == NTO2)
5582 redir = redir->nfile.next;
5585 sv = ckzalloc(sizeof(*sv) + i * sizeof(sv->two_fd[0]));
5588 sv->two_fd[i].orig = sv->two_fd[i].copy = EMPTY;
5589 sv->next = redirlist;
5595 * Undo the effects of the last redirection.
5598 popredir(int drop, int restore)
5600 struct redirtab *rp;
5603 if (redirlist == NULL)
5607 for (i = 0; i < rp->pair_count; i++) {
5608 int fd = rp->two_fd[i].orig;
5609 int copy = rp->two_fd[i].copy;
5610 if (copy == CLOSED) {
5615 if (copy != EMPTY) {
5616 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5617 copy &= ~COPYFD_RESTORE;
5619 dup2_or_raise(copy, fd);
5621 close(copy & ~COPYFD_RESTORE);
5624 redirlist = rp->next;
5630 unwindredir(struct redirtab *stop)
5632 while (redirlist != stop)
5633 popredir(/*drop:*/ 0, /*restore:*/ 0);
5637 /* ============ Routines to expand arguments to commands
5639 * We have to deal with backquotes, shell variables, and file metacharacters.
5642 #if ENABLE_FEATURE_SH_MATH
5644 ash_arith(const char *s)
5646 arith_state_t math_state;
5649 math_state.lookupvar = lookupvar;
5650 math_state.setvar = setvar0;
5651 //math_state.endofname = endofname;
5654 result = arith(&math_state, s);
5655 if (math_state.errmsg)
5656 ash_msg_and_raise_error(math_state.errmsg);
5666 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5667 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5668 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5669 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5670 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5671 * POSIX says for this case:
5672 * Pathname expansion shall not be performed on the word by a
5673 * non-interactive shell; an interactive shell may perform it, but shall
5674 * do so only when the expansion would result in one word.
5675 * Currently, our code complies to the above rule by never globbing
5676 * redirection filenames.
5677 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5678 * (this means that on a typical Linux distro, bash almost always
5679 * performs globbing, and thus diverges from what we do).
5681 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5682 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5683 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5684 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5685 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5689 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5690 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5691 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5692 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5693 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5695 /* Add CTLESC when necessary. */
5696 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT)
5697 /* Do not skip NUL characters. */
5698 #define QUOTES_KEEPNUL EXP_TILDE
5701 * Structure specifying which parts of the string should be searched
5702 * for IFS characters.
5705 struct ifsregion *next; /* next region in list */
5706 int begoff; /* offset of start of region */
5707 int endoff; /* offset of end of region */
5708 int nulonly; /* search for nul bytes only */
5712 struct strlist *list;
5713 struct strlist **lastp;
5716 /* output of current string */
5717 static char *expdest;
5718 /* list of back quote expressions */
5719 static struct nodelist *argbackq;
5720 /* first struct in list of ifs regions */
5721 static struct ifsregion ifsfirst;
5722 /* last struct in list */
5723 static struct ifsregion *ifslastp;
5724 /* holds expanded arg list */
5725 static struct arglist exparg;
5729 * cvtnum() is used even if math support is off (to prepare $? values and such).
5736 /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
5737 len = sizeof(arith_t) * 3;
5738 /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
5739 if (sizeof(arith_t) < 4) len += 2;
5741 expdest = makestrspace(len, expdest);
5742 len = fmtstr(expdest, len, ARITH_FMT, num);
5743 STADJUST(len, expdest);
5748 * Break the argument string into pieces based upon IFS and add the
5749 * strings to the argument list. The regions of the string to be
5750 * searched for IFS characters have been stored by recordregion.
5753 ifsbreakup(char *string, struct arglist *arglist)
5755 struct ifsregion *ifsp;
5760 const char *ifs, *realifs;
5765 if (ifslastp != NULL) {
5768 realifs = ifsset() ? ifsval() : defifs;
5771 p = string + ifsp->begoff;
5772 nulonly = ifsp->nulonly;
5773 ifs = nulonly ? nullstr : realifs;
5775 while (p < string + ifsp->endoff) {
5777 if ((unsigned char)*p == CTLESC)
5779 if (!strchr(ifs, *p)) {
5784 ifsspc = (strchr(defifs, *p) != NULL);
5785 /* Ignore IFS whitespace at start */
5786 if (q == start && ifsspc) {
5792 sp = stzalloc(sizeof(*sp));
5794 *arglist->lastp = sp;
5795 arglist->lastp = &sp->next;
5799 if (p >= string + ifsp->endoff) {
5803 if ((unsigned char)*p == CTLESC)
5805 if (strchr(ifs, *p) == NULL) {
5809 if (strchr(defifs, *p) == NULL) {
5824 } while (ifsp != NULL);
5833 sp = stzalloc(sizeof(*sp));
5835 *arglist->lastp = sp;
5836 arglist->lastp = &sp->next;
5842 struct ifsregion *p = ifsfirst.next;
5849 struct ifsregion *ifsp;
5854 ifsfirst.next = NULL;
5861 esclen(const char *start, const char *p)
5865 while (p > start && (unsigned char)*--p == CTLESC) {
5872 * Remove any CTLESC characters from a string.
5875 rmescapes(char *str, int flag)
5877 static const char qchars[] ALIGN1 = {
5878 IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
5882 unsigned protect_against_glob;
5884 IF_BASH_PATTERN_SUBST(unsigned slash = flag & RMESCAPE_SLASH;)
5886 p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash));
5892 if (flag & RMESCAPE_ALLOC) {
5893 size_t len = p - str;
5894 size_t fulllen = len + strlen(p) + 1;
5896 if (flag & RMESCAPE_GROW) {
5897 int strloc = str - (char *)stackblock();
5898 r = makestrspace(fulllen, expdest);
5899 /* p and str may be invalidated by makestrspace */
5900 str = (char *)stackblock() + strloc;
5902 } else if (flag & RMESCAPE_HEAP) {
5903 r = ckmalloc(fulllen);
5905 r = stalloc(fulllen);
5909 q = (char *)mempcpy(q, str, len);
5914 globbing = flag & RMESCAPE_GLOB;
5915 protect_against_glob = globbing;
5917 if ((unsigned char)*p == CTLQUOTEMARK) {
5918 // Note: both inquotes and protect_against_glob only affect whether
5919 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5920 inquotes = ~inquotes;
5922 protect_against_glob = globbing;
5925 if ((unsigned char)*p == CTLESC) {
5929 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5931 if (protect_against_glob) {
5933 * We used to trust glob() and fnmatch() to eat
5934 * superfluous escapes (\z where z has no
5935 * special meaning anyway). But this causes
5936 * bugs such as string of one greek letter rho
5937 * (unicode-encoded as two bytes "cf,81")
5938 * getting encoded as "cf,CTLESC,81"
5939 * and here, converted to "cf,\,81" -
5940 * which does not go well with some flavors
5941 * of fnmatch() in unicode locales
5942 * (for example, glibc <= 2.22).
5944 * Lets add "\" only on the chars which need it.
5945 * Testcases for less obvious chars are shown.
5950 || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
5951 || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
5952 || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
5953 || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
5954 /* Some libc support [^negate], that's why "^" also needs love */
5955 || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
5960 } else if (*p == '\\' && !inquotes) {
5961 /* naked back slash */
5962 protect_against_glob = 0;
5965 #if BASH_PATTERN_SUBST
5966 else if (*p == '/' && slash) {
5967 /* stop handling globbing and mark location of slash */
5968 globbing = slash = 0;
5972 protect_against_glob = globbing;
5977 if (flag & RMESCAPE_GROW) {
5979 STADJUST(q - r + 1, expdest);
5983 #define pmatch(a, b) !fnmatch((a), (b), 0)
5986 * Prepare a pattern for a expmeta (internal glob(3)) call.
5988 * Returns an stalloced string.
5991 preglob(const char *pattern, int flag)
5993 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5997 * Put a string on the stack.
6000 memtodest(const char *p, size_t len, int syntax, int quotes)
6007 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
6010 unsigned char c = *p++;
6012 if (quotes & QUOTES_ESC) {
6013 int n = SIT(c, syntax);
6015 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
6022 } else if (!(quotes & QUOTES_KEEPNUL))
6031 strtodest(const char *p, int syntax, int quotes)
6033 size_t len = strlen(p);
6034 memtodest(p, len, syntax, quotes);
6039 * Record the fact that we have to scan this region of the
6040 * string for IFS characters.
6043 recordregion(int start, int end, int nulonly)
6045 struct ifsregion *ifsp;
6047 if (ifslastp == NULL) {
6051 ifsp = ckzalloc(sizeof(*ifsp));
6052 /*ifsp->next = NULL; - ckzalloc did it */
6053 ifslastp->next = ifsp;
6057 ifslastp->begoff = start;
6058 ifslastp->endoff = end;
6059 ifslastp->nulonly = nulonly;
6063 removerecordregions(int endoff)
6065 if (ifslastp == NULL)
6068 if (ifsfirst.endoff > endoff) {
6069 while (ifsfirst.next) {
6070 struct ifsregion *ifsp;
6072 ifsp = ifsfirst.next->next;
6073 free(ifsfirst.next);
6074 ifsfirst.next = ifsp;
6077 if (ifsfirst.begoff > endoff) {
6080 ifslastp = &ifsfirst;
6081 ifsfirst.endoff = endoff;
6086 ifslastp = &ifsfirst;
6087 while (ifslastp->next && ifslastp->next->begoff < endoff)
6088 ifslastp = ifslastp->next;
6089 while (ifslastp->next) {
6090 struct ifsregion *ifsp;
6092 ifsp = ifslastp->next->next;
6093 free(ifslastp->next);
6094 ifslastp->next = ifsp;
6097 if (ifslastp->endoff > endoff)
6098 ifslastp->endoff = endoff;
6102 exptilde(char *startp, char *p, int flags)
6108 int quotes = flags & QUOTES_ESC;
6112 while ((c = *++p) != '\0') {
6119 if (flags & EXP_VARTILDE)
6129 if (*name == '\0') {
6130 home = lookupvar("HOME");
6132 pw = getpwnam(name);
6137 if (!home || !*home)
6140 strtodest(home, SQSYNTAX, quotes);
6148 * Execute a command inside back quotes. If it's a builtin command, we
6149 * want to save its output in a block obtained from malloc. Otherwise
6150 * we fork off a subprocess and get the output of the command via a pipe.
6151 * Should be called with interrupts off.
6153 struct backcmd { /* result of evalbackcmd */
6154 int fd; /* file descriptor to read from */
6155 int nleft; /* number of chars in buffer */
6156 char *buf; /* buffer */
6157 struct job *jp; /* job structure for command */
6160 /* These forward decls are needed to use "eval" code for backticks handling: */
6161 /* flags in argument to evaltree */
6162 #define EV_EXIT 01 /* exit after evaluating tree */
6163 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
6164 static int evaltree(union node *, int);
6166 /* An evaltree() which is known to never return.
6167 * Used to use an alias:
6168 * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
6169 * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
6171 static ALWAYS_INLINE NORETURN void
6172 evaltreenr(union node *n, int flags)
6175 bb_unreachable(abort());
6179 static void FAST_FUNC
6180 evalbackcmd(union node *n, struct backcmd *result)
6194 ash_msg_and_raise_error("pipe call failed");
6195 jp = makejob(/*n,*/ 1);
6196 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6202 dup2_or_raise(pip[1], 1);
6205 /* TODO: eflag clearing makes the following not abort:
6206 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6207 * which is what bash does (unless it is in POSIX mode).
6208 * dash deleted "eflag = 0" line in the commit
6209 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6210 * [EVAL] Don't clear eflag in evalbackcmd
6211 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6215 evaltreenr(n, EV_EXIT);
6220 result->fd = pip[0];
6224 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6225 result->fd, result->buf, result->nleft, result->jp));
6229 * Expand stuff in backwards quotes.
6232 expbackq(union node *cmd, int flag)
6240 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6241 struct stackmark smark;
6244 startloc = expdest - (char *)stackblock();
6245 pushstackmark(&smark, startloc);
6246 evalbackcmd(cmd, &in);
6247 popstackmark(&smark);
6254 memtodest(p, i, syntax, flag & QUOTES_ESC);
6258 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6259 TRACE(("expbackq: read returns %d\n", i));
6268 back_exitstatus = waitforjob(in.jp);
6272 /* Eat all trailing newlines */
6274 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6278 if (!(flag & EXP_QUOTED))
6279 recordregion(startloc, dest - (char *)stackblock(), 0);
6280 TRACE(("evalbackq: size:%d:'%.*s'\n",
6281 (int)((dest - (char *)stackblock()) - startloc),
6282 (int)((dest - (char *)stackblock()) - startloc),
6283 stackblock() + startloc));
6286 #if ENABLE_FEATURE_SH_MATH
6288 * Expand arithmetic expression. Backup to start of expression,
6289 * evaluate, place result in (backed up) result, adjust string position.
6301 * This routine is slightly over-complicated for
6302 * efficiency. Next we scan backwards looking for the
6303 * start of arithmetic.
6305 start = stackblock();
6312 while ((unsigned char)*p != CTLARI) {
6316 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6321 esc = esclen(start, p);
6331 removerecordregions(begoff);
6335 if (flag & QUOTES_ESC)
6336 rmescapes(p + 1, 0);
6338 len = cvtnum(ash_arith(p + 1));
6340 if (!(flag & EXP_QUOTED))
6341 recordregion(begoff, begoff + len, 0);
6345 /* argstr needs it */
6346 static char *evalvar(char *p, int flags);
6349 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6350 * characters to allow for further processing. Otherwise treat
6351 * $@ like $* since no splitting will be performed.
6354 argstr(char *p, int flags)
6356 static const char spclchars[] ALIGN1 = {
6364 #if ENABLE_FEATURE_SH_MATH
6369 const char *reject = spclchars;
6370 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6375 if (!(flags & EXP_VARTILDE)) {
6377 } else if (flags & EXP_VARTILDE2) {
6382 if (flags & EXP_TILDE) {
6385 flags &= ~EXP_TILDE;
6389 p = exptilde(p, q, flags);
6392 startloc = expdest - (char *)stackblock();
6396 length += strcspn(p + length, reject);
6400 IF_FEATURE_SH_MATH(|| c == CTLENDARI)
6402 /* c == '=' || c == ':' || c == CTLENDARI */
6408 expdest = stack_nputstr(p, length, expdest);
6409 newloc = expdest - (char *)stackblock();
6410 if (breakall && !inquotes && newloc > startloc) {
6411 recordregion(startloc, newloc, 0);
6422 if (flags & EXP_VARTILDE2) {
6426 flags |= EXP_VARTILDE2;
6431 * sort of a hack - expand tildes in variable
6432 * assignments (after the first '=' and after ':'s).
6441 case CTLENDVAR: /* ??? */
6444 inquotes ^= EXP_QUOTED;
6445 /* "$@" syntax adherence hack */
6446 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6447 p = evalvar(p + 1, flags | inquotes) + 1;
6451 if (flags & QUOTES_ESC) {
6462 * Quoted parameter expansion pattern: remove quote
6463 * unless inside inner quotes or we have a literal
6466 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6467 EXP_QPAT && *p != '\\')
6472 TRACE(("argstr: evalvar('%s')\n", p));
6473 p = evalvar(p, flags | inquotes);
6474 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6477 expbackq(argbackq->n, flags | inquotes);
6478 argbackq = argbackq->next;
6480 #if ENABLE_FEATURE_SH_MATH
6483 expari(flags | inquotes);
6492 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6493 char *pattern, int quotes, int zero)
6502 const char *s = loc2;
6509 match = pmatch(pattern, s);
6514 if (quotes && (unsigned char)*loc == CTLESC)
6523 scanright(char *startp, char *rmesc, char *rmescend,
6524 char *pattern, int quotes, int match_at_start)
6526 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6527 int try2optimize = match_at_start;
6533 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6534 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6535 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6537 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6538 * and on each iteration they go back two/one char until they reach the beginning.
6539 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6541 /* TODO: document in what other circumstances we are called. */
6543 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6546 const char *s = loc2;
6547 if (match_at_start) {
6551 match = pmatch(pattern, s);
6552 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6556 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6558 /* Maybe we can optimize this:
6559 * if pattern ends with unescaped *, we can avoid checking
6560 * shorter strings: if "foo*" doesn't match "raw_value_of_v",
6561 * it won't match truncated "raw_value_of_" strings too.
6563 unsigned plen = strlen(pattern);
6564 /* Does it end with "*"? */
6565 if (plen != 0 && pattern[--plen] == '*') {
6566 /* "xxxx*" is not escaped */
6567 /* "xxx\*" is escaped */
6568 /* "xx\\*" is not escaped */
6569 /* "x\\\*" is escaped */
6571 while (plen != 0 && pattern[--plen] == '\\')
6574 break; /* ends with unescaped "*" */
6582 esc = esclen(startp, loc);
6593 static void varunset(const char *, const char *, const char *, int) NORETURN;
6595 varunset(const char *end, const char *var, const char *umsg, int varflags)
6601 msg = "parameter not set";
6603 if ((unsigned char)*end == CTLENDVAR) {
6604 if (varflags & VSNUL)
6610 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6614 subevalvar(char *p, char *varname, int strloc, int subtype,
6615 int startloc, int varflags, int flag)
6617 struct nodelist *saveargbackq = argbackq;
6618 int quotes = flag & QUOTES_ESC;
6621 char *rmesc, *rmescend;
6623 int amount, resetloc;
6624 IF_BASH_PATTERN_SUBST(int workloc;)
6625 IF_BASH_PATTERN_SUBST(char *repl = NULL;)
6627 char *(*scan)(char*, char*, char*, char*, int, int);
6629 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6630 // p, varname, strloc, subtype, startloc, varflags, quotes);
6632 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6633 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0)
6635 STPUTC('\0', expdest);
6636 argbackq = saveargbackq;
6637 startp = (char *)stackblock() + startloc;
6641 setvar0(varname, startp);
6642 amount = startp - expdest;
6643 STADJUST(amount, expdest);
6647 varunset(p, varname, startp, varflags);
6652 int pos, len, orig_len;
6655 loc = str = stackblock() + strloc;
6657 # if !ENABLE_FEATURE_SH_MATH
6658 # define ash_arith number
6660 /* Read POS in ${var:POS:LEN} */
6661 colon = strchr(loc, ':');
6662 if (colon) *colon = '\0';
6663 pos = ash_arith(loc);
6664 if (colon) *colon = ':';
6666 /* Read LEN in ${var:POS:LEN} */
6667 len = str - startp - 1;
6668 /* *loc != '\0', guaranteed by parser */
6672 /* Adjust the length by the number of escapes */
6673 for (ptr = startp; ptr < (str - 1); ptr++) {
6674 if ((unsigned char)*ptr == CTLESC) {
6681 if (*loc++ == ':') {
6683 len = ash_arith(loc);
6685 /* Skip POS in ${var:POS:LEN} */
6687 while (*loc && *loc != ':') {
6690 if (*loc++ == ':') {
6691 len = ash_arith(loc);
6697 /* ${VAR:$((-n)):l} starts n chars from the end */
6698 pos = orig_len + pos;
6700 if ((unsigned)pos >= orig_len) {
6701 /* apart from obvious ${VAR:999999:l},
6702 * covers ${VAR:$((-9999999)):l} - result is ""
6709 /* ${VAR:N:-M} sets LEN to strlen()-M */
6710 len = (orig_len - pos) + len;
6712 if ((unsigned)len > (orig_len - pos))
6713 len = orig_len - pos;
6715 for (str = startp; pos; str++, pos--) {
6716 if (quotes && (unsigned char)*str == CTLESC)
6719 for (loc = startp; len; len--) {
6720 if (quotes && (unsigned char)*str == CTLESC)
6725 amount = loc - expdest;
6726 STADJUST(amount, expdest);
6729 #endif /* BASH_SUBSTR */
6732 resetloc = expdest - (char *)stackblock();
6734 #if BASH_PATTERN_SUBST
6735 /* We'll comeback here if we grow the stack while handling
6736 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6737 * stack will need rebasing, and we'll need to remove our work
6743 amount = expdest - ((char *)stackblock() + resetloc);
6744 STADJUST(-amount, expdest);
6745 startp = (char *)stackblock() + startloc;
6748 rmescend = (char *)stackblock() + strloc;
6750 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6751 if (rmesc != startp) {
6753 startp = (char *)stackblock() + startloc;
6757 str = (char *)stackblock() + strloc;
6759 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6760 * The result is a_\_z_c (not a\_\_z_c)!
6762 * The search pattern and replace string treat backslashes differently!
6763 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6764 * and string. It's only used on the first call.
6766 preglob(str, IF_BASH_PATTERN_SUBST(
6767 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6768 RMESCAPE_SLASH : ) 0);
6770 #if BASH_PATTERN_SUBST
6771 workloc = expdest - (char *)stackblock();
6772 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6777 repl = strchr(str, CTLESC);
6783 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6785 /* If there's no pattern to match, return the expansion unmolested */
6794 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6795 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6797 /* No match, advance */
6798 char *restart_detect = stackblock();
6800 STPUTC(*idx, expdest);
6801 if (quotes && (unsigned char)*idx == CTLESC) {
6804 STPUTC(*idx, expdest);
6806 if (stackblock() != restart_detect)
6811 /* continue; - prone to quadratic behavior, smarter code: */
6814 if (str[0] == '*') {
6815 /* Pattern is "*foo". If "*foo" does not match "long_string",
6816 * it would never match "ong_string" etc, no point in trying.
6823 if (subtype == VSREPLACEALL) {
6825 if (quotes && (unsigned char)*idx == CTLESC)
6834 //bb_error_msg("repl:'%s'", repl);
6835 for (loc = (char*)repl; *loc; loc++) {
6836 char *restart_detect = stackblock();
6837 if (quotes && *loc == '\\') {
6838 STPUTC(CTLESC, expdest);
6841 STPUTC(*loc, expdest);
6842 if (stackblock() != restart_detect)
6847 if (subtype == VSREPLACE) {
6848 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6850 char *restart_detect = stackblock();
6851 STPUTC(*idx, expdest);
6852 if (stackblock() != restart_detect)
6861 /* We've put the replaced text into a buffer at workloc, now
6862 * move it to the right place and adjust the stack.
6864 STPUTC('\0', expdest);
6865 startp = (char *)stackblock() + startloc;
6866 memmove(startp, (char *)stackblock() + workloc, len + 1);
6867 //bb_error_msg("startp:'%s'", startp);
6868 amount = expdest - (startp + len);
6869 STADJUST(-amount, expdest);
6872 #endif /* BASH_PATTERN_SUBST */
6874 subtype -= VSTRIMRIGHT;
6876 if (subtype < 0 || subtype > 7)
6879 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6880 zero = subtype >> 1;
6881 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6882 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6884 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6887 memmove(startp, loc, str - loc);
6888 loc = startp + (str - loc) - 1;
6891 amount = loc - expdest;
6892 STADJUST(amount, expdest);
6898 * Add the value of a specialized variable to the stack string.
6899 * name parameter (examples):
6900 * ash -c 'echo $1' name:'1='
6901 * ash -c 'echo $qwe' name:'qwe='
6902 * ash -c 'echo $$' name:'$='
6903 * ash -c 'echo ${$}' name:'$='
6904 * ash -c 'echo ${$##q}' name:'$=q'
6905 * ash -c 'echo ${#$}' name:'$='
6906 * note: examples with bad shell syntax:
6907 * ash -c 'echo ${#$1}' name:'$=1'
6908 * ash -c 'echo ${#1#}' name:'1=#'
6910 static NOINLINE ssize_t
6911 varvalue(char *name, int varflags, int flags, int *quotedp)
6918 int quoted = *quotedp;
6919 int subtype = varflags & VSTYPE;
6920 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6921 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6924 sep = (flags & EXP_FULL) << CHAR_BIT;
6925 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6935 num = shellparam.nparam;
6943 goto check_1char_name;
6945 expdest = makestrspace(NOPTS, expdest);
6946 for (i = NOPTS - 1; i >= 0; i--) {
6948 USTPUTC(optletters(i), expdest);
6954 /* handles cases similar to ${#$1} */
6955 if (name[2] != '\0')
6956 raise_error_syntax("bad substitution");
6969 sep |= ifsset() ? ifsval()[0] : ' ';
6976 while ((p = *ap++) != NULL) {
6977 len += strtodest(p, syntax, quotes);
6981 memtodest(&sepc, 1, syntax, quotes);
6996 num = atoi(name); /* number(name) fails on ${N#str} etc */
6997 if (num < 0 || num > shellparam.nparam)
6999 p = num ? shellparam.p[num - 1] : arg0;
7002 /* NB: name has form "VAR=..." */
7003 p = lookupvar(name);
7008 len = strtodest(p, syntax, quotes);
7009 #if ENABLE_UNICODE_SUPPORT
7010 if (subtype == VSLENGTH && len > 0) {
7011 reinit_unicode_for_ash();
7012 if (unicode_status == UNICODE_ON) {
7013 STADJUST(-len, expdest);
7015 len = unicode_strlen(p);
7023 STADJUST(-len, expdest);
7028 * Expand a variable, and return a pointer to the next character in the
7032 evalvar(char *p, int flag)
7043 varflags = (unsigned char) *p++;
7044 subtype = varflags & VSTYPE;
7047 raise_error_syntax("bad substitution");
7049 quoted = flag & EXP_QUOTED;
7051 easy = (!quoted || (*var == '@' && shellparam.nparam));
7052 startloc = expdest - (char *)stackblock();
7053 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
7056 varlen = varvalue(var, varflags, flag, "ed);
7057 if (varflags & VSNUL)
7060 if (subtype == VSPLUS) {
7061 varlen = -1 - varlen;
7065 if (subtype == VSMINUS) {
7070 flag | EXP_TILDE | EXP_WORD
7077 if (subtype == VSASSIGN || subtype == VSQUESTION) {
7081 subevalvar(p, var, 0, subtype, startloc, varflags,
7082 flag & ~QUOTES_ESC);
7085 * Remove any recorded regions beyond
7088 removerecordregions(startloc);
7092 if (varlen < 0 && uflag)
7093 varunset(p, var, 0, 0);
7095 if (subtype == VSLENGTH) {
7096 cvtnum(varlen > 0 ? varlen : 0);
7100 if (subtype == VSNORMAL) {
7104 recordregion(startloc, expdest - (char *)stackblock(), quoted);
7113 case VSTRIMRIGHTMAX:
7117 #if BASH_PATTERN_SUBST
7129 * Terminate the string and start recording the pattern
7132 STPUTC('\0', expdest);
7133 patloc = expdest - (char *)stackblock();
7134 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
7135 startloc, varflags, flag)) {
7136 int amount = expdest - (
7137 (char *)stackblock() + patloc - 1
7139 STADJUST(-amount, expdest);
7141 /* Remove any recorded regions beyond start of variable */
7142 removerecordregions(startloc);
7147 if (subtype != VSNORMAL) { /* skip to end of alternative */
7150 unsigned char c = *p++;
7153 else if (c == CTLBACKQ) {
7155 argbackq = argbackq->next;
7156 } else if (c == CTLVAR) {
7157 if ((*p++ & VSTYPE) != VSNORMAL)
7159 } else if (c == CTLENDVAR) {
7169 * Add a file name to the list.
7172 addfname(const char *name)
7176 sp = stzalloc(sizeof(*sp));
7177 sp->text = sstrdup(name);
7179 exparg.lastp = &sp->next;
7182 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7184 hasmeta(const char *p)
7186 static const char chars[] ALIGN1 = {
7187 '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
7191 p = strpbrk(p, chars);
7194 switch ((unsigned char) *p) {
7198 if (*p == CTLQUOTEMARK)
7202 if (*p == '\0') /* huh? */
7213 if (!strchr(p + 1, ']')) {
7214 /* It's not a properly closed [] pattern,
7215 * but other metas may follow. Continue checking.
7216 * my[file* _is_ globbed by bash
7217 * and matches filenames like "my[file1".
7233 /* If we want to use glob() from libc... */
7234 #if !ENABLE_ASH_INTERNAL_GLOB
7236 /* Add the result of glob() to the list */
7238 addglob(const glob_t *pglob)
7240 char **p = pglob->gl_pathv;
7247 expandmeta(struct strlist *str /*, int flag*/)
7249 /* TODO - EXP_REDIR */
7259 if (!hasmeta(str->text))
7263 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7264 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7265 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7267 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7268 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7269 // Which means you need to unescape the string, right? Not so fast:
7270 // if there _is_ a file named "file\?" (with backslash), it is returned
7271 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7272 // You DON'T KNOW by looking at the result whether you need to unescape it.
7274 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7275 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7276 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7277 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7278 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7279 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7280 i = glob(p, 0, NULL, &pglob);
7281 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7286 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7287 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7288 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7300 *exparg.lastp = str;
7301 rmescapes(str->text, 0);
7302 exparg.lastp = &str->next;
7304 default: /* GLOB_NOSPACE */
7307 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7314 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7317 * Do metacharacter (i.e. *, ?, [...]) expansion.
7320 expmeta(char *expdir, char *enddir, char *name)
7336 for (p = name; esc = 0, *p; p += esc + 1) {
7337 if (*p == '*' || *p == '?')
7339 else if (*p == '[') {
7346 if (*q == '/' || *q == '\0')
7356 if (p[esc] == '/') {
7359 start = p + esc + 1;
7363 if (metaflag == 0) { /* we've reached the end of the file name */
7364 if (enddir != expdir)
7372 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7383 } while (p < start);
7385 if (enddir == expdir) {
7387 } else if (enddir == expdir + 1 && *expdir == '/') {
7396 if (enddir != expdir)
7398 if (*endname == 0) {
7411 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7412 if (dp->d_name[0] == '.' && !matchdot)
7414 if (pmatch(start, dp->d_name)) {
7416 strcpy(enddir, dp->d_name);
7419 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7422 expmeta(expdir, p, endname);
7428 endname[-esc - 1] = esc ? '\\' : '/';
7431 static struct strlist *
7432 msort(struct strlist *list, int len)
7434 struct strlist *p, *q = NULL;
7435 struct strlist **lpp;
7443 for (n = half; --n >= 0;) {
7447 q->next = NULL; /* terminate first half of list */
7448 q = msort(list, half); /* sort first half of list */
7449 p = msort(p, len - half); /* sort second half */
7452 #if ENABLE_LOCALE_SUPPORT
7453 if (strcoll(p->text, q->text) < 0)
7455 if (strcmp(p->text, q->text) < 0)
7479 * Sort the results of file name expansion. It calculates the number of
7480 * strings to sort and then calls msort (short for merge sort) to do the
7483 static struct strlist *
7484 expsort(struct strlist *str)
7490 for (sp = str; sp; sp = sp->next)
7492 return msort(str, len);
7496 expandmeta(struct strlist *str /*, int flag*/)
7498 /* TODO - EXP_REDIR */
7502 struct strlist **savelastp;
7508 if (!hasmeta(str->text))
7510 savelastp = exparg.lastp;
7513 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7515 int i = strlen(str->text);
7516 //BUGGY estimation of how long expanded name can be
7517 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7519 expmeta(expdir, expdir, p);
7524 if (exparg.lastp == savelastp) {
7529 *exparg.lastp = str;
7530 rmescapes(str->text, 0);
7531 exparg.lastp = &str->next;
7533 *exparg.lastp = NULL;
7534 *savelastp = sp = expsort(*savelastp);
7535 while (sp->next != NULL)
7537 exparg.lastp = &sp->next;
7542 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7545 * Perform variable substitution and command substitution on an argument,
7546 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7547 * perform splitting and file name expansion. When arglist is NULL, perform
7548 * here document expansion.
7551 expandarg(union node *arg, struct arglist *arglist, int flag)
7556 argbackq = arg->narg.backquote;
7557 STARTSTACKSTR(expdest);
7558 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7559 argstr(arg->narg.text, flag);
7560 p = _STPUTC('\0', expdest);
7562 if (arglist == NULL) {
7563 /* here document expanded */
7566 p = grabstackstr(p);
7567 TRACE(("expandarg: p:'%s'\n", p));
7568 exparg.lastp = &exparg.list;
7572 if (flag & EXP_FULL) {
7573 ifsbreakup(p, &exparg);
7574 *exparg.lastp = NULL;
7575 exparg.lastp = &exparg.list;
7576 expandmeta(exparg.list /*, flag*/);
7578 sp = stzalloc(sizeof(*sp));
7581 exparg.lastp = &sp->next;
7583 *exparg.lastp = NULL;
7585 *arglist->lastp = exparg.list;
7586 arglist->lastp = exparg.lastp;
7594 * Expand shell variables and backquotes inside a here document.
7597 expandhere(union node *arg, int fd)
7599 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7600 full_write(fd, stackblock(), expdest - (char *)stackblock());
7604 * Returns true if the pattern matches the string.
7607 patmatch(char *pattern, const char *string)
7609 char *p = preglob(pattern, 0);
7610 //bb_error_msg("fnmatch(pattern:'%s',str:'%s')", p, string);
7611 return pmatch(p, string);
7615 * See if a pattern matches in a case statement.
7618 casematch(union node *pattern, char *val)
7620 struct stackmark smark;
7623 setstackmark(&smark);
7624 argbackq = pattern->narg.backquote;
7625 STARTSTACKSTR(expdest);
7626 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
7627 STACKSTRNUL(expdest);
7629 result = patmatch(stackblock(), val);
7630 popstackmark(&smark);
7635 /* ============ find_command */
7639 int (*builtin)(int, char **) FAST_FUNC;
7640 /* unsigned flags; */
7642 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7643 /* "regular" builtins always take precedence over commands,
7644 * regardless of PATH=....%builtin... position */
7645 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7646 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7649 smallint cmdtype; /* CMDxxx */
7652 /* index >= 0 for commands without path (slashes) */
7653 /* (TODO: what exactly does the value mean? PATH position?) */
7654 /* index == -1 for commands with slashes */
7655 /* index == (-2 - applet_no) for NOFORK applets */
7656 const struct builtincmd *cmd;
7657 struct funcnode *func;
7660 /* values of cmdtype */
7661 #define CMDUNKNOWN -1 /* no entry in table for command */
7662 #define CMDNORMAL 0 /* command is an executable program */
7663 #define CMDFUNCTION 1 /* command is a shell function */
7664 #define CMDBUILTIN 2 /* command is a shell builtin */
7666 /* action to find_command() */
7667 #define DO_ERR 0x01 /* prints errors */
7668 #define DO_ABS 0x02 /* checks absolute paths */
7669 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7670 #define DO_ALTPATH 0x08 /* using alternate path */
7671 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7673 static void find_command(char *, struct cmdentry *, int, const char *);
7676 /* ============ Hashing commands */
7679 * When commands are first encountered, they are entered in a hash table.
7680 * This ensures that a full path search will not have to be done for them
7681 * on each invocation.
7683 * We should investigate converting to a linear search, even though that
7684 * would make the command name "hash" a misnomer.
7688 struct tblentry *next; /* next entry in hash chain */
7689 union param param; /* definition of builtin function */
7690 smallint cmdtype; /* CMDxxx */
7691 char rehash; /* if set, cd done since entry created */
7692 char cmdname[1]; /* name of command */
7695 static struct tblentry **cmdtable;
7696 #define INIT_G_cmdtable() do { \
7697 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7700 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7704 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
7706 #if ENABLE_FEATURE_SH_STANDALONE
7707 if (applet_no >= 0) {
7708 if (APPLET_IS_NOEXEC(applet_no)) {
7712 popredir(/*drop:*/ 1, /*restore:*/ 0);
7713 run_applet_no_and_exit(applet_no, cmd, argv);
7715 /* re-exec ourselves with the new arguments */
7716 execve(bb_busybox_exec_path, argv, envp);
7717 /* If they called chroot or otherwise made the binary no longer
7718 * executable, fall through */
7725 execve(cmd, argv, envp);
7726 } while (errno == EINTR);
7728 execve(cmd, argv, envp);
7730 if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
7731 /* Run "cmd" as a shell script:
7732 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7733 * "If the execve() function fails with ENOEXEC, the shell
7734 * shall execute a command equivalent to having a shell invoked
7735 * with the command name as its first operand,
7736 * with any remaining arguments passed to the new shell"
7738 * That is, do not use $SHELL, user's shell, or /bin/sh;
7739 * just call ourselves.
7741 * Note that bash reads ~80 chars of the file, and if it sees
7742 * a zero byte before it sees newline, it doesn't try to
7743 * interpret it, but fails with "cannot execute binary file"
7744 * message and exit code 126. For one, this prevents attempts
7745 * to interpret foreign ELF binaries as shell scripts.
7747 argv[0] = (char*) cmd;
7748 cmd = bb_busybox_exec_path;
7749 /* NB: this is only possible because all callers of shellexec()
7750 * ensure that the argv[-1] slot exists!
7753 argv[0] = (char*) "ash";
7759 * Exec a program. Never returns. If you change this routine, you may
7760 * have to change the find_command routine as well.
7761 * argv[-1] must exist and be writable! See tryexec() for why.
7763 static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
7764 static void shellexec(char *prog, char **argv, const char *path, int idx)
7770 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7772 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7773 if (strchr(prog, '/') != NULL
7774 #if ENABLE_FEATURE_SH_STANDALONE
7775 || (applet_no = find_applet_by_name(prog)) >= 0
7778 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
7779 if (applet_no >= 0) {
7780 /* We tried execing ourself, but it didn't work.
7781 * Maybe /proc/self/exe doesn't exist?
7790 while ((cmdname = path_advance(&path, prog)) != NULL) {
7791 if (--idx < 0 && pathopt == NULL) {
7792 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7793 if (errno != ENOENT && errno != ENOTDIR)
7800 /* Map to POSIX errors */
7812 exitstatus = exerrno;
7813 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7814 prog, e, suppress_int));
7815 ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
7820 printentry(struct tblentry *cmdp)
7826 idx = cmdp->param.index;
7829 name = path_advance(&path, cmdp->cmdname);
7831 } while (--idx >= 0);
7832 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7836 * Clear out command entries. The argument specifies the first entry in
7837 * PATH which has changed.
7840 clearcmdentry(int firstchange)
7842 struct tblentry **tblp;
7843 struct tblentry **pp;
7844 struct tblentry *cmdp;
7847 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7849 while ((cmdp = *pp) != NULL) {
7850 if ((cmdp->cmdtype == CMDNORMAL &&
7851 cmdp->param.index >= firstchange)
7852 || (cmdp->cmdtype == CMDBUILTIN &&
7853 builtinloc >= firstchange)
7866 * Locate a command in the command hash table. If "add" is nonzero,
7867 * add the command to the table if it is not already present. The
7868 * variable "lastcmdentry" is set to point to the address of the link
7869 * pointing to the entry, so that delete_cmd_entry can delete the
7872 * Interrupts must be off if called with add != 0.
7874 static struct tblentry **lastcmdentry;
7876 static struct tblentry *
7877 cmdlookup(const char *name, int add)
7879 unsigned int hashval;
7881 struct tblentry *cmdp;
7882 struct tblentry **pp;
7885 hashval = (unsigned char)*p << 4;
7887 hashval += (unsigned char)*p++;
7889 pp = &cmdtable[hashval % CMDTABLESIZE];
7890 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7891 if (strcmp(cmdp->cmdname, name) == 0)
7895 if (add && cmdp == NULL) {
7896 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7898 /* + 1 - already done because
7899 * tblentry::cmdname is char[1] */);
7900 /*cmdp->next = NULL; - ckzalloc did it */
7901 cmdp->cmdtype = CMDUNKNOWN;
7902 strcpy(cmdp->cmdname, name);
7909 * Delete the command entry returned on the last lookup.
7912 delete_cmd_entry(void)
7914 struct tblentry *cmdp;
7917 cmdp = *lastcmdentry;
7918 *lastcmdentry = cmdp->next;
7919 if (cmdp->cmdtype == CMDFUNCTION)
7920 freefunc(cmdp->param.func);
7926 * Add a new command entry, replacing any existing command entry for
7927 * the same name - except special builtins.
7930 addcmdentry(char *name, struct cmdentry *entry)
7932 struct tblentry *cmdp;
7934 cmdp = cmdlookup(name, 1);
7935 if (cmdp->cmdtype == CMDFUNCTION) {
7936 freefunc(cmdp->param.func);
7938 cmdp->cmdtype = entry->cmdtype;
7939 cmdp->param = entry->u;
7943 static int FAST_FUNC
7944 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7946 struct tblentry **pp;
7947 struct tblentry *cmdp;
7949 struct cmdentry entry;
7952 if (nextopt("r") != '\0') {
7957 if (*argptr == NULL) {
7958 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7959 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7960 if (cmdp->cmdtype == CMDNORMAL)
7968 while ((name = *argptr) != NULL) {
7969 cmdp = cmdlookup(name, 0);
7971 && (cmdp->cmdtype == CMDNORMAL
7972 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7976 find_command(name, &entry, DO_ERR, pathval());
7977 if (entry.cmdtype == CMDUNKNOWN)
7985 * Called when a cd is done. Marks all commands so the next time they
7986 * are executed they will be rehashed.
7991 struct tblentry **pp;
7992 struct tblentry *cmdp;
7994 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7995 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7996 if (cmdp->cmdtype == CMDNORMAL
7997 || (cmdp->cmdtype == CMDBUILTIN
7998 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
8008 * Fix command hash table when PATH changed.
8009 * Called before PATH is changed. The argument is the new value of PATH;
8010 * pathval() still returns the old value at this point.
8011 * Called with interrupts off.
8013 static void FAST_FUNC
8014 changepath(const char *new)
8022 firstchange = 9999; /* assume no change */
8028 if ((*old == '\0' && *new == ':')
8029 || (*old == ':' && *new == '\0')
8033 old = new; /* ignore subsequent differences */
8037 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
8044 if (builtinloc < 0 && idx_bltin >= 0)
8045 builtinloc = idx_bltin; /* zap builtins */
8046 if (builtinloc >= 0 && idx_bltin < 0)
8048 clearcmdentry(firstchange);
8049 builtinloc = idx_bltin;
8085 typedef smallint token_id_t;
8087 /* Nth bit indicates if token marks the end of a list */
8090 /* 0 */ | (1u << TEOF)
8091 /* 1 */ | (0u << TNL)
8092 /* 2 */ | (0u << TREDIR)
8093 /* 3 */ | (0u << TWORD)
8094 /* 4 */ | (0u << TSEMI)
8095 /* 5 */ | (0u << TBACKGND)
8096 /* 6 */ | (0u << TAND)
8097 /* 7 */ | (0u << TOR)
8098 /* 8 */ | (0u << TPIPE)
8099 /* 9 */ | (0u << TLP)
8100 /* 10 */ | (1u << TRP)
8101 /* 11 */ | (1u << TENDCASE)
8102 /* 12 */ | (1u << TENDBQUOTE)
8103 /* 13 */ | (0u << TNOT)
8104 /* 14 */ | (0u << TCASE)
8105 /* 15 */ | (1u << TDO)
8106 /* 16 */ | (1u << TDONE)
8107 /* 17 */ | (1u << TELIF)
8108 /* 18 */ | (1u << TELSE)
8109 /* 19 */ | (1u << TESAC)
8110 /* 20 */ | (1u << TFI)
8111 /* 21 */ | (0u << TFOR)
8113 /* 22 */ | (0u << TFUNCTION)
8115 /* 23 */ | (0u << TIF)
8116 /* 24 */ | (0u << TIN)
8117 /* 25 */ | (1u << TTHEN)
8118 /* 26 */ | (0u << TUNTIL)
8119 /* 27 */ | (0u << TWHILE)
8120 /* 28 */ | (0u << TBEGIN)
8121 /* 29 */ | (1u << TEND)
8122 , /* thus far 29 bits used */
8125 static const char *const tokname_array[] = {
8139 #define KWDOFFSET 13
8140 /* the following are keywords */
8162 /* Wrapper around strcmp for qsort/bsearch/... */
8164 pstrcmp(const void *a, const void *b)
8166 return strcmp((char*)a, *(char**)b);
8169 static const char *const *
8170 findkwd(const char *s)
8172 return bsearch(s, tokname_array + KWDOFFSET,
8173 ARRAY_SIZE(tokname_array) - KWDOFFSET,
8174 sizeof(tokname_array[0]), pstrcmp);
8178 * Locate and print what a word is...
8181 describe_command(char *command, const char *path, int describe_command_verbose)
8183 struct cmdentry entry;
8184 #if ENABLE_ASH_ALIAS
8185 const struct alias *ap;
8188 path = path ? path : pathval();
8190 if (describe_command_verbose) {
8194 /* First look at the keywords */
8195 if (findkwd(command)) {
8196 out1str(describe_command_verbose ? " is a shell keyword" : command);
8200 #if ENABLE_ASH_ALIAS
8201 /* Then look at the aliases */
8202 ap = lookupalias(command, 0);
8204 if (!describe_command_verbose) {
8209 out1fmt(" is an alias for %s", ap->val);
8214 find_command(command, &entry, DO_ABS, path);
8216 switch (entry.cmdtype) {
8218 int j = entry.u.index;
8224 p = path_advance(&path, command);
8228 if (describe_command_verbose) {
8229 out1fmt(" is %s", p);
8237 if (describe_command_verbose) {
8238 out1str(" is a shell function");
8245 if (describe_command_verbose) {
8246 out1fmt(" is a %sshell builtin",
8247 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8248 "special " : nullstr
8256 if (describe_command_verbose) {
8257 out1str(": not found\n");
8266 static int FAST_FUNC
8267 typecmd(int argc UNUSED_PARAM, char **argv)
8273 /* type -p ... ? (we don't bother checking for 'p') */
8274 if (argv[1] && argv[1][0] == '-') {
8279 err |= describe_command(argv[i++], NULL, verbose);
8284 #if ENABLE_ASH_CMDCMD
8285 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8287 parse_command_args(char **argv, const char **path)
8300 if (c == '-' && !*cp) {
8308 *path = bb_default_path;
8311 /* run 'typecmd' for other options */
8320 static int FAST_FUNC
8321 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8329 const char *path = NULL;
8331 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8332 * never reaches this function.
8335 while ((c = nextopt("pvV")) != '\0')
8337 verify |= VERIFY_VERBOSE;
8339 /*verify |= VERIFY_BRIEF*/;
8345 path = bb_default_path;
8347 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8349 if (/*verify && */ cmd)
8350 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8357 /*static int funcblocksize; // size of structures in function */
8358 /*static int funcstringsize; // size of strings in node */
8359 static void *funcblock; /* block to allocate function from */
8360 static char *funcstring_end; /* end of block to allocate strings from */
8362 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8363 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8364 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8365 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8366 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8367 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8368 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8369 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8370 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8371 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8372 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8373 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8374 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8375 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8376 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8377 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8378 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8379 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8380 #if BASH_REDIR_OUTPUT
8381 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8383 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8384 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8385 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8386 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8387 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8388 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8389 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8390 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8391 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8394 static int calcsize(int funcblocksize, union node *n);
8397 sizenodelist(int funcblocksize, struct nodelist *lp)
8400 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8401 funcblocksize = calcsize(funcblocksize, lp->n);
8404 return funcblocksize;
8408 calcsize(int funcblocksize, union node *n)
8411 return funcblocksize;
8412 funcblocksize += nodesize[n->type];
8415 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8416 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8417 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8420 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8425 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8426 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8433 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8434 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8437 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8438 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8439 funcblocksize = calcsize(funcblocksize, n->nif.test);
8442 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8443 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8444 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8447 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8448 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8451 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8452 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8453 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8457 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8458 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8459 funcblocksize = calcsize(funcblocksize, n->narg.next);
8462 #if BASH_REDIR_OUTPUT
8469 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8470 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8474 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8475 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8479 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8480 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8483 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8486 return funcblocksize;
8490 nodeckstrdup(char *s)
8492 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8493 return strcpy(funcstring_end, s);
8496 static union node *copynode(union node *);
8498 static struct nodelist *
8499 copynodelist(struct nodelist *lp)
8501 struct nodelist *start;
8502 struct nodelist **lpp;
8507 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8508 (*lpp)->n = copynode(lp->n);
8510 lpp = &(*lpp)->next;
8517 copynode(union node *n)
8524 funcblock = (char *) funcblock + nodesize[n->type];
8528 new->ncmd.redirect = copynode(n->ncmd.redirect);
8529 new->ncmd.args = copynode(n->ncmd.args);
8530 new->ncmd.assign = copynode(n->ncmd.assign);
8533 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8534 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8539 new->nredir.redirect = copynode(n->nredir.redirect);
8540 new->nredir.n = copynode(n->nredir.n);
8547 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8548 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8551 new->nif.elsepart = copynode(n->nif.elsepart);
8552 new->nif.ifpart = copynode(n->nif.ifpart);
8553 new->nif.test = copynode(n->nif.test);
8556 new->nfor.var = nodeckstrdup(n->nfor.var);
8557 new->nfor.body = copynode(n->nfor.body);
8558 new->nfor.args = copynode(n->nfor.args);
8561 new->ncase.cases = copynode(n->ncase.cases);
8562 new->ncase.expr = copynode(n->ncase.expr);
8565 new->nclist.body = copynode(n->nclist.body);
8566 new->nclist.pattern = copynode(n->nclist.pattern);
8567 new->nclist.next = copynode(n->nclist.next);
8571 new->narg.backquote = copynodelist(n->narg.backquote);
8572 new->narg.text = nodeckstrdup(n->narg.text);
8573 new->narg.next = copynode(n->narg.next);
8576 #if BASH_REDIR_OUTPUT
8583 new->nfile.fname = copynode(n->nfile.fname);
8584 new->nfile.fd = n->nfile.fd;
8585 new->nfile.next = copynode(n->nfile.next);
8589 new->ndup.vname = copynode(n->ndup.vname);
8590 new->ndup.dupfd = n->ndup.dupfd;
8591 new->ndup.fd = n->ndup.fd;
8592 new->ndup.next = copynode(n->ndup.next);
8596 new->nhere.doc = copynode(n->nhere.doc);
8597 new->nhere.fd = n->nhere.fd;
8598 new->nhere.next = copynode(n->nhere.next);
8601 new->nnot.com = copynode(n->nnot.com);
8604 new->type = n->type;
8609 * Make a copy of a parse tree.
8611 static struct funcnode *
8612 copyfunc(union node *n)
8617 /*funcstringsize = 0;*/
8618 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8619 f = ckzalloc(blocksize /* + funcstringsize */);
8620 funcblock = (char *) f + offsetof(struct funcnode, n);
8621 funcstring_end = (char *) f + blocksize;
8623 /* f->count = 0; - ckzalloc did it */
8628 * Define a shell function.
8631 defun(union node *func)
8633 struct cmdentry entry;
8636 entry.cmdtype = CMDFUNCTION;
8637 entry.u.func = copyfunc(func);
8638 addcmdentry(func->narg.text, &entry);
8642 /* Reasons for skipping commands (see comment on breakcmd routine) */
8643 #define SKIPBREAK (1 << 0)
8644 #define SKIPCONT (1 << 1)
8645 #define SKIPFUNC (1 << 2)
8646 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8647 static int skipcount; /* number of levels to skip */
8648 static int funcnest; /* depth of function calls */
8649 static int loopnest; /* current loop nesting level */
8651 /* Forward decl way out to parsing code - dotrap needs it */
8652 static int evalstring(char *s, int flags);
8654 /* Called to execute a trap.
8655 * Single callsite - at the end of evaltree().
8656 * If we return non-zero, evaltree raises EXEXIT exception.
8658 * Perhaps we should avoid entering new trap handlers
8659 * while we are executing a trap handler. [is it a TODO?]
8666 uint8_t last_status;
8671 last_status = exitstatus;
8675 TRACE(("dotrap entered\n"));
8676 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8688 /* non-trapped SIGINT is handled separately by raise_interrupt,
8689 * don't upset it by resetting gotsig[SIGINT-1] */
8690 if (sig == SIGINT && !p)
8693 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8699 exitstatus = last_status;
8700 TRACE(("dotrap returns\n"));
8703 /* forward declarations - evaluation is fairly recursive business... */
8704 static int evalloop(union node *, int);
8705 static int evalfor(union node *, int);
8706 static int evalcase(union node *, int);
8707 static int evalsubshell(union node *, int);
8708 static void expredir(union node *);
8709 static int evalpipe(union node *, int);
8710 static int evalcommand(union node *, int);
8711 static int evalbltin(const struct builtincmd *, int, char **, int);
8712 static void prehash(union node *);
8715 * Evaluate a parse tree. The value is left in the global variable
8719 evaltree(union node *n, int flags)
8722 int (*evalfn)(union node *, int);
8726 TRACE(("evaltree(NULL) called\n"));
8729 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8736 out1fmt("Node type = %d\n", n->type);
8741 status = !evaltree(n->nnot.com, EV_TESTED);
8744 expredir(n->nredir.redirect);
8745 pushredir(n->nredir.redirect);
8746 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8748 status = evaltree(n->nredir.n, flags & EV_TESTED);
8750 if (n->nredir.redirect)
8751 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8754 evalfn = evalcommand;
8756 if (eflag && !(flags & EV_TESTED))
8768 evalfn = evalsubshell;
8781 #error NAND + 1 != NOR
8783 #if NOR + 1 != NSEMI
8784 #error NOR + 1 != NSEMI
8786 unsigned is_or = n->type - NAND;
8789 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8791 if ((!status) == is_or || evalskip)
8797 status = evalfn(n, flags);
8801 status = evaltree(n->nif.test, EV_TESTED);
8808 if (n->nif.elsepart) {
8809 n = n->nif.elsepart;
8816 /* Not necessary. To test it:
8817 * "false; f() { qwerty; }; echo $?" should print 0.
8821 exitstatus = status;
8825 /* Order of checks below is important:
8826 * signal handlers trigger before exit caused by "set -e".
8830 if (checkexit & status)
8831 raise_exception(EXEXIT);
8832 if (flags & EV_EXIT)
8833 raise_exception(EXEXIT);
8835 TRACE(("leaving evaltree (no interrupts)\n"));
8842 int skip = evalskip;
8849 if (--skipcount <= 0) {
8860 evalloop(union node *n, int flags)
8871 i = evaltree(n->nbinary.ch1, EV_TESTED);
8873 if (skip == SKIPFUNC)
8877 if (n->type != NWHILE)
8881 status = evaltree(n->nbinary.ch2, flags);
8883 } while (!(skip & ~SKIPCONT));
8890 evalfor(union node *n, int flags)
8892 struct arglist arglist;
8895 struct stackmark smark;
8898 setstackmark(&smark);
8899 arglist.list = NULL;
8900 arglist.lastp = &arglist.list;
8901 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8902 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8904 *arglist.lastp = NULL;
8908 for (sp = arglist.list; sp; sp = sp->next) {
8909 setvar0(n->nfor.var, sp->text);
8910 status = evaltree(n->nfor.body, flags);
8911 if (skiploop() & ~SKIPCONT)
8915 popstackmark(&smark);
8921 evalcase(union node *n, int flags)
8925 struct arglist arglist;
8926 struct stackmark smark;
8929 setstackmark(&smark);
8930 arglist.list = NULL;
8931 arglist.lastp = &arglist.list;
8932 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8933 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8934 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8935 if (casematch(patp, arglist.list->text)) {
8936 /* Ensure body is non-empty as otherwise
8937 * EV_EXIT may prevent us from setting the
8940 if (evalskip == 0 && cp->nclist.body) {
8941 status = evaltree(cp->nclist.body, flags);
8948 popstackmark(&smark);
8954 * Kick off a subshell to evaluate a tree.
8957 evalsubshell(union node *n, int flags)
8960 int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
8963 expredir(n->nredir.redirect);
8964 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8967 if (backgnd == FORK_FG)
8969 jp = makejob(/*n,*/ 1);
8970 if (forkshell(jp, n, backgnd) == 0) {
8975 flags &= ~EV_TESTED;
8977 redirect(n->nredir.redirect, 0);
8978 evaltreenr(n->nredir.n, flags);
8983 if (backgnd == FORK_FG)
8984 status = waitforjob(jp);
8990 * Compute the names of the files in a redirection list.
8992 static void fixredir(union node *, const char *, int);
8994 expredir(union node *n)
8998 for (redir = n; redir; redir = redir->nfile.next) {
9002 fn.lastp = &fn.list;
9003 switch (redir->type) {
9007 #if BASH_REDIR_OUTPUT
9012 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
9013 TRACE(("expredir expanded to '%s'\n", fn.list->text));
9014 #if BASH_REDIR_OUTPUT
9018 // By the design of stack allocator, the loop of this kind:
9019 // while true; do while true; do break; done </dev/null; done
9020 // will look like a memory leak: ash plans to free expfname's
9021 // of "/dev/null" as soon as it finishes running the loop
9022 // (in this case, never).
9023 // This "fix" is wrong:
9024 if (redir->nfile.expfname)
9025 stunalloc(redir->nfile.expfname);
9026 // It results in corrupted state of stacked allocations.
9028 redir->nfile.expfname = fn.list->text;
9031 case NTOFD: /* >& */
9032 if (redir->ndup.vname) {
9033 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
9034 if (fn.list == NULL)
9035 ash_msg_and_raise_error("redir error");
9036 #if BASH_REDIR_OUTPUT
9037 //FIXME: we used expandarg with different args!
9038 if (!isdigit_str9(fn.list->text)) {
9039 /* >&file, not >&fd */
9040 if (redir->nfile.fd != 1) /* 123>&file - BAD */
9041 ash_msg_and_raise_error("redir error");
9043 goto store_expfname;
9046 fixredir(redir, fn.list->text, 1);
9054 * Evaluate a pipeline. All the processes in the pipeline are children
9055 * of the process creating the pipeline. (This differs from some versions
9056 * of the shell, which make the last process in a pipeline the parent
9060 evalpipe(union node *n, int flags)
9063 struct nodelist *lp;
9069 TRACE(("evalpipe(0x%lx) called\n", (long)n));
9071 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
9075 if (n->npipe.pipe_backgnd == 0)
9077 jp = makejob(/*n,*/ pipelen);
9079 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
9083 if (pipe(pip) < 0) {
9085 ash_msg_and_raise_error("pipe call failed");
9088 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
9102 evaltreenr(lp->n, flags);
9109 /* Don't want to trigger debugging */
9113 if (n->npipe.pipe_backgnd == 0) {
9114 status = waitforjob(jp);
9115 TRACE(("evalpipe: job done exit status %d\n", status));
9123 * Controls whether the shell is interactive or not.
9126 setinteractive(int on)
9128 static smallint is_interactive;
9130 if (++on == is_interactive)
9132 is_interactive = on;
9136 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9137 if (is_interactive > 1) {
9138 /* Looks like they want an interactive shell */
9139 static smallint did_banner;
9142 /* note: ash and hush share this string */
9143 out1fmt("\n\n%s %s\n"
9144 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
9147 "built-in shell (ash)"
9161 setinteractive(iflag);
9163 #if ENABLE_FEATURE_EDITING_VI
9165 line_input_state->flags |= VI_MODE;
9167 line_input_state->flags &= ~VI_MODE;
9169 viflag = 0; /* forcibly keep the option off */
9173 struct localvar_list {
9174 struct localvar_list *next;
9175 struct localvar *lv;
9178 static struct localvar_list *localvar_stack;
9181 * Called after a function returns.
9182 * Interrupts must be off.
9185 poplocalvars(int keep)
9187 struct localvar_list *ll;
9188 struct localvar *lvp, *next;
9192 ll = localvar_stack;
9193 localvar_stack = ll->next;
9198 while ((lvp = next) != NULL) {
9201 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9203 int bits = VSTRFIXED;
9205 if (lvp->flags != VUNSET) {
9206 if (vp->var_text == lvp->text)
9208 else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
9209 free((char*)lvp->text);
9213 vp->flags |= (lvp->flags & bits);
9216 (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
9217 unsetvar(vp->var_text);
9218 } else if (vp == NULL) { /* $- saved */
9219 memcpy(optlist, lvp->text, sizeof(optlist));
9220 free((char*)lvp->text);
9222 } else if (lvp->flags == VUNSET) {
9223 vp->flags &= ~(VSTRFIXED|VREADONLY);
9224 unsetvar(vp->var_text);
9227 vp->var_func(var_end(lvp->text));
9228 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9229 free((char*)vp->var_text);
9230 vp->flags = lvp->flags;
9231 vp->var_text = lvp->text;
9239 * Create a new localvar environment.
9241 static struct localvar_list *
9244 struct localvar_list *ll;
9247 ll = ckzalloc(sizeof(*ll));
9248 /*ll->lv = NULL; - zalloc did it */
9249 ll->next = localvar_stack;
9250 localvar_stack = ll;
9257 unwindlocalvars(struct localvar_list *stop)
9259 while (localvar_stack != stop)
9264 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9266 volatile struct shparam saveparam;
9267 struct jmploc *volatile savehandler;
9268 struct jmploc jmploc;
9271 saveparam = shellparam;
9272 savehandler = exception_handler;
9273 e = setjmp(jmploc.loc);
9278 exception_handler = &jmploc;
9279 shellparam.malloced = 0;
9283 shellparam.nparam = argc - 1;
9284 shellparam.p = argv + 1;
9285 #if ENABLE_ASH_GETOPTS
9286 shellparam.optind = 1;
9287 shellparam.optoff = -1;
9290 evaltree(func->n.narg.next, flags & EV_TESTED);
9296 freeparam(&shellparam);
9297 shellparam = saveparam;
9298 exception_handler = savehandler;
9300 evalskip &= ~SKIPFUNC;
9305 * Make a variable a local variable. When a variable is made local, it's
9306 * value and flags are saved in a localvar structure. The saved values
9307 * will be restored when the shell function returns. We handle the name
9308 * "-" as a special case: it makes changes to "set +-options" local
9309 * (options will be restored on return from the function).
9314 struct localvar *lvp;
9317 char *eq = strchr(name, '=');
9320 /* Cater for duplicate "local". Examples:
9321 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9322 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9324 lvp = localvar_stack->lv;
9326 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9330 * it's a duplicate "local VAR" declaration, do nothing
9337 lvp = ckzalloc(sizeof(*lvp));
9338 if (LONE_DASH(name)) {
9340 p = ckmalloc(sizeof(optlist));
9341 lvp->text = memcpy(p, optlist, sizeof(optlist));
9344 vpp = hashvar(name);
9345 vp = *findvar(vpp, name);
9347 /* variable did not exist yet */
9349 vp = setvareq(name, VSTRFIXED);
9351 vp = setvar(name, NULL, VSTRFIXED);
9352 lvp->flags = VUNSET;
9354 lvp->text = vp->var_text;
9355 lvp->flags = vp->flags;
9356 /* make sure neither "struct var" nor string gets freed
9357 * during (un)setting:
9359 vp->flags |= VSTRFIXED|VTEXTFIXED;
9363 /* "local VAR" unsets VAR: */
9364 setvar0(name, NULL);
9368 lvp->next = localvar_stack->lv;
9369 localvar_stack->lv = lvp;
9375 * The "local" command.
9377 static int FAST_FUNC
9378 localcmd(int argc UNUSED_PARAM, char **argv)
9382 if (!localvar_stack)
9383 ash_msg_and_raise_error("not in a function");
9386 while ((name = *argv++) != NULL) {
9392 static int FAST_FUNC
9393 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9398 static int FAST_FUNC
9399 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9404 static int FAST_FUNC
9405 execcmd(int argc UNUSED_PARAM, char **argv)
9408 while (nextopt("a:") != '\0')
9409 /* nextopt() sets optionarg to "-a ARGV0" */;
9415 iflag = 0; /* exit on error */
9418 /* We should set up signals for "exec CMD"
9419 * the same way as for "CMD" without "exec".
9420 * But optschanged->setinteractive->setsignal
9421 * still thought we are a root shell. Therefore, for example,
9422 * SIGQUIT is still set to IGN. Fix it:
9426 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9427 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9428 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9432 argv[0] = optionarg;
9433 shellexec(prog, argv, pathval(), 0);
9440 * The return command.
9442 static int FAST_FUNC
9443 returncmd(int argc UNUSED_PARAM, char **argv)
9446 * If called outside a function, do what ksh does;
9447 * skip the rest of the file.
9449 evalskip = SKIPFUNC;
9450 return argv[1] ? number(argv[1]) : exitstatus;
9453 /* Forward declarations for builtintab[] */
9454 static int breakcmd(int, char **) FAST_FUNC;
9455 static int dotcmd(int, char **) FAST_FUNC;
9456 static int evalcmd(int, char **, int) FAST_FUNC;
9457 static int exitcmd(int, char **) FAST_FUNC;
9458 static int exportcmd(int, char **) FAST_FUNC;
9459 #if ENABLE_ASH_GETOPTS
9460 static int getoptscmd(int, char **) FAST_FUNC;
9463 static int helpcmd(int, char **) FAST_FUNC;
9466 static int historycmd(int, char **) FAST_FUNC;
9468 #if ENABLE_FEATURE_SH_MATH
9469 static int letcmd(int, char **) FAST_FUNC;
9471 static int readcmd(int, char **) FAST_FUNC;
9472 static int setcmd(int, char **) FAST_FUNC;
9473 static int shiftcmd(int, char **) FAST_FUNC;
9474 static int timescmd(int, char **) FAST_FUNC;
9475 static int trapcmd(int, char **) FAST_FUNC;
9476 static int umaskcmd(int, char **) FAST_FUNC;
9477 static int unsetcmd(int, char **) FAST_FUNC;
9478 static int ulimitcmd(int, char **) FAST_FUNC;
9480 #define BUILTIN_NOSPEC "0"
9481 #define BUILTIN_SPECIAL "1"
9482 #define BUILTIN_REGULAR "2"
9483 #define BUILTIN_SPEC_REG "3"
9484 #define BUILTIN_ASSIGN "4"
9485 #define BUILTIN_SPEC_ASSG "5"
9486 #define BUILTIN_REG_ASSG "6"
9487 #define BUILTIN_SPEC_REG_ASSG "7"
9489 /* Stubs for calling non-FAST_FUNC's */
9491 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9493 #if ENABLE_ASH_PRINTF
9494 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9496 #if ENABLE_ASH_TEST || BASH_TEST2
9497 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9500 /* Keep these in proper order since it is searched via bsearch() */
9501 static const struct builtincmd builtintab[] = {
9502 { BUILTIN_SPEC_REG "." , dotcmd },
9503 { BUILTIN_SPEC_REG ":" , truecmd },
9505 { BUILTIN_REGULAR "[" , testcmd },
9508 { BUILTIN_REGULAR "[[" , testcmd },
9510 #if ENABLE_ASH_ALIAS
9511 { BUILTIN_REG_ASSG "alias" , aliascmd },
9514 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9516 { BUILTIN_SPEC_REG "break" , breakcmd },
9517 { BUILTIN_REGULAR "cd" , cdcmd },
9518 { BUILTIN_NOSPEC "chdir" , cdcmd },
9519 #if ENABLE_ASH_CMDCMD
9520 { BUILTIN_REGULAR "command" , commandcmd },
9522 { BUILTIN_SPEC_REG "continue", breakcmd },
9524 { BUILTIN_REGULAR "echo" , echocmd },
9526 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9527 { BUILTIN_SPEC_REG "exec" , execcmd },
9528 { BUILTIN_SPEC_REG "exit" , exitcmd },
9529 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9530 { BUILTIN_REGULAR "false" , falsecmd },
9532 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9534 #if ENABLE_ASH_GETOPTS
9535 { BUILTIN_REGULAR "getopts" , getoptscmd },
9537 { BUILTIN_NOSPEC "hash" , hashcmd },
9539 { BUILTIN_NOSPEC "help" , helpcmd },
9542 { BUILTIN_NOSPEC "history" , historycmd },
9545 { BUILTIN_REGULAR "jobs" , jobscmd },
9546 { BUILTIN_REGULAR "kill" , killcmd },
9548 #if ENABLE_FEATURE_SH_MATH
9549 { BUILTIN_NOSPEC "let" , letcmd },
9551 { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
9552 #if ENABLE_ASH_PRINTF
9553 { BUILTIN_REGULAR "printf" , printfcmd },
9555 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9556 { BUILTIN_REGULAR "read" , readcmd },
9557 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9558 { BUILTIN_SPEC_REG "return" , returncmd },
9559 { BUILTIN_SPEC_REG "set" , setcmd },
9560 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9562 { BUILTIN_SPEC_REG "source" , dotcmd },
9565 { BUILTIN_REGULAR "test" , testcmd },
9567 { BUILTIN_SPEC_REG "times" , timescmd },
9568 { BUILTIN_SPEC_REG "trap" , trapcmd },
9569 { BUILTIN_REGULAR "true" , truecmd },
9570 { BUILTIN_NOSPEC "type" , typecmd },
9571 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9572 { BUILTIN_REGULAR "umask" , umaskcmd },
9573 #if ENABLE_ASH_ALIAS
9574 { BUILTIN_REGULAR "unalias" , unaliascmd },
9576 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9577 { BUILTIN_REGULAR "wait" , waitcmd },
9580 /* Should match the above table! */
9581 #define COMMANDCMD (builtintab + \
9583 /* [ */ 1 * ENABLE_ASH_TEST + \
9584 /* [[ */ 1 * BASH_TEST2 + \
9585 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9586 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9587 /* break cd cddir */ 3)
9588 #define EVALCMD (COMMANDCMD + \
9589 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9590 /* continue */ 1 + \
9591 /* echo */ 1 * ENABLE_ASH_ECHO + \
9593 #define EXECCMD (EVALCMD + \
9597 * Search the table of builtin commands.
9600 pstrcmp1(const void *a, const void *b)
9602 return strcmp((char*)a, *(char**)b + 1);
9604 static struct builtincmd *
9605 find_builtin(const char *name)
9607 struct builtincmd *bp;
9610 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9617 * Execute a simple command.
9620 isassignment(const char *p)
9622 const char *q = endofname(p);
9627 static int FAST_FUNC
9628 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9630 /* Preserve exitstatus of a previous possible redirection
9631 * as POSIX mandates */
9632 return back_exitstatus;
9635 evalcommand(union node *cmd, int flags)
9637 static const struct builtincmd null_bltin = {
9638 "\0\0", bltincmd /* why three NULs? */
9640 struct localvar_list *localvar_stop;
9641 struct redirtab *redir_stop;
9642 struct stackmark smark;
9644 struct arglist arglist;
9645 struct arglist varlist;
9648 const struct strlist *sp;
9649 struct cmdentry cmdentry;
9656 struct builtincmd *bcmd;
9657 smallint cmd_is_exec;
9658 smallint pseudovarflag = 0;
9660 /* First expand the arguments. */
9661 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9662 setstackmark(&smark);
9663 localvar_stop = pushlocalvars();
9664 back_exitstatus = 0;
9666 cmdentry.cmdtype = CMDBUILTIN;
9667 cmdentry.u.cmd = &null_bltin;
9668 varlist.lastp = &varlist.list;
9669 *varlist.lastp = NULL;
9670 arglist.lastp = &arglist.list;
9671 *arglist.lastp = NULL;
9674 if (cmd->ncmd.args) {
9675 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9676 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9679 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9680 struct strlist **spp;
9682 spp = arglist.lastp;
9683 if (pseudovarflag && isassignment(argp->narg.text))
9684 expandarg(argp, &arglist, EXP_VARTILDE);
9686 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9688 for (sp = *spp; sp; sp = sp->next)
9692 /* Reserve one extra spot at the front for shellexec. */
9693 nargv = stalloc(sizeof(char *) * (argc + 2));
9695 for (sp = arglist.list; sp; sp = sp->next) {
9696 TRACE(("evalcommand arg: %s\n", sp->text));
9697 *nargv++ = sp->text;
9702 if (iflag && funcnest == 0 && argc > 0)
9703 lastarg = nargv[-1];
9706 expredir(cmd->ncmd.redirect);
9707 redir_stop = pushredir(cmd->ncmd.redirect);
9708 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9710 path = vpath.var_text;
9711 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9712 struct strlist **spp;
9715 spp = varlist.lastp;
9716 expandarg(argp, &varlist, EXP_VARTILDE);
9718 mklocal((*spp)->text);
9721 * Modify the command lookup path, if a PATH= assignment
9725 if (varcmp(p, path) == 0)
9729 /* Print the command if xflag is set. */
9731 const char *pfx = "";
9733 fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
9737 char *varval = sp->text;
9738 char *eq = strchrnul(varval, '=');
9741 fdprintf(preverrout_fd, "%s%.*s%s",
9743 (int)(eq - varval), varval,
9744 maybe_single_quote(eq)
9752 fdprintf(preverrout_fd, "%s%s",
9754 /* always quote if matches reserved word: */
9756 ? single_quote(sp->text)
9757 : maybe_single_quote(sp->text)
9762 safe_write(preverrout_fd, "\n", 1);
9768 /* Now locate the command. */
9770 int cmd_flag = DO_ERR;
9771 #if ENABLE_ASH_CMDCMD
9772 const char *oldpath = path + 5;
9776 find_command(argv[0], &cmdentry, cmd_flag, path);
9777 if (cmdentry.cmdtype == CMDUNKNOWN) {
9778 flush_stdout_stderr();
9783 /* implement bltin and command here */
9784 if (cmdentry.cmdtype != CMDBUILTIN)
9787 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9788 if (cmdentry.u.cmd == EXECCMD)
9790 #if ENABLE_ASH_CMDCMD
9791 if (cmdentry.u.cmd == COMMANDCMD) {
9793 nargv = parse_command_args(argv, &path);
9796 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9797 * nargv => "PROG". path is updated if -p.
9799 argc -= nargv - argv;
9801 cmd_flag |= DO_NOFUNC;
9810 exitstatus = status;
9812 /* We have a redirection error. */
9814 raise_exception(EXERROR);
9819 /* Execute the command. */
9820 switch (cmdentry.cmdtype) {
9823 #if ENABLE_FEATURE_SH_NOFORK
9824 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9825 * around run_nofork_applet() call.
9826 * (2) Should this check also be done in forkshell()?
9827 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9829 /* find_command() encodes applet_no as (-2 - applet_no) */
9830 int applet_no = (- cmdentry.u.index - 2);
9831 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9832 listsetvar(varlist.list, VEXPORT|VSTACK);
9833 /* run <applet>_main() */
9834 status = run_nofork_applet(applet_no, argv);
9838 /* Can we avoid forking off? For example, very last command
9839 * in a script or a subshell does not need forking,
9840 * we can just exec it.
9842 if (!(flags & EV_EXIT) || may_have_traps) {
9843 /* No, forking off a child is necessary */
9846 jp = makejob(/*cmd,*/ 1);
9847 if (forkshell(jp, cmd, FORK_FG) != 0) {
9849 status = waitforjob(jp);
9851 TRACE(("forked child exited with %d\n", status));
9856 /* fall through to exec'ing external program */
9858 listsetvar(varlist.list, VEXPORT|VSTACK);
9859 shellexec(argv[0], argv, path, cmdentry.u.index);
9863 if (spclbltin > 0 || argc == 0) {
9865 if (cmd_is_exec && argc > 1)
9866 listsetvar(varlist.list, VEXPORT);
9869 /* Tight loop with builtins only:
9870 * "while kill -0 $child; do true; done"
9871 * will never exit even if $child died, unless we do this
9872 * to reap the zombie and make kill detect that it's gone: */
9873 dowait(DOWAIT_NONBLOCK, NULL);
9875 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
9876 if (exception_type == EXERROR && spclbltin <= 0) {
9881 longjmp(exception_handler->loc, 1);
9887 /* See above for the rationale */
9888 dowait(DOWAIT_NONBLOCK, NULL);
9889 if (evalfun(cmdentry.u.func, argc, argv, flags))
9892 status = exitstatus;
9897 if (cmd->ncmd.redirect)
9898 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9899 unwindredir(redir_stop);
9900 unwindlocalvars(localvar_stop);
9902 /* dsl: I think this is intended to be used to support
9903 * '_' in 'vi' command mode during line editing...
9904 * However I implemented that within libedit itself.
9906 setvar0("_", lastarg);
9908 popstackmark(&smark);
9914 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
9916 char *volatile savecmdname;
9917 struct jmploc *volatile savehandler;
9918 struct jmploc jmploc;
9922 savecmdname = commandname;
9923 savehandler = exception_handler;
9924 i = setjmp(jmploc.loc);
9927 exception_handler = &jmploc;
9928 commandname = argv[0];
9930 optptr = NULL; /* initialize nextopt */
9932 status = evalcmd(argc, argv, flags);
9934 status = (*cmd->builtin)(argc, argv);
9935 flush_stdout_stderr();
9936 status |= ferror(stdout);
9937 exitstatus = status;
9940 commandname = savecmdname;
9941 exception_handler = savehandler;
9947 goodname(const char *p)
9949 return endofname(p)[0] == '\0';
9954 * Search for a command. This is called before we fork so that the
9955 * location of the command will be available in the parent as well as
9956 * the child. The check for "goodname" is an overly conservative
9957 * check that the name will not be subject to expansion.
9960 prehash(union node *n)
9962 struct cmdentry entry;
9964 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9965 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9969 /* ============ Builtin commands
9971 * Builtin commands whose functions are closely tied to evaluation
9972 * are implemented here.
9976 * Handle break and continue commands. Break, continue, and return are
9977 * all handled by setting the evalskip flag. The evaluation routines
9978 * above all check this flag, and if it is set they start skipping
9979 * commands rather than executing them. The variable skipcount is
9980 * the number of loops to break/continue, or the number of function
9981 * levels to return. (The latter is always 1.) It should probably
9982 * be an error to break out of more loops than exist, but it isn't
9983 * in the standard shell so we don't make it one here.
9985 static int FAST_FUNC
9986 breakcmd(int argc UNUSED_PARAM, char **argv)
9988 int n = argv[1] ? number(argv[1]) : 1;
9991 ash_msg_and_raise_error(msg_illnum, argv[1]);
9995 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
10003 * This implements the input routines used by the parser.
10007 INPUT_PUSH_FILE = 1,
10008 INPUT_NOFILE_OK = 2,
10011 static smallint checkkwd;
10012 /* values of checkkwd variable */
10013 #define CHKALIAS 0x1
10016 #define CHKEOFMARK 0x8
10019 * Push a string back onto the input at this current parsefile level.
10020 * We handle aliases this way.
10022 #if !ENABLE_ASH_ALIAS
10023 #define pushstring(s, ap) pushstring(s)
10026 pushstring(char *s, struct alias *ap)
10028 struct strpush *sp;
10033 if (g_parsefile->strpush) {
10034 sp = ckzalloc(sizeof(*sp));
10035 sp->prev = g_parsefile->strpush;
10037 sp = &(g_parsefile->basestrpush);
10039 g_parsefile->strpush = sp;
10040 sp->prev_string = g_parsefile->next_to_pgetc;
10041 sp->prev_left_in_line = g_parsefile->left_in_line;
10042 sp->unget = g_parsefile->unget;
10043 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
10044 #if ENABLE_ASH_ALIAS
10047 ap->flag |= ALIASINUSE;
10051 g_parsefile->next_to_pgetc = s;
10052 g_parsefile->left_in_line = len;
10053 g_parsefile->unget = 0;
10060 struct strpush *sp = g_parsefile->strpush;
10063 #if ENABLE_ASH_ALIAS
10065 if (g_parsefile->next_to_pgetc[-1] == ' '
10066 || g_parsefile->next_to_pgetc[-1] == '\t'
10068 checkkwd |= CHKALIAS;
10070 if (sp->string != sp->ap->val) {
10073 sp->ap->flag &= ~ALIASINUSE;
10074 if (sp->ap->flag & ALIASDEAD) {
10075 unalias(sp->ap->name);
10079 g_parsefile->next_to_pgetc = sp->prev_string;
10080 g_parsefile->left_in_line = sp->prev_left_in_line;
10081 g_parsefile->unget = sp->unget;
10082 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
10083 g_parsefile->strpush = sp->prev;
10084 if (sp != &(g_parsefile->basestrpush))
10093 char *buf = g_parsefile->buf;
10095 g_parsefile->next_to_pgetc = buf;
10096 #if ENABLE_FEATURE_EDITING
10098 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
10099 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10102 # if ENABLE_ASH_IDLE_TIMEOUT
10104 const char *tmout_var = lookupvar("TMOUT");
10106 timeout = atoi(tmout_var) * 1000;
10112 # if ENABLE_FEATURE_TAB_COMPLETION
10113 line_input_state->path_lookup = pathval();
10115 reinit_unicode_for_ash();
10116 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
10118 /* ^C pressed, "convert" to SIGINT */
10119 write(STDOUT_FILENO, "^C", 2);
10120 if (trap[SIGINT]) {
10126 exitstatus = 128 + SIGINT;
10132 /* Ctrl+D pressed */
10135 # if ENABLE_ASH_IDLE_TIMEOUT
10136 else if (errno == EAGAIN && timeout > 0) {
10137 puts("\007timed out waiting for input: auto-logout");
10144 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10147 #if 0 /* disabled: nonblock_immune_read() handles this problem */
10149 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
10150 int flags = fcntl(0, F_GETFL);
10151 if (flags >= 0 && (flags & O_NONBLOCK)) {
10152 flags &= ~O_NONBLOCK;
10153 if (fcntl(0, F_SETFL, flags) >= 0) {
10154 out2str("sh: turning off NDELAY mode\n");
10165 * Refill the input buffer and return the next input character:
10167 * 1) If a string was pushed back on the input, pop it;
10168 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
10169 * or we are reading from a string so we can't refill the buffer,
10171 * 3) If there is more stuff in this buffer, use it else call read to fill it.
10172 * 4) Process input up to the next newline, deleting nul characters.
10174 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
10175 #define pgetc_debug(...) ((void)0)
10176 static int pgetc(void);
10183 if (g_parsefile->strpush) {
10184 #if ENABLE_ASH_ALIAS
10185 if (g_parsefile->left_in_line == -1
10186 && g_parsefile->strpush->ap
10187 && g_parsefile->next_to_pgetc[-1] != ' '
10188 && g_parsefile->next_to_pgetc[-1] != '\t'
10190 pgetc_debug("preadbuffer PEOA");
10197 /* on both branches above g_parsefile->left_in_line < 0.
10198 * "pgetc" needs refilling.
10201 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
10202 * pungetc() may increment it a few times.
10203 * Assuming it won't increment it to less than -90.
10205 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
10206 pgetc_debug("preadbuffer PEOF1");
10207 /* even in failure keep left_in_line and next_to_pgetc
10208 * in lock step, for correct multi-layer pungetc.
10209 * left_in_line was decremented before preadbuffer(),
10210 * must inc next_to_pgetc: */
10211 g_parsefile->next_to_pgetc++;
10215 more = g_parsefile->left_in_buffer;
10217 flush_stdout_stderr();
10221 /* don't try reading again */
10222 g_parsefile->left_in_line = -99;
10223 pgetc_debug("preadbuffer PEOF2");
10224 g_parsefile->next_to_pgetc++;
10229 /* Find out where's the end of line.
10230 * Set g_parsefile->left_in_line
10231 * and g_parsefile->left_in_buffer acordingly.
10232 * NUL chars are deleted.
10234 q = g_parsefile->next_to_pgetc;
10242 memmove(q, q + 1, more);
10246 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10252 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10253 if (g_parsefile->left_in_line < 0)
10258 g_parsefile->left_in_buffer = more;
10263 out2str(g_parsefile->next_to_pgetc);
10267 pgetc_debug("preadbuffer at %d:%p'%s'",
10268 g_parsefile->left_in_line,
10269 g_parsefile->next_to_pgetc,
10270 g_parsefile->next_to_pgetc);
10271 return (unsigned char)*g_parsefile->next_to_pgetc++;
10277 g_parsefile->linno++;
10278 setprompt_if(doprompt, 2);
10283 g_parsefile->linno++;
10284 needprompt = doprompt;
10292 pgetc_debug("pgetc at %d:%p'%s'",
10293 g_parsefile->left_in_line,
10294 g_parsefile->next_to_pgetc,
10295 g_parsefile->next_to_pgetc);
10296 if (g_parsefile->unget)
10297 return g_parsefile->lastc[--g_parsefile->unget];
10299 if (--g_parsefile->left_in_line >= 0)
10300 c = (unsigned char)*g_parsefile->next_to_pgetc++;
10304 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10305 g_parsefile->lastc[0] = c;
10310 #if ENABLE_ASH_ALIAS
10312 pgetc_without_PEOA(void)
10316 pgetc_debug("pgetc at %d:%p'%s'",
10317 g_parsefile->left_in_line,
10318 g_parsefile->next_to_pgetc,
10319 g_parsefile->next_to_pgetc);
10321 } while (c == PEOA);
10325 # define pgetc_without_PEOA() pgetc()
10329 * Undo a call to pgetc. Only two characters may be pushed back.
10330 * PEOF may be pushed back.
10335 g_parsefile->unget++;
10338 /* This one eats backslash+newline */
10344 while ((c = pgetc()) == '\\') {
10345 if (pgetc() != '\n') {
10357 * To handle the "." command, a stack of input files is used. Pushfile
10358 * adds a new entry to the stack and popfile restores the previous level.
10363 struct parsefile *pf;
10365 pf = ckzalloc(sizeof(*pf));
10366 pf->prev = g_parsefile;
10368 /*pf->strpush = NULL; - ckzalloc did it */
10369 /*pf->basestrpush.prev = NULL;*/
10377 struct parsefile *pf = g_parsefile;
10383 if (pf->pf_fd >= 0)
10386 while (pf->strpush)
10388 g_parsefile = pf->prev;
10394 * Return to top level.
10399 while (g_parsefile != &basepf)
10404 * Close the file(s) that the shell is reading commands from. Called
10405 * after a fork is done.
10411 if (g_parsefile->pf_fd > 0) {
10412 close(g_parsefile->pf_fd);
10413 g_parsefile->pf_fd = 0;
10418 * Like setinputfile, but takes an open file descriptor. Call this with
10422 setinputfd(int fd, int push)
10426 g_parsefile->buf = NULL;
10428 g_parsefile->pf_fd = fd;
10429 if (g_parsefile->buf == NULL)
10430 g_parsefile->buf = ckmalloc(IBUFSIZ);
10431 g_parsefile->left_in_buffer = 0;
10432 g_parsefile->left_in_line = 0;
10433 g_parsefile->linno = 1;
10437 * Set the input to take input from a file. If push is set, push the
10438 * old input onto the stack first.
10441 setinputfile(const char *fname, int flags)
10446 fd = open(fname, O_RDONLY);
10448 if (flags & INPUT_NOFILE_OK)
10451 ash_msg_and_raise_error("can't open '%s'", fname);
10456 close_on_exec_on(fd);
10457 setinputfd(fd, flags & INPUT_PUSH_FILE);
10464 * Like setinputfile, but takes input from a string.
10467 setinputstring(char *string)
10471 g_parsefile->next_to_pgetc = string;
10472 g_parsefile->left_in_line = strlen(string);
10473 g_parsefile->buf = NULL;
10474 g_parsefile->linno = 1;
10480 * Routines to check for mail.
10483 #if ENABLE_ASH_MAIL
10485 /* Hash of mtimes of mailboxes */
10486 static unsigned mailtime_hash;
10487 /* Set if MAIL or MAILPATH is changed. */
10488 static smallint mail_var_path_changed;
10491 * Print appropriate message(s) if mail has arrived.
10492 * If mail_var_path_changed is set,
10493 * then the value of MAIL has mail_var_path_changed,
10494 * so we just update the values.
10503 struct stackmark smark;
10506 setstackmark(&smark);
10507 mpath = mpathset() ? mpathval() : mailval();
10510 p = path_advance(&mpath, nullstr);
10515 for (q = p; *q; q++)
10521 q[-1] = '\0'; /* delete trailing '/' */
10522 if (stat(p, &statb) < 0) {
10525 /* Very simplistic "hash": just a sum of all mtimes */
10526 new_hash += (unsigned)statb.st_mtime;
10528 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10529 if (mailtime_hash != 0)
10530 out2str("you have mail\n");
10531 mailtime_hash = new_hash;
10533 mail_var_path_changed = 0;
10534 popstackmark(&smark);
10537 static void FAST_FUNC
10538 changemail(const char *val UNUSED_PARAM)
10540 mail_var_path_changed = 1;
10543 #endif /* ASH_MAIL */
10546 /* ============ ??? */
10549 * Set the shell parameters.
10552 setparam(char **argv)
10558 for (nparam = 0; argv[nparam]; nparam++)
10560 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10562 *ap++ = ckstrdup(*argv++);
10565 freeparam(&shellparam);
10566 shellparam.malloced = 1;
10567 shellparam.nparam = nparam;
10568 shellparam.p = newparam;
10569 #if ENABLE_ASH_GETOPTS
10570 shellparam.optind = 1;
10571 shellparam.optoff = -1;
10576 * Process shell options. The global variable argptr contains a pointer
10577 * to the argument list; we advance it past the options.
10579 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10580 * For a non-interactive shell, an error condition encountered
10581 * by a special built-in ... shall cause the shell to write a diagnostic message
10582 * to standard error and exit as shown in the following table:
10583 * Error Special Built-In
10585 * Utility syntax error (option or operand error) Shall exit
10587 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10588 * we see that bash does not do that (set "finishes" with error code 1 instead,
10589 * and shell continues), and people rely on this behavior!
10591 * set -o barfoo 2>/dev/null
10594 * Oh well. Let's mimic that.
10597 plus_minus_o(char *name, int val)
10602 for (i = 0; i < NOPTS; i++) {
10603 if (strcmp(name, optnames(i)) == 0) {
10608 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10611 for (i = 0; i < NOPTS; i++) {
10613 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10615 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10621 setoption(int flag, int val)
10625 for (i = 0; i < NOPTS; i++) {
10626 if (optletters(i) == flag) {
10631 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10635 options(int cmdline)
10643 while ((p = *argptr) != NULL) {
10645 if (c != '-' && c != '+')
10648 val = 0; /* val = 0 if c == '+' */
10651 if (p[0] == '\0' || LONE_DASH(p)) {
10653 /* "-" means turn off -x and -v */
10656 /* "--" means reset params */
10657 else if (*argptr == NULL)
10660 break; /* "-" or "--" terminates options */
10663 /* first char was + or - */
10664 while ((c = *p++) != '\0') {
10665 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10666 if (c == 'c' && cmdline) {
10667 minusc = p; /* command is after shell args */
10668 } else if (c == 'o') {
10669 if (plus_minus_o(*argptr, val)) {
10670 /* it already printed err message */
10671 return 1; /* error */
10675 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10677 /* bash does not accept +-login, we also won't */
10678 } else if (cmdline && val && (c == '-')) { /* long options */
10679 if (strcmp(p, "login") == 0)
10691 * The shift builtin command.
10693 static int FAST_FUNC
10694 shiftcmd(int argc UNUSED_PARAM, char **argv)
10701 n = number(argv[1]);
10702 if (n > shellparam.nparam)
10703 n = 0; /* bash compat, was = shellparam.nparam; */
10705 shellparam.nparam -= n;
10706 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10707 if (shellparam.malloced)
10710 ap2 = shellparam.p;
10711 while ((*ap2++ = *ap1++) != NULL)
10713 #if ENABLE_ASH_GETOPTS
10714 shellparam.optind = 1;
10715 shellparam.optoff = -1;
10722 * POSIX requires that 'set' (but not export or readonly) output the
10723 * variables in lexicographic order - by the locale's collating order (sigh).
10724 * Maybe we could keep them in an ordered balanced binary tree
10725 * instead of hashed lists.
10726 * For now just roll 'em through qsort for printing...
10729 showvars(const char *sep_prefix, int on, int off)
10732 char **ep, **epend;
10734 ep = listvars(on, off, &epend);
10735 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10737 sep = *sep_prefix ? " " : sep_prefix;
10739 for (; ep < epend; ep++) {
10743 p = strchrnul(*ep, '=');
10746 q = single_quote(++p);
10747 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10753 * The set command builtin.
10755 static int FAST_FUNC
10756 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10761 return showvars(nullstr, 0, VUNSET);
10764 retval = options(/*cmdline:*/ 0);
10765 if (retval == 0) { /* if no parse error... */
10767 if (*argptr != NULL) {
10775 #if ENABLE_ASH_RANDOM_SUPPORT
10776 static void FAST_FUNC
10777 change_random(const char *value)
10781 if (value == NULL) {
10782 /* "get", generate */
10783 t = next_random(&random_gen);
10784 /* set without recursion */
10785 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10786 vrandom.flags &= ~VNOFUNC;
10789 t = strtoul(value, NULL, 10);
10790 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10795 #if ENABLE_ASH_GETOPTS
10797 getopts(char *optstr, char *optvar, char **optfirst)
10804 int ind = shellparam.optind;
10805 int off = shellparam.optoff;
10809 shellparam.optind = -1;
10810 optnext = optfirst + ind - 1;
10812 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
10815 p = optnext[-1] + off;
10816 if (p == NULL || *p == '\0') {
10817 /* Current word is done, advance */
10819 if (p == NULL || *p != '-' || *++p == '\0') {
10826 if (LONE_DASH(p)) /* check for "--" */
10831 for (q = optstr; *q != c;) {
10833 if (optstr[0] == ':') {
10835 /*sbuf[1] = '\0'; - already is */
10836 setvar0("OPTARG", sbuf);
10838 fprintf(stderr, "Illegal option -%c\n", c);
10839 unsetvar("OPTARG");
10849 if (*p == '\0' && (p = *optnext) == NULL) {
10850 if (optstr[0] == ':') {
10852 /*sbuf[1] = '\0'; - already is */
10853 setvar0("OPTARG", sbuf);
10856 fprintf(stderr, "No arg for -%c option\n", c);
10857 unsetvar("OPTARG");
10865 setvar0("OPTARG", p);
10868 setvar0("OPTARG", nullstr);
10870 ind = optnext - optfirst + 1;
10871 setvar("OPTIND", itoa(ind), VNOFUNC);
10873 /*sbuf[1] = '\0'; - already is */
10874 setvar0(optvar, sbuf);
10876 shellparam.optoff = p ? p - *(optnext - 1) : -1;
10877 shellparam.optind = ind;
10883 * The getopts builtin. Shellparam.optnext points to the next argument
10884 * to be processed. Shellparam.optptr points to the next character to
10885 * be processed in the current argument. If shellparam.optnext is NULL,
10886 * then it's the first time getopts has been called.
10888 static int FAST_FUNC
10889 getoptscmd(int argc, char **argv)
10894 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10896 optbase = shellparam.p;
10897 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
10898 shellparam.optind = 1;
10899 shellparam.optoff = -1;
10902 optbase = &argv[3];
10903 if ((unsigned)shellparam.optind > argc - 2) {
10904 shellparam.optind = 1;
10905 shellparam.optoff = -1;
10909 return getopts(argv[1], argv[2], optbase);
10911 #endif /* ASH_GETOPTS */
10914 /* ============ Shell parser */
10917 struct heredoc *next; /* next here document in list */
10918 union node *here; /* redirection node */
10919 char *eofmark; /* string indicating end of input */
10920 smallint striptabs; /* if set, strip leading tabs */
10923 static smallint tokpushback; /* last token pushed back */
10924 static smallint quoteflag; /* set if (part of) last token was quoted */
10925 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10926 static struct heredoc *heredoclist; /* list of here documents to read */
10927 static char *wordtext; /* text of last word returned by readtoken */
10928 static struct nodelist *backquotelist;
10929 static union node *redirnode;
10930 static struct heredoc *heredoc;
10932 static const char *
10933 tokname(char *buf, int tok)
10936 return tokname_array[tok];
10937 sprintf(buf, "\"%s\"", tokname_array[tok]);
10941 /* raise_error_unexpected_syntax:
10942 * Called when an unexpected token is read during the parse. The argument
10943 * is the token that is expected, or -1 if more than one type of token can
10944 * occur at this point.
10946 static void raise_error_unexpected_syntax(int) NORETURN;
10948 raise_error_unexpected_syntax(int token)
10954 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10956 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10957 raise_error_syntax(msg);
10961 /* parsing is heavily cross-recursive, need these forward decls */
10962 static union node *andor(void);
10963 static union node *pipeline(void);
10964 static union node *parse_command(void);
10965 static void parseheredoc(void);
10966 static int peektoken(void);
10967 static int readtoken(void);
10969 static union node *
10972 union node *n1, *n2, *n3;
10977 switch (peektoken()) {
10985 if (!n1 && (nlflag & 1))
10991 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10992 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
10998 if (tok == TBACKGND) {
10999 if (n2->type == NPIPE) {
11000 n2->npipe.pipe_backgnd = 1;
11002 if (n2->type != NREDIR) {
11003 n3 = stzalloc(sizeof(struct nredir));
11005 /*n3->nredir.redirect = NULL; - stzalloc did it */
11008 n2->type = NBACKGND;
11014 n3 = stzalloc(sizeof(struct nbinary));
11016 n3->nbinary.ch1 = n1;
11017 n3->nbinary.ch2 = n2;
11030 raise_error_unexpected_syntax(-1);
11037 static union node *
11040 union node *n1, *n2, *n3;
11048 } else if (t == TOR) {
11054 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11056 n3 = stzalloc(sizeof(struct nbinary));
11058 n3->nbinary.ch1 = n1;
11059 n3->nbinary.ch2 = n2;
11064 static union node *
11067 union node *n1, *n2, *pipenode;
11068 struct nodelist *lp, *prev;
11072 TRACE(("pipeline: entered\n"));
11073 if (readtoken() == TNOT) {
11075 checkkwd = CHKKWD | CHKALIAS;
11078 n1 = parse_command();
11079 if (readtoken() == TPIPE) {
11080 pipenode = stzalloc(sizeof(struct npipe));
11081 pipenode->type = NPIPE;
11082 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
11083 lp = stzalloc(sizeof(struct nodelist));
11084 pipenode->npipe.cmdlist = lp;
11088 lp = stzalloc(sizeof(struct nodelist));
11089 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11090 lp->n = parse_command();
11092 } while (readtoken() == TPIPE);
11098 n2 = stzalloc(sizeof(struct nnot));
11106 static union node *
11111 n = stzalloc(sizeof(struct narg));
11113 /*n->narg.next = NULL; - stzalloc did it */
11114 n->narg.text = wordtext;
11115 n->narg.backquote = backquotelist;
11120 fixredir(union node *n, const char *text, int err)
11124 TRACE(("Fix redir %s %d\n", text, err));
11126 n->ndup.vname = NULL;
11128 fd = bb_strtou(text, NULL, 10);
11129 if (!errno && fd >= 0)
11130 n->ndup.dupfd = fd;
11131 else if (LONE_DASH(text))
11132 n->ndup.dupfd = -1;
11135 raise_error_syntax("bad fd number");
11136 n->ndup.vname = makename();
11143 union node *n = redirnode;
11145 if (n->type == NHERE)
11146 checkkwd = CHKEOFMARK;
11147 if (readtoken() != TWORD)
11148 raise_error_unexpected_syntax(-1);
11149 if (n->type == NHERE) {
11150 struct heredoc *here = heredoc;
11153 if (quoteflag == 0)
11155 TRACE(("Here document %d\n", n->type));
11156 rmescapes(wordtext, 0);
11157 here->eofmark = wordtext;
11159 if (heredoclist == NULL)
11160 heredoclist = here;
11162 for (p = heredoclist; p->next; p = p->next)
11166 } else if (n->type == NTOFD || n->type == NFROMFD) {
11167 fixredir(n, wordtext, 0);
11169 n->nfile.fname = makename();
11173 static union node *
11176 union node *args, **app;
11177 union node *n = NULL;
11178 union node *vars, **vpp;
11179 union node **rpp, *redir;
11182 smallint double_brackets_flag = 0;
11184 IF_BASH_FUNCTION(smallint function_flag = 0;)
11193 savecheckkwd = CHKALIAS;
11196 checkkwd = savecheckkwd;
11201 if (peektoken() != TWORD)
11202 raise_error_unexpected_syntax(TWORD);
11207 case TAND: /* "&&" */
11208 case TOR: /* "||" */
11209 if (!double_brackets_flag) {
11213 wordtext = (char *) (t == TAND ? "-a" : "-o");
11216 n = stzalloc(sizeof(struct narg));
11218 /*n->narg.next = NULL; - stzalloc did it */
11219 n->narg.text = wordtext;
11221 if (strcmp("[[", wordtext) == 0)
11222 double_brackets_flag = 1;
11223 else if (strcmp("]]", wordtext) == 0)
11224 double_brackets_flag = 0;
11226 n->narg.backquote = backquotelist;
11227 if (savecheckkwd && isassignment(wordtext)) {
11229 vpp = &n->narg.next;
11232 app = &n->narg.next;
11236 if (function_flag) {
11237 checkkwd = CHKNL | CHKKWD;
11238 switch (peektoken()) {
11250 if (strcmp("[[", wordtext) == 0)
11254 raise_error_unexpected_syntax(-1);
11260 *rpp = n = redirnode;
11261 rpp = &n->nfile.next;
11262 parsefname(); /* read name of redirection file */
11265 IF_BASH_FUNCTION(do_func:)
11266 if (args && app == &args->narg.next
11269 struct builtincmd *bcmd;
11272 /* We have a function */
11273 if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
11274 raise_error_unexpected_syntax(TRP);
11275 name = n->narg.text;
11276 if (!goodname(name)
11277 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11279 raise_error_syntax("bad function name");
11282 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11283 n->narg.next = parse_command();
11286 IF_BASH_FUNCTION(function_flag = 0;)
11297 n = stzalloc(sizeof(struct ncmd));
11299 n->ncmd.args = args;
11300 n->ncmd.assign = vars;
11301 n->ncmd.redirect = redir;
11305 static union node *
11306 parse_command(void)
11308 union node *n1, *n2;
11309 union node *ap, **app;
11310 union node *cp, **cpp;
11311 union node *redir, **rpp;
11318 switch (readtoken()) {
11320 raise_error_unexpected_syntax(-1);
11323 n1 = stzalloc(sizeof(struct nif));
11325 n1->nif.test = list(0);
11326 if (readtoken() != TTHEN)
11327 raise_error_unexpected_syntax(TTHEN);
11328 n1->nif.ifpart = list(0);
11330 while (readtoken() == TELIF) {
11331 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11332 n2 = n2->nif.elsepart;
11334 n2->nif.test = list(0);
11335 if (readtoken() != TTHEN)
11336 raise_error_unexpected_syntax(TTHEN);
11337 n2->nif.ifpart = list(0);
11339 if (lasttoken == TELSE)
11340 n2->nif.elsepart = list(0);
11342 n2->nif.elsepart = NULL;
11350 n1 = stzalloc(sizeof(struct nbinary));
11351 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11352 n1->nbinary.ch1 = list(0);
11355 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11356 got == TWORD ? wordtext : ""));
11357 raise_error_unexpected_syntax(TDO);
11359 n1->nbinary.ch2 = list(0);
11364 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11365 raise_error_syntax("bad for loop variable");
11366 n1 = stzalloc(sizeof(struct nfor));
11368 n1->nfor.var = wordtext;
11369 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11370 if (readtoken() == TIN) {
11372 while (readtoken() == TWORD) {
11373 n2 = stzalloc(sizeof(struct narg));
11375 /*n2->narg.next = NULL; - stzalloc did it */
11376 n2->narg.text = wordtext;
11377 n2->narg.backquote = backquotelist;
11379 app = &n2->narg.next;
11382 n1->nfor.args = ap;
11383 if (lasttoken != TNL && lasttoken != TSEMI)
11384 raise_error_unexpected_syntax(-1);
11386 n2 = stzalloc(sizeof(struct narg));
11388 /*n2->narg.next = NULL; - stzalloc did it */
11389 n2->narg.text = (char *)dolatstr;
11390 /*n2->narg.backquote = NULL;*/
11391 n1->nfor.args = n2;
11393 * Newline or semicolon here is optional (but note
11394 * that the original Bourne shell only allowed NL).
11396 if (lasttoken != TSEMI)
11399 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11400 if (readtoken() != TDO)
11401 raise_error_unexpected_syntax(TDO);
11402 n1->nfor.body = list(0);
11406 n1 = stzalloc(sizeof(struct ncase));
11408 if (readtoken() != TWORD)
11409 raise_error_unexpected_syntax(TWORD);
11410 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11412 /*n2->narg.next = NULL; - stzalloc did it */
11413 n2->narg.text = wordtext;
11414 n2->narg.backquote = backquotelist;
11415 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11416 if (readtoken() != TIN)
11417 raise_error_unexpected_syntax(TIN);
11418 cpp = &n1->ncase.cases;
11420 checkkwd = CHKNL | CHKKWD;
11422 while (t != TESAC) {
11423 if (lasttoken == TLP)
11425 *cpp = cp = stzalloc(sizeof(struct nclist));
11427 app = &cp->nclist.pattern;
11429 *app = ap = stzalloc(sizeof(struct narg));
11431 /*ap->narg.next = NULL; - stzalloc did it */
11432 ap->narg.text = wordtext;
11433 ap->narg.backquote = backquotelist;
11434 if (readtoken() != TPIPE)
11436 app = &ap->narg.next;
11439 //ap->narg.next = NULL;
11440 if (lasttoken != TRP)
11441 raise_error_unexpected_syntax(TRP);
11442 cp->nclist.body = list(2);
11444 cpp = &cp->nclist.next;
11446 checkkwd = CHKNL | CHKKWD;
11450 raise_error_unexpected_syntax(TENDCASE);
11457 n1 = stzalloc(sizeof(struct nredir));
11458 n1->type = NSUBSHELL;
11459 n1->nredir.n = list(0);
11460 /*n1->nredir.redirect = NULL; - stzalloc did it */
11467 IF_BASH_FUNCTION(case TFUNCTION:)
11471 return simplecmd();
11474 if (readtoken() != t)
11475 raise_error_unexpected_syntax(t);
11478 /* Now check for redirection which may follow command */
11479 checkkwd = CHKKWD | CHKALIAS;
11481 while (readtoken() == TREDIR) {
11482 *rpp = n2 = redirnode;
11483 rpp = &n2->nfile.next;
11489 if (n1->type != NSUBSHELL) {
11490 n2 = stzalloc(sizeof(struct nredir));
11495 n1->nredir.redirect = redir;
11500 #if BASH_DOLLAR_SQUOTE
11502 decode_dollar_squote(void)
11504 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11510 p = strchr(C_escapes, c);
11515 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11519 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11521 } else if (c == 'x') { /* \xHH */
11525 } while (isxdigit(c) && --cnt);
11527 if (cnt == 3) { /* \x but next char is "bad" */
11531 } else { /* simple seq like \\ or \t */
11536 c = bb_process_escape_sequence((void*)&p);
11537 } else { /* unrecognized "\z": print both chars unless ' or " */
11538 if (c != '\'' && c != '"') {
11540 c |= 0x100; /* "please encode \, then me" */
11547 /* Used by expandstr to get here-doc like behaviour. */
11548 #define FAKEEOFMARK ((char*)(uintptr_t)1)
11550 static ALWAYS_INLINE int
11551 realeofmark(const char *eofmark)
11553 return eofmark && eofmark != FAKEEOFMARK;
11557 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11558 * is not NULL, read a here document. In the latter case, eofmark is the
11559 * word which marks the end of the document and striptabs is true if
11560 * leading tabs should be stripped from the document. The argument c
11561 * is the first character of the input token or document.
11563 * Because C does not have internal subroutines, I have simulated them
11564 * using goto's to implement the subroutine linkage. The following macros
11565 * will run code that appears at the end of readtoken1.
11567 #define CHECKEND() {goto checkend; checkend_return:;}
11568 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11569 #define PARSESUB() {goto parsesub; parsesub_return:;}
11570 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11571 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11572 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11574 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11576 /* NB: syntax parameter fits into smallint */
11577 /* c parameter is an unsigned char or PEOF or PEOA */
11580 struct nodelist *bqlist;
11584 IF_FEATURE_SH_MATH(smallint prevsyntax;) /* syntax before arithmetic */
11585 smallint pssyntax; /* we are expanding a prompt string */
11586 int varnest; /* levels of variables expansion */
11587 IF_FEATURE_SH_MATH(int arinest;) /* levels of arithmetic expansion */
11588 IF_FEATURE_SH_MATH(int parenlevel;) /* levels of parens in arithmetic */
11589 int dqvarnest; /* levels of variables expansion within double quotes */
11591 IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
11593 startlinno = g_parsefile->linno;
11596 IF_FEATURE_SH_MATH(prevsyntax = 0;)
11597 pssyntax = (syntax == PSSYNTAX);
11600 dblquote = (syntax == DQSYNTAX);
11602 IF_FEATURE_SH_MATH(arinest = 0;)
11603 IF_FEATURE_SH_MATH(parenlevel = 0;)
11606 STARTSTACKSTR(out);
11608 /* For each line, until end of word */
11609 CHECKEND(); /* set c to PEOF if at end of here document */
11610 for (;;) { /* until end of line or end of word */
11611 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11612 switch (SIT(c, syntax)) {
11613 case CNL: /* '\n' */
11614 if (syntax == BASESYNTAX)
11615 goto endword; /* exit outer loop */
11619 goto loop; /* continue outer loop */
11624 #if BASH_DOLLAR_SQUOTE
11625 if (c == '\\' && bash_dollar_squote) {
11626 c = decode_dollar_squote();
11628 /* skip $'\000', $'\x00' (like bash) */
11632 /* Unknown escape. Encode as '\z' */
11633 c = (unsigned char)c;
11634 if (eofmark == NULL || dblquote)
11635 USTPUTC(CTLESC, out);
11636 USTPUTC('\\', out);
11640 if (eofmark == NULL || dblquote)
11641 USTPUTC(CTLESC, out);
11644 case CBACK: /* backslash */
11645 c = pgetc_without_PEOA();
11647 USTPUTC(CTLESC, out);
11648 USTPUTC('\\', out);
11650 } else if (c == '\n') {
11653 if (c == '$' && pssyntax) {
11654 USTPUTC(CTLESC, out);
11655 USTPUTC('\\', out);
11657 /* Backslash is retained if we are in "str" and next char isn't special */
11662 && (c != '"' || eofmark != NULL)
11664 USTPUTC('\\', out);
11666 USTPUTC(CTLESC, out);
11674 if (eofmark == NULL) {
11675 USTPUTC(CTLQUOTEMARK, out);
11683 IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
11684 if (eofmark != NULL && varnest == 0) {
11687 if (dqvarnest == 0) {
11688 syntax = BASESYNTAX;
11695 case CVAR: /* '$' */
11696 PARSESUB(); /* parse substitution */
11698 case CENDVAR: /* '}' */
11701 if (dqvarnest > 0) {
11708 #if ENABLE_FEATURE_SH_MATH
11709 case CLP: /* '(' in arithmetic */
11713 case CRP: /* ')' in arithmetic */
11714 if (parenlevel > 0) {
11717 if (pgetc_eatbnl() == ')') {
11719 if (--arinest == 0) {
11720 syntax = prevsyntax;
11724 * unbalanced parens
11725 * (don't 2nd guess - no error)
11733 case CBQUOTE: /* '`' */
11737 goto endword; /* exit outer loop */
11741 if (varnest == 0) {
11742 #if BASH_REDIR_OUTPUT
11744 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11745 if (pgetc() == '>')
11746 c = 0x100 + '>'; /* flag &> */
11750 goto endword; /* exit outer loop */
11752 IF_ASH_ALIAS(if (c != PEOA))
11759 #if ENABLE_FEATURE_SH_MATH
11760 if (syntax == ARISYNTAX)
11761 raise_error_syntax("missing '))'");
11763 if (syntax != BASESYNTAX && eofmark == NULL)
11764 raise_error_syntax("unterminated quoted string");
11765 if (varnest != 0) {
11766 startlinno = g_parsefile->linno;
11768 raise_error_syntax("missing '}'");
11770 USTPUTC('\0', out);
11771 len = out - (char *)stackblock();
11772 out = stackblock();
11773 if (eofmark == NULL) {
11774 if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
11777 if (isdigit_str9(out)) {
11778 PARSEREDIR(); /* passed as params: out, c */
11779 lasttoken = TREDIR;
11782 /* else: non-number X seen, interpret it
11783 * as "NNNX>file" = "NNNX >file" */
11787 quoteflag = quotef;
11788 backquotelist = bqlist;
11789 grabstackblock(len);
11793 /* end of readtoken routine */
11796 * Check to see whether we are at the end of the here document. When this
11797 * is called, c is set to the first character of the next input line. If
11798 * we are at the end of the here document, this routine sets the c to PEOF.
11801 if (realeofmark(eofmark)) {
11805 #if ENABLE_ASH_ALIAS
11807 c = pgetc_without_PEOA();
11810 while (c == '\t') {
11811 c = pgetc_without_PEOA();
11815 markloc = out - (char *)stackblock();
11816 for (p = eofmark; STPUTC(c, out), *p; p++) {
11820 c = pgetc_without_PEOA();
11823 if (c == '\n' || c == PEOF) {
11825 g_parsefile->linno++;
11826 needprompt = doprompt;
11831 p = (char *)stackblock() + markloc + 1;
11832 len_here = out - p;
11835 len_here -= (c >= PEOF);
11841 str = alloca(len_here + 1);
11842 *(char *)mempcpy(str, p, len_here) = '\0';
11844 pushstring(str, NULL);
11849 STADJUST((char *)stackblock() + markloc - out, out);
11851 goto checkend_return;
11855 * Parse a redirection operator. The variable "out" points to a string
11856 * specifying the fd to be redirected. The variable "c" contains the
11857 * first character of the redirection operator.
11860 /* out is already checked to be a valid number or "" */
11861 int fd = (*out == '\0' ? -1 : atoi(out));
11864 np = stzalloc(sizeof(struct nfile));
11869 np->type = NAPPEND;
11871 np->type = NCLOBBER;
11874 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11880 #if BASH_REDIR_OUTPUT
11881 else if (c == 0x100 + '>') { /* this flags &> redirection */
11883 pgetc(); /* this is '>', no need to check */
11887 else { /* c == '<' */
11888 /*np->nfile.fd = 0; - stzalloc did it */
11892 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11893 np = stzalloc(sizeof(struct nhere));
11894 /*np->nfile.fd = 0; - stzalloc did it */
11897 heredoc = stzalloc(sizeof(struct heredoc));
11898 heredoc->here = np;
11901 heredoc->striptabs = 1;
11903 /*heredoc->striptabs = 0; - stzalloc did it */
11909 np->type = NFROMFD;
11913 np->type = NFROMTO;
11925 goto parseredir_return;
11929 * Parse a substitution. At this point, we have read the dollar sign
11930 * and nothing else.
11933 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11934 * (assuming ascii char codes, as the original implementation did) */
11935 #define is_special(c) \
11936 (((unsigned)(c) - 33 < 32) \
11937 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11939 unsigned char subtype;
11942 c = pgetc_eatbnl();
11943 if ((checkkwd & CHKEOFMARK)
11944 || c > 255 /* PEOA or PEOF */
11945 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11947 #if BASH_DOLLAR_SQUOTE
11948 if (syntax != DQSYNTAX && c == '\'')
11949 bash_dollar_squote = 1;
11954 } else if (c == '(') {
11955 /* $(command) or $((arith)) */
11956 if (pgetc_eatbnl() == '(') {
11957 #if ENABLE_FEATURE_SH_MATH
11960 raise_error_syntax("support for $((arith)) is disabled");
11967 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11968 USTPUTC(CTLVAR, out);
11969 typeloc = out - (char *)stackblock();
11971 subtype = VSNORMAL;
11973 c = pgetc_eatbnl();
11978 /* $[{[#]]NAME[}] */
11981 c = pgetc_eatbnl();
11982 } while (is_in_name(c));
11983 } else if (isdigit(c)) {
11984 /* $[{[#]]NUM[}] */
11987 c = pgetc_eatbnl();
11988 } while (isdigit(c));
11989 } else if (is_special(c)) {
11990 /* $[{[#]]<specialchar>[}] */
11993 c = pgetc_eatbnl();
11994 if (!subtype && cc == '#') {
11995 subtype = VSLENGTH;
11996 if (c == '_' || isalnum(c))
11999 c = pgetc_eatbnl();
12000 if (cc == '}' || c != '}') {
12011 if (c != '}' && subtype == VSLENGTH) {
12012 /* ${#VAR didn't end with } */
12016 if (subtype == 0) {
12017 static const char types[] ALIGN1 = "}-+?=";
12018 /* ${VAR...} but not $VAR or ${#VAR} */
12019 /* c == first char after VAR */
12022 c = pgetc_eatbnl();
12024 /* This check is only needed to not misinterpret
12025 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
12028 if (!strchr(types, c)) {
12029 subtype = VSSUBSTR;
12031 break; /* "goto badsub" is bigger (!) */
12037 const char *p = strchr(types, c);
12040 subtype |= p - types + VSNORMAL;
12046 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
12047 c = pgetc_eatbnl();
12053 #if BASH_PATTERN_SUBST
12055 /* ${v/[/]pattern/repl} */
12056 //TODO: encode pattern and repl separately.
12057 // Currently ${v/$var_with_slash/repl} is horribly broken
12058 subtype = VSREPLACE;
12059 c = pgetc_eatbnl();
12062 subtype++; /* VSREPLACEALL */
12070 ((unsigned char *)stackblock())[typeloc] = subtype;
12071 if (subtype != VSNORMAL) {
12078 goto parsesub_return;
12082 * Called to parse command substitutions. Newstyle is set if the command
12083 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
12084 * list of commands (passed by reference), and savelen is the number of
12085 * characters on the top of the stack which must be preserved.
12088 struct nodelist **nlpp;
12092 smallint saveprompt = 0;
12095 savelen = out - (char *)stackblock();
12098 * FIXME: this can allocate very large block on stack and SEGV.
12100 * echo "..<100kbytes>..`true` $(true) `true` ..."
12101 * allocates 100kb for every command subst. With about
12102 * a hundred command substitutions stack overflows.
12103 * With larger prepended string, SEGV happens sooner.
12105 str = alloca(savelen);
12106 memcpy(str, stackblock(), savelen);
12110 /* We must read until the closing backquote, giving special
12111 * treatment to some slashes, and then push the string and
12112 * reread it as input, interpreting it normally.
12118 STARTSTACKSTR(pout);
12122 setprompt_if(needprompt, 2);
12133 * If eating a newline, avoid putting
12134 * the newline into the new character
12135 * stream (via the STPUTC after the
12140 if (pc != '\\' && pc != '`' && pc != '$'
12141 && (!dblquote || pc != '"')
12143 STPUTC('\\', pout);
12145 if (pc <= 255 /* not PEOA or PEOF */) {
12151 IF_ASH_ALIAS(case PEOA:)
12152 startlinno = g_parsefile->linno;
12153 raise_error_syntax("EOF in backquote substitution");
12165 STPUTC('\0', pout);
12166 psavelen = pout - (char *)stackblock();
12167 if (psavelen > 0) {
12168 pstr = grabstackstr(pout);
12169 setinputstring(pstr);
12174 nlpp = &(*nlpp)->next;
12175 *nlpp = stzalloc(sizeof(**nlpp));
12176 /* (*nlpp)->next = NULL; - stzalloc did it */
12179 saveprompt = doprompt;
12186 doprompt = saveprompt;
12187 else if (readtoken() != TRP)
12188 raise_error_unexpected_syntax(TRP);
12193 * Start reading from old file again, ignoring any pushed back
12194 * tokens left from the backquote parsing
12199 while (stackblocksize() <= savelen)
12201 STARTSTACKSTR(out);
12203 memcpy(out, str, savelen);
12204 STADJUST(savelen, out);
12206 USTPUTC(CTLBACKQ, out);
12208 goto parsebackq_oldreturn;
12209 goto parsebackq_newreturn;
12212 #if ENABLE_FEATURE_SH_MATH
12214 * Parse an arithmetic expansion (indicate start of one and set state)
12217 if (++arinest == 1) {
12218 prevsyntax = syntax;
12219 syntax = ARISYNTAX;
12221 USTPUTC(CTLARI, out);
12222 goto parsearith_return;
12225 } /* end of readtoken */
12228 * Read the next input token.
12229 * If the token is a word, we set backquotelist to the list of cmds in
12230 * backquotes. We set quoteflag to true if any part of the word was
12232 * If the token is TREDIR, then we set redirnode to a structure containing
12234 * In all cases, the variable startlinno is set to the number of the line
12235 * on which the token starts.
12237 * [Change comment: here documents and internal procedures]
12238 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12239 * word parsing code into a separate routine. In this case, readtoken
12240 * doesn't need to have any internal procedures, but parseword does.
12241 * We could also make parseoperator in essence the main routine, and
12242 * have parseword (readtoken1?) handle both words and redirection.]
12244 #define NEW_xxreadtoken
12245 #ifdef NEW_xxreadtoken
12246 /* singles must be first! */
12247 static const char xxreadtoken_chars[7] ALIGN1 = {
12248 '\n', '(', ')', /* singles */
12249 '&', '|', ';', /* doubles */
12253 #define xxreadtoken_singles 3
12254 #define xxreadtoken_doubles 3
12256 static const char xxreadtoken_tokens[] ALIGN1 = {
12257 TNL, TLP, TRP, /* only single occurrence allowed */
12258 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12259 TEOF, /* corresponds to trailing nul */
12260 TAND, TOR, TENDCASE /* if double occurrence */
12272 setprompt_if(needprompt, 2);
12273 startlinno = g_parsefile->linno;
12274 for (;;) { /* until token or start of word found */
12276 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12280 while ((c = pgetc()) != '\n' && c != PEOF)
12283 } else if (c == '\\') {
12284 if (pgetc() != '\n') {
12286 break; /* return readtoken1(...) */
12292 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12298 p = strchr(xxreadtoken_chars, c);
12300 break; /* return readtoken1(...) */
12302 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12304 if (cc == c) { /* double occurrence? */
12305 p += xxreadtoken_doubles + 1;
12308 #if BASH_REDIR_OUTPUT
12309 if (c == '&' && cc == '>') /* &> */
12310 break; /* return readtoken1(...) */
12315 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12320 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12322 #else /* old xxreadtoken */
12323 #define RETURN(token) return lasttoken = token
12333 setprompt_if(needprompt, 2);
12334 startlinno = g_parsefile->linno;
12335 for (;;) { /* until token or start of word found */
12338 case ' ': case '\t':
12339 IF_ASH_ALIAS(case PEOA:)
12342 while ((c = pgetc()) != '\n' && c != PEOF)
12347 if (pgetc() == '\n') {
12359 if (pgetc() == '&')
12364 if (pgetc() == '|')
12369 if (pgetc() == ';')
12382 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12385 #endif /* old xxreadtoken */
12391 int kwd = checkkwd;
12393 smallint alreadyseen = tokpushback;
12396 #if ENABLE_ASH_ALIAS
12412 if (t != TWORD || quoteflag) {
12417 * check for keywords
12419 if (kwd & CHKKWD) {
12420 const char *const *pp;
12422 pp = findkwd(wordtext);
12424 lasttoken = t = pp - tokname_array;
12425 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12430 if (checkkwd & CHKALIAS) {
12431 #if ENABLE_ASH_ALIAS
12433 ap = lookupalias(wordtext, 1);
12436 pushstring(ap->val, ap);
12446 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12448 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12464 * Read and parse a command. Returns NODE_EOF on end of file.
12465 * (NULL is a valid parse tree indicating a blank line.)
12467 static union node *
12468 parsecmd(int interact)
12473 doprompt = interact;
12474 setprompt_if(doprompt, doprompt);
12480 * Input any here documents.
12485 struct heredoc *here;
12488 here = heredoclist;
12489 heredoclist = NULL;
12492 setprompt_if(needprompt, 2);
12493 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12494 here->eofmark, here->striptabs);
12495 n = stzalloc(sizeof(struct narg));
12496 n->narg.type = NARG;
12497 /*n->narg.next = NULL; - stzalloc did it */
12498 n->narg.text = wordtext;
12499 n->narg.backquote = backquotelist;
12500 here->here->nhere.doc = n;
12506 static const char *
12507 expandstr(const char *ps, int syntax_type)
12512 /* XXX Fix (char *) cast. */
12513 setinputstring((char *)ps);
12515 saveprompt = doprompt;
12517 readtoken1(pgetc(), syntax_type, FAKEEOFMARK, 0);
12518 doprompt = saveprompt;
12522 n.narg.type = NARG;
12523 n.narg.next = NULL;
12524 n.narg.text = wordtext;
12525 n.narg.backquote = backquotelist;
12527 expandarg(&n, NULL, EXP_QUOTED);
12528 return stackblock();
12534 return tokpushback && lasttoken == TEOF;
12538 * Execute a command or commands contained in a string.
12541 evalstring(char *s, int flags)
12543 struct jmploc *volatile savehandler;
12544 struct jmploc jmploc;
12548 struct stackmark smark;
12553 setstackmark(&smark);
12556 /* On exception inside execution loop, we must popfile().
12557 * Try interactively:
12559 * command eval "a=b" # throws "is read only" error
12560 * "command BLTIN" is not supposed to abort (even in non-interactive use).
12561 * But if we skip popfile(), we hit EOF in eval's string, and exit.
12563 savehandler = exception_handler;
12564 ex = setjmp(jmploc.loc);
12567 exception_handler = &jmploc;
12569 while ((n = parsecmd(0)) != NODE_EOF) {
12572 i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
12575 popstackmark(&smark);
12580 popstackmark(&smark);
12584 exception_handler = savehandler;
12586 longjmp(exception_handler->loc, ex);
12592 * The eval command.
12594 static int FAST_FUNC
12595 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12604 STARTSTACKSTR(concat);
12606 concat = stack_putstr(p, concat);
12610 STPUTC(' ', concat);
12612 STPUTC('\0', concat);
12613 p = grabstackstr(concat);
12615 return evalstring(p, flags & EV_TESTED);
12621 * Read and execute commands.
12622 * "Top" is nonzero for the top level command loop;
12623 * it turns on prompting if the shell is interactive.
12629 struct stackmark smark;
12634 TRACE(("cmdloop(%d) called\n", top));
12638 setstackmark(&smark);
12641 showjobs(SHOW_CHANGED|SHOW_STDERR);
12644 if (iflag && top) {
12648 n = parsecmd(inter);
12650 if (DEBUG > 2 && debug && (n != NODE_EOF))
12653 if (n == NODE_EOF) {
12654 if (!top || numeof >= 50)
12656 if (!stoppedjobs()) {
12659 out2str("\nUse \"exit\" to leave shell.\n");
12662 } else if (nflag == 0) {
12665 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12668 i = evaltree(n, 0);
12672 popstackmark(&smark);
12676 evalskip &= ~SKIPFUNC;
12684 * Take commands from a file. To be compatible we should do a path
12685 * search for the file, which is necessary to find sub-commands.
12688 find_dot_file(char *name)
12691 const char *path = pathval();
12694 /* don't try this for absolute or relative paths */
12695 if (strchr(name, '/'))
12698 while ((fullname = path_advance(&path, name)) != NULL) {
12699 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12701 * Don't bother freeing here, since it will
12702 * be freed by the caller.
12706 if (fullname != name)
12707 stunalloc(fullname);
12710 /* not found in the PATH */
12711 ash_msg_and_raise_error("%s: not found", name);
12715 static int FAST_FUNC
12716 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12718 /* "false; . empty_file; echo $?" should print 0, not 1: */
12722 char *args_need_save;
12723 volatile struct shparam saveparam;
12726 // struct strlist *sp;
12727 // for (sp = cmdenviron; sp; sp = sp->next)
12728 // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12730 nextopt(nullstr); /* handle possible "--" */
12734 /* bash says: "bash: .: filename argument required" */
12735 return 2; /* bash compat */
12738 /* This aborts if file isn't found, which is POSIXly correct.
12739 * bash returns exitcode 1 instead.
12741 fullname = find_dot_file(argv[0]);
12743 args_need_save = argv[0];
12744 if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
12746 saveparam = shellparam;
12747 shellparam.malloced = 0;
12751 shellparam.nparam = argc;
12752 shellparam.p = argv;
12755 /* This aborts if file can't be opened, which is POSIXly correct.
12756 * bash returns exitcode 1 instead.
12758 setinputfile(fullname, INPUT_PUSH_FILE);
12759 commandname = fullname;
12760 status = cmdloop(0);
12763 if (args_need_save) {
12764 freeparam(&shellparam);
12765 shellparam = saveparam;
12771 static int FAST_FUNC
12772 exitcmd(int argc UNUSED_PARAM, char **argv)
12777 exitstatus = number(argv[1]);
12778 raise_exception(EXEXIT);
12783 * Read a file containing shell functions.
12786 readcmdfile(char *name)
12788 setinputfile(name, INPUT_PUSH_FILE);
12794 /* ============ find_command inplementation */
12797 * Resolve a command name. If you change this routine, you may have to
12798 * change the shellexec routine as well.
12801 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12803 struct tblentry *cmdp;
12810 struct builtincmd *bcmd;
12812 /* If name contains a slash, don't use PATH or hash table */
12813 if (strchr(name, '/') != NULL) {
12814 entry->u.index = -1;
12815 if (act & DO_ABS) {
12816 while (stat(name, &statb) < 0) {
12818 if (errno == EINTR)
12821 entry->cmdtype = CMDUNKNOWN;
12825 entry->cmdtype = CMDNORMAL;
12829 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12831 updatetbl = (path == pathval());
12834 if (strstr(path, "%builtin") != NULL)
12835 act |= DO_ALTBLTIN;
12838 /* If name is in the table, check answer will be ok */
12839 cmdp = cmdlookup(name, 0);
12840 if (cmdp != NULL) {
12843 switch (cmdp->cmdtype) {
12861 } else if (cmdp->rehash == 0)
12862 /* if not invalidated by cd, we're done */
12866 /* If %builtin not in path, check for builtin next */
12867 bcmd = find_builtin(name);
12869 if (IS_BUILTIN_REGULAR(bcmd))
12870 goto builtin_success;
12871 if (act & DO_ALTPATH) {
12872 if (!(act & DO_ALTBLTIN))
12873 goto builtin_success;
12874 } else if (builtinloc <= 0) {
12875 goto builtin_success;
12879 #if ENABLE_FEATURE_SH_STANDALONE
12881 int applet_no = find_applet_by_name(name);
12882 if (applet_no >= 0) {
12883 entry->cmdtype = CMDNORMAL;
12884 entry->u.index = -2 - applet_no;
12890 /* We have to search path. */
12891 prev = -1; /* where to start */
12892 if (cmdp && cmdp->rehash) { /* doing a rehash */
12893 if (cmdp->cmdtype == CMDBUILTIN)
12896 prev = cmdp->param.index;
12902 while ((fullname = path_advance(&path, name)) != NULL) {
12903 stunalloc(fullname);
12904 /* NB: code below will still use fullname
12905 * despite it being "unallocated" */
12908 if (prefix(pathopt, "builtin")) {
12910 goto builtin_success;
12913 if ((act & DO_NOFUNC)
12914 || !prefix(pathopt, "func")
12915 ) { /* ignore unimplemented options */
12919 /* if rehash, don't redo absolute path names */
12920 if (fullname[0] == '/' && idx <= prev) {
12923 TRACE(("searchexec \"%s\": no change\n", name));
12926 while (stat(fullname, &statb) < 0) {
12928 if (errno == EINTR)
12931 if (errno != ENOENT && errno != ENOTDIR)
12935 e = EACCES; /* if we fail, this will be the error */
12936 if (!S_ISREG(statb.st_mode))
12938 if (pathopt) { /* this is a %func directory */
12939 stalloc(strlen(fullname) + 1);
12940 /* NB: stalloc will return space pointed by fullname
12941 * (because we don't have any intervening allocations
12942 * between stunalloc above and this stalloc) */
12943 readcmdfile(fullname);
12944 cmdp = cmdlookup(name, 0);
12945 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12946 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12947 stunalloc(fullname);
12950 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12952 entry->cmdtype = CMDNORMAL;
12953 entry->u.index = idx;
12957 cmdp = cmdlookup(name, 1);
12958 cmdp->cmdtype = CMDNORMAL;
12959 cmdp->param.index = idx;
12964 /* We failed. If there was an entry for this command, delete it */
12965 if (cmdp && updatetbl)
12966 delete_cmd_entry();
12968 ash_msg("%s: %s", name, errmsg(e, "not found"));
12969 entry->cmdtype = CMDUNKNOWN;
12974 entry->cmdtype = CMDBUILTIN;
12975 entry->u.cmd = bcmd;
12979 cmdp = cmdlookup(name, 1);
12980 cmdp->cmdtype = CMDBUILTIN;
12981 cmdp->param.cmd = bcmd;
12985 entry->cmdtype = cmdp->cmdtype;
12986 entry->u = cmdp->param;
12991 * The trap builtin.
12993 static int FAST_FUNC
12994 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12998 int signo, exitcode;
13003 for (signo = 0; signo < NSIG; signo++) {
13004 char *tr = trap_ptr[signo];
13006 /* note: bash adds "SIG", but only if invoked
13007 * as "bash". If called as "sh", or if set -o posix,
13008 * then it prints short signal names.
13009 * We are printing short names: */
13010 out1fmt("trap -- %s %s\n",
13012 get_signame(signo));
13013 /* trap_ptr != trap only if we are in special-cased `trap` code.
13014 * In this case, we will exit very soon, no need to free(). */
13015 /* if (trap_ptr != trap && tp[0]) */
13020 if (trap_ptr != trap) {
13028 /* Why the second check?
13029 * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
13030 * In this case, NUM is signal no, not an action.
13033 if (ap[1] && !is_number(ap[0]))
13038 signo = get_signum(*ap);
13040 /* Mimic bash message exactly */
13041 ash_msg("%s: invalid signal specification", *ap);
13047 if (LONE_DASH(action))
13050 if (action[0]) /* not NULL and not "" and not "-" */
13051 may_have_traps = 1;
13052 action = ckstrdup(action);
13056 trap[signo] = action;
13067 /* ============ Builtins */
13069 #if ENABLE_ASH_HELP
13070 static int FAST_FUNC
13071 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13077 "Built-in commands:\n"
13078 "------------------\n");
13079 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
13080 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
13081 builtintab[i].name + 1);
13087 # if ENABLE_FEATURE_SH_STANDALONE
13089 const char *a = applet_names;
13091 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
13096 while (*a++ != '\0')
13101 newline_and_flush(stdout);
13102 return EXIT_SUCCESS;
13107 static int FAST_FUNC
13108 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13110 show_history(line_input_state);
13111 return EXIT_SUCCESS;
13116 * The export and readonly commands.
13118 static int FAST_FUNC
13119 exportcmd(int argc UNUSED_PARAM, char **argv)
13129 /* "readonly" in bash accepts, but ignores -n.
13130 * We do the same: it saves a conditional in nextopt's param.
13133 while ((opt = nextopt("np")) != '\0') {
13135 flag_off = VEXPORT;
13138 if (argv[0][0] == 'r') {
13140 flag_off = 0; /* readonly ignores -n */
13142 flag_off = ~flag_off;
13144 /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
13150 p = strchr(name, '=');
13154 vp = *findvar(hashvar(name), name);
13156 vp->flags = ((vp->flags | flag) & flag_off);
13160 setvar(name, p, (flag & flag_off));
13161 } while ((name = *++aptr) != NULL);
13166 /* No arguments. Show the list of exported or readonly vars.
13169 showvars(argv[0], flag, 0);
13174 * Delete a function if it exists.
13177 unsetfunc(const char *name)
13179 struct tblentry *cmdp;
13181 cmdp = cmdlookup(name, 0);
13182 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
13183 delete_cmd_entry();
13187 * The unset builtin command. We unset the function before we unset the
13188 * variable to allow a function to be unset when there is a readonly variable
13189 * with the same name.
13191 static int FAST_FUNC
13192 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13198 while ((i = nextopt("vf")) != 0) {
13202 for (ap = argptr; *ap; ap++) {
13213 static const unsigned char timescmd_str[] ALIGN1 = {
13214 ' ', offsetof(struct tms, tms_utime),
13215 '\n', offsetof(struct tms, tms_stime),
13216 ' ', offsetof(struct tms, tms_cutime),
13217 '\n', offsetof(struct tms, tms_cstime),
13220 static int FAST_FUNC
13221 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13223 unsigned long clk_tck, s, t;
13224 const unsigned char *p;
13227 clk_tck = bb_clk_tck();
13232 t = *(clock_t *)(((char *) &buf) + p[1]);
13235 out1fmt("%lum%lu.%03lus%c",
13237 (t * 1000) / clk_tck,
13245 #if ENABLE_FEATURE_SH_MATH
13247 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13248 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13250 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13252 static int FAST_FUNC
13253 letcmd(int argc UNUSED_PARAM, char **argv)
13259 ash_msg_and_raise_error("expression expected");
13261 i = ash_arith(*argv);
13269 * The read builtin. Options:
13270 * -r Do not interpret '\' specially
13271 * -s Turn off echo (tty only)
13272 * -n NCHARS Read NCHARS max
13273 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13274 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13275 * -u FD Read from given FD instead of fd 0
13276 * This uses unbuffered input, which may be avoidable in some cases.
13277 * TODO: bash also has:
13278 * -a ARRAY Read into array[0],[1],etc
13279 * -d DELIM End on DELIM char, not newline
13280 * -e Use line editing (tty only)
13282 static int FAST_FUNC
13283 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13285 char *opt_n = NULL;
13286 char *opt_p = NULL;
13287 char *opt_t = NULL;
13288 char *opt_u = NULL;
13289 int read_flags = 0;
13293 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
13302 read_flags |= BUILTIN_READ_SILENT;
13308 read_flags |= BUILTIN_READ_RAW;
13318 /* "read -s" needs to save/restore termios, can't allow ^C
13319 * to jump out of it.
13323 r = shell_builtin_read(setvar0,
13325 bltinlookup("IFS"), /* can be NULL */
13334 if ((uintptr_t)r == 1 && errno == EINTR) {
13335 /* to get SIGCHLD: sleep 1 & read x; echo $x */
13336 if (pending_sig == 0)
13340 if ((uintptr_t)r > 1)
13341 ash_msg_and_raise_error(r);
13343 return (uintptr_t)r;
13346 static int FAST_FUNC
13347 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13349 static const char permuser[3] ALIGN1 = "ogu";
13352 int symbolic_mode = 0;
13354 while (nextopt("S") != '\0') {
13363 if (*argptr == NULL) {
13364 if (symbolic_mode) {
13365 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13372 *p++ = permuser[i];
13374 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13375 if (!(mask & 0400)) *p++ = 'r';
13376 if (!(mask & 0200)) *p++ = 'w';
13377 if (!(mask & 0100)) *p++ = 'x';
13385 out1fmt("%04o\n", mask);
13388 char *modestr = *argptr;
13389 /* numeric umasks are taken as-is */
13390 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13391 if (!isdigit(modestr[0]))
13393 mask = bb_parse_mode(modestr, mask);
13394 if ((unsigned)mask > 0777) {
13395 ash_msg_and_raise_error("illegal mode: %s", modestr);
13397 if (!isdigit(modestr[0]))
13404 static int FAST_FUNC
13405 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13407 return shell_builtin_ulimit(argv);
13410 /* ============ main() and helpers */
13413 * Called to exit the shell.
13422 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13423 save_history(line_input_state);
13425 status = exitstatus;
13426 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13427 if (setjmp(loc.loc)) {
13428 if (exception_type == EXEXIT)
13429 status = exitstatus;
13432 exception_handler = &loc;
13438 /*free(p); - we'll exit soon */
13441 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13442 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13445 flush_stdout_stderr();
13453 /* we will never free this */
13454 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13456 sigmode[SIGCHLD - 1] = S_DFL;
13457 setsignal(SIGCHLD);
13459 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13460 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13462 signal(SIGHUP, SIG_DFL);
13467 struct stat st1, st2;
13470 for (envp = environ; envp && *envp; envp++) {
13471 p = endofname(*envp);
13472 if (p != *envp && *p == '=') {
13473 setvareq(*envp, VEXPORT|VTEXTFIXED);
13477 setvareq((char*)defoptindvar, VTEXTFIXED);
13479 setvar0("PPID", utoa(getppid()));
13481 p = lookupvar("SHLVL");
13482 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13484 #if BASH_HOSTNAME_VAR
13485 if (!lookupvar("HOSTNAME")) {
13486 struct utsname uts;
13488 setvar0("HOSTNAME", uts.nodename);
13491 p = lookupvar("PWD");
13493 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13494 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13504 //usage:#define ash_trivial_usage
13505 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13506 //usage:#define ash_full_usage "\n\n"
13507 //usage: "Unix shell interpreter"
13510 * Process the shell command line arguments.
13513 procargs(char **argv)
13516 const char *xminusc;
13521 /* if (xargv[0]) - mmm, this is always true! */
13523 for (i = 0; i < NOPTS; i++)
13526 if (options(/*cmdline:*/ 1)) {
13527 /* it already printed err message */
13528 raise_exception(EXERROR);
13532 if (*xargv == NULL) {
13534 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13537 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13541 for (i = 0; i < NOPTS; i++)
13542 if (optlist[i] == 2)
13547 /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
13552 } else if (!sflag) {
13553 setinputfile(*xargv, 0);
13556 commandname = arg0;
13559 shellparam.p = xargv;
13560 #if ENABLE_ASH_GETOPTS
13561 shellparam.optind = 1;
13562 shellparam.optoff = -1;
13564 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13566 shellparam.nparam++;
13573 * Read /etc/profile, ~/.profile, $ENV.
13576 read_profile(const char *name)
13578 name = expandstr(name, DQSYNTAX);
13579 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13586 * This routine is called when an error or an interrupt occurs in an
13587 * interactive shell and control is returned to the main command loop.
13588 * (In dash, this function is auto-generated by build machinery).
13597 /* from expand.c: */
13600 /* from input.c: */
13601 g_parsefile->left_in_buffer = 0;
13602 g_parsefile->left_in_line = 0; /* clear input buffer */
13605 /* from redir.c: */
13609 unwindlocalvars(NULL);
13613 static short profile_buf[16384];
13614 extern int etext();
13618 * Main routine. We initialize things, parse the arguments, execute
13619 * profiles if we're a login shell, and then call cmdloop to execute
13620 * commands. The setjmp call sets up the location to jump to when an
13621 * exception occurs. When an exception occurs the variable "state"
13622 * is used to figure out how far we had gotten.
13624 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13625 int ash_main(int argc UNUSED_PARAM, char **argv)
13627 volatile smallint state;
13628 struct jmploc jmploc;
13629 struct stackmark smark;
13631 /* Initialize global data */
13635 #if ENABLE_ASH_ALIAS
13641 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13644 #if ENABLE_FEATURE_EDITING
13645 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13648 if (setjmp(jmploc.loc)) {
13654 e = exception_type;
13656 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13660 newline_and_flush(stderr);
13663 popstackmark(&smark);
13664 FORCE_INT_ON; /* enable interrupts */
13673 exception_handler = &jmploc;
13674 rootpid = getpid();
13677 setstackmark(&smark);
13680 TRACE(("Shell args: "));
13681 trace_puts_args(argv);
13684 if (argv[0] && argv[0][0] == '-')
13690 read_profile("/etc/profile");
13693 hp = lookupvar("HOME");
13695 read_profile("$HOME/.profile");
13701 getuid() == geteuid() && getgid() == getegid() &&
13705 const char *shinit = lookupvar("ENV");
13706 if (shinit != NULL && *shinit != '\0')
13707 read_profile(shinit);
13709 popstackmark(&smark);
13713 /* evalstring pushes parsefile stack.
13714 * Ensure we don't falsely claim that 0 (stdin)
13715 * is one of stacked source fds.
13716 * Testcase: ash -c 'exec 1>&0' must not complain. */
13717 // if (!sflag) g_parsefile->pf_fd = -1;
13718 // ^^ not necessary since now we special-case fd 0
13719 // in is_hidden_fd() to not be considered "hidden fd"
13720 evalstring(minusc, sflag ? 0 : EV_EXIT);
13723 if (sflag || minusc == NULL) {
13724 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13726 const char *hp = lookupvar("HISTFILE");
13728 hp = lookupvar("HOME");
13731 hp = concat_path_file(hp, ".ash_history");
13732 setvar0("HISTFILE", hp);
13735 hp = lookupvar("HISTFILE");
13739 line_input_state->hist_file = hp;
13740 # if ENABLE_FEATURE_SH_HISTFILESIZE
13741 hp = lookupvar("HISTFILESIZE");
13742 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13746 state4: /* XXX ??? - why isn't this before the "if" statement */
13754 extern void _mcleanup(void);
13758 TRACE(("End of main reached\n"));
13765 * Copyright (c) 1989, 1991, 1993, 1994
13766 * The Regents of the University of California. All rights reserved.
13768 * This code is derived from software contributed to Berkeley by
13769 * Kenneth Almquist.
13771 * Redistribution and use in source and binary forms, with or without
13772 * modification, are permitted provided that the following conditions
13774 * 1. Redistributions of source code must retain the above copyright
13775 * notice, this list of conditions and the following disclaimer.
13776 * 2. Redistributions in binary form must reproduce the above copyright
13777 * notice, this list of conditions and the following disclaimer in the
13778 * documentation and/or other materials provided with the distribution.
13779 * 3. Neither the name of the University nor the names of its contributors
13780 * may be used to endorse or promote products derived from this software
13781 * without specific prior written permission.
13783 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13784 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13785 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13786 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13787 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13788 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13789 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13790 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13791 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13792 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF