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;
5445 if (flags & REDIR_PUSH) {
5446 union node *tmp = redir;
5449 #if BASH_REDIR_OUTPUT
5450 if (tmp->nfile.type == NTO2)
5453 tmp = tmp->nfile.next;
5455 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5456 sv->next = redirlist;
5457 sv->pair_count = sv_pos;
5459 while (sv_pos > 0) {
5461 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5467 fd = redir->nfile.fd;
5468 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5469 right_fd = redir->ndup.dupfd;
5470 //bb_error_msg("doing %d > %d", fd, right_fd);
5471 /* redirect from/to same file descriptor? */
5474 /* "echo >&10" and 10 is a fd opened to a sh script? */
5475 if (is_hidden_fd(sv, right_fd)) {
5476 errno = EBADF; /* as if it is closed */
5477 ash_msg_and_raise_perror("%d", right_fd);
5481 newfd = openredirect(redir); /* always >= 0 */
5483 /* Descriptor wasn't open before redirect.
5484 * Mark it for close in the future */
5485 if (need_to_remember(sv, fd)) {
5486 goto remember_to_close;
5491 #if BASH_REDIR_OUTPUT
5494 if (need_to_remember(sv, fd)) {
5495 /* Copy old descriptor */
5496 /* Careful to not accidentally "save"
5497 * to the same fd as right side fd in N>&M */
5498 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5499 #if defined(F_DUPFD_CLOEXEC)
5500 i = fcntl(fd, F_DUPFD_CLOEXEC, minfd);
5502 i = fcntl(fd, F_DUPFD, minfd);
5507 /* Strange error (e.g. "too many files" EMFILE?) */
5511 ash_msg_and_raise_perror("%d", fd);
5514 /* EBADF: it is not open - good, remember to close it */
5517 } else { /* fd is open, save its copy */
5518 #if !defined(F_DUPFD_CLOEXEC)
5519 fcntl(i, F_SETFD, FD_CLOEXEC);
5521 /* "exec fd>&-" should not close fds
5522 * which point to script file(s).
5523 * Force them to be restored afterwards */
5524 if (is_hidden_fd(sv, fd))
5525 i |= COPYFD_RESTORE;
5529 sv->two_fd[sv_pos].orig = fd;
5530 sv->two_fd[sv_pos].copy = i;
5534 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5535 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5536 /* Don't want to trigger debugging */
5540 dup2_or_raise(redir->ndup.dupfd, fd);
5542 } else if (fd != newfd) { /* move newfd to fd */
5543 dup2_or_raise(newfd, fd);
5544 #if BASH_REDIR_OUTPUT
5545 if (!(redir->nfile.type == NTO2 && fd == 2))
5549 #if BASH_REDIR_OUTPUT
5550 if (redir->nfile.type == NTO2 && fd == 1) {
5551 /* We already redirected it to fd 1, now copy it to 2 */
5557 } while ((redir = redir->nfile.next) != NULL);
5560 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5561 preverrout_fd = copied_fd2;
5565 redirectsafe(union node *redir, int flags)
5568 volatile int saveint;
5569 struct jmploc *volatile savehandler = exception_handler;
5570 struct jmploc jmploc;
5573 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5574 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5576 exception_handler = &jmploc;
5577 redirect(redir, flags);
5579 exception_handler = savehandler;
5580 if (err && exception_type != EXERROR)
5581 longjmp(exception_handler->loc, 1);
5582 RESTORE_INT(saveint);
5587 * Undo the effects of the last redirection.
5590 popredir(int drop, int restore)
5592 struct redirtab *rp;
5595 if (redirlist == NULL)
5599 for (i = 0; i < rp->pair_count; i++) {
5600 int fd = rp->two_fd[i].orig;
5601 int copy = rp->two_fd[i].copy;
5602 if (copy == CLOSED) {
5607 if (copy != EMPTY) {
5608 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5609 copy &= ~COPYFD_RESTORE;
5611 dup2_or_raise(copy, fd);
5613 close(copy & ~COPYFD_RESTORE);
5616 redirlist = rp->next;
5622 /* ============ Routines to expand arguments to commands
5624 * We have to deal with backquotes, shell variables, and file metacharacters.
5627 #if ENABLE_FEATURE_SH_MATH
5629 ash_arith(const char *s)
5631 arith_state_t math_state;
5634 math_state.lookupvar = lookupvar;
5635 math_state.setvar = setvar0;
5636 //math_state.endofname = endofname;
5639 result = arith(&math_state, s);
5640 if (math_state.errmsg)
5641 ash_msg_and_raise_error(math_state.errmsg);
5651 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5652 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5653 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5654 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5655 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5656 * POSIX says for this case:
5657 * Pathname expansion shall not be performed on the word by a
5658 * non-interactive shell; an interactive shell may perform it, but shall
5659 * do so only when the expansion would result in one word.
5660 * Currently, our code complies to the above rule by never globbing
5661 * redirection filenames.
5662 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5663 * (this means that on a typical Linux distro, bash almost always
5664 * performs globbing, and thus diverges from what we do).
5666 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5667 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5668 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5669 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5670 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5674 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5675 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5676 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5677 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5678 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5680 /* Add CTLESC when necessary. */
5681 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT)
5682 /* Do not skip NUL characters. */
5683 #define QUOTES_KEEPNUL EXP_TILDE
5686 * Structure specifying which parts of the string should be searched
5687 * for IFS characters.
5690 struct ifsregion *next; /* next region in list */
5691 int begoff; /* offset of start of region */
5692 int endoff; /* offset of end of region */
5693 int nulonly; /* search for nul bytes only */
5697 struct strlist *list;
5698 struct strlist **lastp;
5701 /* output of current string */
5702 static char *expdest;
5703 /* list of back quote expressions */
5704 static struct nodelist *argbackq;
5705 /* first struct in list of ifs regions */
5706 static struct ifsregion ifsfirst;
5707 /* last struct in list */
5708 static struct ifsregion *ifslastp;
5709 /* holds expanded arg list */
5710 static struct arglist exparg;
5714 * cvtnum() is used even if math support is off (to prepare $? values and such).
5721 /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
5722 len = sizeof(arith_t) * 3;
5723 /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
5724 if (sizeof(arith_t) < 4) len += 2;
5726 expdest = makestrspace(len, expdest);
5727 len = fmtstr(expdest, len, ARITH_FMT, num);
5728 STADJUST(len, expdest);
5733 * Break the argument string into pieces based upon IFS and add the
5734 * strings to the argument list. The regions of the string to be
5735 * searched for IFS characters have been stored by recordregion.
5738 ifsbreakup(char *string, struct arglist *arglist)
5740 struct ifsregion *ifsp;
5745 const char *ifs, *realifs;
5750 if (ifslastp != NULL) {
5753 realifs = ifsset() ? ifsval() : defifs;
5756 p = string + ifsp->begoff;
5757 nulonly = ifsp->nulonly;
5758 ifs = nulonly ? nullstr : realifs;
5760 while (p < string + ifsp->endoff) {
5762 if ((unsigned char)*p == CTLESC)
5764 if (!strchr(ifs, *p)) {
5769 ifsspc = (strchr(defifs, *p) != NULL);
5770 /* Ignore IFS whitespace at start */
5771 if (q == start && ifsspc) {
5777 sp = stzalloc(sizeof(*sp));
5779 *arglist->lastp = sp;
5780 arglist->lastp = &sp->next;
5784 if (p >= string + ifsp->endoff) {
5788 if ((unsigned char)*p == CTLESC)
5790 if (strchr(ifs, *p) == NULL) {
5794 if (strchr(defifs, *p) == NULL) {
5809 } while (ifsp != NULL);
5818 sp = stzalloc(sizeof(*sp));
5820 *arglist->lastp = sp;
5821 arglist->lastp = &sp->next;
5827 struct ifsregion *p = ifsfirst.next;
5834 struct ifsregion *ifsp;
5839 ifsfirst.next = NULL;
5846 esclen(const char *start, const char *p)
5850 while (p > start && (unsigned char)*--p == CTLESC) {
5857 * Remove any CTLESC characters from a string.
5860 rmescapes(char *str, int flag)
5862 static const char qchars[] ALIGN1 = {
5863 IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
5867 unsigned protect_against_glob;
5869 IF_BASH_PATTERN_SUBST(unsigned slash = flag & RMESCAPE_SLASH;)
5871 p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash));
5877 if (flag & RMESCAPE_ALLOC) {
5878 size_t len = p - str;
5879 size_t fulllen = len + strlen(p) + 1;
5881 if (flag & RMESCAPE_GROW) {
5882 int strloc = str - (char *)stackblock();
5883 r = makestrspace(fulllen, expdest);
5884 /* p and str may be invalidated by makestrspace */
5885 str = (char *)stackblock() + strloc;
5887 } else if (flag & RMESCAPE_HEAP) {
5888 r = ckmalloc(fulllen);
5890 r = stalloc(fulllen);
5894 q = (char *)mempcpy(q, str, len);
5899 globbing = flag & RMESCAPE_GLOB;
5900 protect_against_glob = globbing;
5902 if ((unsigned char)*p == CTLQUOTEMARK) {
5903 // Note: both inquotes and protect_against_glob only affect whether
5904 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5905 inquotes = ~inquotes;
5907 protect_against_glob = globbing;
5910 if ((unsigned char)*p == CTLESC) {
5914 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5916 if (protect_against_glob) {
5918 * We used to trust glob() and fnmatch() to eat
5919 * superfluous escapes (\z where z has no
5920 * special meaning anyway). But this causes
5921 * bugs such as string of one greek letter rho
5922 * (unicode-encoded as two bytes "cf,81")
5923 * getting encoded as "cf,CTLESC,81"
5924 * and here, converted to "cf,\,81" -
5925 * which does not go well with some flavors
5926 * of fnmatch() in unicode locales
5927 * (for example, glibc <= 2.22).
5929 * Lets add "\" only on the chars which need it.
5930 * Testcases for less obvious chars are shown.
5935 || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
5936 || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
5937 || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
5938 || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
5939 /* Some libc support [^negate], that's why "^" also needs love */
5940 || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
5945 } else if (*p == '\\' && !inquotes) {
5946 /* naked back slash */
5947 protect_against_glob = 0;
5950 #if BASH_PATTERN_SUBST
5951 else if (*p == '/' && slash) {
5952 /* stop handling globbing and mark location of slash */
5953 globbing = slash = 0;
5957 protect_against_glob = globbing;
5962 if (flag & RMESCAPE_GROW) {
5964 STADJUST(q - r + 1, expdest);
5968 #define pmatch(a, b) !fnmatch((a), (b), 0)
5971 * Prepare a pattern for a expmeta (internal glob(3)) call.
5973 * Returns an stalloced string.
5976 preglob(const char *pattern, int flag)
5978 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5982 * Put a string on the stack.
5985 memtodest(const char *p, size_t len, int syntax, int quotes)
5992 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
5995 unsigned char c = *p++;
5997 if (quotes & QUOTES_ESC) {
5998 int n = SIT(c, syntax);
6000 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
6007 } else if (!(quotes & QUOTES_KEEPNUL))
6016 strtodest(const char *p, int syntax, int quotes)
6018 size_t len = strlen(p);
6019 memtodest(p, len, syntax, quotes);
6024 * Record the fact that we have to scan this region of the
6025 * string for IFS characters.
6028 recordregion(int start, int end, int nulonly)
6030 struct ifsregion *ifsp;
6032 if (ifslastp == NULL) {
6036 ifsp = ckzalloc(sizeof(*ifsp));
6037 /*ifsp->next = NULL; - ckzalloc did it */
6038 ifslastp->next = ifsp;
6042 ifslastp->begoff = start;
6043 ifslastp->endoff = end;
6044 ifslastp->nulonly = nulonly;
6048 removerecordregions(int endoff)
6050 if (ifslastp == NULL)
6053 if (ifsfirst.endoff > endoff) {
6054 while (ifsfirst.next) {
6055 struct ifsregion *ifsp;
6057 ifsp = ifsfirst.next->next;
6058 free(ifsfirst.next);
6059 ifsfirst.next = ifsp;
6062 if (ifsfirst.begoff > endoff) {
6065 ifslastp = &ifsfirst;
6066 ifsfirst.endoff = endoff;
6071 ifslastp = &ifsfirst;
6072 while (ifslastp->next && ifslastp->next->begoff < endoff)
6073 ifslastp = ifslastp->next;
6074 while (ifslastp->next) {
6075 struct ifsregion *ifsp;
6077 ifsp = ifslastp->next->next;
6078 free(ifslastp->next);
6079 ifslastp->next = ifsp;
6082 if (ifslastp->endoff > endoff)
6083 ifslastp->endoff = endoff;
6087 exptilde(char *startp, char *p, int flags)
6093 int quotes = flags & QUOTES_ESC;
6097 while ((c = *++p) != '\0') {
6104 if (flags & EXP_VARTILDE)
6114 if (*name == '\0') {
6115 home = lookupvar("HOME");
6117 pw = getpwnam(name);
6122 if (!home || !*home)
6125 strtodest(home, SQSYNTAX, quotes);
6133 * Execute a command inside back quotes. If it's a builtin command, we
6134 * want to save its output in a block obtained from malloc. Otherwise
6135 * we fork off a subprocess and get the output of the command via a pipe.
6136 * Should be called with interrupts off.
6138 struct backcmd { /* result of evalbackcmd */
6139 int fd; /* file descriptor to read from */
6140 int nleft; /* number of chars in buffer */
6141 char *buf; /* buffer */
6142 struct job *jp; /* job structure for command */
6145 /* These forward decls are needed to use "eval" code for backticks handling: */
6146 /* flags in argument to evaltree */
6147 #define EV_EXIT 01 /* exit after evaluating tree */
6148 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
6149 static int evaltree(union node *, int);
6151 /* An evaltree() which is known to never return.
6152 * Used to use an alias:
6153 * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
6154 * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
6156 static ALWAYS_INLINE NORETURN void
6157 evaltreenr(union node *n, int flags)
6160 bb_unreachable(abort());
6164 static void FAST_FUNC
6165 evalbackcmd(union node *n, struct backcmd *result)
6179 ash_msg_and_raise_error("pipe call failed");
6180 jp = makejob(/*n,*/ 1);
6181 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6187 dup2_or_raise(pip[1], 1);
6190 /* TODO: eflag clearing makes the following not abort:
6191 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6192 * which is what bash does (unless it is in POSIX mode).
6193 * dash deleted "eflag = 0" line in the commit
6194 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6195 * [EVAL] Don't clear eflag in evalbackcmd
6196 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6200 evaltreenr(n, EV_EXIT);
6205 result->fd = pip[0];
6209 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6210 result->fd, result->buf, result->nleft, result->jp));
6214 * Expand stuff in backwards quotes.
6217 expbackq(union node *cmd, int flag)
6225 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6226 struct stackmark smark;
6229 startloc = expdest - (char *)stackblock();
6230 pushstackmark(&smark, startloc);
6231 evalbackcmd(cmd, &in);
6232 popstackmark(&smark);
6239 memtodest(p, i, syntax, flag & QUOTES_ESC);
6243 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6244 TRACE(("expbackq: read returns %d\n", i));
6253 back_exitstatus = waitforjob(in.jp);
6257 /* Eat all trailing newlines */
6259 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6263 if (!(flag & EXP_QUOTED))
6264 recordregion(startloc, dest - (char *)stackblock(), 0);
6265 TRACE(("evalbackq: size:%d:'%.*s'\n",
6266 (int)((dest - (char *)stackblock()) - startloc),
6267 (int)((dest - (char *)stackblock()) - startloc),
6268 stackblock() + startloc));
6271 #if ENABLE_FEATURE_SH_MATH
6273 * Expand arithmetic expression. Backup to start of expression,
6274 * evaluate, place result in (backed up) result, adjust string position.
6286 * This routine is slightly over-complicated for
6287 * efficiency. Next we scan backwards looking for the
6288 * start of arithmetic.
6290 start = stackblock();
6297 while ((unsigned char)*p != CTLARI) {
6301 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6306 esc = esclen(start, p);
6316 removerecordregions(begoff);
6320 if (flag & QUOTES_ESC)
6321 rmescapes(p + 1, 0);
6323 len = cvtnum(ash_arith(p + 1));
6325 if (!(flag & EXP_QUOTED))
6326 recordregion(begoff, begoff + len, 0);
6330 /* argstr needs it */
6331 static char *evalvar(char *p, int flags);
6334 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6335 * characters to allow for further processing. Otherwise treat
6336 * $@ like $* since no splitting will be performed.
6339 argstr(char *p, int flags)
6341 static const char spclchars[] ALIGN1 = {
6349 #if ENABLE_FEATURE_SH_MATH
6354 const char *reject = spclchars;
6355 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6360 if (!(flags & EXP_VARTILDE)) {
6362 } else if (flags & EXP_VARTILDE2) {
6367 if (flags & EXP_TILDE) {
6370 flags &= ~EXP_TILDE;
6374 p = exptilde(p, q, flags);
6377 startloc = expdest - (char *)stackblock();
6381 length += strcspn(p + length, reject);
6385 IF_FEATURE_SH_MATH(|| c == CTLENDARI)
6387 /* c == '=' || c == ':' || c == CTLENDARI */
6393 expdest = stack_nputstr(p, length, expdest);
6394 newloc = expdest - (char *)stackblock();
6395 if (breakall && !inquotes && newloc > startloc) {
6396 recordregion(startloc, newloc, 0);
6407 if (flags & EXP_VARTILDE2) {
6411 flags |= EXP_VARTILDE2;
6416 * sort of a hack - expand tildes in variable
6417 * assignments (after the first '=' and after ':'s).
6426 case CTLENDVAR: /* ??? */
6429 inquotes ^= EXP_QUOTED;
6430 /* "$@" syntax adherence hack */
6431 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6432 p = evalvar(p + 1, flags | inquotes) + 1;
6436 if (flags & QUOTES_ESC) {
6447 * Quoted parameter expansion pattern: remove quote
6448 * unless inside inner quotes or we have a literal
6451 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6452 EXP_QPAT && *p != '\\')
6457 TRACE(("argstr: evalvar('%s')\n", p));
6458 p = evalvar(p, flags | inquotes);
6459 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6462 expbackq(argbackq->n, flags | inquotes);
6463 argbackq = argbackq->next;
6465 #if ENABLE_FEATURE_SH_MATH
6468 expari(flags | inquotes);
6477 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6478 char *pattern, int quotes, int zero)
6487 const char *s = loc2;
6494 match = pmatch(pattern, s);
6499 if (quotes && (unsigned char)*loc == CTLESC)
6508 scanright(char *startp, char *rmesc, char *rmescend,
6509 char *pattern, int quotes, int match_at_start)
6511 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6512 int try2optimize = match_at_start;
6518 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6519 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6520 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6522 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6523 * and on each iteration they go back two/one char until they reach the beginning.
6524 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6526 /* TODO: document in what other circumstances we are called. */
6528 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6531 const char *s = loc2;
6532 if (match_at_start) {
6536 match = pmatch(pattern, s);
6537 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6541 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6543 /* Maybe we can optimize this:
6544 * if pattern ends with unescaped *, we can avoid checking
6545 * shorter strings: if "foo*" doesn't match "raw_value_of_v",
6546 * it won't match truncated "raw_value_of_" strings too.
6548 unsigned plen = strlen(pattern);
6549 /* Does it end with "*"? */
6550 if (plen != 0 && pattern[--plen] == '*') {
6551 /* "xxxx*" is not escaped */
6552 /* "xxx\*" is escaped */
6553 /* "xx\\*" is not escaped */
6554 /* "x\\\*" is escaped */
6556 while (plen != 0 && pattern[--plen] == '\\')
6559 break; /* ends with unescaped "*" */
6567 esc = esclen(startp, loc);
6578 static void varunset(const char *, const char *, const char *, int) NORETURN;
6580 varunset(const char *end, const char *var, const char *umsg, int varflags)
6586 msg = "parameter not set";
6588 if ((unsigned char)*end == CTLENDVAR) {
6589 if (varflags & VSNUL)
6595 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6599 subevalvar(char *p, char *varname, int strloc, int subtype,
6600 int startloc, int varflags, int flag)
6602 struct nodelist *saveargbackq = argbackq;
6603 int quotes = flag & QUOTES_ESC;
6606 char *rmesc, *rmescend;
6608 int amount, resetloc;
6609 IF_BASH_PATTERN_SUBST(int workloc;)
6610 IF_BASH_PATTERN_SUBST(char *repl = NULL;)
6612 char *(*scan)(char*, char*, char*, char*, int, int);
6614 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6615 // p, varname, strloc, subtype, startloc, varflags, quotes);
6617 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6618 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0)
6620 STPUTC('\0', expdest);
6621 argbackq = saveargbackq;
6622 startp = (char *)stackblock() + startloc;
6626 setvar0(varname, startp);
6627 amount = startp - expdest;
6628 STADJUST(amount, expdest);
6632 varunset(p, varname, startp, varflags);
6637 int pos, len, orig_len;
6640 loc = str = stackblock() + strloc;
6642 # if !ENABLE_FEATURE_SH_MATH
6643 # define ash_arith number
6645 /* Read POS in ${var:POS:LEN} */
6646 colon = strchr(loc, ':');
6647 if (colon) *colon = '\0';
6648 pos = ash_arith(loc);
6649 if (colon) *colon = ':';
6651 /* Read LEN in ${var:POS:LEN} */
6652 len = str - startp - 1;
6653 /* *loc != '\0', guaranteed by parser */
6657 /* Adjust the length by the number of escapes */
6658 for (ptr = startp; ptr < (str - 1); ptr++) {
6659 if ((unsigned char)*ptr == CTLESC) {
6666 if (*loc++ == ':') {
6668 len = ash_arith(loc);
6670 /* Skip POS in ${var:POS:LEN} */
6672 while (*loc && *loc != ':') {
6675 if (*loc++ == ':') {
6676 len = ash_arith(loc);
6682 /* ${VAR:$((-n)):l} starts n chars from the end */
6683 pos = orig_len + pos;
6685 if ((unsigned)pos >= orig_len) {
6686 /* apart from obvious ${VAR:999999:l},
6687 * covers ${VAR:$((-9999999)):l} - result is ""
6694 /* ${VAR:N:-M} sets LEN to strlen()-M */
6695 len = (orig_len - pos) + len;
6697 if ((unsigned)len > (orig_len - pos))
6698 len = orig_len - pos;
6700 for (str = startp; pos; str++, pos--) {
6701 if (quotes && (unsigned char)*str == CTLESC)
6704 for (loc = startp; len; len--) {
6705 if (quotes && (unsigned char)*str == CTLESC)
6710 amount = loc - expdest;
6711 STADJUST(amount, expdest);
6714 #endif /* BASH_SUBSTR */
6717 resetloc = expdest - (char *)stackblock();
6719 #if BASH_PATTERN_SUBST
6720 /* We'll comeback here if we grow the stack while handling
6721 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6722 * stack will need rebasing, and we'll need to remove our work
6728 amount = expdest - ((char *)stackblock() + resetloc);
6729 STADJUST(-amount, expdest);
6730 startp = (char *)stackblock() + startloc;
6733 rmescend = (char *)stackblock() + strloc;
6735 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6736 if (rmesc != startp) {
6738 startp = (char *)stackblock() + startloc;
6742 str = (char *)stackblock() + strloc;
6744 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6745 * The result is a_\_z_c (not a\_\_z_c)!
6747 * The search pattern and replace string treat backslashes differently!
6748 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6749 * and string. It's only used on the first call.
6751 preglob(str, IF_BASH_PATTERN_SUBST(
6752 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6753 RMESCAPE_SLASH : ) 0);
6755 #if BASH_PATTERN_SUBST
6756 workloc = expdest - (char *)stackblock();
6757 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6762 repl = strchr(str, CTLESC);
6768 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6770 /* If there's no pattern to match, return the expansion unmolested */
6779 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6780 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6782 /* No match, advance */
6783 char *restart_detect = stackblock();
6785 STPUTC(*idx, expdest);
6786 if (quotes && (unsigned char)*idx == CTLESC) {
6789 STPUTC(*idx, expdest);
6791 if (stackblock() != restart_detect)
6796 /* continue; - prone to quadratic behavior, smarter code: */
6799 if (str[0] == '*') {
6800 /* Pattern is "*foo". If "*foo" does not match "long_string",
6801 * it would never match "ong_string" etc, no point in trying.
6808 if (subtype == VSREPLACEALL) {
6810 if (quotes && (unsigned char)*idx == CTLESC)
6819 //bb_error_msg("repl:'%s'", repl);
6820 for (loc = (char*)repl; *loc; loc++) {
6821 char *restart_detect = stackblock();
6822 if (quotes && *loc == '\\') {
6823 STPUTC(CTLESC, expdest);
6826 STPUTC(*loc, expdest);
6827 if (stackblock() != restart_detect)
6832 if (subtype == VSREPLACE) {
6833 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6835 char *restart_detect = stackblock();
6836 STPUTC(*idx, expdest);
6837 if (stackblock() != restart_detect)
6846 /* We've put the replaced text into a buffer at workloc, now
6847 * move it to the right place and adjust the stack.
6849 STPUTC('\0', expdest);
6850 startp = (char *)stackblock() + startloc;
6851 memmove(startp, (char *)stackblock() + workloc, len + 1);
6852 //bb_error_msg("startp:'%s'", startp);
6853 amount = expdest - (startp + len);
6854 STADJUST(-amount, expdest);
6857 #endif /* BASH_PATTERN_SUBST */
6859 subtype -= VSTRIMRIGHT;
6861 if (subtype < 0 || subtype > 7)
6864 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6865 zero = subtype >> 1;
6866 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6867 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6869 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6872 memmove(startp, loc, str - loc);
6873 loc = startp + (str - loc) - 1;
6876 amount = loc - expdest;
6877 STADJUST(amount, expdest);
6883 * Add the value of a specialized variable to the stack string.
6884 * name parameter (examples):
6885 * ash -c 'echo $1' name:'1='
6886 * ash -c 'echo $qwe' name:'qwe='
6887 * ash -c 'echo $$' name:'$='
6888 * ash -c 'echo ${$}' name:'$='
6889 * ash -c 'echo ${$##q}' name:'$=q'
6890 * ash -c 'echo ${#$}' name:'$='
6891 * note: examples with bad shell syntax:
6892 * ash -c 'echo ${#$1}' name:'$=1'
6893 * ash -c 'echo ${#1#}' name:'1=#'
6895 static NOINLINE ssize_t
6896 varvalue(char *name, int varflags, int flags, int *quotedp)
6903 int quoted = *quotedp;
6904 int subtype = varflags & VSTYPE;
6905 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6906 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6909 sep = (flags & EXP_FULL) << CHAR_BIT;
6910 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6920 num = shellparam.nparam;
6928 goto check_1char_name;
6930 expdest = makestrspace(NOPTS, expdest);
6931 for (i = NOPTS - 1; i >= 0; i--) {
6933 USTPUTC(optletters(i), expdest);
6939 /* handles cases similar to ${#$1} */
6940 if (name[2] != '\0')
6941 raise_error_syntax("bad substitution");
6954 sep |= ifsset() ? ifsval()[0] : ' ';
6961 while ((p = *ap++) != NULL) {
6962 len += strtodest(p, syntax, quotes);
6966 memtodest(&sepc, 1, syntax, quotes);
6981 num = atoi(name); /* number(name) fails on ${N#str} etc */
6982 if (num < 0 || num > shellparam.nparam)
6984 p = num ? shellparam.p[num - 1] : arg0;
6987 /* NB: name has form "VAR=..." */
6988 p = lookupvar(name);
6993 len = strtodest(p, syntax, quotes);
6994 #if ENABLE_UNICODE_SUPPORT
6995 if (subtype == VSLENGTH && len > 0) {
6996 reinit_unicode_for_ash();
6997 if (unicode_status == UNICODE_ON) {
6998 STADJUST(-len, expdest);
7000 len = unicode_strlen(p);
7008 STADJUST(-len, expdest);
7013 * Expand a variable, and return a pointer to the next character in the
7017 evalvar(char *p, int flag)
7028 varflags = (unsigned char) *p++;
7029 subtype = varflags & VSTYPE;
7032 raise_error_syntax("bad substitution");
7034 quoted = flag & EXP_QUOTED;
7036 easy = (!quoted || (*var == '@' && shellparam.nparam));
7037 startloc = expdest - (char *)stackblock();
7038 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
7041 varlen = varvalue(var, varflags, flag, "ed);
7042 if (varflags & VSNUL)
7045 if (subtype == VSPLUS) {
7046 varlen = -1 - varlen;
7050 if (subtype == VSMINUS) {
7055 flag | EXP_TILDE | EXP_WORD
7062 if (subtype == VSASSIGN || subtype == VSQUESTION) {
7066 subevalvar(p, var, 0, subtype, startloc, varflags,
7067 flag & ~QUOTES_ESC);
7070 * Remove any recorded regions beyond
7073 removerecordregions(startloc);
7077 if (varlen < 0 && uflag)
7078 varunset(p, var, 0, 0);
7080 if (subtype == VSLENGTH) {
7081 cvtnum(varlen > 0 ? varlen : 0);
7085 if (subtype == VSNORMAL) {
7089 recordregion(startloc, expdest - (char *)stackblock(), quoted);
7098 case VSTRIMRIGHTMAX:
7102 #if BASH_PATTERN_SUBST
7114 * Terminate the string and start recording the pattern
7117 STPUTC('\0', expdest);
7118 patloc = expdest - (char *)stackblock();
7119 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
7120 startloc, varflags, flag)) {
7121 int amount = expdest - (
7122 (char *)stackblock() + patloc - 1
7124 STADJUST(-amount, expdest);
7126 /* Remove any recorded regions beyond start of variable */
7127 removerecordregions(startloc);
7132 if (subtype != VSNORMAL) { /* skip to end of alternative */
7135 unsigned char c = *p++;
7138 else if (c == CTLBACKQ) {
7140 argbackq = argbackq->next;
7141 } else if (c == CTLVAR) {
7142 if ((*p++ & VSTYPE) != VSNORMAL)
7144 } else if (c == CTLENDVAR) {
7154 * Add a file name to the list.
7157 addfname(const char *name)
7161 sp = stzalloc(sizeof(*sp));
7162 sp->text = sstrdup(name);
7164 exparg.lastp = &sp->next;
7167 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7169 hasmeta(const char *p)
7171 static const char chars[] ALIGN1 = {
7172 '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
7176 p = strpbrk(p, chars);
7179 switch ((unsigned char) *p) {
7183 if (*p == CTLQUOTEMARK)
7187 if (*p == '\0') /* huh? */
7198 if (!strchr(p + 1, ']')) {
7199 /* It's not a properly closed [] pattern,
7200 * but other metas may follow. Continue checking.
7201 * my[file* _is_ globbed by bash
7202 * and matches filenames like "my[file1".
7218 /* If we want to use glob() from libc... */
7219 #if !ENABLE_ASH_INTERNAL_GLOB
7221 /* Add the result of glob() to the list */
7223 addglob(const glob_t *pglob)
7225 char **p = pglob->gl_pathv;
7232 expandmeta(struct strlist *str /*, int flag*/)
7234 /* TODO - EXP_REDIR */
7244 if (!hasmeta(str->text))
7248 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7249 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7250 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7252 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7253 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7254 // Which means you need to unescape the string, right? Not so fast:
7255 // if there _is_ a file named "file\?" (with backslash), it is returned
7256 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7257 // You DON'T KNOW by looking at the result whether you need to unescape it.
7259 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7260 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7261 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7262 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7263 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7264 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7265 i = glob(p, 0, NULL, &pglob);
7266 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7271 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7272 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7273 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7285 *exparg.lastp = str;
7286 rmescapes(str->text, 0);
7287 exparg.lastp = &str->next;
7289 default: /* GLOB_NOSPACE */
7292 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7299 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7302 * Do metacharacter (i.e. *, ?, [...]) expansion.
7305 expmeta(char *expdir, char *enddir, char *name)
7321 for (p = name; esc = 0, *p; p += esc + 1) {
7322 if (*p == '*' || *p == '?')
7324 else if (*p == '[') {
7331 if (*q == '/' || *q == '\0')
7341 if (p[esc] == '/') {
7344 start = p + esc + 1;
7348 if (metaflag == 0) { /* we've reached the end of the file name */
7349 if (enddir != expdir)
7357 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7368 } while (p < start);
7370 if (enddir == expdir) {
7372 } else if (enddir == expdir + 1 && *expdir == '/') {
7381 if (enddir != expdir)
7383 if (*endname == 0) {
7396 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7397 if (dp->d_name[0] == '.' && !matchdot)
7399 if (pmatch(start, dp->d_name)) {
7401 strcpy(enddir, dp->d_name);
7404 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7407 expmeta(expdir, p, endname);
7413 endname[-esc - 1] = esc ? '\\' : '/';
7416 static struct strlist *
7417 msort(struct strlist *list, int len)
7419 struct strlist *p, *q = NULL;
7420 struct strlist **lpp;
7428 for (n = half; --n >= 0;) {
7432 q->next = NULL; /* terminate first half of list */
7433 q = msort(list, half); /* sort first half of list */
7434 p = msort(p, len - half); /* sort second half */
7437 #if ENABLE_LOCALE_SUPPORT
7438 if (strcoll(p->text, q->text) < 0)
7440 if (strcmp(p->text, q->text) < 0)
7464 * Sort the results of file name expansion. It calculates the number of
7465 * strings to sort and then calls msort (short for merge sort) to do the
7468 static struct strlist *
7469 expsort(struct strlist *str)
7475 for (sp = str; sp; sp = sp->next)
7477 return msort(str, len);
7481 expandmeta(struct strlist *str /*, int flag*/)
7483 /* TODO - EXP_REDIR */
7487 struct strlist **savelastp;
7493 if (!hasmeta(str->text))
7495 savelastp = exparg.lastp;
7498 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7500 int i = strlen(str->text);
7501 //BUGGY estimation of how long expanded name can be
7502 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7504 expmeta(expdir, expdir, p);
7509 if (exparg.lastp == savelastp) {
7514 *exparg.lastp = str;
7515 rmescapes(str->text, 0);
7516 exparg.lastp = &str->next;
7518 *exparg.lastp = NULL;
7519 *savelastp = sp = expsort(*savelastp);
7520 while (sp->next != NULL)
7522 exparg.lastp = &sp->next;
7527 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7530 * Perform variable substitution and command substitution on an argument,
7531 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7532 * perform splitting and file name expansion. When arglist is NULL, perform
7533 * here document expansion.
7536 expandarg(union node *arg, struct arglist *arglist, int flag)
7541 argbackq = arg->narg.backquote;
7542 STARTSTACKSTR(expdest);
7543 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7544 argstr(arg->narg.text, flag);
7545 p = _STPUTC('\0', expdest);
7547 if (arglist == NULL) {
7548 /* here document expanded */
7551 p = grabstackstr(p);
7552 TRACE(("expandarg: p:'%s'\n", p));
7553 exparg.lastp = &exparg.list;
7557 if (flag & EXP_FULL) {
7558 ifsbreakup(p, &exparg);
7559 *exparg.lastp = NULL;
7560 exparg.lastp = &exparg.list;
7561 expandmeta(exparg.list /*, flag*/);
7563 sp = stzalloc(sizeof(*sp));
7566 exparg.lastp = &sp->next;
7568 *exparg.lastp = NULL;
7570 *arglist->lastp = exparg.list;
7571 arglist->lastp = exparg.lastp;
7579 * Expand shell variables and backquotes inside a here document.
7582 expandhere(union node *arg, int fd)
7584 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7585 full_write(fd, stackblock(), expdest - (char *)stackblock());
7589 * Returns true if the pattern matches the string.
7592 patmatch(char *pattern, const char *string)
7594 char *p = preglob(pattern, 0);
7595 //bb_error_msg("fnmatch(pattern:'%s',str:'%s')", p, string);
7596 return pmatch(p, string);
7600 * See if a pattern matches in a case statement.
7603 casematch(union node *pattern, char *val)
7605 struct stackmark smark;
7608 setstackmark(&smark);
7609 argbackq = pattern->narg.backquote;
7610 STARTSTACKSTR(expdest);
7611 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
7612 STACKSTRNUL(expdest);
7614 result = patmatch(stackblock(), val);
7615 popstackmark(&smark);
7620 /* ============ find_command */
7624 int (*builtin)(int, char **) FAST_FUNC;
7625 /* unsigned flags; */
7627 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7628 /* "regular" builtins always take precedence over commands,
7629 * regardless of PATH=....%builtin... position */
7630 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7631 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7634 smallint cmdtype; /* CMDxxx */
7637 /* index >= 0 for commands without path (slashes) */
7638 /* (TODO: what exactly does the value mean? PATH position?) */
7639 /* index == -1 for commands with slashes */
7640 /* index == (-2 - applet_no) for NOFORK applets */
7641 const struct builtincmd *cmd;
7642 struct funcnode *func;
7645 /* values of cmdtype */
7646 #define CMDUNKNOWN -1 /* no entry in table for command */
7647 #define CMDNORMAL 0 /* command is an executable program */
7648 #define CMDFUNCTION 1 /* command is a shell function */
7649 #define CMDBUILTIN 2 /* command is a shell builtin */
7651 /* action to find_command() */
7652 #define DO_ERR 0x01 /* prints errors */
7653 #define DO_ABS 0x02 /* checks absolute paths */
7654 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7655 #define DO_ALTPATH 0x08 /* using alternate path */
7656 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7658 static void find_command(char *, struct cmdentry *, int, const char *);
7661 /* ============ Hashing commands */
7664 * When commands are first encountered, they are entered in a hash table.
7665 * This ensures that a full path search will not have to be done for them
7666 * on each invocation.
7668 * We should investigate converting to a linear search, even though that
7669 * would make the command name "hash" a misnomer.
7673 struct tblentry *next; /* next entry in hash chain */
7674 union param param; /* definition of builtin function */
7675 smallint cmdtype; /* CMDxxx */
7676 char rehash; /* if set, cd done since entry created */
7677 char cmdname[1]; /* name of command */
7680 static struct tblentry **cmdtable;
7681 #define INIT_G_cmdtable() do { \
7682 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7685 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7689 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
7691 #if ENABLE_FEATURE_SH_STANDALONE
7692 if (applet_no >= 0) {
7693 if (APPLET_IS_NOEXEC(applet_no)) {
7697 popredir(/*drop:*/ 1, /*restore:*/ 0);
7698 run_applet_no_and_exit(applet_no, cmd, argv);
7700 /* re-exec ourselves with the new arguments */
7701 execve(bb_busybox_exec_path, argv, envp);
7702 /* If they called chroot or otherwise made the binary no longer
7703 * executable, fall through */
7710 execve(cmd, argv, envp);
7711 } while (errno == EINTR);
7713 execve(cmd, argv, envp);
7715 if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
7716 /* Run "cmd" as a shell script:
7717 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7718 * "If the execve() function fails with ENOEXEC, the shell
7719 * shall execute a command equivalent to having a shell invoked
7720 * with the command name as its first operand,
7721 * with any remaining arguments passed to the new shell"
7723 * That is, do not use $SHELL, user's shell, or /bin/sh;
7724 * just call ourselves.
7726 * Note that bash reads ~80 chars of the file, and if it sees
7727 * a zero byte before it sees newline, it doesn't try to
7728 * interpret it, but fails with "cannot execute binary file"
7729 * message and exit code 126. For one, this prevents attempts
7730 * to interpret foreign ELF binaries as shell scripts.
7732 argv[0] = (char*) cmd;
7733 cmd = bb_busybox_exec_path;
7734 /* NB: this is only possible because all callers of shellexec()
7735 * ensure that the argv[-1] slot exists!
7738 argv[0] = (char*) "ash";
7744 * Exec a program. Never returns. If you change this routine, you may
7745 * have to change the find_command routine as well.
7746 * argv[-1] must exist and be writable! See tryexec() for why.
7748 static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
7749 static void shellexec(char *prog, char **argv, const char *path, int idx)
7755 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7757 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7758 if (strchr(prog, '/') != NULL
7759 #if ENABLE_FEATURE_SH_STANDALONE
7760 || (applet_no = find_applet_by_name(prog)) >= 0
7763 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
7764 if (applet_no >= 0) {
7765 /* We tried execing ourself, but it didn't work.
7766 * Maybe /proc/self/exe doesn't exist?
7775 while ((cmdname = path_advance(&path, prog)) != NULL) {
7776 if (--idx < 0 && pathopt == NULL) {
7777 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7778 if (errno != ENOENT && errno != ENOTDIR)
7785 /* Map to POSIX errors */
7797 exitstatus = exerrno;
7798 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7799 prog, e, suppress_int));
7800 ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
7805 printentry(struct tblentry *cmdp)
7811 idx = cmdp->param.index;
7814 name = path_advance(&path, cmdp->cmdname);
7816 } while (--idx >= 0);
7817 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7821 * Clear out command entries. The argument specifies the first entry in
7822 * PATH which has changed.
7825 clearcmdentry(int firstchange)
7827 struct tblentry **tblp;
7828 struct tblentry **pp;
7829 struct tblentry *cmdp;
7832 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7834 while ((cmdp = *pp) != NULL) {
7835 if ((cmdp->cmdtype == CMDNORMAL &&
7836 cmdp->param.index >= firstchange)
7837 || (cmdp->cmdtype == CMDBUILTIN &&
7838 builtinloc >= firstchange)
7851 * Locate a command in the command hash table. If "add" is nonzero,
7852 * add the command to the table if it is not already present. The
7853 * variable "lastcmdentry" is set to point to the address of the link
7854 * pointing to the entry, so that delete_cmd_entry can delete the
7857 * Interrupts must be off if called with add != 0.
7859 static struct tblentry **lastcmdentry;
7861 static struct tblentry *
7862 cmdlookup(const char *name, int add)
7864 unsigned int hashval;
7866 struct tblentry *cmdp;
7867 struct tblentry **pp;
7870 hashval = (unsigned char)*p << 4;
7872 hashval += (unsigned char)*p++;
7874 pp = &cmdtable[hashval % CMDTABLESIZE];
7875 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7876 if (strcmp(cmdp->cmdname, name) == 0)
7880 if (add && cmdp == NULL) {
7881 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7883 /* + 1 - already done because
7884 * tblentry::cmdname is char[1] */);
7885 /*cmdp->next = NULL; - ckzalloc did it */
7886 cmdp->cmdtype = CMDUNKNOWN;
7887 strcpy(cmdp->cmdname, name);
7894 * Delete the command entry returned on the last lookup.
7897 delete_cmd_entry(void)
7899 struct tblentry *cmdp;
7902 cmdp = *lastcmdentry;
7903 *lastcmdentry = cmdp->next;
7904 if (cmdp->cmdtype == CMDFUNCTION)
7905 freefunc(cmdp->param.func);
7911 * Add a new command entry, replacing any existing command entry for
7912 * the same name - except special builtins.
7915 addcmdentry(char *name, struct cmdentry *entry)
7917 struct tblentry *cmdp;
7919 cmdp = cmdlookup(name, 1);
7920 if (cmdp->cmdtype == CMDFUNCTION) {
7921 freefunc(cmdp->param.func);
7923 cmdp->cmdtype = entry->cmdtype;
7924 cmdp->param = entry->u;
7928 static int FAST_FUNC
7929 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7931 struct tblentry **pp;
7932 struct tblentry *cmdp;
7934 struct cmdentry entry;
7937 if (nextopt("r") != '\0') {
7942 if (*argptr == NULL) {
7943 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7944 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7945 if (cmdp->cmdtype == CMDNORMAL)
7953 while ((name = *argptr) != NULL) {
7954 cmdp = cmdlookup(name, 0);
7956 && (cmdp->cmdtype == CMDNORMAL
7957 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7961 find_command(name, &entry, DO_ERR, pathval());
7962 if (entry.cmdtype == CMDUNKNOWN)
7970 * Called when a cd is done. Marks all commands so the next time they
7971 * are executed they will be rehashed.
7976 struct tblentry **pp;
7977 struct tblentry *cmdp;
7979 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7980 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7981 if (cmdp->cmdtype == CMDNORMAL
7982 || (cmdp->cmdtype == CMDBUILTIN
7983 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7993 * Fix command hash table when PATH changed.
7994 * Called before PATH is changed. The argument is the new value of PATH;
7995 * pathval() still returns the old value at this point.
7996 * Called with interrupts off.
7998 static void FAST_FUNC
7999 changepath(const char *new)
8007 firstchange = 9999; /* assume no change */
8013 if ((*old == '\0' && *new == ':')
8014 || (*old == ':' && *new == '\0')
8018 old = new; /* ignore subsequent differences */
8022 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
8029 if (builtinloc < 0 && idx_bltin >= 0)
8030 builtinloc = idx_bltin; /* zap builtins */
8031 if (builtinloc >= 0 && idx_bltin < 0)
8033 clearcmdentry(firstchange);
8034 builtinloc = idx_bltin;
8070 typedef smallint token_id_t;
8072 /* Nth bit indicates if token marks the end of a list */
8075 /* 0 */ | (1u << TEOF)
8076 /* 1 */ | (0u << TNL)
8077 /* 2 */ | (0u << TREDIR)
8078 /* 3 */ | (0u << TWORD)
8079 /* 4 */ | (0u << TSEMI)
8080 /* 5 */ | (0u << TBACKGND)
8081 /* 6 */ | (0u << TAND)
8082 /* 7 */ | (0u << TOR)
8083 /* 8 */ | (0u << TPIPE)
8084 /* 9 */ | (0u << TLP)
8085 /* 10 */ | (1u << TRP)
8086 /* 11 */ | (1u << TENDCASE)
8087 /* 12 */ | (1u << TENDBQUOTE)
8088 /* 13 */ | (0u << TNOT)
8089 /* 14 */ | (0u << TCASE)
8090 /* 15 */ | (1u << TDO)
8091 /* 16 */ | (1u << TDONE)
8092 /* 17 */ | (1u << TELIF)
8093 /* 18 */ | (1u << TELSE)
8094 /* 19 */ | (1u << TESAC)
8095 /* 20 */ | (1u << TFI)
8096 /* 21 */ | (0u << TFOR)
8098 /* 22 */ | (0u << TFUNCTION)
8100 /* 23 */ | (0u << TIF)
8101 /* 24 */ | (0u << TIN)
8102 /* 25 */ | (1u << TTHEN)
8103 /* 26 */ | (0u << TUNTIL)
8104 /* 27 */ | (0u << TWHILE)
8105 /* 28 */ | (0u << TBEGIN)
8106 /* 29 */ | (1u << TEND)
8107 , /* thus far 29 bits used */
8110 static const char *const tokname_array[] = {
8124 #define KWDOFFSET 13
8125 /* the following are keywords */
8147 /* Wrapper around strcmp for qsort/bsearch/... */
8149 pstrcmp(const void *a, const void *b)
8151 return strcmp((char*)a, *(char**)b);
8154 static const char *const *
8155 findkwd(const char *s)
8157 return bsearch(s, tokname_array + KWDOFFSET,
8158 ARRAY_SIZE(tokname_array) - KWDOFFSET,
8159 sizeof(tokname_array[0]), pstrcmp);
8163 * Locate and print what a word is...
8166 describe_command(char *command, const char *path, int describe_command_verbose)
8168 struct cmdentry entry;
8169 #if ENABLE_ASH_ALIAS
8170 const struct alias *ap;
8173 path = path ? path : pathval();
8175 if (describe_command_verbose) {
8179 /* First look at the keywords */
8180 if (findkwd(command)) {
8181 out1str(describe_command_verbose ? " is a shell keyword" : command);
8185 #if ENABLE_ASH_ALIAS
8186 /* Then look at the aliases */
8187 ap = lookupalias(command, 0);
8189 if (!describe_command_verbose) {
8194 out1fmt(" is an alias for %s", ap->val);
8199 find_command(command, &entry, DO_ABS, path);
8201 switch (entry.cmdtype) {
8203 int j = entry.u.index;
8209 p = path_advance(&path, command);
8213 if (describe_command_verbose) {
8214 out1fmt(" is %s", p);
8222 if (describe_command_verbose) {
8223 out1str(" is a shell function");
8230 if (describe_command_verbose) {
8231 out1fmt(" is a %sshell builtin",
8232 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8233 "special " : nullstr
8241 if (describe_command_verbose) {
8242 out1str(": not found\n");
8251 static int FAST_FUNC
8252 typecmd(int argc UNUSED_PARAM, char **argv)
8258 /* type -p ... ? (we don't bother checking for 'p') */
8259 if (argv[1] && argv[1][0] == '-') {
8264 err |= describe_command(argv[i++], NULL, verbose);
8269 #if ENABLE_ASH_CMDCMD
8270 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8272 parse_command_args(char **argv, const char **path)
8285 if (c == '-' && !*cp) {
8293 *path = bb_default_path;
8296 /* run 'typecmd' for other options */
8305 static int FAST_FUNC
8306 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8314 const char *path = NULL;
8316 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8317 * never reaches this function.
8320 while ((c = nextopt("pvV")) != '\0')
8322 verify |= VERIFY_VERBOSE;
8324 /*verify |= VERIFY_BRIEF*/;
8330 path = bb_default_path;
8332 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8334 if (/*verify && */ cmd)
8335 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8342 /*static int funcblocksize; // size of structures in function */
8343 /*static int funcstringsize; // size of strings in node */
8344 static void *funcblock; /* block to allocate function from */
8345 static char *funcstring_end; /* end of block to allocate strings from */
8347 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8348 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8349 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8350 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8351 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8352 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8353 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8354 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8355 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8356 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8357 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8358 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8359 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8360 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8361 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8362 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8363 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8364 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8365 #if BASH_REDIR_OUTPUT
8366 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8368 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8369 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8370 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8371 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8372 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8373 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8374 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8375 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8376 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8379 static int calcsize(int funcblocksize, union node *n);
8382 sizenodelist(int funcblocksize, struct nodelist *lp)
8385 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8386 funcblocksize = calcsize(funcblocksize, lp->n);
8389 return funcblocksize;
8393 calcsize(int funcblocksize, union node *n)
8396 return funcblocksize;
8397 funcblocksize += nodesize[n->type];
8400 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8401 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8402 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8405 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8410 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8411 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8418 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8419 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8422 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8423 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8424 funcblocksize = calcsize(funcblocksize, n->nif.test);
8427 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8428 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8429 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8432 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8433 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8436 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8437 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8438 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8442 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8443 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8444 funcblocksize = calcsize(funcblocksize, n->narg.next);
8447 #if BASH_REDIR_OUTPUT
8454 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8455 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8459 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8460 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8464 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8465 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8468 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8471 return funcblocksize;
8475 nodeckstrdup(char *s)
8477 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8478 return strcpy(funcstring_end, s);
8481 static union node *copynode(union node *);
8483 static struct nodelist *
8484 copynodelist(struct nodelist *lp)
8486 struct nodelist *start;
8487 struct nodelist **lpp;
8492 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8493 (*lpp)->n = copynode(lp->n);
8495 lpp = &(*lpp)->next;
8502 copynode(union node *n)
8509 funcblock = (char *) funcblock + nodesize[n->type];
8513 new->ncmd.redirect = copynode(n->ncmd.redirect);
8514 new->ncmd.args = copynode(n->ncmd.args);
8515 new->ncmd.assign = copynode(n->ncmd.assign);
8518 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8519 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8524 new->nredir.redirect = copynode(n->nredir.redirect);
8525 new->nredir.n = copynode(n->nredir.n);
8532 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8533 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8536 new->nif.elsepart = copynode(n->nif.elsepart);
8537 new->nif.ifpart = copynode(n->nif.ifpart);
8538 new->nif.test = copynode(n->nif.test);
8541 new->nfor.var = nodeckstrdup(n->nfor.var);
8542 new->nfor.body = copynode(n->nfor.body);
8543 new->nfor.args = copynode(n->nfor.args);
8546 new->ncase.cases = copynode(n->ncase.cases);
8547 new->ncase.expr = copynode(n->ncase.expr);
8550 new->nclist.body = copynode(n->nclist.body);
8551 new->nclist.pattern = copynode(n->nclist.pattern);
8552 new->nclist.next = copynode(n->nclist.next);
8556 new->narg.backquote = copynodelist(n->narg.backquote);
8557 new->narg.text = nodeckstrdup(n->narg.text);
8558 new->narg.next = copynode(n->narg.next);
8561 #if BASH_REDIR_OUTPUT
8568 new->nfile.fname = copynode(n->nfile.fname);
8569 new->nfile.fd = n->nfile.fd;
8570 new->nfile.next = copynode(n->nfile.next);
8574 new->ndup.vname = copynode(n->ndup.vname);
8575 new->ndup.dupfd = n->ndup.dupfd;
8576 new->ndup.fd = n->ndup.fd;
8577 new->ndup.next = copynode(n->ndup.next);
8581 new->nhere.doc = copynode(n->nhere.doc);
8582 new->nhere.fd = n->nhere.fd;
8583 new->nhere.next = copynode(n->nhere.next);
8586 new->nnot.com = copynode(n->nnot.com);
8589 new->type = n->type;
8594 * Make a copy of a parse tree.
8596 static struct funcnode *
8597 copyfunc(union node *n)
8602 /*funcstringsize = 0;*/
8603 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8604 f = ckzalloc(blocksize /* + funcstringsize */);
8605 funcblock = (char *) f + offsetof(struct funcnode, n);
8606 funcstring_end = (char *) f + blocksize;
8608 /* f->count = 0; - ckzalloc did it */
8613 * Define a shell function.
8616 defun(union node *func)
8618 struct cmdentry entry;
8621 entry.cmdtype = CMDFUNCTION;
8622 entry.u.func = copyfunc(func);
8623 addcmdentry(func->narg.text, &entry);
8627 /* Reasons for skipping commands (see comment on breakcmd routine) */
8628 #define SKIPBREAK (1 << 0)
8629 #define SKIPCONT (1 << 1)
8630 #define SKIPFUNC (1 << 2)
8631 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8632 static int skipcount; /* number of levels to skip */
8633 static int funcnest; /* depth of function calls */
8634 static int loopnest; /* current loop nesting level */
8636 /* Forward decl way out to parsing code - dotrap needs it */
8637 static int evalstring(char *s, int flags);
8639 /* Called to execute a trap.
8640 * Single callsite - at the end of evaltree().
8641 * If we return non-zero, evaltree raises EXEXIT exception.
8643 * Perhaps we should avoid entering new trap handlers
8644 * while we are executing a trap handler. [is it a TODO?]
8651 uint8_t last_status;
8656 last_status = exitstatus;
8660 TRACE(("dotrap entered\n"));
8661 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8673 /* non-trapped SIGINT is handled separately by raise_interrupt,
8674 * don't upset it by resetting gotsig[SIGINT-1] */
8675 if (sig == SIGINT && !p)
8678 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8684 exitstatus = last_status;
8685 TRACE(("dotrap returns\n"));
8688 /* forward declarations - evaluation is fairly recursive business... */
8689 static int evalloop(union node *, int);
8690 static int evalfor(union node *, int);
8691 static int evalcase(union node *, int);
8692 static int evalsubshell(union node *, int);
8693 static void expredir(union node *);
8694 static int evalpipe(union node *, int);
8695 static int evalcommand(union node *, int);
8696 static int evalbltin(const struct builtincmd *, int, char **, int);
8697 static void prehash(union node *);
8700 * Evaluate a parse tree. The value is left in the global variable
8704 evaltree(union node *n, int flags)
8707 int (*evalfn)(union node *, int);
8711 TRACE(("evaltree(NULL) called\n"));
8714 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8721 out1fmt("Node type = %d\n", n->type);
8726 status = !evaltree(n->nnot.com, EV_TESTED);
8729 expredir(n->nredir.redirect);
8730 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8732 status = evaltree(n->nredir.n, flags & EV_TESTED);
8734 if (n->nredir.redirect)
8735 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8738 evalfn = evalcommand;
8740 if (eflag && !(flags & EV_TESTED))
8752 evalfn = evalsubshell;
8765 #error NAND + 1 != NOR
8767 #if NOR + 1 != NSEMI
8768 #error NOR + 1 != NSEMI
8770 unsigned is_or = n->type - NAND;
8773 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8775 if ((!status) == is_or || evalskip)
8781 status = evalfn(n, flags);
8785 status = evaltree(n->nif.test, EV_TESTED);
8792 if (n->nif.elsepart) {
8793 n = n->nif.elsepart;
8800 /* Not necessary. To test it:
8801 * "false; f() { qwerty; }; echo $?" should print 0.
8805 exitstatus = status;
8809 /* Order of checks below is important:
8810 * signal handlers trigger before exit caused by "set -e".
8814 if (checkexit & status)
8815 raise_exception(EXEXIT);
8816 if (flags & EV_EXIT)
8817 raise_exception(EXEXIT);
8819 TRACE(("leaving evaltree (no interrupts)\n"));
8826 int skip = evalskip;
8833 if (--skipcount <= 0) {
8844 evalloop(union node *n, int flags)
8855 i = evaltree(n->nbinary.ch1, EV_TESTED);
8857 if (skip == SKIPFUNC)
8861 if (n->type != NWHILE)
8865 status = evaltree(n->nbinary.ch2, flags);
8867 } while (!(skip & ~SKIPCONT));
8874 evalfor(union node *n, int flags)
8876 struct arglist arglist;
8879 struct stackmark smark;
8882 setstackmark(&smark);
8883 arglist.list = NULL;
8884 arglist.lastp = &arglist.list;
8885 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8886 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8888 *arglist.lastp = NULL;
8892 for (sp = arglist.list; sp; sp = sp->next) {
8893 setvar0(n->nfor.var, sp->text);
8894 status = evaltree(n->nfor.body, flags);
8895 if (skiploop() & ~SKIPCONT)
8899 popstackmark(&smark);
8905 evalcase(union node *n, int flags)
8909 struct arglist arglist;
8910 struct stackmark smark;
8913 setstackmark(&smark);
8914 arglist.list = NULL;
8915 arglist.lastp = &arglist.list;
8916 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8917 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8918 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8919 if (casematch(patp, arglist.list->text)) {
8920 /* Ensure body is non-empty as otherwise
8921 * EV_EXIT may prevent us from setting the
8924 if (evalskip == 0 && cp->nclist.body) {
8925 status = evaltree(cp->nclist.body, flags);
8932 popstackmark(&smark);
8938 * Kick off a subshell to evaluate a tree.
8941 evalsubshell(union node *n, int flags)
8944 int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
8947 expredir(n->nredir.redirect);
8948 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8951 if (backgnd == FORK_FG)
8953 jp = makejob(/*n,*/ 1);
8954 if (forkshell(jp, n, backgnd) == 0) {
8959 flags &= ~EV_TESTED;
8961 redirect(n->nredir.redirect, 0);
8962 evaltreenr(n->nredir.n, flags);
8967 if (backgnd == FORK_FG)
8968 status = waitforjob(jp);
8974 * Compute the names of the files in a redirection list.
8976 static void fixredir(union node *, const char *, int);
8978 expredir(union node *n)
8982 for (redir = n; redir; redir = redir->nfile.next) {
8986 fn.lastp = &fn.list;
8987 switch (redir->type) {
8991 #if BASH_REDIR_OUTPUT
8996 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8997 TRACE(("expredir expanded to '%s'\n", fn.list->text));
8998 #if BASH_REDIR_OUTPUT
9002 // By the design of stack allocator, the loop of this kind:
9003 // while true; do while true; do break; done </dev/null; done
9004 // will look like a memory leak: ash plans to free expfname's
9005 // of "/dev/null" as soon as it finishes running the loop
9006 // (in this case, never).
9007 // This "fix" is wrong:
9008 if (redir->nfile.expfname)
9009 stunalloc(redir->nfile.expfname);
9010 // It results in corrupted state of stacked allocations.
9012 redir->nfile.expfname = fn.list->text;
9015 case NTOFD: /* >& */
9016 if (redir->ndup.vname) {
9017 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
9018 if (fn.list == NULL)
9019 ash_msg_and_raise_error("redir error");
9020 #if BASH_REDIR_OUTPUT
9021 //FIXME: we used expandarg with different args!
9022 if (!isdigit_str9(fn.list->text)) {
9023 /* >&file, not >&fd */
9024 if (redir->nfile.fd != 1) /* 123>&file - BAD */
9025 ash_msg_and_raise_error("redir error");
9027 goto store_expfname;
9030 fixredir(redir, fn.list->text, 1);
9038 * Evaluate a pipeline. All the processes in the pipeline are children
9039 * of the process creating the pipeline. (This differs from some versions
9040 * of the shell, which make the last process in a pipeline the parent
9044 evalpipe(union node *n, int flags)
9047 struct nodelist *lp;
9053 TRACE(("evalpipe(0x%lx) called\n", (long)n));
9055 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
9059 if (n->npipe.pipe_backgnd == 0)
9061 jp = makejob(/*n,*/ pipelen);
9063 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
9067 if (pipe(pip) < 0) {
9069 ash_msg_and_raise_error("pipe call failed");
9072 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
9086 evaltreenr(lp->n, flags);
9093 /* Don't want to trigger debugging */
9097 if (n->npipe.pipe_backgnd == 0) {
9098 status = waitforjob(jp);
9099 TRACE(("evalpipe: job done exit status %d\n", status));
9107 * Controls whether the shell is interactive or not.
9110 setinteractive(int on)
9112 static smallint is_interactive;
9114 if (++on == is_interactive)
9116 is_interactive = on;
9120 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9121 if (is_interactive > 1) {
9122 /* Looks like they want an interactive shell */
9123 static smallint did_banner;
9126 /* note: ash and hush share this string */
9127 out1fmt("\n\n%s %s\n"
9128 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
9131 "built-in shell (ash)"
9145 setinteractive(iflag);
9147 #if ENABLE_FEATURE_EDITING_VI
9149 line_input_state->flags |= VI_MODE;
9151 line_input_state->flags &= ~VI_MODE;
9153 viflag = 0; /* forcibly keep the option off */
9157 struct localvar_list {
9158 struct localvar_list *next;
9159 struct localvar *lv;
9162 static struct localvar_list *localvar_stack;
9165 * Called after a function returns.
9166 * Interrupts must be off.
9169 poplocalvars(int keep)
9171 struct localvar_list *ll;
9172 struct localvar *lvp, *next;
9176 ll = localvar_stack;
9177 localvar_stack = ll->next;
9182 while ((lvp = next) != NULL) {
9185 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9187 int bits = VSTRFIXED;
9189 if (lvp->flags != VUNSET) {
9190 if (vp->var_text == lvp->text)
9192 else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
9193 free((char*)lvp->text);
9197 vp->flags |= (lvp->flags & bits);
9200 (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
9201 unsetvar(vp->var_text);
9202 } else if (vp == NULL) { /* $- saved */
9203 memcpy(optlist, lvp->text, sizeof(optlist));
9204 free((char*)lvp->text);
9206 } else if (lvp->flags == VUNSET) {
9207 vp->flags &= ~(VSTRFIXED|VREADONLY);
9208 unsetvar(vp->var_text);
9211 vp->var_func(var_end(lvp->text));
9212 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9213 free((char*)vp->var_text);
9214 vp->flags = lvp->flags;
9215 vp->var_text = lvp->text;
9223 * Create a new localvar environment.
9225 static struct localvar_list *
9228 struct localvar_list *ll;
9231 ll = ckzalloc(sizeof(*ll));
9232 /*ll->lv = NULL; - zalloc did it */
9233 ll->next = localvar_stack;
9234 localvar_stack = ll;
9241 unwindlocalvars(struct localvar_list *stop)
9243 while (localvar_stack != stop)
9248 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9250 volatile struct shparam saveparam;
9251 struct jmploc *volatile savehandler;
9252 struct jmploc jmploc;
9255 saveparam = shellparam;
9256 savehandler = exception_handler;
9257 e = setjmp(jmploc.loc);
9262 exception_handler = &jmploc;
9263 shellparam.malloced = 0;
9267 shellparam.nparam = argc - 1;
9268 shellparam.p = argv + 1;
9269 #if ENABLE_ASH_GETOPTS
9270 shellparam.optind = 1;
9271 shellparam.optoff = -1;
9274 evaltree(func->n.narg.next, flags & EV_TESTED);
9280 freeparam(&shellparam);
9281 shellparam = saveparam;
9282 exception_handler = savehandler;
9284 evalskip &= ~SKIPFUNC;
9289 * Make a variable a local variable. When a variable is made local, it's
9290 * value and flags are saved in a localvar structure. The saved values
9291 * will be restored when the shell function returns. We handle the name
9292 * "-" as a special case: it makes changes to "set +-options" local
9293 * (options will be restored on return from the function).
9298 struct localvar *lvp;
9301 char *eq = strchr(name, '=');
9304 /* Cater for duplicate "local". Examples:
9305 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9306 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9308 lvp = localvar_stack->lv;
9310 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9314 * it's a duplicate "local VAR" declaration, do nothing
9321 lvp = ckzalloc(sizeof(*lvp));
9322 if (LONE_DASH(name)) {
9324 p = ckmalloc(sizeof(optlist));
9325 lvp->text = memcpy(p, optlist, sizeof(optlist));
9328 vpp = hashvar(name);
9329 vp = *findvar(vpp, name);
9331 /* variable did not exist yet */
9333 vp = setvareq(name, VSTRFIXED);
9335 vp = setvar(name, NULL, VSTRFIXED);
9336 lvp->flags = VUNSET;
9338 lvp->text = vp->var_text;
9339 lvp->flags = vp->flags;
9340 /* make sure neither "struct var" nor string gets freed
9341 * during (un)setting:
9343 vp->flags |= VSTRFIXED|VTEXTFIXED;
9347 /* "local VAR" unsets VAR: */
9348 setvar0(name, NULL);
9352 lvp->next = localvar_stack->lv;
9353 localvar_stack->lv = lvp;
9359 * The "local" command.
9361 static int FAST_FUNC
9362 localcmd(int argc UNUSED_PARAM, char **argv)
9366 if (!localvar_stack)
9367 ash_msg_and_raise_error("not in a function");
9370 while ((name = *argv++) != NULL) {
9376 static int FAST_FUNC
9377 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9382 static int FAST_FUNC
9383 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9388 static int FAST_FUNC
9389 execcmd(int argc UNUSED_PARAM, char **argv)
9392 while (nextopt("a:") != '\0')
9393 /* nextopt() sets optionarg to "-a ARGV0" */;
9399 iflag = 0; /* exit on error */
9402 /* We should set up signals for "exec CMD"
9403 * the same way as for "CMD" without "exec".
9404 * But optschanged->setinteractive->setsignal
9405 * still thought we are a root shell. Therefore, for example,
9406 * SIGQUIT is still set to IGN. Fix it:
9410 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9411 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9412 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9416 argv[0] = optionarg;
9417 shellexec(prog, argv, pathval(), 0);
9424 * The return command.
9426 static int FAST_FUNC
9427 returncmd(int argc UNUSED_PARAM, char **argv)
9430 * If called outside a function, do what ksh does;
9431 * skip the rest of the file.
9433 evalskip = SKIPFUNC;
9434 return argv[1] ? number(argv[1]) : exitstatus;
9437 /* Forward declarations for builtintab[] */
9438 static int breakcmd(int, char **) FAST_FUNC;
9439 static int dotcmd(int, char **) FAST_FUNC;
9440 static int evalcmd(int, char **, int) FAST_FUNC;
9441 static int exitcmd(int, char **) FAST_FUNC;
9442 static int exportcmd(int, char **) FAST_FUNC;
9443 #if ENABLE_ASH_GETOPTS
9444 static int getoptscmd(int, char **) FAST_FUNC;
9447 static int helpcmd(int, char **) FAST_FUNC;
9450 static int historycmd(int, char **) FAST_FUNC;
9452 #if ENABLE_FEATURE_SH_MATH
9453 static int letcmd(int, char **) FAST_FUNC;
9455 static int readcmd(int, char **) FAST_FUNC;
9456 static int setcmd(int, char **) FAST_FUNC;
9457 static int shiftcmd(int, char **) FAST_FUNC;
9458 static int timescmd(int, char **) FAST_FUNC;
9459 static int trapcmd(int, char **) FAST_FUNC;
9460 static int umaskcmd(int, char **) FAST_FUNC;
9461 static int unsetcmd(int, char **) FAST_FUNC;
9462 static int ulimitcmd(int, char **) FAST_FUNC;
9464 #define BUILTIN_NOSPEC "0"
9465 #define BUILTIN_SPECIAL "1"
9466 #define BUILTIN_REGULAR "2"
9467 #define BUILTIN_SPEC_REG "3"
9468 #define BUILTIN_ASSIGN "4"
9469 #define BUILTIN_SPEC_ASSG "5"
9470 #define BUILTIN_REG_ASSG "6"
9471 #define BUILTIN_SPEC_REG_ASSG "7"
9473 /* Stubs for calling non-FAST_FUNC's */
9475 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9477 #if ENABLE_ASH_PRINTF
9478 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9480 #if ENABLE_ASH_TEST || BASH_TEST2
9481 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9484 /* Keep these in proper order since it is searched via bsearch() */
9485 static const struct builtincmd builtintab[] = {
9486 { BUILTIN_SPEC_REG "." , dotcmd },
9487 { BUILTIN_SPEC_REG ":" , truecmd },
9489 { BUILTIN_REGULAR "[" , testcmd },
9492 { BUILTIN_REGULAR "[[" , testcmd },
9494 #if ENABLE_ASH_ALIAS
9495 { BUILTIN_REG_ASSG "alias" , aliascmd },
9498 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9500 { BUILTIN_SPEC_REG "break" , breakcmd },
9501 { BUILTIN_REGULAR "cd" , cdcmd },
9502 { BUILTIN_NOSPEC "chdir" , cdcmd },
9503 #if ENABLE_ASH_CMDCMD
9504 { BUILTIN_REGULAR "command" , commandcmd },
9506 { BUILTIN_SPEC_REG "continue", breakcmd },
9508 { BUILTIN_REGULAR "echo" , echocmd },
9510 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9511 { BUILTIN_SPEC_REG "exec" , execcmd },
9512 { BUILTIN_SPEC_REG "exit" , exitcmd },
9513 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9514 { BUILTIN_REGULAR "false" , falsecmd },
9516 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9518 #if ENABLE_ASH_GETOPTS
9519 { BUILTIN_REGULAR "getopts" , getoptscmd },
9521 { BUILTIN_NOSPEC "hash" , hashcmd },
9523 { BUILTIN_NOSPEC "help" , helpcmd },
9526 { BUILTIN_NOSPEC "history" , historycmd },
9529 { BUILTIN_REGULAR "jobs" , jobscmd },
9530 { BUILTIN_REGULAR "kill" , killcmd },
9532 #if ENABLE_FEATURE_SH_MATH
9533 { BUILTIN_NOSPEC "let" , letcmd },
9535 { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
9536 #if ENABLE_ASH_PRINTF
9537 { BUILTIN_REGULAR "printf" , printfcmd },
9539 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9540 { BUILTIN_REGULAR "read" , readcmd },
9541 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9542 { BUILTIN_SPEC_REG "return" , returncmd },
9543 { BUILTIN_SPEC_REG "set" , setcmd },
9544 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9546 { BUILTIN_SPEC_REG "source" , dotcmd },
9549 { BUILTIN_REGULAR "test" , testcmd },
9551 { BUILTIN_SPEC_REG "times" , timescmd },
9552 { BUILTIN_SPEC_REG "trap" , trapcmd },
9553 { BUILTIN_REGULAR "true" , truecmd },
9554 { BUILTIN_NOSPEC "type" , typecmd },
9555 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9556 { BUILTIN_REGULAR "umask" , umaskcmd },
9557 #if ENABLE_ASH_ALIAS
9558 { BUILTIN_REGULAR "unalias" , unaliascmd },
9560 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9561 { BUILTIN_REGULAR "wait" , waitcmd },
9564 /* Should match the above table! */
9565 #define COMMANDCMD (builtintab + \
9567 /* [ */ 1 * ENABLE_ASH_TEST + \
9568 /* [[ */ 1 * BASH_TEST2 + \
9569 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9570 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9571 /* break cd cddir */ 3)
9572 #define EVALCMD (COMMANDCMD + \
9573 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9574 /* continue */ 1 + \
9575 /* echo */ 1 * ENABLE_ASH_ECHO + \
9577 #define EXECCMD (EVALCMD + \
9581 * Search the table of builtin commands.
9584 pstrcmp1(const void *a, const void *b)
9586 return strcmp((char*)a, *(char**)b + 1);
9588 static struct builtincmd *
9589 find_builtin(const char *name)
9591 struct builtincmd *bp;
9594 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9601 * Execute a simple command.
9604 isassignment(const char *p)
9606 const char *q = endofname(p);
9611 static int FAST_FUNC
9612 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9614 /* Preserve exitstatus of a previous possible redirection
9615 * as POSIX mandates */
9616 return back_exitstatus;
9619 evalcommand(union node *cmd, int flags)
9621 static const struct builtincmd null_bltin = {
9622 "\0\0", bltincmd /* why three NULs? */
9624 struct localvar_list *localvar_stop;
9625 struct stackmark smark;
9627 struct arglist arglist;
9628 struct arglist varlist;
9631 const struct strlist *sp;
9632 struct cmdentry cmdentry;
9639 struct builtincmd *bcmd;
9640 smallint cmd_is_exec;
9641 smallint pseudovarflag = 0;
9643 /* First expand the arguments. */
9644 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9645 setstackmark(&smark);
9646 localvar_stop = pushlocalvars();
9647 back_exitstatus = 0;
9649 cmdentry.cmdtype = CMDBUILTIN;
9650 cmdentry.u.cmd = &null_bltin;
9651 varlist.lastp = &varlist.list;
9652 *varlist.lastp = NULL;
9653 arglist.lastp = &arglist.list;
9654 *arglist.lastp = NULL;
9657 if (cmd->ncmd.args) {
9658 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9659 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9662 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9663 struct strlist **spp;
9665 spp = arglist.lastp;
9666 if (pseudovarflag && isassignment(argp->narg.text))
9667 expandarg(argp, &arglist, EXP_VARTILDE);
9669 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9671 for (sp = *spp; sp; sp = sp->next)
9675 /* Reserve one extra spot at the front for shellexec. */
9676 nargv = stalloc(sizeof(char *) * (argc + 2));
9678 for (sp = arglist.list; sp; sp = sp->next) {
9679 TRACE(("evalcommand arg: %s\n", sp->text));
9680 *nargv++ = sp->text;
9685 if (iflag && funcnest == 0 && argc > 0)
9686 lastarg = nargv[-1];
9689 expredir(cmd->ncmd.redirect);
9690 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9692 path = vpath.var_text;
9693 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9694 struct strlist **spp;
9697 spp = varlist.lastp;
9698 expandarg(argp, &varlist, EXP_VARTILDE);
9700 mklocal((*spp)->text);
9703 * Modify the command lookup path, if a PATH= assignment
9707 if (varcmp(p, path) == 0)
9711 /* Print the command if xflag is set. */
9713 const char *pfx = "";
9715 fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
9719 char *varval = sp->text;
9720 char *eq = strchrnul(varval, '=');
9723 fdprintf(preverrout_fd, "%s%.*s%s",
9725 (int)(eq - varval), varval,
9726 maybe_single_quote(eq)
9734 fdprintf(preverrout_fd, "%s%s",
9736 /* always quote if matches reserved word: */
9738 ? single_quote(sp->text)
9739 : maybe_single_quote(sp->text)
9744 safe_write(preverrout_fd, "\n", 1);
9750 /* Now locate the command. */
9752 int cmd_flag = DO_ERR;
9753 #if ENABLE_ASH_CMDCMD
9754 const char *oldpath = path + 5;
9758 find_command(argv[0], &cmdentry, cmd_flag, path);
9759 if (cmdentry.cmdtype == CMDUNKNOWN) {
9760 flush_stdout_stderr();
9765 /* implement bltin and command here */
9766 if (cmdentry.cmdtype != CMDBUILTIN)
9769 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9770 if (cmdentry.u.cmd == EXECCMD)
9772 #if ENABLE_ASH_CMDCMD
9773 if (cmdentry.u.cmd == COMMANDCMD) {
9775 nargv = parse_command_args(argv, &path);
9778 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9779 * nargv => "PROG". path is updated if -p.
9781 argc -= nargv - argv;
9783 cmd_flag |= DO_NOFUNC;
9792 exitstatus = status;
9794 /* We have a redirection error. */
9796 raise_exception(EXERROR);
9801 /* Execute the command. */
9802 switch (cmdentry.cmdtype) {
9805 #if ENABLE_FEATURE_SH_NOFORK
9806 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9807 * around run_nofork_applet() call.
9808 * (2) Should this check also be done in forkshell()?
9809 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9811 /* find_command() encodes applet_no as (-2 - applet_no) */
9812 int applet_no = (- cmdentry.u.index - 2);
9813 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9814 listsetvar(varlist.list, VEXPORT|VSTACK);
9815 /* run <applet>_main() */
9816 status = run_nofork_applet(applet_no, argv);
9820 /* Can we avoid forking off? For example, very last command
9821 * in a script or a subshell does not need forking,
9822 * we can just exec it.
9824 if (!(flags & EV_EXIT) || may_have_traps) {
9825 /* No, forking off a child is necessary */
9828 jp = makejob(/*cmd,*/ 1);
9829 if (forkshell(jp, cmd, FORK_FG) != 0) {
9831 status = waitforjob(jp);
9833 TRACE(("forked child exited with %d\n", status));
9838 /* fall through to exec'ing external program */
9840 listsetvar(varlist.list, VEXPORT|VSTACK);
9841 shellexec(argv[0], argv, path, cmdentry.u.index);
9845 if (spclbltin > 0 || argc == 0) {
9847 if (cmd_is_exec && argc > 1)
9848 listsetvar(varlist.list, VEXPORT);
9851 /* Tight loop with builtins only:
9852 * "while kill -0 $child; do true; done"
9853 * will never exit even if $child died, unless we do this
9854 * to reap the zombie and make kill detect that it's gone: */
9855 dowait(DOWAIT_NONBLOCK, NULL);
9857 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
9858 if (exception_type == EXERROR && spclbltin <= 0) {
9863 longjmp(exception_handler->loc, 1);
9869 /* See above for the rationale */
9870 dowait(DOWAIT_NONBLOCK, NULL);
9871 if (evalfun(cmdentry.u.func, argc, argv, flags))
9874 status = exitstatus;
9879 if (cmd->ncmd.redirect)
9880 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9881 unwindlocalvars(localvar_stop);
9883 /* dsl: I think this is intended to be used to support
9884 * '_' in 'vi' command mode during line editing...
9885 * However I implemented that within libedit itself.
9887 setvar0("_", lastarg);
9889 popstackmark(&smark);
9895 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
9897 char *volatile savecmdname;
9898 struct jmploc *volatile savehandler;
9899 struct jmploc jmploc;
9903 savecmdname = commandname;
9904 savehandler = exception_handler;
9905 i = setjmp(jmploc.loc);
9908 exception_handler = &jmploc;
9909 commandname = argv[0];
9911 optptr = NULL; /* initialize nextopt */
9913 status = evalcmd(argc, argv, flags);
9915 status = (*cmd->builtin)(argc, argv);
9916 flush_stdout_stderr();
9917 status |= ferror(stdout);
9918 exitstatus = status;
9921 commandname = savecmdname;
9922 exception_handler = savehandler;
9928 goodname(const char *p)
9930 return endofname(p)[0] == '\0';
9935 * Search for a command. This is called before we fork so that the
9936 * location of the command will be available in the parent as well as
9937 * the child. The check for "goodname" is an overly conservative
9938 * check that the name will not be subject to expansion.
9941 prehash(union node *n)
9943 struct cmdentry entry;
9945 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9946 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9950 /* ============ Builtin commands
9952 * Builtin commands whose functions are closely tied to evaluation
9953 * are implemented here.
9957 * Handle break and continue commands. Break, continue, and return are
9958 * all handled by setting the evalskip flag. The evaluation routines
9959 * above all check this flag, and if it is set they start skipping
9960 * commands rather than executing them. The variable skipcount is
9961 * the number of loops to break/continue, or the number of function
9962 * levels to return. (The latter is always 1.) It should probably
9963 * be an error to break out of more loops than exist, but it isn't
9964 * in the standard shell so we don't make it one here.
9966 static int FAST_FUNC
9967 breakcmd(int argc UNUSED_PARAM, char **argv)
9969 int n = argv[1] ? number(argv[1]) : 1;
9972 ash_msg_and_raise_error(msg_illnum, argv[1]);
9976 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9984 * This implements the input routines used by the parser.
9988 INPUT_PUSH_FILE = 1,
9989 INPUT_NOFILE_OK = 2,
9992 static smallint checkkwd;
9993 /* values of checkkwd variable */
9994 #define CHKALIAS 0x1
9997 #define CHKEOFMARK 0x8
10000 * Push a string back onto the input at this current parsefile level.
10001 * We handle aliases this way.
10003 #if !ENABLE_ASH_ALIAS
10004 #define pushstring(s, ap) pushstring(s)
10007 pushstring(char *s, struct alias *ap)
10009 struct strpush *sp;
10014 if (g_parsefile->strpush) {
10015 sp = ckzalloc(sizeof(*sp));
10016 sp->prev = g_parsefile->strpush;
10018 sp = &(g_parsefile->basestrpush);
10020 g_parsefile->strpush = sp;
10021 sp->prev_string = g_parsefile->next_to_pgetc;
10022 sp->prev_left_in_line = g_parsefile->left_in_line;
10023 sp->unget = g_parsefile->unget;
10024 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
10025 #if ENABLE_ASH_ALIAS
10028 ap->flag |= ALIASINUSE;
10032 g_parsefile->next_to_pgetc = s;
10033 g_parsefile->left_in_line = len;
10034 g_parsefile->unget = 0;
10041 struct strpush *sp = g_parsefile->strpush;
10044 #if ENABLE_ASH_ALIAS
10046 if (g_parsefile->next_to_pgetc[-1] == ' '
10047 || g_parsefile->next_to_pgetc[-1] == '\t'
10049 checkkwd |= CHKALIAS;
10051 if (sp->string != sp->ap->val) {
10054 sp->ap->flag &= ~ALIASINUSE;
10055 if (sp->ap->flag & ALIASDEAD) {
10056 unalias(sp->ap->name);
10060 g_parsefile->next_to_pgetc = sp->prev_string;
10061 g_parsefile->left_in_line = sp->prev_left_in_line;
10062 g_parsefile->unget = sp->unget;
10063 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
10064 g_parsefile->strpush = sp->prev;
10065 if (sp != &(g_parsefile->basestrpush))
10074 char *buf = g_parsefile->buf;
10076 g_parsefile->next_to_pgetc = buf;
10077 #if ENABLE_FEATURE_EDITING
10079 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
10080 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10083 # if ENABLE_ASH_IDLE_TIMEOUT
10085 const char *tmout_var = lookupvar("TMOUT");
10087 timeout = atoi(tmout_var) * 1000;
10093 # if ENABLE_FEATURE_TAB_COMPLETION
10094 line_input_state->path_lookup = pathval();
10096 reinit_unicode_for_ash();
10097 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
10099 /* ^C pressed, "convert" to SIGINT */
10100 write(STDOUT_FILENO, "^C", 2);
10101 if (trap[SIGINT]) {
10107 exitstatus = 128 + SIGINT;
10113 /* Ctrl+D pressed */
10116 # if ENABLE_ASH_IDLE_TIMEOUT
10117 else if (errno == EAGAIN && timeout > 0) {
10118 puts("\007timed out waiting for input: auto-logout");
10125 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10128 #if 0 /* disabled: nonblock_immune_read() handles this problem */
10130 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
10131 int flags = fcntl(0, F_GETFL);
10132 if (flags >= 0 && (flags & O_NONBLOCK)) {
10133 flags &= ~O_NONBLOCK;
10134 if (fcntl(0, F_SETFL, flags) >= 0) {
10135 out2str("sh: turning off NDELAY mode\n");
10146 * Refill the input buffer and return the next input character:
10148 * 1) If a string was pushed back on the input, pop it;
10149 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
10150 * or we are reading from a string so we can't refill the buffer,
10152 * 3) If there is more stuff in this buffer, use it else call read to fill it.
10153 * 4) Process input up to the next newline, deleting nul characters.
10155 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
10156 #define pgetc_debug(...) ((void)0)
10157 static int pgetc(void);
10164 if (g_parsefile->strpush) {
10165 #if ENABLE_ASH_ALIAS
10166 if (g_parsefile->left_in_line == -1
10167 && g_parsefile->strpush->ap
10168 && g_parsefile->next_to_pgetc[-1] != ' '
10169 && g_parsefile->next_to_pgetc[-1] != '\t'
10171 pgetc_debug("preadbuffer PEOA");
10178 /* on both branches above g_parsefile->left_in_line < 0.
10179 * "pgetc" needs refilling.
10182 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
10183 * pungetc() may increment it a few times.
10184 * Assuming it won't increment it to less than -90.
10186 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
10187 pgetc_debug("preadbuffer PEOF1");
10188 /* even in failure keep left_in_line and next_to_pgetc
10189 * in lock step, for correct multi-layer pungetc.
10190 * left_in_line was decremented before preadbuffer(),
10191 * must inc next_to_pgetc: */
10192 g_parsefile->next_to_pgetc++;
10196 more = g_parsefile->left_in_buffer;
10198 flush_stdout_stderr();
10202 /* don't try reading again */
10203 g_parsefile->left_in_line = -99;
10204 pgetc_debug("preadbuffer PEOF2");
10205 g_parsefile->next_to_pgetc++;
10210 /* Find out where's the end of line.
10211 * Set g_parsefile->left_in_line
10212 * and g_parsefile->left_in_buffer acordingly.
10213 * NUL chars are deleted.
10215 q = g_parsefile->next_to_pgetc;
10223 memmove(q, q + 1, more);
10227 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10233 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10234 if (g_parsefile->left_in_line < 0)
10239 g_parsefile->left_in_buffer = more;
10244 out2str(g_parsefile->next_to_pgetc);
10248 pgetc_debug("preadbuffer at %d:%p'%s'",
10249 g_parsefile->left_in_line,
10250 g_parsefile->next_to_pgetc,
10251 g_parsefile->next_to_pgetc);
10252 return (unsigned char)*g_parsefile->next_to_pgetc++;
10258 g_parsefile->linno++;
10259 setprompt_if(doprompt, 2);
10264 g_parsefile->linno++;
10265 needprompt = doprompt;
10273 pgetc_debug("pgetc at %d:%p'%s'",
10274 g_parsefile->left_in_line,
10275 g_parsefile->next_to_pgetc,
10276 g_parsefile->next_to_pgetc);
10277 if (g_parsefile->unget)
10278 return g_parsefile->lastc[--g_parsefile->unget];
10280 if (--g_parsefile->left_in_line >= 0)
10281 c = (unsigned char)*g_parsefile->next_to_pgetc++;
10285 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10286 g_parsefile->lastc[0] = c;
10291 #if ENABLE_ASH_ALIAS
10293 pgetc_without_PEOA(void)
10297 pgetc_debug("pgetc at %d:%p'%s'",
10298 g_parsefile->left_in_line,
10299 g_parsefile->next_to_pgetc,
10300 g_parsefile->next_to_pgetc);
10302 } while (c == PEOA);
10306 # define pgetc_without_PEOA() pgetc()
10310 * Undo a call to pgetc. Only two characters may be pushed back.
10311 * PEOF may be pushed back.
10316 g_parsefile->unget++;
10319 /* This one eats backslash+newline */
10325 while ((c = pgetc()) == '\\') {
10326 if (pgetc() != '\n') {
10338 * To handle the "." command, a stack of input files is used. Pushfile
10339 * adds a new entry to the stack and popfile restores the previous level.
10344 struct parsefile *pf;
10346 pf = ckzalloc(sizeof(*pf));
10347 pf->prev = g_parsefile;
10349 /*pf->strpush = NULL; - ckzalloc did it */
10350 /*pf->basestrpush.prev = NULL;*/
10358 struct parsefile *pf = g_parsefile;
10364 if (pf->pf_fd >= 0)
10367 while (pf->strpush)
10369 g_parsefile = pf->prev;
10375 * Return to top level.
10380 while (g_parsefile != &basepf)
10385 * Close the file(s) that the shell is reading commands from. Called
10386 * after a fork is done.
10392 if (g_parsefile->pf_fd > 0) {
10393 close(g_parsefile->pf_fd);
10394 g_parsefile->pf_fd = 0;
10399 * Like setinputfile, but takes an open file descriptor. Call this with
10403 setinputfd(int fd, int push)
10407 g_parsefile->buf = NULL;
10409 g_parsefile->pf_fd = fd;
10410 if (g_parsefile->buf == NULL)
10411 g_parsefile->buf = ckmalloc(IBUFSIZ);
10412 g_parsefile->left_in_buffer = 0;
10413 g_parsefile->left_in_line = 0;
10414 g_parsefile->linno = 1;
10418 * Set the input to take input from a file. If push is set, push the
10419 * old input onto the stack first.
10422 setinputfile(const char *fname, int flags)
10427 fd = open(fname, O_RDONLY);
10429 if (flags & INPUT_NOFILE_OK)
10432 ash_msg_and_raise_error("can't open '%s'", fname);
10437 close_on_exec_on(fd);
10438 setinputfd(fd, flags & INPUT_PUSH_FILE);
10445 * Like setinputfile, but takes input from a string.
10448 setinputstring(char *string)
10452 g_parsefile->next_to_pgetc = string;
10453 g_parsefile->left_in_line = strlen(string);
10454 g_parsefile->buf = NULL;
10455 g_parsefile->linno = 1;
10461 * Routines to check for mail.
10464 #if ENABLE_ASH_MAIL
10466 /* Hash of mtimes of mailboxes */
10467 static unsigned mailtime_hash;
10468 /* Set if MAIL or MAILPATH is changed. */
10469 static smallint mail_var_path_changed;
10472 * Print appropriate message(s) if mail has arrived.
10473 * If mail_var_path_changed is set,
10474 * then the value of MAIL has mail_var_path_changed,
10475 * so we just update the values.
10484 struct stackmark smark;
10487 setstackmark(&smark);
10488 mpath = mpathset() ? mpathval() : mailval();
10491 p = path_advance(&mpath, nullstr);
10496 for (q = p; *q; q++)
10502 q[-1] = '\0'; /* delete trailing '/' */
10503 if (stat(p, &statb) < 0) {
10506 /* Very simplistic "hash": just a sum of all mtimes */
10507 new_hash += (unsigned)statb.st_mtime;
10509 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10510 if (mailtime_hash != 0)
10511 out2str("you have mail\n");
10512 mailtime_hash = new_hash;
10514 mail_var_path_changed = 0;
10515 popstackmark(&smark);
10518 static void FAST_FUNC
10519 changemail(const char *val UNUSED_PARAM)
10521 mail_var_path_changed = 1;
10524 #endif /* ASH_MAIL */
10527 /* ============ ??? */
10530 * Set the shell parameters.
10533 setparam(char **argv)
10539 for (nparam = 0; argv[nparam]; nparam++)
10541 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10543 *ap++ = ckstrdup(*argv++);
10546 freeparam(&shellparam);
10547 shellparam.malloced = 1;
10548 shellparam.nparam = nparam;
10549 shellparam.p = newparam;
10550 #if ENABLE_ASH_GETOPTS
10551 shellparam.optind = 1;
10552 shellparam.optoff = -1;
10557 * Process shell options. The global variable argptr contains a pointer
10558 * to the argument list; we advance it past the options.
10560 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10561 * For a non-interactive shell, an error condition encountered
10562 * by a special built-in ... shall cause the shell to write a diagnostic message
10563 * to standard error and exit as shown in the following table:
10564 * Error Special Built-In
10566 * Utility syntax error (option or operand error) Shall exit
10568 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10569 * we see that bash does not do that (set "finishes" with error code 1 instead,
10570 * and shell continues), and people rely on this behavior!
10572 * set -o barfoo 2>/dev/null
10575 * Oh well. Let's mimic that.
10578 plus_minus_o(char *name, int val)
10583 for (i = 0; i < NOPTS; i++) {
10584 if (strcmp(name, optnames(i)) == 0) {
10589 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10592 for (i = 0; i < NOPTS; i++) {
10594 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10596 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10602 setoption(int flag, int val)
10606 for (i = 0; i < NOPTS; i++) {
10607 if (optletters(i) == flag) {
10612 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10616 options(int cmdline)
10624 while ((p = *argptr) != NULL) {
10626 if (c != '-' && c != '+')
10629 val = 0; /* val = 0 if c == '+' */
10632 if (p[0] == '\0' || LONE_DASH(p)) {
10634 /* "-" means turn off -x and -v */
10637 /* "--" means reset params */
10638 else if (*argptr == NULL)
10641 break; /* "-" or "--" terminates options */
10644 /* first char was + or - */
10645 while ((c = *p++) != '\0') {
10646 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10647 if (c == 'c' && cmdline) {
10648 minusc = p; /* command is after shell args */
10649 } else if (c == 'o') {
10650 if (plus_minus_o(*argptr, val)) {
10651 /* it already printed err message */
10652 return 1; /* error */
10656 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10658 /* bash does not accept +-login, we also won't */
10659 } else if (cmdline && val && (c == '-')) { /* long options */
10660 if (strcmp(p, "login") == 0)
10672 * The shift builtin command.
10674 static int FAST_FUNC
10675 shiftcmd(int argc UNUSED_PARAM, char **argv)
10682 n = number(argv[1]);
10683 if (n > shellparam.nparam)
10684 n = 0; /* bash compat, was = shellparam.nparam; */
10686 shellparam.nparam -= n;
10687 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10688 if (shellparam.malloced)
10691 ap2 = shellparam.p;
10692 while ((*ap2++ = *ap1++) != NULL)
10694 #if ENABLE_ASH_GETOPTS
10695 shellparam.optind = 1;
10696 shellparam.optoff = -1;
10703 * POSIX requires that 'set' (but not export or readonly) output the
10704 * variables in lexicographic order - by the locale's collating order (sigh).
10705 * Maybe we could keep them in an ordered balanced binary tree
10706 * instead of hashed lists.
10707 * For now just roll 'em through qsort for printing...
10710 showvars(const char *sep_prefix, int on, int off)
10713 char **ep, **epend;
10715 ep = listvars(on, off, &epend);
10716 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10718 sep = *sep_prefix ? " " : sep_prefix;
10720 for (; ep < epend; ep++) {
10724 p = strchrnul(*ep, '=');
10727 q = single_quote(++p);
10728 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10734 * The set command builtin.
10736 static int FAST_FUNC
10737 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10742 return showvars(nullstr, 0, VUNSET);
10745 retval = options(/*cmdline:*/ 0);
10746 if (retval == 0) { /* if no parse error... */
10748 if (*argptr != NULL) {
10756 #if ENABLE_ASH_RANDOM_SUPPORT
10757 static void FAST_FUNC
10758 change_random(const char *value)
10762 if (value == NULL) {
10763 /* "get", generate */
10764 t = next_random(&random_gen);
10765 /* set without recursion */
10766 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10767 vrandom.flags &= ~VNOFUNC;
10770 t = strtoul(value, NULL, 10);
10771 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10776 #if ENABLE_ASH_GETOPTS
10778 getopts(char *optstr, char *optvar, char **optfirst)
10785 int ind = shellparam.optind;
10786 int off = shellparam.optoff;
10790 shellparam.optind = -1;
10791 optnext = optfirst + ind - 1;
10793 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
10796 p = optnext[-1] + off;
10797 if (p == NULL || *p == '\0') {
10798 /* Current word is done, advance */
10800 if (p == NULL || *p != '-' || *++p == '\0') {
10807 if (LONE_DASH(p)) /* check for "--" */
10812 for (q = optstr; *q != c;) {
10814 if (optstr[0] == ':') {
10816 /*sbuf[1] = '\0'; - already is */
10817 setvar0("OPTARG", sbuf);
10819 fprintf(stderr, "Illegal option -%c\n", c);
10820 unsetvar("OPTARG");
10830 if (*p == '\0' && (p = *optnext) == NULL) {
10831 if (optstr[0] == ':') {
10833 /*sbuf[1] = '\0'; - already is */
10834 setvar0("OPTARG", sbuf);
10837 fprintf(stderr, "No arg for -%c option\n", c);
10838 unsetvar("OPTARG");
10846 setvar0("OPTARG", p);
10849 setvar0("OPTARG", nullstr);
10851 ind = optnext - optfirst + 1;
10852 setvar("OPTIND", itoa(ind), VNOFUNC);
10854 /*sbuf[1] = '\0'; - already is */
10855 setvar0(optvar, sbuf);
10857 shellparam.optoff = p ? p - *(optnext - 1) : -1;
10858 shellparam.optind = ind;
10864 * The getopts builtin. Shellparam.optnext points to the next argument
10865 * to be processed. Shellparam.optptr points to the next character to
10866 * be processed in the current argument. If shellparam.optnext is NULL,
10867 * then it's the first time getopts has been called.
10869 static int FAST_FUNC
10870 getoptscmd(int argc, char **argv)
10875 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10877 optbase = shellparam.p;
10878 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
10879 shellparam.optind = 1;
10880 shellparam.optoff = -1;
10883 optbase = &argv[3];
10884 if ((unsigned)shellparam.optind > argc - 2) {
10885 shellparam.optind = 1;
10886 shellparam.optoff = -1;
10890 return getopts(argv[1], argv[2], optbase);
10892 #endif /* ASH_GETOPTS */
10895 /* ============ Shell parser */
10898 struct heredoc *next; /* next here document in list */
10899 union node *here; /* redirection node */
10900 char *eofmark; /* string indicating end of input */
10901 smallint striptabs; /* if set, strip leading tabs */
10904 static smallint tokpushback; /* last token pushed back */
10905 static smallint quoteflag; /* set if (part of) last token was quoted */
10906 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10907 static struct heredoc *heredoclist; /* list of here documents to read */
10908 static char *wordtext; /* text of last word returned by readtoken */
10909 static struct nodelist *backquotelist;
10910 static union node *redirnode;
10911 static struct heredoc *heredoc;
10913 static const char *
10914 tokname(char *buf, int tok)
10917 return tokname_array[tok];
10918 sprintf(buf, "\"%s\"", tokname_array[tok]);
10922 /* raise_error_unexpected_syntax:
10923 * Called when an unexpected token is read during the parse. The argument
10924 * is the token that is expected, or -1 if more than one type of token can
10925 * occur at this point.
10927 static void raise_error_unexpected_syntax(int) NORETURN;
10929 raise_error_unexpected_syntax(int token)
10935 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10937 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10938 raise_error_syntax(msg);
10942 /* parsing is heavily cross-recursive, need these forward decls */
10943 static union node *andor(void);
10944 static union node *pipeline(void);
10945 static union node *parse_command(void);
10946 static void parseheredoc(void);
10947 static int peektoken(void);
10948 static int readtoken(void);
10950 static union node *
10953 union node *n1, *n2, *n3;
10958 switch (peektoken()) {
10966 if (!n1 && (nlflag & 1))
10972 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10973 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
10979 if (tok == TBACKGND) {
10980 if (n2->type == NPIPE) {
10981 n2->npipe.pipe_backgnd = 1;
10983 if (n2->type != NREDIR) {
10984 n3 = stzalloc(sizeof(struct nredir));
10986 /*n3->nredir.redirect = NULL; - stzalloc did it */
10989 n2->type = NBACKGND;
10995 n3 = stzalloc(sizeof(struct nbinary));
10997 n3->nbinary.ch1 = n1;
10998 n3->nbinary.ch2 = n2;
11011 raise_error_unexpected_syntax(-1);
11018 static union node *
11021 union node *n1, *n2, *n3;
11029 } else if (t == TOR) {
11035 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11037 n3 = stzalloc(sizeof(struct nbinary));
11039 n3->nbinary.ch1 = n1;
11040 n3->nbinary.ch2 = n2;
11045 static union node *
11048 union node *n1, *n2, *pipenode;
11049 struct nodelist *lp, *prev;
11053 TRACE(("pipeline: entered\n"));
11054 if (readtoken() == TNOT) {
11056 checkkwd = CHKKWD | CHKALIAS;
11059 n1 = parse_command();
11060 if (readtoken() == TPIPE) {
11061 pipenode = stzalloc(sizeof(struct npipe));
11062 pipenode->type = NPIPE;
11063 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
11064 lp = stzalloc(sizeof(struct nodelist));
11065 pipenode->npipe.cmdlist = lp;
11069 lp = stzalloc(sizeof(struct nodelist));
11070 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11071 lp->n = parse_command();
11073 } while (readtoken() == TPIPE);
11079 n2 = stzalloc(sizeof(struct nnot));
11087 static union node *
11092 n = stzalloc(sizeof(struct narg));
11094 /*n->narg.next = NULL; - stzalloc did it */
11095 n->narg.text = wordtext;
11096 n->narg.backquote = backquotelist;
11101 fixredir(union node *n, const char *text, int err)
11105 TRACE(("Fix redir %s %d\n", text, err));
11107 n->ndup.vname = NULL;
11109 fd = bb_strtou(text, NULL, 10);
11110 if (!errno && fd >= 0)
11111 n->ndup.dupfd = fd;
11112 else if (LONE_DASH(text))
11113 n->ndup.dupfd = -1;
11116 raise_error_syntax("bad fd number");
11117 n->ndup.vname = makename();
11124 union node *n = redirnode;
11126 if (n->type == NHERE)
11127 checkkwd = CHKEOFMARK;
11128 if (readtoken() != TWORD)
11129 raise_error_unexpected_syntax(-1);
11130 if (n->type == NHERE) {
11131 struct heredoc *here = heredoc;
11134 if (quoteflag == 0)
11136 TRACE(("Here document %d\n", n->type));
11137 rmescapes(wordtext, 0);
11138 here->eofmark = wordtext;
11140 if (heredoclist == NULL)
11141 heredoclist = here;
11143 for (p = heredoclist; p->next; p = p->next)
11147 } else if (n->type == NTOFD || n->type == NFROMFD) {
11148 fixredir(n, wordtext, 0);
11150 n->nfile.fname = makename();
11154 static union node *
11157 union node *args, **app;
11158 union node *n = NULL;
11159 union node *vars, **vpp;
11160 union node **rpp, *redir;
11163 smallint double_brackets_flag = 0;
11165 IF_BASH_FUNCTION(smallint function_flag = 0;)
11174 savecheckkwd = CHKALIAS;
11177 checkkwd = savecheckkwd;
11182 if (peektoken() != TWORD)
11183 raise_error_unexpected_syntax(TWORD);
11188 case TAND: /* "&&" */
11189 case TOR: /* "||" */
11190 if (!double_brackets_flag) {
11194 wordtext = (char *) (t == TAND ? "-a" : "-o");
11197 n = stzalloc(sizeof(struct narg));
11199 /*n->narg.next = NULL; - stzalloc did it */
11200 n->narg.text = wordtext;
11202 if (strcmp("[[", wordtext) == 0)
11203 double_brackets_flag = 1;
11204 else if (strcmp("]]", wordtext) == 0)
11205 double_brackets_flag = 0;
11207 n->narg.backquote = backquotelist;
11208 if (savecheckkwd && isassignment(wordtext)) {
11210 vpp = &n->narg.next;
11213 app = &n->narg.next;
11217 if (function_flag) {
11218 checkkwd = CHKNL | CHKKWD;
11219 switch (peektoken()) {
11231 if (strcmp("[[", wordtext) == 0)
11235 raise_error_unexpected_syntax(-1);
11241 *rpp = n = redirnode;
11242 rpp = &n->nfile.next;
11243 parsefname(); /* read name of redirection file */
11246 IF_BASH_FUNCTION(do_func:)
11247 if (args && app == &args->narg.next
11250 struct builtincmd *bcmd;
11253 /* We have a function */
11254 if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
11255 raise_error_unexpected_syntax(TRP);
11256 name = n->narg.text;
11257 if (!goodname(name)
11258 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11260 raise_error_syntax("bad function name");
11263 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11264 n->narg.next = parse_command();
11267 IF_BASH_FUNCTION(function_flag = 0;)
11278 n = stzalloc(sizeof(struct ncmd));
11280 n->ncmd.args = args;
11281 n->ncmd.assign = vars;
11282 n->ncmd.redirect = redir;
11286 static union node *
11287 parse_command(void)
11289 union node *n1, *n2;
11290 union node *ap, **app;
11291 union node *cp, **cpp;
11292 union node *redir, **rpp;
11299 switch (readtoken()) {
11301 raise_error_unexpected_syntax(-1);
11304 n1 = stzalloc(sizeof(struct nif));
11306 n1->nif.test = list(0);
11307 if (readtoken() != TTHEN)
11308 raise_error_unexpected_syntax(TTHEN);
11309 n1->nif.ifpart = list(0);
11311 while (readtoken() == TELIF) {
11312 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11313 n2 = n2->nif.elsepart;
11315 n2->nif.test = list(0);
11316 if (readtoken() != TTHEN)
11317 raise_error_unexpected_syntax(TTHEN);
11318 n2->nif.ifpart = list(0);
11320 if (lasttoken == TELSE)
11321 n2->nif.elsepart = list(0);
11323 n2->nif.elsepart = NULL;
11331 n1 = stzalloc(sizeof(struct nbinary));
11332 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11333 n1->nbinary.ch1 = list(0);
11336 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11337 got == TWORD ? wordtext : ""));
11338 raise_error_unexpected_syntax(TDO);
11340 n1->nbinary.ch2 = list(0);
11345 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11346 raise_error_syntax("bad for loop variable");
11347 n1 = stzalloc(sizeof(struct nfor));
11349 n1->nfor.var = wordtext;
11350 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11351 if (readtoken() == TIN) {
11353 while (readtoken() == TWORD) {
11354 n2 = stzalloc(sizeof(struct narg));
11356 /*n2->narg.next = NULL; - stzalloc did it */
11357 n2->narg.text = wordtext;
11358 n2->narg.backquote = backquotelist;
11360 app = &n2->narg.next;
11363 n1->nfor.args = ap;
11364 if (lasttoken != TNL && lasttoken != TSEMI)
11365 raise_error_unexpected_syntax(-1);
11367 n2 = stzalloc(sizeof(struct narg));
11369 /*n2->narg.next = NULL; - stzalloc did it */
11370 n2->narg.text = (char *)dolatstr;
11371 /*n2->narg.backquote = NULL;*/
11372 n1->nfor.args = n2;
11374 * Newline or semicolon here is optional (but note
11375 * that the original Bourne shell only allowed NL).
11377 if (lasttoken != TSEMI)
11380 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11381 if (readtoken() != TDO)
11382 raise_error_unexpected_syntax(TDO);
11383 n1->nfor.body = list(0);
11387 n1 = stzalloc(sizeof(struct ncase));
11389 if (readtoken() != TWORD)
11390 raise_error_unexpected_syntax(TWORD);
11391 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11393 /*n2->narg.next = NULL; - stzalloc did it */
11394 n2->narg.text = wordtext;
11395 n2->narg.backquote = backquotelist;
11396 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11397 if (readtoken() != TIN)
11398 raise_error_unexpected_syntax(TIN);
11399 cpp = &n1->ncase.cases;
11401 checkkwd = CHKNL | CHKKWD;
11403 while (t != TESAC) {
11404 if (lasttoken == TLP)
11406 *cpp = cp = stzalloc(sizeof(struct nclist));
11408 app = &cp->nclist.pattern;
11410 *app = ap = stzalloc(sizeof(struct narg));
11412 /*ap->narg.next = NULL; - stzalloc did it */
11413 ap->narg.text = wordtext;
11414 ap->narg.backquote = backquotelist;
11415 if (readtoken() != TPIPE)
11417 app = &ap->narg.next;
11420 //ap->narg.next = NULL;
11421 if (lasttoken != TRP)
11422 raise_error_unexpected_syntax(TRP);
11423 cp->nclist.body = list(2);
11425 cpp = &cp->nclist.next;
11427 checkkwd = CHKNL | CHKKWD;
11431 raise_error_unexpected_syntax(TENDCASE);
11438 n1 = stzalloc(sizeof(struct nredir));
11439 n1->type = NSUBSHELL;
11440 n1->nredir.n = list(0);
11441 /*n1->nredir.redirect = NULL; - stzalloc did it */
11448 IF_BASH_FUNCTION(case TFUNCTION:)
11452 return simplecmd();
11455 if (readtoken() != t)
11456 raise_error_unexpected_syntax(t);
11459 /* Now check for redirection which may follow command */
11460 checkkwd = CHKKWD | CHKALIAS;
11462 while (readtoken() == TREDIR) {
11463 *rpp = n2 = redirnode;
11464 rpp = &n2->nfile.next;
11470 if (n1->type != NSUBSHELL) {
11471 n2 = stzalloc(sizeof(struct nredir));
11476 n1->nredir.redirect = redir;
11481 #if BASH_DOLLAR_SQUOTE
11483 decode_dollar_squote(void)
11485 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11491 p = strchr(C_escapes, c);
11496 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11500 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11502 } else if (c == 'x') { /* \xHH */
11506 } while (isxdigit(c) && --cnt);
11508 if (cnt == 3) { /* \x but next char is "bad" */
11512 } else { /* simple seq like \\ or \t */
11517 c = bb_process_escape_sequence((void*)&p);
11518 } else { /* unrecognized "\z": print both chars unless ' or " */
11519 if (c != '\'' && c != '"') {
11521 c |= 0x100; /* "please encode \, then me" */
11528 /* Used by expandstr to get here-doc like behaviour. */
11529 #define FAKEEOFMARK ((char*)(uintptr_t)1)
11531 static ALWAYS_INLINE int
11532 realeofmark(const char *eofmark)
11534 return eofmark && eofmark != FAKEEOFMARK;
11538 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11539 * is not NULL, read a here document. In the latter case, eofmark is the
11540 * word which marks the end of the document and striptabs is true if
11541 * leading tabs should be stripped from the document. The argument c
11542 * is the first character of the input token or document.
11544 * Because C does not have internal subroutines, I have simulated them
11545 * using goto's to implement the subroutine linkage. The following macros
11546 * will run code that appears at the end of readtoken1.
11548 #define CHECKEND() {goto checkend; checkend_return:;}
11549 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11550 #define PARSESUB() {goto parsesub; parsesub_return:;}
11551 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11552 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11553 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11555 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11557 /* NB: syntax parameter fits into smallint */
11558 /* c parameter is an unsigned char or PEOF or PEOA */
11561 struct nodelist *bqlist;
11565 IF_FEATURE_SH_MATH(smallint prevsyntax;) /* syntax before arithmetic */
11566 smallint pssyntax; /* we are expanding a prompt string */
11567 int varnest; /* levels of variables expansion */
11568 IF_FEATURE_SH_MATH(int arinest;) /* levels of arithmetic expansion */
11569 IF_FEATURE_SH_MATH(int parenlevel;) /* levels of parens in arithmetic */
11570 int dqvarnest; /* levels of variables expansion within double quotes */
11572 IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
11574 startlinno = g_parsefile->linno;
11577 IF_FEATURE_SH_MATH(prevsyntax = 0;)
11578 pssyntax = (syntax == PSSYNTAX);
11581 dblquote = (syntax == DQSYNTAX);
11583 IF_FEATURE_SH_MATH(arinest = 0;)
11584 IF_FEATURE_SH_MATH(parenlevel = 0;)
11587 STARTSTACKSTR(out);
11589 /* For each line, until end of word */
11590 CHECKEND(); /* set c to PEOF if at end of here document */
11591 for (;;) { /* until end of line or end of word */
11592 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11593 switch (SIT(c, syntax)) {
11594 case CNL: /* '\n' */
11595 if (syntax == BASESYNTAX)
11596 goto endword; /* exit outer loop */
11600 goto loop; /* continue outer loop */
11605 #if BASH_DOLLAR_SQUOTE
11606 if (c == '\\' && bash_dollar_squote) {
11607 c = decode_dollar_squote();
11609 /* skip $'\000', $'\x00' (like bash) */
11613 /* Unknown escape. Encode as '\z' */
11614 c = (unsigned char)c;
11615 if (eofmark == NULL || dblquote)
11616 USTPUTC(CTLESC, out);
11617 USTPUTC('\\', out);
11621 if (eofmark == NULL || dblquote)
11622 USTPUTC(CTLESC, out);
11625 case CBACK: /* backslash */
11626 c = pgetc_without_PEOA();
11628 USTPUTC(CTLESC, out);
11629 USTPUTC('\\', out);
11631 } else if (c == '\n') {
11634 if (c == '$' && pssyntax) {
11635 USTPUTC(CTLESC, out);
11636 USTPUTC('\\', out);
11638 /* Backslash is retained if we are in "str" and next char isn't special */
11643 && (c != '"' || eofmark != NULL)
11645 USTPUTC('\\', out);
11647 USTPUTC(CTLESC, out);
11655 if (eofmark == NULL) {
11656 USTPUTC(CTLQUOTEMARK, out);
11664 IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
11665 if (eofmark != NULL && varnest == 0) {
11668 if (dqvarnest == 0) {
11669 syntax = BASESYNTAX;
11676 case CVAR: /* '$' */
11677 PARSESUB(); /* parse substitution */
11679 case CENDVAR: /* '}' */
11682 if (dqvarnest > 0) {
11689 #if ENABLE_FEATURE_SH_MATH
11690 case CLP: /* '(' in arithmetic */
11694 case CRP: /* ')' in arithmetic */
11695 if (parenlevel > 0) {
11698 if (pgetc_eatbnl() == ')') {
11700 if (--arinest == 0) {
11701 syntax = prevsyntax;
11705 * unbalanced parens
11706 * (don't 2nd guess - no error)
11714 case CBQUOTE: /* '`' */
11718 goto endword; /* exit outer loop */
11722 if (varnest == 0) {
11723 #if BASH_REDIR_OUTPUT
11725 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11726 if (pgetc() == '>')
11727 c = 0x100 + '>'; /* flag &> */
11731 goto endword; /* exit outer loop */
11733 IF_ASH_ALIAS(if (c != PEOA))
11740 #if ENABLE_FEATURE_SH_MATH
11741 if (syntax == ARISYNTAX)
11742 raise_error_syntax("missing '))'");
11744 if (syntax != BASESYNTAX && eofmark == NULL)
11745 raise_error_syntax("unterminated quoted string");
11746 if (varnest != 0) {
11747 startlinno = g_parsefile->linno;
11749 raise_error_syntax("missing '}'");
11751 USTPUTC('\0', out);
11752 len = out - (char *)stackblock();
11753 out = stackblock();
11754 if (eofmark == NULL) {
11755 if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
11758 if (isdigit_str9(out)) {
11759 PARSEREDIR(); /* passed as params: out, c */
11760 lasttoken = TREDIR;
11763 /* else: non-number X seen, interpret it
11764 * as "NNNX>file" = "NNNX >file" */
11768 quoteflag = quotef;
11769 backquotelist = bqlist;
11770 grabstackblock(len);
11774 /* end of readtoken routine */
11777 * Check to see whether we are at the end of the here document. When this
11778 * is called, c is set to the first character of the next input line. If
11779 * we are at the end of the here document, this routine sets the c to PEOF.
11782 if (realeofmark(eofmark)) {
11786 #if ENABLE_ASH_ALIAS
11788 c = pgetc_without_PEOA();
11791 while (c == '\t') {
11792 c = pgetc_without_PEOA();
11796 markloc = out - (char *)stackblock();
11797 for (p = eofmark; STPUTC(c, out), *p; p++) {
11801 c = pgetc_without_PEOA();
11804 if (c == '\n' || c == PEOF) {
11806 g_parsefile->linno++;
11807 needprompt = doprompt;
11812 p = (char *)stackblock() + markloc + 1;
11813 len_here = out - p;
11816 len_here -= (c >= PEOF);
11822 str = alloca(len_here + 1);
11823 *(char *)mempcpy(str, p, len_here) = '\0';
11825 pushstring(str, NULL);
11830 STADJUST((char *)stackblock() + markloc - out, out);
11832 goto checkend_return;
11836 * Parse a redirection operator. The variable "out" points to a string
11837 * specifying the fd to be redirected. The variable "c" contains the
11838 * first character of the redirection operator.
11841 /* out is already checked to be a valid number or "" */
11842 int fd = (*out == '\0' ? -1 : atoi(out));
11845 np = stzalloc(sizeof(struct nfile));
11850 np->type = NAPPEND;
11852 np->type = NCLOBBER;
11855 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11861 #if BASH_REDIR_OUTPUT
11862 else if (c == 0x100 + '>') { /* this flags &> redirection */
11864 pgetc(); /* this is '>', no need to check */
11868 else { /* c == '<' */
11869 /*np->nfile.fd = 0; - stzalloc did it */
11873 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11874 np = stzalloc(sizeof(struct nhere));
11875 /*np->nfile.fd = 0; - stzalloc did it */
11878 heredoc = stzalloc(sizeof(struct heredoc));
11879 heredoc->here = np;
11882 heredoc->striptabs = 1;
11884 /*heredoc->striptabs = 0; - stzalloc did it */
11890 np->type = NFROMFD;
11894 np->type = NFROMTO;
11906 goto parseredir_return;
11910 * Parse a substitution. At this point, we have read the dollar sign
11911 * and nothing else.
11914 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11915 * (assuming ascii char codes, as the original implementation did) */
11916 #define is_special(c) \
11917 (((unsigned)(c) - 33 < 32) \
11918 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11920 unsigned char subtype;
11923 c = pgetc_eatbnl();
11924 if ((checkkwd & CHKEOFMARK)
11925 || c > 255 /* PEOA or PEOF */
11926 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11928 #if BASH_DOLLAR_SQUOTE
11929 if (syntax != DQSYNTAX && c == '\'')
11930 bash_dollar_squote = 1;
11935 } else if (c == '(') {
11936 /* $(command) or $((arith)) */
11937 if (pgetc_eatbnl() == '(') {
11938 #if ENABLE_FEATURE_SH_MATH
11941 raise_error_syntax("support for $((arith)) is disabled");
11948 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11949 USTPUTC(CTLVAR, out);
11950 typeloc = out - (char *)stackblock();
11952 subtype = VSNORMAL;
11954 c = pgetc_eatbnl();
11959 /* $[{[#]]NAME[}] */
11962 c = pgetc_eatbnl();
11963 } while (is_in_name(c));
11964 } else if (isdigit(c)) {
11965 /* $[{[#]]NUM[}] */
11968 c = pgetc_eatbnl();
11969 } while (isdigit(c));
11970 } else if (is_special(c)) {
11971 /* $[{[#]]<specialchar>[}] */
11974 c = pgetc_eatbnl();
11975 if (!subtype && cc == '#') {
11976 subtype = VSLENGTH;
11977 if (c == '_' || isalnum(c))
11980 c = pgetc_eatbnl();
11981 if (cc == '}' || c != '}') {
11992 if (c != '}' && subtype == VSLENGTH) {
11993 /* ${#VAR didn't end with } */
11997 if (subtype == 0) {
11998 static const char types[] ALIGN1 = "}-+?=";
11999 /* ${VAR...} but not $VAR or ${#VAR} */
12000 /* c == first char after VAR */
12003 c = pgetc_eatbnl();
12005 /* This check is only needed to not misinterpret
12006 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
12009 if (!strchr(types, c)) {
12010 subtype = VSSUBSTR;
12012 break; /* "goto badsub" is bigger (!) */
12018 const char *p = strchr(types, c);
12021 subtype |= p - types + VSNORMAL;
12027 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
12028 c = pgetc_eatbnl();
12034 #if BASH_PATTERN_SUBST
12036 /* ${v/[/]pattern/repl} */
12037 //TODO: encode pattern and repl separately.
12038 // Currently ${v/$var_with_slash/repl} is horribly broken
12039 subtype = VSREPLACE;
12040 c = pgetc_eatbnl();
12043 subtype++; /* VSREPLACEALL */
12051 ((unsigned char *)stackblock())[typeloc] = subtype;
12052 if (subtype != VSNORMAL) {
12059 goto parsesub_return;
12063 * Called to parse command substitutions. Newstyle is set if the command
12064 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
12065 * list of commands (passed by reference), and savelen is the number of
12066 * characters on the top of the stack which must be preserved.
12069 struct nodelist **nlpp;
12073 smallint saveprompt = 0;
12076 savelen = out - (char *)stackblock();
12079 * FIXME: this can allocate very large block on stack and SEGV.
12081 * echo "..<100kbytes>..`true` $(true) `true` ..."
12082 * allocates 100kb for every command subst. With about
12083 * a hundred command substitutions stack overflows.
12084 * With larger prepended string, SEGV happens sooner.
12086 str = alloca(savelen);
12087 memcpy(str, stackblock(), savelen);
12091 /* We must read until the closing backquote, giving special
12092 * treatment to some slashes, and then push the string and
12093 * reread it as input, interpreting it normally.
12099 STARTSTACKSTR(pout);
12103 setprompt_if(needprompt, 2);
12114 * If eating a newline, avoid putting
12115 * the newline into the new character
12116 * stream (via the STPUTC after the
12121 if (pc != '\\' && pc != '`' && pc != '$'
12122 && (!dblquote || pc != '"')
12124 STPUTC('\\', pout);
12126 if (pc <= 255 /* not PEOA or PEOF */) {
12132 IF_ASH_ALIAS(case PEOA:)
12133 startlinno = g_parsefile->linno;
12134 raise_error_syntax("EOF in backquote substitution");
12146 STPUTC('\0', pout);
12147 psavelen = pout - (char *)stackblock();
12148 if (psavelen > 0) {
12149 pstr = grabstackstr(pout);
12150 setinputstring(pstr);
12155 nlpp = &(*nlpp)->next;
12156 *nlpp = stzalloc(sizeof(**nlpp));
12157 /* (*nlpp)->next = NULL; - stzalloc did it */
12160 saveprompt = doprompt;
12167 doprompt = saveprompt;
12168 else if (readtoken() != TRP)
12169 raise_error_unexpected_syntax(TRP);
12174 * Start reading from old file again, ignoring any pushed back
12175 * tokens left from the backquote parsing
12180 while (stackblocksize() <= savelen)
12182 STARTSTACKSTR(out);
12184 memcpy(out, str, savelen);
12185 STADJUST(savelen, out);
12187 USTPUTC(CTLBACKQ, out);
12189 goto parsebackq_oldreturn;
12190 goto parsebackq_newreturn;
12193 #if ENABLE_FEATURE_SH_MATH
12195 * Parse an arithmetic expansion (indicate start of one and set state)
12198 if (++arinest == 1) {
12199 prevsyntax = syntax;
12200 syntax = ARISYNTAX;
12202 USTPUTC(CTLARI, out);
12203 goto parsearith_return;
12206 } /* end of readtoken */
12209 * Read the next input token.
12210 * If the token is a word, we set backquotelist to the list of cmds in
12211 * backquotes. We set quoteflag to true if any part of the word was
12213 * If the token is TREDIR, then we set redirnode to a structure containing
12215 * In all cases, the variable startlinno is set to the number of the line
12216 * on which the token starts.
12218 * [Change comment: here documents and internal procedures]
12219 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12220 * word parsing code into a separate routine. In this case, readtoken
12221 * doesn't need to have any internal procedures, but parseword does.
12222 * We could also make parseoperator in essence the main routine, and
12223 * have parseword (readtoken1?) handle both words and redirection.]
12225 #define NEW_xxreadtoken
12226 #ifdef NEW_xxreadtoken
12227 /* singles must be first! */
12228 static const char xxreadtoken_chars[7] ALIGN1 = {
12229 '\n', '(', ')', /* singles */
12230 '&', '|', ';', /* doubles */
12234 #define xxreadtoken_singles 3
12235 #define xxreadtoken_doubles 3
12237 static const char xxreadtoken_tokens[] ALIGN1 = {
12238 TNL, TLP, TRP, /* only single occurrence allowed */
12239 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12240 TEOF, /* corresponds to trailing nul */
12241 TAND, TOR, TENDCASE /* if double occurrence */
12253 setprompt_if(needprompt, 2);
12254 startlinno = g_parsefile->linno;
12255 for (;;) { /* until token or start of word found */
12257 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12261 while ((c = pgetc()) != '\n' && c != PEOF)
12264 } else if (c == '\\') {
12265 if (pgetc() != '\n') {
12267 break; /* return readtoken1(...) */
12273 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12279 p = strchr(xxreadtoken_chars, c);
12281 break; /* return readtoken1(...) */
12283 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12285 if (cc == c) { /* double occurrence? */
12286 p += xxreadtoken_doubles + 1;
12289 #if BASH_REDIR_OUTPUT
12290 if (c == '&' && cc == '>') /* &> */
12291 break; /* return readtoken1(...) */
12296 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12301 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12303 #else /* old xxreadtoken */
12304 #define RETURN(token) return lasttoken = token
12314 setprompt_if(needprompt, 2);
12315 startlinno = g_parsefile->linno;
12316 for (;;) { /* until token or start of word found */
12319 case ' ': case '\t':
12320 IF_ASH_ALIAS(case PEOA:)
12323 while ((c = pgetc()) != '\n' && c != PEOF)
12328 if (pgetc() == '\n') {
12340 if (pgetc() == '&')
12345 if (pgetc() == '|')
12350 if (pgetc() == ';')
12363 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12366 #endif /* old xxreadtoken */
12372 int kwd = checkkwd;
12374 smallint alreadyseen = tokpushback;
12377 #if ENABLE_ASH_ALIAS
12393 if (t != TWORD || quoteflag) {
12398 * check for keywords
12400 if (kwd & CHKKWD) {
12401 const char *const *pp;
12403 pp = findkwd(wordtext);
12405 lasttoken = t = pp - tokname_array;
12406 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12411 if (checkkwd & CHKALIAS) {
12412 #if ENABLE_ASH_ALIAS
12414 ap = lookupalias(wordtext, 1);
12417 pushstring(ap->val, ap);
12427 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12429 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12445 * Read and parse a command. Returns NODE_EOF on end of file.
12446 * (NULL is a valid parse tree indicating a blank line.)
12448 static union node *
12449 parsecmd(int interact)
12454 doprompt = interact;
12455 setprompt_if(doprompt, doprompt);
12461 * Input any here documents.
12466 struct heredoc *here;
12469 here = heredoclist;
12470 heredoclist = NULL;
12473 setprompt_if(needprompt, 2);
12474 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12475 here->eofmark, here->striptabs);
12476 n = stzalloc(sizeof(struct narg));
12477 n->narg.type = NARG;
12478 /*n->narg.next = NULL; - stzalloc did it */
12479 n->narg.text = wordtext;
12480 n->narg.backquote = backquotelist;
12481 here->here->nhere.doc = n;
12487 static const char *
12488 expandstr(const char *ps, int syntax_type)
12493 /* XXX Fix (char *) cast. */
12494 setinputstring((char *)ps);
12496 saveprompt = doprompt;
12498 readtoken1(pgetc(), syntax_type, FAKEEOFMARK, 0);
12499 doprompt = saveprompt;
12503 n.narg.type = NARG;
12504 n.narg.next = NULL;
12505 n.narg.text = wordtext;
12506 n.narg.backquote = backquotelist;
12508 expandarg(&n, NULL, EXP_QUOTED);
12509 return stackblock();
12515 return tokpushback && lasttoken == TEOF;
12519 * Execute a command or commands contained in a string.
12522 evalstring(char *s, int flags)
12524 struct jmploc *volatile savehandler;
12525 struct jmploc jmploc;
12529 struct stackmark smark;
12534 setstackmark(&smark);
12537 /* On exception inside execution loop, we must popfile().
12538 * Try interactively:
12540 * command eval "a=b" # throws "is read only" error
12541 * "command BLTIN" is not supposed to abort (even in non-interactive use).
12542 * But if we skip popfile(), we hit EOF in eval's string, and exit.
12544 savehandler = exception_handler;
12545 ex = setjmp(jmploc.loc);
12548 exception_handler = &jmploc;
12550 while ((n = parsecmd(0)) != NODE_EOF) {
12553 i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
12556 popstackmark(&smark);
12561 popstackmark(&smark);
12565 exception_handler = savehandler;
12567 longjmp(exception_handler->loc, ex);
12573 * The eval command.
12575 static int FAST_FUNC
12576 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12585 STARTSTACKSTR(concat);
12587 concat = stack_putstr(p, concat);
12591 STPUTC(' ', concat);
12593 STPUTC('\0', concat);
12594 p = grabstackstr(concat);
12596 return evalstring(p, flags & EV_TESTED);
12602 * Read and execute commands.
12603 * "Top" is nonzero for the top level command loop;
12604 * it turns on prompting if the shell is interactive.
12610 struct stackmark smark;
12615 TRACE(("cmdloop(%d) called\n", top));
12619 setstackmark(&smark);
12622 showjobs(SHOW_CHANGED|SHOW_STDERR);
12625 if (iflag && top) {
12629 n = parsecmd(inter);
12631 if (DEBUG > 2 && debug && (n != NODE_EOF))
12634 if (n == NODE_EOF) {
12635 if (!top || numeof >= 50)
12637 if (!stoppedjobs()) {
12640 out2str("\nUse \"exit\" to leave shell.\n");
12643 } else if (nflag == 0) {
12646 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12649 i = evaltree(n, 0);
12653 popstackmark(&smark);
12657 evalskip &= ~SKIPFUNC;
12665 * Take commands from a file. To be compatible we should do a path
12666 * search for the file, which is necessary to find sub-commands.
12669 find_dot_file(char *name)
12672 const char *path = pathval();
12675 /* don't try this for absolute or relative paths */
12676 if (strchr(name, '/'))
12679 while ((fullname = path_advance(&path, name)) != NULL) {
12680 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12682 * Don't bother freeing here, since it will
12683 * be freed by the caller.
12687 if (fullname != name)
12688 stunalloc(fullname);
12691 /* not found in the PATH */
12692 ash_msg_and_raise_error("%s: not found", name);
12696 static int FAST_FUNC
12697 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12699 /* "false; . empty_file; echo $?" should print 0, not 1: */
12703 char *args_need_save;
12704 volatile struct shparam saveparam;
12707 // struct strlist *sp;
12708 // for (sp = cmdenviron; sp; sp = sp->next)
12709 // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12711 nextopt(nullstr); /* handle possible "--" */
12715 /* bash says: "bash: .: filename argument required" */
12716 return 2; /* bash compat */
12719 /* This aborts if file isn't found, which is POSIXly correct.
12720 * bash returns exitcode 1 instead.
12722 fullname = find_dot_file(argv[0]);
12724 args_need_save = argv[0];
12725 if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
12727 saveparam = shellparam;
12728 shellparam.malloced = 0;
12732 shellparam.nparam = argc;
12733 shellparam.p = argv;
12736 /* This aborts if file can't be opened, which is POSIXly correct.
12737 * bash returns exitcode 1 instead.
12739 setinputfile(fullname, INPUT_PUSH_FILE);
12740 commandname = fullname;
12741 status = cmdloop(0);
12744 if (args_need_save) {
12745 freeparam(&shellparam);
12746 shellparam = saveparam;
12752 static int FAST_FUNC
12753 exitcmd(int argc UNUSED_PARAM, char **argv)
12758 exitstatus = number(argv[1]);
12759 raise_exception(EXEXIT);
12764 * Read a file containing shell functions.
12767 readcmdfile(char *name)
12769 setinputfile(name, INPUT_PUSH_FILE);
12775 /* ============ find_command inplementation */
12778 * Resolve a command name. If you change this routine, you may have to
12779 * change the shellexec routine as well.
12782 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12784 struct tblentry *cmdp;
12791 struct builtincmd *bcmd;
12793 /* If name contains a slash, don't use PATH or hash table */
12794 if (strchr(name, '/') != NULL) {
12795 entry->u.index = -1;
12796 if (act & DO_ABS) {
12797 while (stat(name, &statb) < 0) {
12799 if (errno == EINTR)
12802 entry->cmdtype = CMDUNKNOWN;
12806 entry->cmdtype = CMDNORMAL;
12810 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12812 updatetbl = (path == pathval());
12815 if (strstr(path, "%builtin") != NULL)
12816 act |= DO_ALTBLTIN;
12819 /* If name is in the table, check answer will be ok */
12820 cmdp = cmdlookup(name, 0);
12821 if (cmdp != NULL) {
12824 switch (cmdp->cmdtype) {
12842 } else if (cmdp->rehash == 0)
12843 /* if not invalidated by cd, we're done */
12847 /* If %builtin not in path, check for builtin next */
12848 bcmd = find_builtin(name);
12850 if (IS_BUILTIN_REGULAR(bcmd))
12851 goto builtin_success;
12852 if (act & DO_ALTPATH) {
12853 if (!(act & DO_ALTBLTIN))
12854 goto builtin_success;
12855 } else if (builtinloc <= 0) {
12856 goto builtin_success;
12860 #if ENABLE_FEATURE_SH_STANDALONE
12862 int applet_no = find_applet_by_name(name);
12863 if (applet_no >= 0) {
12864 entry->cmdtype = CMDNORMAL;
12865 entry->u.index = -2 - applet_no;
12871 /* We have to search path. */
12872 prev = -1; /* where to start */
12873 if (cmdp && cmdp->rehash) { /* doing a rehash */
12874 if (cmdp->cmdtype == CMDBUILTIN)
12877 prev = cmdp->param.index;
12883 while ((fullname = path_advance(&path, name)) != NULL) {
12884 stunalloc(fullname);
12885 /* NB: code below will still use fullname
12886 * despite it being "unallocated" */
12889 if (prefix(pathopt, "builtin")) {
12891 goto builtin_success;
12894 if ((act & DO_NOFUNC)
12895 || !prefix(pathopt, "func")
12896 ) { /* ignore unimplemented options */
12900 /* if rehash, don't redo absolute path names */
12901 if (fullname[0] == '/' && idx <= prev) {
12904 TRACE(("searchexec \"%s\": no change\n", name));
12907 while (stat(fullname, &statb) < 0) {
12909 if (errno == EINTR)
12912 if (errno != ENOENT && errno != ENOTDIR)
12916 e = EACCES; /* if we fail, this will be the error */
12917 if (!S_ISREG(statb.st_mode))
12919 if (pathopt) { /* this is a %func directory */
12920 stalloc(strlen(fullname) + 1);
12921 /* NB: stalloc will return space pointed by fullname
12922 * (because we don't have any intervening allocations
12923 * between stunalloc above and this stalloc) */
12924 readcmdfile(fullname);
12925 cmdp = cmdlookup(name, 0);
12926 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12927 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12928 stunalloc(fullname);
12931 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12933 entry->cmdtype = CMDNORMAL;
12934 entry->u.index = idx;
12938 cmdp = cmdlookup(name, 1);
12939 cmdp->cmdtype = CMDNORMAL;
12940 cmdp->param.index = idx;
12945 /* We failed. If there was an entry for this command, delete it */
12946 if (cmdp && updatetbl)
12947 delete_cmd_entry();
12949 ash_msg("%s: %s", name, errmsg(e, "not found"));
12950 entry->cmdtype = CMDUNKNOWN;
12955 entry->cmdtype = CMDBUILTIN;
12956 entry->u.cmd = bcmd;
12960 cmdp = cmdlookup(name, 1);
12961 cmdp->cmdtype = CMDBUILTIN;
12962 cmdp->param.cmd = bcmd;
12966 entry->cmdtype = cmdp->cmdtype;
12967 entry->u = cmdp->param;
12972 * The trap builtin.
12974 static int FAST_FUNC
12975 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12979 int signo, exitcode;
12984 for (signo = 0; signo < NSIG; signo++) {
12985 char *tr = trap_ptr[signo];
12987 /* note: bash adds "SIG", but only if invoked
12988 * as "bash". If called as "sh", or if set -o posix,
12989 * then it prints short signal names.
12990 * We are printing short names: */
12991 out1fmt("trap -- %s %s\n",
12993 get_signame(signo));
12994 /* trap_ptr != trap only if we are in special-cased `trap` code.
12995 * In this case, we will exit very soon, no need to free(). */
12996 /* if (trap_ptr != trap && tp[0]) */
13001 if (trap_ptr != trap) {
13009 /* Why the second check?
13010 * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
13011 * In this case, NUM is signal no, not an action.
13014 if (ap[1] && !is_number(ap[0]))
13019 signo = get_signum(*ap);
13021 /* Mimic bash message exactly */
13022 ash_msg("%s: invalid signal specification", *ap);
13028 if (LONE_DASH(action))
13031 if (action[0]) /* not NULL and not "" and not "-" */
13032 may_have_traps = 1;
13033 action = ckstrdup(action);
13037 trap[signo] = action;
13048 /* ============ Builtins */
13050 #if ENABLE_ASH_HELP
13051 static int FAST_FUNC
13052 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13058 "Built-in commands:\n"
13059 "------------------\n");
13060 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
13061 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
13062 builtintab[i].name + 1);
13068 # if ENABLE_FEATURE_SH_STANDALONE
13070 const char *a = applet_names;
13072 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
13077 while (*a++ != '\0')
13082 newline_and_flush(stdout);
13083 return EXIT_SUCCESS;
13088 static int FAST_FUNC
13089 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13091 show_history(line_input_state);
13092 return EXIT_SUCCESS;
13097 * The export and readonly commands.
13099 static int FAST_FUNC
13100 exportcmd(int argc UNUSED_PARAM, char **argv)
13110 /* "readonly" in bash accepts, but ignores -n.
13111 * We do the same: it saves a conditional in nextopt's param.
13114 while ((opt = nextopt("np")) != '\0') {
13116 flag_off = VEXPORT;
13119 if (argv[0][0] == 'r') {
13121 flag_off = 0; /* readonly ignores -n */
13123 flag_off = ~flag_off;
13125 /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
13131 p = strchr(name, '=');
13135 vp = *findvar(hashvar(name), name);
13137 vp->flags = ((vp->flags | flag) & flag_off);
13141 setvar(name, p, (flag & flag_off));
13142 } while ((name = *++aptr) != NULL);
13147 /* No arguments. Show the list of exported or readonly vars.
13150 showvars(argv[0], flag, 0);
13155 * Delete a function if it exists.
13158 unsetfunc(const char *name)
13160 struct tblentry *cmdp;
13162 cmdp = cmdlookup(name, 0);
13163 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
13164 delete_cmd_entry();
13168 * The unset builtin command. We unset the function before we unset the
13169 * variable to allow a function to be unset when there is a readonly variable
13170 * with the same name.
13172 static int FAST_FUNC
13173 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13179 while ((i = nextopt("vf")) != 0) {
13183 for (ap = argptr; *ap; ap++) {
13194 static const unsigned char timescmd_str[] ALIGN1 = {
13195 ' ', offsetof(struct tms, tms_utime),
13196 '\n', offsetof(struct tms, tms_stime),
13197 ' ', offsetof(struct tms, tms_cutime),
13198 '\n', offsetof(struct tms, tms_cstime),
13201 static int FAST_FUNC
13202 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13204 unsigned long clk_tck, s, t;
13205 const unsigned char *p;
13208 clk_tck = bb_clk_tck();
13213 t = *(clock_t *)(((char *) &buf) + p[1]);
13216 out1fmt("%lum%lu.%03lus%c",
13218 (t * 1000) / clk_tck,
13226 #if ENABLE_FEATURE_SH_MATH
13228 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13229 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13231 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13233 static int FAST_FUNC
13234 letcmd(int argc UNUSED_PARAM, char **argv)
13240 ash_msg_and_raise_error("expression expected");
13242 i = ash_arith(*argv);
13250 * The read builtin. Options:
13251 * -r Do not interpret '\' specially
13252 * -s Turn off echo (tty only)
13253 * -n NCHARS Read NCHARS max
13254 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13255 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13256 * -u FD Read from given FD instead of fd 0
13257 * This uses unbuffered input, which may be avoidable in some cases.
13258 * TODO: bash also has:
13259 * -a ARRAY Read into array[0],[1],etc
13260 * -d DELIM End on DELIM char, not newline
13261 * -e Use line editing (tty only)
13263 static int FAST_FUNC
13264 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13266 char *opt_n = NULL;
13267 char *opt_p = NULL;
13268 char *opt_t = NULL;
13269 char *opt_u = NULL;
13270 int read_flags = 0;
13274 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
13283 read_flags |= BUILTIN_READ_SILENT;
13289 read_flags |= BUILTIN_READ_RAW;
13299 /* "read -s" needs to save/restore termios, can't allow ^C
13300 * to jump out of it.
13304 r = shell_builtin_read(setvar0,
13306 bltinlookup("IFS"), /* can be NULL */
13315 if ((uintptr_t)r == 1 && errno == EINTR) {
13316 /* to get SIGCHLD: sleep 1 & read x; echo $x */
13317 if (pending_sig == 0)
13321 if ((uintptr_t)r > 1)
13322 ash_msg_and_raise_error(r);
13324 return (uintptr_t)r;
13327 static int FAST_FUNC
13328 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13330 static const char permuser[3] ALIGN1 = "ogu";
13333 int symbolic_mode = 0;
13335 while (nextopt("S") != '\0') {
13344 if (*argptr == NULL) {
13345 if (symbolic_mode) {
13346 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13353 *p++ = permuser[i];
13355 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13356 if (!(mask & 0400)) *p++ = 'r';
13357 if (!(mask & 0200)) *p++ = 'w';
13358 if (!(mask & 0100)) *p++ = 'x';
13366 out1fmt("%04o\n", mask);
13369 char *modestr = *argptr;
13370 /* numeric umasks are taken as-is */
13371 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13372 if (!isdigit(modestr[0]))
13374 mask = bb_parse_mode(modestr, mask);
13375 if ((unsigned)mask > 0777) {
13376 ash_msg_and_raise_error("illegal mode: %s", modestr);
13378 if (!isdigit(modestr[0]))
13385 static int FAST_FUNC
13386 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13388 return shell_builtin_ulimit(argv);
13391 /* ============ main() and helpers */
13394 * Called to exit the shell.
13403 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13404 save_history(line_input_state);
13406 status = exitstatus;
13407 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13408 if (setjmp(loc.loc)) {
13409 if (exception_type == EXEXIT)
13410 status = exitstatus;
13413 exception_handler = &loc;
13419 /*free(p); - we'll exit soon */
13422 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13423 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13426 flush_stdout_stderr();
13434 /* we will never free this */
13435 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13437 sigmode[SIGCHLD - 1] = S_DFL;
13438 setsignal(SIGCHLD);
13440 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13441 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13443 signal(SIGHUP, SIG_DFL);
13448 struct stat st1, st2;
13451 for (envp = environ; envp && *envp; envp++) {
13452 p = endofname(*envp);
13453 if (p != *envp && *p == '=') {
13454 setvareq(*envp, VEXPORT|VTEXTFIXED);
13458 setvareq((char*)defoptindvar, VTEXTFIXED);
13460 setvar0("PPID", utoa(getppid()));
13462 p = lookupvar("SHLVL");
13463 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13465 #if BASH_HOSTNAME_VAR
13466 if (!lookupvar("HOSTNAME")) {
13467 struct utsname uts;
13469 setvar0("HOSTNAME", uts.nodename);
13472 p = lookupvar("PWD");
13474 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13475 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13485 //usage:#define ash_trivial_usage
13486 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13487 //usage:#define ash_full_usage "\n\n"
13488 //usage: "Unix shell interpreter"
13491 * Process the shell command line arguments.
13494 procargs(char **argv)
13497 const char *xminusc;
13502 /* if (xargv[0]) - mmm, this is always true! */
13504 for (i = 0; i < NOPTS; i++)
13507 if (options(/*cmdline:*/ 1)) {
13508 /* it already printed err message */
13509 raise_exception(EXERROR);
13513 if (*xargv == NULL) {
13515 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13518 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13522 for (i = 0; i < NOPTS; i++)
13523 if (optlist[i] == 2)
13528 /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
13533 } else if (!sflag) {
13534 setinputfile(*xargv, 0);
13537 commandname = arg0;
13540 shellparam.p = xargv;
13541 #if ENABLE_ASH_GETOPTS
13542 shellparam.optind = 1;
13543 shellparam.optoff = -1;
13545 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13547 shellparam.nparam++;
13554 * Read /etc/profile, ~/.profile, $ENV.
13557 read_profile(const char *name)
13559 name = expandstr(name, DQSYNTAX);
13560 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13567 * This routine is called when an error or an interrupt occurs in an
13568 * interactive shell and control is returned to the main command loop.
13569 * (In dash, this function is auto-generated by build machinery).
13578 /* from expand.c: */
13581 /* from input.c: */
13582 g_parsefile->left_in_buffer = 0;
13583 g_parsefile->left_in_line = 0; /* clear input buffer */
13586 /* from redir.c: */
13588 popredir(/*drop:*/ 0, /*restore:*/ 0);
13591 unwindlocalvars(NULL);
13595 static short profile_buf[16384];
13596 extern int etext();
13600 * Main routine. We initialize things, parse the arguments, execute
13601 * profiles if we're a login shell, and then call cmdloop to execute
13602 * commands. The setjmp call sets up the location to jump to when an
13603 * exception occurs. When an exception occurs the variable "state"
13604 * is used to figure out how far we had gotten.
13606 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13607 int ash_main(int argc UNUSED_PARAM, char **argv)
13609 volatile smallint state;
13610 struct jmploc jmploc;
13611 struct stackmark smark;
13613 /* Initialize global data */
13617 #if ENABLE_ASH_ALIAS
13623 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13626 #if ENABLE_FEATURE_EDITING
13627 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13630 if (setjmp(jmploc.loc)) {
13636 e = exception_type;
13638 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13642 newline_and_flush(stderr);
13645 popstackmark(&smark);
13646 FORCE_INT_ON; /* enable interrupts */
13655 exception_handler = &jmploc;
13656 rootpid = getpid();
13659 setstackmark(&smark);
13662 TRACE(("Shell args: "));
13663 trace_puts_args(argv);
13666 if (argv[0] && argv[0][0] == '-')
13672 read_profile("/etc/profile");
13675 hp = lookupvar("HOME");
13677 read_profile("$HOME/.profile");
13683 getuid() == geteuid() && getgid() == getegid() &&
13687 const char *shinit = lookupvar("ENV");
13688 if (shinit != NULL && *shinit != '\0')
13689 read_profile(shinit);
13691 popstackmark(&smark);
13695 /* evalstring pushes parsefile stack.
13696 * Ensure we don't falsely claim that 0 (stdin)
13697 * is one of stacked source fds.
13698 * Testcase: ash -c 'exec 1>&0' must not complain. */
13699 // if (!sflag) g_parsefile->pf_fd = -1;
13700 // ^^ not necessary since now we special-case fd 0
13701 // in is_hidden_fd() to not be considered "hidden fd"
13702 evalstring(minusc, sflag ? 0 : EV_EXIT);
13705 if (sflag || minusc == NULL) {
13706 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13708 const char *hp = lookupvar("HISTFILE");
13710 hp = lookupvar("HOME");
13713 hp = concat_path_file(hp, ".ash_history");
13714 setvar0("HISTFILE", hp);
13717 hp = lookupvar("HISTFILE");
13721 line_input_state->hist_file = hp;
13722 # if ENABLE_FEATURE_SH_HISTFILESIZE
13723 hp = lookupvar("HISTFILESIZE");
13724 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13728 state4: /* XXX ??? - why isn't this before the "if" statement */
13736 extern void _mcleanup(void);
13740 TRACE(("End of main reached\n"));
13747 * Copyright (c) 1989, 1991, 1993, 1994
13748 * The Regents of the University of California. All rights reserved.
13750 * This code is derived from software contributed to Berkeley by
13751 * Kenneth Almquist.
13753 * Redistribution and use in source and binary forms, with or without
13754 * modification, are permitted provided that the following conditions
13756 * 1. Redistributions of source code must retain the above copyright
13757 * notice, this list of conditions and the following disclaimer.
13758 * 2. Redistributions in binary form must reproduce the above copyright
13759 * notice, this list of conditions and the following disclaimer in the
13760 * documentation and/or other materials provided with the distribution.
13761 * 3. Neither the name of the University nor the names of its contributors
13762 * may be used to endorse or promote products derived from this software
13763 * without specific prior written permission.
13765 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13766 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13767 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13768 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13769 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13770 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13771 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13772 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13773 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13774 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF