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
191 #define BASH_XTRACEFD ENABLE_ASH_BASH_COMPAT
192 #define BASH_READ_D ENABLE_ASH_BASH_COMPAT
193 #define IF_BASH_READ_D IF_ASH_BASH_COMPAT
195 #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
196 /* Bionic at least up to version 24 has no glob() */
197 # undef ENABLE_ASH_INTERNAL_GLOB
198 # define ENABLE_ASH_INTERNAL_GLOB 1
201 #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
202 # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
203 # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
204 # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
205 # error glob() should unbackslash them and match. uClibc does not unbackslash,
206 # error fails to match dirname, subsequently not expanding <pattern> in it.
208 // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
209 // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
212 #if !ENABLE_ASH_INTERNAL_GLOB
217 #include "shell_common.h"
218 #if ENABLE_FEATURE_SH_MATH
221 typedef long arith_t;
222 # define ARITH_FMT "%ld"
224 #if ENABLE_ASH_RANDOM_SUPPORT
227 # define CLEAR_RANDOM_T(rnd) ((void)0)
230 #include "NUM_APPLETS.h"
232 /* STANDALONE does not make sense, and won't compile */
233 # undef CONFIG_FEATURE_SH_STANDALONE
234 # undef ENABLE_FEATURE_SH_STANDALONE
235 # undef IF_FEATURE_SH_STANDALONE
236 # undef IF_NOT_FEATURE_SH_STANDALONE
237 # define ENABLE_FEATURE_SH_STANDALONE 0
238 # define IF_FEATURE_SH_STANDALONE(...)
239 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
243 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
247 # error "Do not even bother, ash will not run on NOMMU machine"
251 /* ============ Hash table sizes. Configurable. */
255 #define CMDTABLESIZE 31 /* should be prime */
258 /* ============ Shell options */
260 static const char *const optletters_optnames[] = {
284 #define optletters(n) optletters_optnames[n][0]
285 #define optnames(n) (optletters_optnames[n] + 1)
287 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
290 /* ============ Misc data */
292 #define msg_illnum "Illegal number: %s"
295 * We enclose jmp_buf in a structure so that we can declare pointers to
296 * jump locations. The global variable handler contains the location to
297 * jump to when an exception occurs, and the global variable exception_type
298 * contains a code identifying the exception. To implement nested
299 * exception handlers, the user should save the value of handler on entry
300 * to an inner scope, set handler to point to a jmploc structure for the
301 * inner scope, and restore handler on exit from the scope.
307 struct globals_misc {
308 uint8_t exitstatus; /* exit status of last command */
309 uint8_t back_exitstatus;/* exit status of backquoted command */
310 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
311 int rootpid; /* pid of main shell */
312 /* shell level: 0 for the main shell, 1 for its children, and so on */
314 #define rootshell (!shlvl)
315 char *minusc; /* argument to -c option */
317 char *curdir; // = nullstr; /* current working directory */
318 char *physdir; // = nullstr; /* physical working directory */
320 char *arg0; /* value of $0 */
322 struct jmploc *exception_handler;
324 volatile int suppress_int; /* counter */
325 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
326 volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
327 volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
328 smallint exception_type; /* kind of exception (0..5) */
330 #define EXINT 0 /* SIGINT received */
331 #define EXERROR 1 /* a generic error */
332 #define EXEXIT 4 /* exit the shell */
334 char nullstr[1]; /* zero length string */
337 #define eflag optlist[0]
338 #define fflag optlist[1]
339 #define Iflag optlist[2]
340 #define iflag optlist[3]
341 #define mflag optlist[4]
342 #define nflag optlist[5]
343 #define sflag optlist[6]
344 #define xflag optlist[7]
345 #define vflag optlist[8]
346 #define Cflag optlist[9]
347 #define aflag optlist[10]
348 #define bflag optlist[11]
349 #define uflag optlist[12]
350 #define viflag optlist[13]
352 # define pipefail optlist[14]
357 # define nolog optlist[14 + BASH_PIPEFAIL]
358 # define debug optlist[15 + BASH_PIPEFAIL]
361 /* trap handler commands */
363 * Sigmode records the current value of the signal handlers for the various
364 * modes. A value of zero means that the current handler is not known.
365 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
367 char sigmode[NSIG - 1];
368 #define S_DFL 1 /* default signal handling (SIG_DFL) */
369 #define S_CATCH 2 /* signal is caught */
370 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
371 #define S_HARD_IGN 4 /* signal is ignored permanently (it was SIG_IGN on entry to shell) */
373 /* indicates specified signal received */
374 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
375 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
377 char **trap_ptr; /* used only by "trap hack" */
379 /* Rarely referenced stuff */
380 #if ENABLE_ASH_RANDOM_SUPPORT
383 pid_t backgndpid; /* pid of last background process */
385 extern struct globals_misc *const ash_ptr_to_globals_misc;
386 #define G_misc (*ash_ptr_to_globals_misc)
387 #define exitstatus (G_misc.exitstatus )
388 #define back_exitstatus (G_misc.back_exitstatus )
389 #define job_warning (G_misc.job_warning)
390 #define rootpid (G_misc.rootpid )
391 #define shlvl (G_misc.shlvl )
392 #define minusc (G_misc.minusc )
393 #define curdir (G_misc.curdir )
394 #define physdir (G_misc.physdir )
395 #define arg0 (G_misc.arg0 )
396 #define exception_handler (G_misc.exception_handler)
397 #define exception_type (G_misc.exception_type )
398 #define suppress_int (G_misc.suppress_int )
399 #define pending_int (G_misc.pending_int )
400 #define got_sigchld (G_misc.got_sigchld )
401 #define pending_sig (G_misc.pending_sig )
402 #define nullstr (G_misc.nullstr )
403 #define optlist (G_misc.optlist )
404 #define sigmode (G_misc.sigmode )
405 #define gotsig (G_misc.gotsig )
406 #define may_have_traps (G_misc.may_have_traps )
407 #define trap (G_misc.trap )
408 #define trap_ptr (G_misc.trap_ptr )
409 #define random_gen (G_misc.random_gen )
410 #define backgndpid (G_misc.backgndpid )
411 #define INIT_G_misc() do { \
412 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
420 /* ============ DEBUG */
422 static void trace_printf(const char *fmt, ...);
423 static void trace_vprintf(const char *fmt, va_list va);
424 # define TRACE(param) trace_printf param
425 # define TRACEV(param) trace_vprintf param
426 # define close(fd) do { \
428 if (close(dfd) < 0) \
429 bb_error_msg("bug on %d: closing %d(0x%x)", \
430 __LINE__, dfd, dfd); \
433 # define TRACE(param)
434 # define TRACEV(param)
438 /* ============ Utility functions */
439 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
440 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
443 isdigit_str9(const char *str)
445 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
446 while (--maxlen && isdigit(*str))
448 return (*str == '\0');
452 var_end(const char *var)
461 /* ============ Interrupts / exceptions */
463 static void exitshell(void) NORETURN;
466 * These macros allow the user to suspend the handling of interrupt signals
467 * over a period of time. This is similar to SIGHOLD or to sigblock, but
468 * much more efficient and portable. (But hacking the kernel is so much
469 * more fun than worrying about efficiency and portability. :-))
472 # define INT_OFF do { \
473 TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
478 # define INT_OFF do { \
485 * Called to raise an exception. Since C doesn't include exceptions, we
486 * just do a longjmp to the exception handler. The type of exception is
487 * stored in the global variable "exception_type".
489 static void raise_exception(int) NORETURN;
491 raise_exception(int e)
494 if (exception_handler == NULL)
499 longjmp(exception_handler->loc, 1);
502 #define raise_exception(e) do { \
503 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
504 raise_exception(e); \
509 * Called when a SIGINT is received. (If the user specifies
510 * that SIGINT is to be trapped or ignored using the trap builtin, then
511 * this routine is not called.) Suppressint is nonzero when interrupts
512 * are held using the INT_OFF macro. (The test for iflag is just
513 * defensive programming.)
515 static void raise_interrupt(void) NORETURN;
517 raise_interrupt(void)
520 /* Signal is not automatically unmasked after it is raised,
521 * do it ourself - unmask all signals */
522 sigprocmask_allsigs(SIG_UNBLOCK);
523 /* pending_sig = 0; - now done in signal_handler() */
525 if (!(rootshell && iflag)) {
526 /* Kill ourself with SIGINT */
527 signal(SIGINT, SIG_DFL);
530 /* bash: ^C even on empty command line sets $? */
531 exitstatus = SIGINT + 128;
532 raise_exception(EXINT);
536 #define raise_interrupt() do { \
537 TRACE(("raising interrupt on line %d\n", __LINE__)); \
542 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
546 if (--suppress_int == 0 && pending_int) {
551 # define INT_ON do { \
552 TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
556 # define INT_ON int_on()
558 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
566 #define FORCE_INT_ON force_int_on()
568 #define SAVE_INT(v) ((v) = suppress_int)
570 #define RESTORE_INT(v) do { \
572 suppress_int = (v); \
573 if (suppress_int == 0 && pending_int) \
578 /* ============ Stdout/stderr output */
581 outstr(const char *p, FILE *file)
589 flush_stdout_stderr(void)
596 /* Was called outcslow(c,FILE*), but c was always '\n' */
598 newline_and_flush(FILE *dest)
606 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
608 out1fmt(const char *fmt, ...)
615 r = vprintf(fmt, ap);
621 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
623 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
630 ret = vsnprintf(outbuf, length, fmt, ap);
637 out1str(const char *p)
643 out2str(const char *p)
646 flush_stdout_stderr();
650 /* ============ Parser structures */
652 /* control characters in argument strings */
653 #define CTL_FIRST CTLESC
654 #define CTLESC ((unsigned char)'\201') /* escape next character */
655 #define CTLVAR ((unsigned char)'\202') /* variable defn */
656 #define CTLENDVAR ((unsigned char)'\203')
657 #define CTLBACKQ ((unsigned char)'\204')
658 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
659 #define CTLENDARI ((unsigned char)'\207')
660 #define CTLQUOTEMARK ((unsigned char)'\210')
661 #define CTL_LAST CTLQUOTEMARK
663 /* variable substitution byte (follows CTLVAR) */
664 #define VSTYPE 0x0f /* type of variable substitution */
665 #define VSNUL 0x10 /* colon--treat the empty string as unset */
667 /* values of VSTYPE field */
668 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
669 #define VSMINUS 0x2 /* ${var-text} */
670 #define VSPLUS 0x3 /* ${var+text} */
671 #define VSQUESTION 0x4 /* ${var?message} */
672 #define VSASSIGN 0x5 /* ${var=text} */
673 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
674 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
675 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
676 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
677 #define VSLENGTH 0xa /* ${#var} */
679 #define VSSUBSTR 0xc /* ${var:position:length} */
681 #if BASH_PATTERN_SUBST
682 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
683 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
686 static const char dolatstr[] ALIGN1 = {
687 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
689 #define DOLATSTRLEN 6
708 #if BASH_REDIR_OUTPUT
725 smallint type; /* Nxxxx */
728 union node *redirect;
733 smallint pipe_backgnd;
734 struct nodelist *cmdlist;
740 union node *redirect;
753 union node *elsepart;
780 struct nodelist *backquote;
783 /* nfile and ndup layout must match!
784 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
785 * that it is actually NTO2 (>&file), and change its type.
802 char *_unused_expfname;
821 struct nredir nredir;
822 struct nbinary nbinary;
826 struct nclist nclist;
835 * NODE_EOF is returned by parsecmd when it encounters an end of file.
836 * It must be distinct from NULL.
838 #define NODE_EOF ((union node *) -1L)
841 struct nodelist *next;
854 freefunc(struct funcnode *f)
856 if (f && --f->count < 0)
861 /* ============ Debugging output */
865 static FILE *tracefile;
868 trace_printf(const char *fmt, ...)
875 fprintf(tracefile, "%u ", (int) time(NULL));
877 fprintf(tracefile, "[%u] ", (int) getpid());
879 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
881 vfprintf(tracefile, fmt, va);
886 trace_vprintf(const char *fmt, va_list va)
890 vfprintf(tracefile, fmt, va);
891 fprintf(tracefile, "\n");
895 trace_puts(const char *s)
903 trace_puts_quoted(char *s)
910 putc('"', tracefile);
911 for (p = s; *p; p++) {
912 switch ((unsigned char)*p) {
913 case '\n': c = 'n'; goto backslash;
914 case '\t': c = 't'; goto backslash;
915 case '\r': c = 'r'; goto backslash;
916 case '\"': c = '\"'; goto backslash;
917 case '\\': c = '\\'; goto backslash;
918 case CTLESC: c = 'e'; goto backslash;
919 case CTLVAR: c = 'v'; goto backslash;
920 case CTLBACKQ: c = 'q'; goto backslash;
922 putc('\\', tracefile);
926 if (*p >= ' ' && *p <= '~')
929 putc('\\', tracefile);
930 putc((*p >> 6) & 03, tracefile);
931 putc((*p >> 3) & 07, tracefile);
932 putc(*p & 07, tracefile);
937 putc('"', tracefile);
941 trace_puts_args(char **ap)
948 trace_puts_quoted(*ap);
950 putc('\n', tracefile);
953 putc(' ', tracefile);
968 /* leave open because libedit might be using it */
971 strcpy(s, "./trace");
973 if (!freopen(s, "a", tracefile)) {
974 fprintf(stderr, "Can't re-open %s\n", s);
979 tracefile = fopen(s, "a");
980 if (tracefile == NULL) {
981 fprintf(stderr, "Can't open %s\n", s);
987 flags = fcntl(fileno(tracefile), F_GETFL);
989 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
991 setlinebuf(tracefile);
992 fputs("\nTracing started.\n", tracefile);
996 indent(int amount, char *pfx, FILE *fp)
1000 for (i = 0; i < amount; i++) {
1001 if (pfx && i == amount - 1)
1007 /* little circular references here... */
1008 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
1011 sharg(union node *arg, FILE *fp)
1014 struct nodelist *bqlist;
1015 unsigned char subtype;
1017 if (arg->type != NARG) {
1018 out1fmt("<node type %d>\n", arg->type);
1021 bqlist = arg->narg.backquote;
1022 for (p = arg->narg.text; *p; p++) {
1023 switch ((unsigned char)*p) {
1032 if (subtype == VSLENGTH)
1040 if (subtype & VSNUL)
1043 switch (subtype & VSTYPE) {
1069 case VSTRIMRIGHTMAX:
1076 out1fmt("<subtype %d>", subtype);
1085 shtree(bqlist->n, -1, NULL, fp);
1096 shcmd(union node *cmd, FILE *fp)
1104 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1110 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1114 switch (np->nfile.type) {
1115 case NTO: s = ">>"+1; dftfd = 1; break;
1116 case NCLOBBER: s = ">|"; dftfd = 1; break;
1117 case NAPPEND: s = ">>"; dftfd = 1; break;
1118 #if BASH_REDIR_OUTPUT
1121 case NTOFD: s = ">&"; dftfd = 1; break;
1122 case NFROM: s = "<"; break;
1123 case NFROMFD: s = "<&"; break;
1124 case NFROMTO: s = "<>"; break;
1125 default: s = "*error*"; break;
1127 if (np->nfile.fd != dftfd)
1128 fprintf(fp, "%d", np->nfile.fd);
1130 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1131 fprintf(fp, "%d", np->ndup.dupfd);
1133 sharg(np->nfile.fname, fp);
1140 shtree(union node *n, int ind, char *pfx, FILE *fp)
1142 struct nodelist *lp;
1148 indent(ind, pfx, fp);
1150 if (n == NODE_EOF) {
1165 shtree(n->nbinary.ch1, ind, NULL, fp);
1168 shtree(n->nbinary.ch2, ind, NULL, fp);
1176 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1177 shtree(lp->n, 0, NULL, fp);
1181 if (n->npipe.pipe_backgnd)
1187 fprintf(fp, "<node type %d>", n->type);
1195 showtree(union node *n)
1197 trace_puts("showtree called\n");
1198 shtree(n, 1, NULL, stderr);
1204 /* ============ Parser data */
1207 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1210 struct strlist *next;
1217 struct strpush *prev; /* preceding string on stack */
1219 int prev_left_in_line;
1220 #if ENABLE_ASH_ALIAS
1221 struct alias *ap; /* if push was associated with an alias */
1223 char *string; /* remember the string since it may change */
1225 /* Remember last two characters for pungetc. */
1228 /* Number of outstanding calls to pungetc. */
1233 struct parsefile *prev; /* preceding file on stack */
1234 int linno; /* current line */
1235 int pf_fd; /* file descriptor (or -1 if string) */
1236 int left_in_line; /* number of chars left in this line */
1237 int left_in_buffer; /* number of chars left in this buffer past the line */
1238 char *next_to_pgetc; /* next char in buffer */
1239 char *buf; /* input buffer */
1240 struct strpush *strpush; /* for pushing strings at this level */
1241 struct strpush basestrpush; /* so pushing one is fast */
1243 /* Remember last two characters for pungetc. */
1246 /* Number of outstanding calls to pungetc. */
1250 static struct parsefile basepf; /* top level input file */
1251 static struct parsefile *g_parsefile = &basepf; /* current input file */
1252 static int startlinno; /* line # where last token started */
1253 static char *commandname; /* currently executing command */
1256 /* ============ Message printing */
1259 ash_vmsg(const char *msg, va_list ap)
1261 fprintf(stderr, "%s: ", arg0);
1263 if (strcmp(arg0, commandname))
1264 fprintf(stderr, "%s: ", commandname);
1265 if (!iflag || g_parsefile->pf_fd > 0)
1266 fprintf(stderr, "line %d: ", startlinno);
1268 vfprintf(stderr, msg, ap);
1269 newline_and_flush(stderr);
1273 * Exverror is called to raise the error exception. If the second argument
1274 * is not NULL then error prints an error message using printf style
1275 * formatting. It then raises the error exception.
1277 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1279 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1283 TRACE(("ash_vmsg_and_raise(%d):", cond));
1286 TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
1291 flush_stdout_stderr();
1292 raise_exception(cond);
1296 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1298 ash_msg_and_raise_error(const char *msg, ...)
1305 ash_vmsg_and_raise(EXERROR, msg, ap);
1311 * Use '%m' to append error string on platforms that support it, '%s' and
1312 * strerror() on those that don't.
1314 * 'fmt' must be a string literal.
1316 #ifdef HAVE_PRINTF_PERCENTM
1317 #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": %m", ##__VA_ARGS__)
1319 #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": %s", ##__VA_ARGS__, strerror(errno))
1322 static void raise_error_syntax(const char *) NORETURN;
1324 raise_error_syntax(const char *msg)
1326 ash_msg_and_raise_error("syntax error: %s", msg);
1330 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1332 ash_msg_and_raise(int cond, const char *msg, ...)
1337 ash_vmsg_and_raise(cond, msg, ap);
1343 * error/warning routines for external builtins
1346 ash_msg(const char *fmt, ...)
1356 * Return a string describing an error. The returned string may be a
1357 * pointer to a static buffer that will be overwritten on the next call.
1358 * Action describes the operation that got the error.
1361 errmsg(int e, const char *em)
1363 if (e == ENOENT || e == ENOTDIR) {
1370 /* ============ Memory allocation */
1373 /* I consider these wrappers nearly useless:
1374 * ok, they return you to nearest exception handler, but
1375 * how much memory do you leak in the process, making
1376 * memory starvation worse?
1379 ckrealloc(void * p, size_t nbytes)
1381 p = realloc(p, nbytes);
1383 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1388 ckmalloc(size_t nbytes)
1390 return ckrealloc(NULL, nbytes);
1394 ckzalloc(size_t nbytes)
1396 return memset(ckmalloc(nbytes), 0, nbytes);
1400 ckstrdup(const char *s)
1402 char *p = strdup(s);
1404 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1408 /* Using bbox equivalents. They exit if out of memory */
1409 # define ckrealloc xrealloc
1410 # define ckmalloc xmalloc
1411 # define ckzalloc xzalloc
1412 # define ckstrdup xstrdup
1416 * It appears that grabstackstr() will barf with such alignments
1417 * because stalloc() will return a string allocated in a new stackblock.
1419 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1421 /* Most machines require the value returned from malloc to be aligned
1422 * in some way. The following macro will get this right
1423 * on many machines. */
1424 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1425 /* Minimum size of a block */
1426 MINSIZE = SHELL_ALIGN(504),
1429 struct stack_block {
1430 struct stack_block *prev;
1431 char space[MINSIZE];
1435 struct stack_block *stackp;
1441 struct globals_memstack {
1442 struct stack_block *g_stackp; // = &stackbase;
1443 char *g_stacknxt; // = stackbase.space;
1444 char *sstrend; // = stackbase.space + MINSIZE;
1445 size_t g_stacknleft; // = MINSIZE;
1446 struct stack_block stackbase;
1448 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1449 #define G_memstack (*ash_ptr_to_globals_memstack)
1450 #define g_stackp (G_memstack.g_stackp )
1451 #define g_stacknxt (G_memstack.g_stacknxt )
1452 #define sstrend (G_memstack.sstrend )
1453 #define g_stacknleft (G_memstack.g_stacknleft)
1454 #define stackbase (G_memstack.stackbase )
1455 #define INIT_G_memstack() do { \
1456 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1458 g_stackp = &stackbase; \
1459 g_stacknxt = stackbase.space; \
1460 g_stacknleft = MINSIZE; \
1461 sstrend = stackbase.space + MINSIZE; \
1465 #define stackblock() ((void *)g_stacknxt)
1466 #define stackblocksize() g_stacknleft
1469 * Parse trees for commands are allocated in lifo order, so we use a stack
1470 * to make this more efficient, and also to avoid all sorts of exception
1471 * handling code to handle interrupts in the middle of a parse.
1473 * The size 504 was chosen because the Ultrix malloc handles that size
1477 stalloc(size_t nbytes)
1482 aligned = SHELL_ALIGN(nbytes);
1483 if (aligned > g_stacknleft) {
1486 struct stack_block *sp;
1488 blocksize = aligned;
1489 if (blocksize < MINSIZE)
1490 blocksize = MINSIZE;
1491 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1492 if (len < blocksize)
1493 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1496 sp->prev = g_stackp;
1497 g_stacknxt = sp->space;
1498 g_stacknleft = blocksize;
1499 sstrend = g_stacknxt + blocksize;
1504 g_stacknxt += aligned;
1505 g_stacknleft -= aligned;
1510 stzalloc(size_t nbytes)
1512 return memset(stalloc(nbytes), 0, nbytes);
1519 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1520 write(STDERR_FILENO, "stunalloc\n", 10);
1524 g_stacknleft += g_stacknxt - (char *)p;
1529 * Like strdup but works with the ash stack.
1532 sstrdup(const char *p)
1534 size_t len = strlen(p) + 1;
1535 return memcpy(stalloc(len), p, len);
1539 grabstackblock(size_t len)
1545 pushstackmark(struct stackmark *mark, size_t len)
1547 mark->stackp = g_stackp;
1548 mark->stacknxt = g_stacknxt;
1549 mark->stacknleft = g_stacknleft;
1550 grabstackblock(len);
1554 setstackmark(struct stackmark *mark)
1556 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1560 popstackmark(struct stackmark *mark)
1562 struct stack_block *sp;
1568 while (g_stackp != mark->stackp) {
1570 g_stackp = sp->prev;
1573 g_stacknxt = mark->stacknxt;
1574 g_stacknleft = mark->stacknleft;
1575 sstrend = mark->stacknxt + mark->stacknleft;
1580 * When the parser reads in a string, it wants to stick the string on the
1581 * stack and only adjust the stack pointer when it knows how big the
1582 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1583 * of space on top of the stack and stackblocklen returns the length of
1584 * this block. Growstackblock will grow this space by at least one byte,
1585 * possibly moving it (like realloc). Grabstackblock actually allocates the
1586 * part of the block that has been used.
1589 growstackblock(void)
1593 newlen = g_stacknleft * 2;
1594 if (newlen < g_stacknleft)
1595 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1599 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1600 struct stack_block *sp;
1601 struct stack_block *prevstackp;
1606 prevstackp = sp->prev;
1607 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1608 sp = ckrealloc(sp, grosslen);
1609 sp->prev = prevstackp;
1611 g_stacknxt = sp->space;
1612 g_stacknleft = newlen;
1613 sstrend = sp->space + newlen;
1616 char *oldspace = g_stacknxt;
1617 size_t oldlen = g_stacknleft;
1618 char *p = stalloc(newlen);
1620 /* free the space we just allocated */
1621 g_stacknxt = memcpy(p, oldspace, oldlen);
1622 g_stacknleft += newlen;
1627 * The following routines are somewhat easier to use than the above.
1628 * The user declares a variable of type STACKSTR, which may be declared
1629 * to be a register. The macro STARTSTACKSTR initializes things. Then
1630 * the user uses the macro STPUTC to add characters to the string. In
1631 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1632 * grown as necessary. When the user is done, she can just leave the
1633 * string there and refer to it using stackblock(). Or she can allocate
1634 * the space for it using grabstackstr(). If it is necessary to allow
1635 * someone else to use the stack temporarily and then continue to grow
1636 * the string, the user should use grabstack to allocate the space, and
1637 * then call ungrabstr(p) to return to the previous mode of operation.
1639 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1640 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1641 * is space for at least one character.
1646 size_t len = stackblocksize();
1648 return (char *)stackblock() + len;
1652 * Called from CHECKSTRSPACE.
1655 makestrspace(size_t newlen, char *p)
1657 size_t len = p - g_stacknxt;
1663 size = stackblocksize();
1665 if (nleft >= newlen)
1669 return (char *)stackblock() + len;
1673 stack_nputstr(const char *s, size_t n, char *p)
1675 p = makestrspace(n, p);
1676 p = (char *)mempcpy(p, s, n);
1681 stack_putstr(const char *s, char *p)
1683 return stack_nputstr(s, strlen(s), p);
1687 _STPUTC(int c, char *p)
1695 #define STARTSTACKSTR(p) ((p) = stackblock())
1696 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1697 #define CHECKSTRSPACE(n, p) do { \
1700 size_t m = sstrend - q; \
1702 (p) = makestrspace(l, q); \
1704 #define USTPUTC(c, p) (*(p)++ = (c))
1705 #define STACKSTRNUL(p) do { \
1706 if ((p) == sstrend) \
1707 (p) = growstackstr(); \
1710 #define STUNPUTC(p) (--(p))
1711 #define STTOPC(p) ((p)[-1])
1712 #define STADJUST(amount, p) ((p) += (amount))
1714 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1715 #define ungrabstackstr(s, p) stunalloc(s)
1716 #define stackstrend() ((void *)sstrend)
1719 /* ============ String helpers */
1722 * prefix -- see if pfx is a prefix of string.
1725 prefix(const char *string, const char *pfx)
1728 if (*pfx++ != *string++)
1731 return (char *) string;
1735 * Check for a valid number. This should be elsewhere.
1738 is_number(const char *p)
1743 } while (*++p != '\0');
1748 * Convert a string of digits to an integer, printing an error message on
1752 number(const char *s)
1755 ash_msg_and_raise_error(msg_illnum, s);
1760 * Produce a single quoted string suitable as input to the shell.
1761 * The return string is allocated on the stack.
1764 single_quote(const char *s)
1774 len = strchrnul(s, '\'') - s;
1776 q = p = makestrspace(len + 3, p);
1779 q = (char *)mempcpy(q, s, len);
1788 do len++; while (*++s == '\'');
1790 q = p = makestrspace(len + 3, p);
1793 q = (char *)mempcpy(q, s - len, len);
1801 return stackblock();
1805 * Produce a possibly single quoted string suitable as input to the shell.
1806 * If quoting was done, the return string is allocated on the stack,
1807 * otherwise a pointer to the original string is returned.
1810 maybe_single_quote(const char *s)
1815 /* Assuming ACSII */
1816 /* quote ctrl_chars space !"#$%&'()* */
1820 if (*p >= ';' && *p <= '?')
1829 /* quote {|}~ DEL and high bytes */
1832 /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
1833 /* TODO: maybe avoid quoting % */
1839 return single_quote(s);
1843 /* ============ nextopt */
1845 static char **argptr; /* argument list for builtin commands */
1846 static char *optionarg; /* set by nextopt (like getopt) */
1847 static char *optptr; /* used by nextopt */
1850 * XXX - should get rid of. Have all builtins use getopt(3).
1851 * The library getopt must have the BSD extension static variable
1852 * "optreset", otherwise it can't be used within the shell safely.
1854 * Standard option processing (a la getopt) for builtin routines.
1855 * The only argument that is passed to nextopt is the option string;
1856 * the other arguments are unnecessary. It returns the character,
1857 * or '\0' on end of input.
1860 nextopt(const char *optstring)
1867 if (p == NULL || *p == '\0') {
1868 /* We ate entire "-param", take next one */
1874 if (*++p == '\0') /* just "-" ? */
1877 if (LONE_DASH(p)) /* "--" ? */
1879 /* p => next "-param" */
1881 /* p => some option char in the middle of a "-param" */
1883 for (q = optstring; *q != c;) {
1885 ash_msg_and_raise_error("illegal option -%c", c);
1893 ash_msg_and_raise_error("no arg for -%c option", c);
1903 /* ============ Shell variables */
1906 * The parsefile structure pointed to by the global variable parsefile
1907 * contains information about the current file being read.
1910 int nparam; /* # of positional parameters (without $0) */
1911 #if ENABLE_ASH_GETOPTS
1912 int optind; /* next parameter to be processed by getopts */
1913 int optoff; /* used by getopts */
1915 unsigned char malloced; /* if parameter list dynamically allocated */
1916 char **p; /* parameter list */
1920 * Free the list of positional parameters.
1923 freeparam(volatile struct shparam *param)
1925 if (param->malloced) {
1927 ap = ap1 = param->p;
1934 #if ENABLE_ASH_GETOPTS
1935 static void FAST_FUNC getoptsreset(const char *value);
1939 struct var *next; /* next entry in hash list */
1940 int flags; /* flags are defined above */
1941 const char *var_text; /* name=value */
1942 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1943 /* the variable gets set/unset */
1947 struct localvar *next; /* next local variable in list */
1948 struct var *vp; /* the variable that was made local */
1949 int flags; /* saved flags */
1950 const char *text; /* saved text */
1954 #define VEXPORT 0x01 /* variable is exported */
1955 #define VREADONLY 0x02 /* variable cannot be modified */
1956 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1957 #define VTEXTFIXED 0x08 /* text is statically allocated */
1958 #define VSTACK 0x10 /* text is allocated on the stack */
1959 #define VUNSET 0x20 /* the variable is not set */
1960 #define VNOFUNC 0x40 /* don't call the callback function */
1961 #define VNOSET 0x80 /* do not set variable - just readonly test */
1962 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1963 #if ENABLE_ASH_RANDOM_SUPPORT
1964 # define VDYNAMIC 0x200 /* dynamic variable */
1970 /* Need to be before varinit_data[] */
1971 #if ENABLE_LOCALE_SUPPORT
1972 static void FAST_FUNC
1973 change_lc_all(const char *value)
1975 if (value && *value != '\0')
1976 setlocale(LC_ALL, value);
1978 static void FAST_FUNC
1979 change_lc_ctype(const char *value)
1981 if (value && *value != '\0')
1982 setlocale(LC_CTYPE, value);
1986 static void chkmail(void);
1987 static void changemail(const char *var_value) FAST_FUNC;
1989 # define chkmail() ((void)0)
1991 static void changepath(const char *) FAST_FUNC;
1992 #if ENABLE_ASH_RANDOM_SUPPORT
1993 static void change_random(const char *) FAST_FUNC;
1996 static const struct {
1998 const char *var_text;
1999 void (*var_func)(const char *) FAST_FUNC;
2000 } varinit_data[] = {
2002 * Note: VEXPORT would not work correctly here for NOFORK applets:
2003 * some environment strings may be constant.
2005 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
2007 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
2008 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
2010 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
2011 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
2012 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
2013 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
2014 #if ENABLE_ASH_GETOPTS
2015 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
2017 #if ENABLE_ASH_RANDOM_SUPPORT
2018 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
2020 #if ENABLE_LOCALE_SUPPORT
2021 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
2022 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
2024 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
2025 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
2031 struct globals_var {
2032 struct shparam shellparam; /* $@ current positional parameters */
2033 struct redirtab *redirlist;
2034 int preverrout_fd; /* stderr fd: usually 2, unless redirect moved it */
2035 struct var *vartab[VTABSIZE];
2036 struct var varinit[ARRAY_SIZE(varinit_data)];
2038 extern struct globals_var *const ash_ptr_to_globals_var;
2039 #define G_var (*ash_ptr_to_globals_var)
2040 #define shellparam (G_var.shellparam )
2041 //#define redirlist (G_var.redirlist )
2042 #define preverrout_fd (G_var.preverrout_fd)
2043 #define vartab (G_var.vartab )
2044 #define varinit (G_var.varinit )
2045 #define INIT_G_var() do { \
2047 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
2049 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
2050 varinit[i].flags = varinit_data[i].flags; \
2051 varinit[i].var_text = varinit_data[i].var_text; \
2052 varinit[i].var_func = varinit_data[i].var_func; \
2056 #define vifs varinit[0]
2058 # define vmail (&vifs)[1]
2059 # define vmpath (&vmail)[1]
2060 # define vpath (&vmpath)[1]
2062 # define vpath (&vifs)[1]
2064 #define vps1 (&vpath)[1]
2065 #define vps2 (&vps1)[1]
2066 #define vps4 (&vps2)[1]
2067 #if ENABLE_ASH_GETOPTS
2068 # define voptind (&vps4)[1]
2069 # if ENABLE_ASH_RANDOM_SUPPORT
2070 # define vrandom (&voptind)[1]
2073 # if ENABLE_ASH_RANDOM_SUPPORT
2074 # define vrandom (&vps4)[1]
2079 * The following macros access the values of the above variables.
2080 * They have to skip over the name. They return the null string
2081 * for unset variables.
2083 #define ifsval() (vifs.var_text + 4)
2084 #define ifsset() ((vifs.flags & VUNSET) == 0)
2086 # define mailval() (vmail.var_text + 5)
2087 # define mpathval() (vmpath.var_text + 9)
2088 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2090 #define pathval() (vpath.var_text + 5)
2091 #define ps1val() (vps1.var_text + 4)
2092 #define ps2val() (vps2.var_text + 4)
2093 #define ps4val() (vps4.var_text + 4)
2094 #if ENABLE_ASH_GETOPTS
2095 # define optindval() (voptind.var_text + 7)
2098 #if ENABLE_ASH_GETOPTS
2099 static void FAST_FUNC
2100 getoptsreset(const char *value)
2102 shellparam.optind = 1;
2103 if (is_number(value))
2104 shellparam.optind = number(value) ?: 1;
2105 shellparam.optoff = -1;
2110 * Compares two strings up to the first = or '\0'. The first
2111 * string must be terminated by '='; the second may be terminated by
2112 * either '=' or '\0'.
2115 varcmp(const char *p, const char *q)
2119 while ((c = *p) == (d = *q)) {
2120 if (c == '\0' || c == '=')
2134 * Find the appropriate entry in the hash table from the name.
2136 static struct var **
2137 hashvar(const char *p)
2141 hashval = ((unsigned char) *p) << 4;
2142 while (*p && *p != '=')
2143 hashval += (unsigned char) *p++;
2144 return &vartab[hashval % VTABSIZE];
2148 vpcmp(const void *a, const void *b)
2150 return varcmp(*(const char **)a, *(const char **)b);
2154 * This routine initializes the builtin variables.
2164 * PS1 depends on uid
2166 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2167 vps1.var_text = "PS1=\\w \\$ ";
2170 vps1.var_text = "PS1=# ";
2173 end = vp + ARRAY_SIZE(varinit);
2175 vpp = hashvar(vp->var_text);
2178 } while (++vp < end);
2181 static struct var **
2182 findvar(struct var **vpp, const char *name)
2184 for (; *vpp; vpp = &(*vpp)->next) {
2185 if (varcmp((*vpp)->var_text, name) == 0) {
2193 * Find the value of a variable. Returns NULL if not set.
2195 static const char* FAST_FUNC
2196 lookupvar(const char *name)
2200 v = *findvar(hashvar(name), name);
2202 #if ENABLE_ASH_RANDOM_SUPPORT
2204 * Dynamic variables are implemented roughly the same way they are
2205 * in bash. Namely, they're "special" so long as they aren't unset.
2206 * As soon as they're unset, they're no longer dynamic, and dynamic
2207 * lookup will no longer happen at that point. -- PFM.
2209 if (v->flags & VDYNAMIC)
2212 if (!(v->flags & VUNSET))
2213 return var_end(v->var_text);
2218 #if ENABLE_UNICODE_SUPPORT
2220 reinit_unicode_for_ash(void)
2222 /* Unicode support should be activated even if LANG is set
2223 * _during_ shell execution, not only if it was set when
2224 * shell was started. Therefore, re-check LANG every time:
2226 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2227 || ENABLE_UNICODE_USING_LOCALE
2229 const char *s = lookupvar("LC_ALL");
2230 if (!s) s = lookupvar("LC_CTYPE");
2231 if (!s) s = lookupvar("LANG");
2236 # define reinit_unicode_for_ash() ((void)0)
2240 * Search the environment of a builtin command.
2242 static ALWAYS_INLINE const char *
2243 bltinlookup(const char *name)
2245 return lookupvar(name);
2249 * Same as setvar except that the variable and value are passed in
2250 * the first argument as name=value. Since the first argument will
2251 * be actually stored in the table, it should not be a string that
2253 * Called with interrupts off.
2256 setvareq(char *s, int flags)
2258 struct var *vp, **vpp;
2261 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2262 vpp = findvar(vpp, s);
2265 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2268 if (flags & VNOSAVE)
2272 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2278 if (vp->var_func && !(flags & VNOFUNC))
2279 vp->var_func(var_end(s));
2281 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2282 free((char*)vp->var_text);
2284 if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
2288 if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
2293 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2295 /* variable s is not found */
2298 if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
2300 vp = ckzalloc(sizeof(*vp));
2302 /*vp->func = NULL; - ckzalloc did it */
2305 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2315 * Set the value of a variable. The flags argument is ored with the
2316 * flags of the variable. If val is NULL, the variable is unset.
2319 setvar(const char *name, const char *val, int flags)
2328 q = endofname(name);
2329 p = strchrnul(q, '=');
2331 if (!namelen || p != q)
2332 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2337 vallen = strlen(val);
2341 nameeq = ckmalloc(namelen + vallen + 2);
2342 p = mempcpy(nameeq, name, namelen);
2345 p = mempcpy(p, val, vallen);
2348 vp = setvareq(nameeq, flags | VNOSAVE);
2354 static void FAST_FUNC
2355 setvar0(const char *name, const char *val)
2357 setvar(name, val, 0);
2361 * Unset the specified variable.
2364 unsetvar(const char *s)
2370 * Process a linked list of variable assignments.
2373 listsetvar(struct strlist *list_set_var, int flags)
2375 struct strlist *lp = list_set_var;
2381 setvareq(lp->text, flags);
2388 * Generate a list of variables satisfying the given conditions.
2391 listvars(int on, int off, char ***end)
2402 for (vp = *vpp; vp; vp = vp->next) {
2403 if ((vp->flags & mask) == on) {
2404 if (ep == stackstrend())
2405 ep = growstackstr();
2406 *ep++ = (char*)vp->var_text;
2409 } while (++vpp < vartab + VTABSIZE);
2410 if (ep == stackstrend())
2411 ep = growstackstr();
2415 return grabstackstr(ep);
2419 /* ============ Path search helper
2421 * The variable path (passed by reference) should be set to the start
2422 * of the path before the first call; path_advance will update
2423 * this value as it proceeds. Successive calls to path_advance will return
2424 * the possible path expansions in sequence. If an option (indicated by
2425 * a percent sign) appears in the path entry then the global variable
2426 * pathopt will be set to point to it; otherwise pathopt will be set to
2429 static const char *pathopt; /* set by path_advance */
2432 path_advance(const char **path, const char *name)
2442 for (p = start; *p && *p != ':' && *p != '%'; p++)
2444 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2445 while (stackblocksize() < len)
2449 q = mempcpy(q, start, p - start);
2456 while (*p && *p != ':')
2463 return stalloc(len);
2467 /* ============ Prompt */
2469 static smallint doprompt; /* if set, prompt the user */
2470 static smallint needprompt; /* true if interactive and at start of line */
2472 #if ENABLE_FEATURE_EDITING
2473 static line_input_t *line_input_state;
2474 static const char *cmdedit_prompt;
2476 putprompt(const char *s)
2478 if (ENABLE_ASH_EXPAND_PRMT) {
2479 free((char*)cmdedit_prompt);
2480 cmdedit_prompt = ckstrdup(s);
2487 putprompt(const char *s)
2493 /* expandstr() needs parsing machinery, so it is far away ahead... */
2494 static const char *expandstr(const char *ps, int syntax_type);
2495 /* Values for syntax param */
2496 #define BASESYNTAX 0 /* not in quotes */
2497 #define DQSYNTAX 1 /* in double quotes */
2498 #define SQSYNTAX 2 /* in single quotes */
2499 #define ARISYNTAX 3 /* in arithmetic */
2500 #if ENABLE_ASH_EXPAND_PRMT
2501 # define PSSYNTAX 4 /* prompt. never passed to SIT() */
2503 /* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
2506 * called by editline -- any expansions to the prompt should be added here.
2509 setprompt_if(smallint do_set, int whichprompt)
2512 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2519 switch (whichprompt) {
2529 #if ENABLE_ASH_EXPAND_PRMT
2530 pushstackmark(&smark, stackblocksize());
2531 putprompt(expandstr(prompt, PSSYNTAX));
2532 popstackmark(&smark);
2539 /* ============ The cd and pwd commands */
2541 #define CD_PHYSICAL 1
2551 while ((i = nextopt("LP")) != '\0') {
2553 flags ^= CD_PHYSICAL;
2562 * Update curdir (the name of the current directory) in response to a
2566 updatepwd(const char *dir)
2573 cdcomppath = sstrdup(dir);
2576 if (curdir == nullstr)
2578 new = stack_putstr(curdir, new);
2580 new = makestrspace(strlen(dir) + 2, new);
2581 lim = (char *)stackblock() + 1;
2585 if (new > lim && *lim == '/')
2590 if (dir[1] == '/' && dir[2] != '/') {
2596 p = strtok(cdcomppath, "/");
2600 if (p[1] == '.' && p[2] == '\0') {
2612 new = stack_putstr(p, new);
2615 p = strtok(NULL, "/");
2620 return stackblock();
2624 * Find out what the current directory is. If we already know the current
2625 * directory, this routine returns immediately.
2630 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2631 return dir ? dir : nullstr;
2635 setpwd(const char *val, int setold)
2639 oldcur = dir = curdir;
2642 setvar("OLDPWD", oldcur, VEXPORT);
2645 if (physdir != nullstr) {
2646 if (physdir != oldcur)
2650 if (oldcur == val || !val) {
2656 dir = ckstrdup(val);
2657 if (oldcur != dir && oldcur != nullstr) {
2662 setvar("PWD", dir, VEXPORT);
2665 static void hashcd(void);
2668 * Actually do the chdir. We also call hashcd to let other routines
2669 * know that the current directory has changed.
2672 docd(const char *dest, int flags)
2674 const char *dir = NULL;
2677 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2680 if (!(flags & CD_PHYSICAL)) {
2681 dir = updatepwd(dest);
2695 static int FAST_FUNC
2696 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2708 dest = bltinlookup("HOME");
2709 else if (LONE_DASH(dest)) {
2710 dest = bltinlookup("OLDPWD");
2732 path = bltinlookup("CDPATH");
2735 p = path_advance(&path, dest);
2736 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2740 if (!docd(p, flags))
2751 ash_msg_and_raise_error("can't cd to %s", dest);
2754 if (flags & CD_PRINT)
2755 out1fmt("%s\n", curdir);
2759 static int FAST_FUNC
2760 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2763 const char *dir = curdir;
2767 if (physdir == nullstr)
2771 out1fmt("%s\n", dir);
2776 /* ============ ... */
2779 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2781 /* Syntax classes */
2782 #define CWORD 0 /* character is nothing special */
2783 #define CNL 1 /* newline character */
2784 #define CBACK 2 /* a backslash character */
2785 #define CSQUOTE 3 /* single quote */
2786 #define CDQUOTE 4 /* double quote */
2787 #define CENDQUOTE 5 /* a terminating quote */
2788 #define CBQUOTE 6 /* backwards single quote */
2789 #define CVAR 7 /* a dollar sign */
2790 #define CENDVAR 8 /* a '}' character */
2791 #define CLP 9 /* a left paren in arithmetic */
2792 #define CRP 10 /* a right paren in arithmetic */
2793 #define CENDFILE 11 /* end of file */
2794 #define CCTL 12 /* like CWORD, except it must be escaped */
2795 #define CSPCL 13 /* these terminate a word */
2796 #define CIGN 14 /* character should be ignored */
2799 #if ENABLE_ASH_ALIAS
2803 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2805 #if ENABLE_FEATURE_SH_MATH
2806 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2808 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2810 static const uint16_t S_I_T[] ALIGN2 = {
2811 #if ENABLE_ASH_ALIAS
2812 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2814 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2815 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2816 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2817 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2818 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2819 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2820 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2821 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2822 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2823 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2824 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2825 #if !USE_SIT_FUNCTION
2826 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2827 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2828 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2832 /* Constants below must match table above */
2834 #if ENABLE_ASH_ALIAS
2835 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2837 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2838 CNL_CNL_CNL_CNL , /* 2 */
2839 CWORD_CCTL_CCTL_CWORD , /* 3 */
2840 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2841 CVAR_CVAR_CWORD_CVAR , /* 5 */
2842 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2843 CSPCL_CWORD_CWORD_CLP , /* 7 */
2844 CSPCL_CWORD_CWORD_CRP , /* 8 */
2845 CBACK_CBACK_CCTL_CBACK , /* 9 */
2846 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2847 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2848 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2849 CWORD_CWORD_CWORD_CWORD , /* 13 */
2850 CCTL_CCTL_CCTL_CCTL , /* 14 */
2853 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2854 * caller must ensure proper cast on it if c is *char_ptr!
2856 #if USE_SIT_FUNCTION
2859 SIT(int c, int syntax)
2861 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2862 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2864 * This causes '/' to be prepended with CTLESC in dquoted string,
2865 * making "./file"* treated incorrectly because we feed
2866 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2867 * The "homegrown" glob implementation is okay with that,
2868 * but glibc one isn't. With '/' always treated as CWORD,
2871 # if ENABLE_ASH_ALIAS
2872 static const uint8_t syntax_index_table[] ALIGN1 = {
2873 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2874 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2875 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2879 static const uint8_t syntax_index_table[] ALIGN1 = {
2880 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2881 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2882 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2891 # if ENABLE_ASH_ALIAS
2897 /* Cast is purely for paranoia here,
2898 * just in case someone passed signed char to us */
2899 if ((unsigned char)c >= CTL_FIRST
2900 && (unsigned char)c <= CTL_LAST
2904 s = strchrnul(spec_symbls, c);
2907 indx = syntax_index_table[s - spec_symbls];
2909 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2912 #else /* !USE_SIT_FUNCTION */
2914 static const uint8_t syntax_index_table[] ALIGN1 = {
2915 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2916 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2926 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2927 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2945 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2946 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2947 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2948 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2949 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2950 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2951 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2953 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2955 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2956 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2957 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2958 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2959 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2961 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2962 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2963 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2964 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2976 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2977 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2978 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2979 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2980 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2981 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2993 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
3004 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
3005 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
3006 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
3007 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
3008 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
3009 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
3010 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
3011 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
3012 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
3013 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
3014 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
3015 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
3016 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
3017 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
3018 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
3019 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
3020 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
3021 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
3022 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
3023 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
3024 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
3025 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
3026 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
3027 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
3028 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3029 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3030 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3031 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3032 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3033 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3034 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3035 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3036 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3037 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3038 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3039 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3040 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3041 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3042 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3043 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3044 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
3045 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
3047 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
3048 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
3049 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
3050 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
3051 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3052 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3053 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3054 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3113 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3114 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3115 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3116 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3117 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3118 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3119 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3120 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3121 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3122 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3123 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3124 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3125 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3126 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3127 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3128 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3129 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3130 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3131 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3132 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3133 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3134 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3135 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3136 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3137 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3138 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3139 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3140 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3141 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3142 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3143 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3144 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3145 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3146 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3147 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3148 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3149 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3150 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3151 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3152 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3153 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3154 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3155 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3156 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3157 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3158 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3159 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3160 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3161 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3162 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3163 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3164 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3165 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3166 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3167 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3168 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3169 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3170 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3171 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3172 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3173 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3174 # if ENABLE_ASH_ALIAS
3175 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3180 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3181 #else /* debug version, caught one signed char bug */
3182 # define SIT(c, syntax) \
3184 if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
3185 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3186 if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
3187 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3188 ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
3192 #endif /* !USE_SIT_FUNCTION */
3195 /* ============ Alias handling */
3197 #if ENABLE_ASH_ALIAS
3199 #define ALIASINUSE 1
3210 static struct alias **atab; // [ATABSIZE];
3211 #define INIT_G_alias() do { \
3212 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3216 static struct alias **
3217 __lookupalias(const char *name)
3219 unsigned int hashval;
3226 ch = (unsigned char)*p;
3230 ch = (unsigned char)*++p;
3232 app = &atab[hashval % ATABSIZE];
3234 for (; *app; app = &(*app)->next) {
3235 if (strcmp(name, (*app)->name) == 0) {
3243 static struct alias *
3244 lookupalias(const char *name, int check)
3246 struct alias *ap = *__lookupalias(name);
3248 if (check && ap && (ap->flag & ALIASINUSE))
3253 static struct alias *
3254 freealias(struct alias *ap)
3258 if (ap->flag & ALIASINUSE) {
3259 ap->flag |= ALIASDEAD;
3271 setalias(const char *name, const char *val)
3273 struct alias *ap, **app;
3275 app = __lookupalias(name);
3279 if (!(ap->flag & ALIASINUSE)) {
3282 ap->val = ckstrdup(val);
3283 ap->flag &= ~ALIASDEAD;
3286 ap = ckzalloc(sizeof(struct alias));
3287 ap->name = ckstrdup(name);
3288 ap->val = ckstrdup(val);
3289 /*ap->flag = 0; - ckzalloc did it */
3290 /*ap->next = NULL;*/
3297 unalias(const char *name)
3301 app = __lookupalias(name);
3305 *app = freealias(*app);
3316 struct alias *ap, **app;
3320 for (i = 0; i < ATABSIZE; i++) {
3322 for (ap = *app; ap; ap = *app) {
3323 *app = freealias(*app);
3333 printalias(const struct alias *ap)
3335 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3339 * TODO - sort output
3341 static int FAST_FUNC
3342 aliascmd(int argc UNUSED_PARAM, char **argv)
3351 for (i = 0; i < ATABSIZE; i++) {
3352 for (ap = atab[i]; ap; ap = ap->next) {
3358 while ((n = *++argv) != NULL) {
3359 v = strchr(n+1, '=');
3360 if (v == NULL) { /* n+1: funny ksh stuff */
3361 ap = *__lookupalias(n);
3363 fprintf(stderr, "%s: %s not found\n", "alias", n);
3376 static int FAST_FUNC
3377 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3381 while (nextopt("a") != '\0') {
3385 for (i = 0; *argptr; argptr++) {
3386 if (unalias(*argptr)) {
3387 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3395 #endif /* ASH_ALIAS */
3398 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3401 #define FORK_NOJOB 2
3403 /* mode flags for showjob(s) */
3404 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3405 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3406 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3407 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3410 * A job structure contains information about a job. A job is either a
3411 * single process or a set of processes contained in a pipeline. In the
3412 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3416 pid_t ps_pid; /* process id */
3417 int ps_status; /* last process status from wait() */
3418 char *ps_cmd; /* text of command being run */
3422 struct procstat ps0; /* status of process */
3423 struct procstat *ps; /* status or processes when more than one */
3425 int stopstatus; /* status of a stopped job */
3427 unsigned nprocs; /* number of processes */
3429 #define JOBRUNNING 0 /* at least one proc running */
3430 #define JOBSTOPPED 1 /* all procs are stopped */
3431 #define JOBDONE 2 /* all procs are completed */
3435 sigint: 1, /* job was killed by SIGINT */
3436 jobctl: 1, /* job running under job control */
3438 waited: 1, /* true if this entry has been waited for */
3439 used: 1, /* true if this entry is in used */
3440 changed: 1; /* true if status has changed */
3441 struct job *prev_job; /* previous job */
3444 static struct job *makejob(/*union node *,*/ int);
3445 static int forkshell(struct job *, union node *, int);
3446 static int waitforjob(struct job *);
3449 enum { doing_jobctl = 0 };
3450 #define setjobctl(on) do {} while (0)
3452 static smallint doing_jobctl; //references:8
3453 static void setjobctl(int);
3460 ignoresig(int signo)
3462 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3463 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3464 /* No, need to do it */
3465 signal(signo, SIG_IGN);
3467 sigmode[signo - 1] = S_HARD_IGN;
3471 * Only one usage site - in setsignal()
3474 signal_handler(int signo)
3476 if (signo == SIGCHLD) {
3482 gotsig[signo - 1] = 1;
3483 pending_sig = signo;
3485 if (signo == SIGINT && !trap[SIGINT]) {
3486 if (!suppress_int) {
3488 raise_interrupt(); /* does not return */
3495 * Set the signal handler for the specified signal. The routine figures
3496 * out what it should be set to.
3499 setsignal(int signo)
3502 char cur_act, new_act;
3503 struct sigaction act;
3507 if (t != NULL) { /* trap for this sig is set */
3509 if (t[0] == '\0') /* trap is "": ignore this sig */
3513 if (rootshell && new_act == S_DFL) {
3516 if (iflag || minusc || sflag == 0)
3525 * "In all cases, bash ignores SIGQUIT. Non-builtin
3526 * commands run by bash have signal handlers
3527 * set to the values inherited by the shell
3528 * from its parent". */
3544 /* if !rootshell, we reset SIGQUIT to DFL,
3545 * whereas we have to restore it to what shell got on entry.
3546 * This is handled by the fact that if signal was IGNored on entry,
3547 * then cur_act is S_HARD_IGN and we never change its sigaction
3551 if (signo == SIGCHLD)
3554 t = &sigmode[signo - 1];
3557 /* current setting is not yet known */
3558 if (sigaction(signo, NULL, &act)) {
3559 /* pretend it worked; maybe we should give a warning,
3560 * but other shells don't. We don't alter sigmode,
3561 * so we retry every time.
3562 * btw, in Linux it never fails. --vda */
3565 if (act.sa_handler == SIG_IGN) {
3566 cur_act = S_HARD_IGN;
3568 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3570 cur_act = S_IGN; /* don't hard ignore these */
3573 if (act.sa_handler == SIG_DFL && new_act == S_DFL) {
3574 /* installing SIG_DFL over SIG_DFL is a no-op */
3575 /* saves one sigaction call in each "sh -c SCRIPT" invocation */
3580 if (cur_act == S_HARD_IGN || cur_act == new_act)
3585 act.sa_handler = SIG_DFL;
3588 act.sa_handler = signal_handler;
3591 act.sa_handler = SIG_IGN;
3594 /* flags and mask matter only if !DFL and !IGN, but we do it
3595 * for all cases for more deterministic behavior:
3597 act.sa_flags = 0; //TODO: why not SA_RESTART?
3598 sigfillset(&act.sa_mask);
3600 sigaction_set(signo, &act);
3603 /* mode flags for set_curjob */
3604 #define CUR_DELETE 2
3605 #define CUR_RUNNING 1
3606 #define CUR_STOPPED 0
3609 /* pgrp of shell on invocation */
3610 static int initialpgrp; //references:2
3611 static int ttyfd = -1; //5
3614 static struct job *jobtab; //5
3616 static unsigned njobs; //4
3618 static struct job *curjob; //lots
3619 /* number of presumed living untracked jobs */
3620 static int jobless; //4
3623 /* Bash has a feature: it restores termios after a successful wait for
3624 * a foreground job which had at least one stopped or sigkilled member.
3625 * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
3626 * properly restoring tty state. Should we do this too?
3627 * A reproducer: ^Z an interactive python:
3630 * Python 2.7.12 (...)
3632 * { python leaves tty in -icanon -echo state. We do survive that... }
3633 * [1]+ Stopped python
3634 * { ...however, next program (python #2) does not survive it well: }
3636 * Python 2.7.12 (...)
3637 * >>> Traceback (most recent call last):
3638 * { above, I typed "qwerty<CR>", but -echo state is still in effect }
3639 * File "<stdin>", line 1, in <module>
3640 * NameError: name 'qwerty' is not defined
3642 * The implementation below is modeled on bash code and seems to work.
3643 * However, I'm not sure we should do this. For one: what if I'd fg
3644 * the stopped python instead? It'll be confused by "restored" tty state.
3646 static struct termios shell_tty_info;
3650 if (rootshell && ttyfd >= 0)
3651 tcgetattr(ttyfd, &shell_tty_info);
3656 /* if (rootshell) - caller ensures this */
3658 tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
3661 job_signal_status(struct job *jp)
3665 struct procstat *ps = jp->ps;
3666 for (i = 0; i < jp->nprocs; i++) {
3667 status = ps[i].ps_status;
3668 if (WIFSIGNALED(status) || WIFSTOPPED(status))
3674 restore_tty_if_stopped_or_signaled(struct job *jp)
3676 //TODO: check what happens if we come from waitforjob() in expbackq()
3678 int s = job_signal_status(jp);
3679 if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
3684 # define get_tty_state() ((void)0)
3685 # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
3689 set_curjob(struct job *jp, unsigned mode)
3692 struct job **jpp, **curp;
3694 /* first remove from list */
3695 jpp = curp = &curjob;
3700 jpp = &jp1->prev_job;
3702 *jpp = jp1->prev_job;
3704 /* Then re-insert in correct position */
3712 /* job being deleted */
3715 /* newly created job or backgrounded job,
3716 * put after all stopped jobs.
3721 if (!jp1 || jp1->state != JOBSTOPPED)
3724 jpp = &jp1->prev_job;
3730 /* newly stopped job - becomes curjob */
3731 jp->prev_job = *jpp;
3739 jobno(const struct job *jp)
3741 return jp - jobtab + 1;
3746 * Convert a job name to a job structure.
3749 #define getjob(name, getctl) getjob(name)
3752 getjob(const char *name, int getctl)
3756 const char *err_msg = "%s: no such job";
3760 char *(*match)(const char *, const char *);
3775 if (c == '+' || c == '%') {
3777 err_msg = "No current job";
3783 err_msg = "No previous job";
3793 if (num > 0 && num <= njobs) {
3794 jp = jobtab + num - 1;
3809 if (match(jp->ps[0].ps_cmd, p)) {
3813 err_msg = "%s: ambiguous";
3823 err_msg = "job %s not created under job control";
3824 if (getctl && jp->jobctl == 0)
3829 ash_msg_and_raise_error(err_msg, name);
3833 * Mark a job structure as unused.
3836 freejob(struct job *jp)
3838 struct procstat *ps;
3842 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3843 if (ps->ps_cmd != nullstr)
3846 if (jp->ps != &jp->ps0)
3849 set_curjob(jp, CUR_DELETE);
3855 xtcsetpgrp(int fd, pid_t pgrp)
3857 if (tcsetpgrp(fd, pgrp))
3858 ash_msg_and_raise_perror("can't set tty process group");
3862 * Turn job control on and off.
3864 * Note: This code assumes that the third arg to ioctl is a character
3865 * pointer, which is true on Berkeley systems but not System V. Since
3866 * System V doesn't have job control yet, this isn't a problem now.
3868 * Called with interrupts off.
3876 if (on == doing_jobctl || rootshell == 0)
3880 ofd = fd = open(_PATH_TTY, O_RDWR);
3882 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3883 * That sometimes helps to acquire controlling tty.
3884 * Obviously, a workaround for bugs when someone
3885 * failed to provide a controlling tty to bash! :) */
3891 /* fd is a tty at this point */
3892 fd = fcntl(fd, F_DUPFD, 10);
3893 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
3896 goto out; /* F_DUPFD failed */
3897 close_on_exec_on(fd);
3898 while (1) { /* while we are in the background */
3899 pgrp = tcgetpgrp(fd);
3902 ash_msg("can't access tty; job control turned off");
3906 if (pgrp == getpgrp())
3917 xtcsetpgrp(fd, pgrp);
3919 /* turning job control off */
3922 /* was xtcsetpgrp, but this can make exiting ash
3923 * loop forever if pty is already deleted */
3924 tcsetpgrp(fd, pgrp);
3938 static int FAST_FUNC
3939 killcmd(int argc, char **argv)
3941 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3944 if (argv[i][0] == '%') {
3946 * "kill %N" - job kill
3947 * Converting to pgrp / pid kill
3953 jp = getjob(argv[i], 0);
3955 * In jobs started under job control, we signal
3956 * entire process group by kill -PGRP_ID.
3957 * This happens, f.e., in interactive shell.
3959 * Otherwise, we signal each child via
3960 * kill PID1 PID2 PID3.
3962 * sh -c 'sleep 1|sleep 1 & kill %1'
3963 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3964 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3966 n = jp->nprocs; /* can't be 0 (I hope) */
3969 dst = alloca(n * sizeof(int)*4);
3971 for (j = 0; j < n; j++) {
3972 struct procstat *ps = &jp->ps[j];
3973 /* Skip non-running and not-stopped members
3974 * (i.e. dead members) of the job
3976 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3979 * kill_main has matching code to expect
3980 * leading space. Needed to not confuse
3981 * negative pids with "kill -SIGNAL_NO" syntax
3983 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3987 } while (argv[++i]);
3989 return kill_main(argc, argv);
3993 showpipe(struct job *jp /*, FILE *out*/)
3995 struct procstat *ps;
3996 struct procstat *psend;
3998 psend = jp->ps + jp->nprocs;
3999 for (ps = jp->ps + 1; ps < psend; ps++)
4000 printf(" | %s", ps->ps_cmd);
4001 newline_and_flush(stdout);
4002 flush_stdout_stderr();
4007 restartjob(struct job *jp, int mode)
4009 struct procstat *ps;
4015 if (jp->state == JOBDONE)
4017 jp->state = JOBRUNNING;
4018 pgid = jp->ps[0].ps_pid;
4019 if (mode == FORK_FG) {
4021 xtcsetpgrp(ttyfd, pgid);
4023 killpg(pgid, SIGCONT);
4027 if (WIFSTOPPED(ps->ps_status)) {
4033 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
4038 static int FAST_FUNC
4039 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
4045 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
4049 jp = getjob(*argv, 1);
4050 if (mode == FORK_BG) {
4051 set_curjob(jp, CUR_RUNNING);
4052 printf("[%d] ", jobno(jp));
4054 out1str(jp->ps[0].ps_cmd);
4055 showpipe(jp /*, stdout*/);
4056 retval = restartjob(jp, mode);
4057 } while (*argv && *++argv);
4063 sprint_status48(char *s, int status, int sigonly)
4069 if (!WIFEXITED(status)) {
4071 if (WIFSTOPPED(status))
4072 st = WSTOPSIG(status);
4075 st = WTERMSIG(status);
4077 if (st == SIGINT || st == SIGPIPE)
4080 if (WIFSTOPPED(status))
4085 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
4086 col = fmtstr(s, 32, strsignal(st));
4087 if (WCOREDUMP(status)) {
4088 strcpy(s + col, " (core dumped)");
4089 col += sizeof(" (core dumped)")-1;
4091 } else if (!sigonly) {
4092 st = WEXITSTATUS(status);
4093 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
4100 wait_block_or_sig(int *status)
4107 /* Poll all children for changes in their state */
4109 /* if job control is active, accept stopped processes too */
4110 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
4112 break; /* Error (e.g. EINTR, ECHILD) or pid */
4114 /* Children exist, but none are ready. Sleep until interesting signal */
4117 sigprocmask(SIG_SETMASK, &mask, &mask);
4118 while (!got_sigchld && !pending_sig)
4120 sigprocmask(SIG_SETMASK, &mask, NULL);
4121 #else /* unsafe: a signal can set pending_sig after check, but before pause() */
4122 while (!got_sigchld && !pending_sig)
4126 /* If it was SIGCHLD, poll children again */
4127 } while (got_sigchld);
4132 #define DOWAIT_NONBLOCK 0
4133 #define DOWAIT_BLOCK 1
4134 #define DOWAIT_BLOCK_OR_SIG 2
4137 dowait(int block, struct job *job)
4142 struct job *thisjob = NULL;
4144 TRACE(("dowait(0x%x) called\n", block));
4146 /* It's wrong to call waitpid() outside of INT_OFF region:
4147 * signal can arrive just after syscall return and handler can
4148 * longjmp away, losing stop/exit notification processing.
4149 * Thus, for "jobs" builtin, and for waiting for a fg job,
4150 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
4152 * However, for "wait" builtin it is wrong to simply call waitpid()
4153 * in INT_OFF region: "wait" needs to wait for any running job
4154 * to change state, but should exit on any trap too.
4155 * In INT_OFF region, a signal just before syscall entry can set
4156 * pending_sig variables, but we can't check them, and we would
4157 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
4159 * Because of this, we run inside INT_OFF, but use a special routine
4160 * which combines waitpid() and sigsuspend().
4161 * This is the reason why we need to have a handler for SIGCHLD:
4162 * SIG_DFL handler does not wake sigsuspend().
4165 if (block == DOWAIT_BLOCK_OR_SIG) {
4166 pid = wait_block_or_sig(&status);
4169 if (block == DOWAIT_NONBLOCK)
4170 wait_flags = WNOHANG;
4171 /* if job control is active, accept stopped processes too */
4173 wait_flags |= WUNTRACED;
4174 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4175 pid = waitpid(-1, &status, wait_flags);
4177 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4178 pid, status, errno, strerror(errno)));
4183 for (jp = curjob; jp; jp = jp->prev_job) {
4185 struct procstat *ps;
4186 struct procstat *psend;
4187 if (jp->state == JOBDONE)
4191 psend = ps + jp->nprocs;
4193 if (ps->ps_pid == pid) {
4194 TRACE(("Job %d: changing status of proc %d "
4195 "from 0x%x to 0x%x\n",
4196 jobno(jp), pid, ps->ps_status, status));
4197 ps->ps_status = status;
4200 if (ps->ps_status == -1)
4201 jobstate = JOBRUNNING;
4203 if (jobstate == JOBRUNNING)
4205 if (WIFSTOPPED(ps->ps_status)) {
4206 jp->stopstatus = ps->ps_status;
4207 jobstate = JOBSTOPPED;
4210 } while (++ps < psend);
4214 /* Found the job where one of its processes changed its state.
4215 * Is there at least one live and running process in this job? */
4216 if (jobstate != JOBRUNNING) {
4217 /* No. All live processes in the job are stopped
4218 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4220 thisjob->changed = 1;
4221 if (thisjob->state != jobstate) {
4222 TRACE(("Job %d: changing state from %d to %d\n",
4223 jobno(thisjob), thisjob->state, jobstate));
4224 thisjob->state = jobstate;
4226 if (jobstate == JOBSTOPPED)
4227 set_curjob(thisjob, CUR_STOPPED);
4233 /* The process wasn't found in job list */
4235 if (!WIFSTOPPED(status))
4241 if (thisjob && thisjob == job) {
4245 len = sprint_status48(s, status, 1);
4257 showjob(struct job *jp, int mode)
4259 struct procstat *ps;
4260 struct procstat *psend;
4263 char s[16 + 16 + 48];
4264 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4268 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4269 /* just output process (group) id of pipeline */
4270 fprintf(out, "%d\n", ps->ps_pid);
4274 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4279 else if (curjob && jp == curjob->prev_job)
4282 if (mode & SHOW_PIDS)
4283 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4285 psend = ps + jp->nprocs;
4287 if (jp->state == JOBRUNNING) {
4288 strcpy(s + col, "Running");
4289 col += sizeof("Running") - 1;
4291 int status = psend[-1].ps_status;
4292 if (jp->state == JOBSTOPPED)
4293 status = jp->stopstatus;
4294 col += sprint_status48(s + col, status, 0);
4296 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4298 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4299 * or prints several "PID | <cmdN>" lines,
4300 * depending on SHOW_PIDS bit.
4301 * We do not print status of individual processes
4302 * between PID and <cmdN>. bash does it, but not very well:
4303 * first line shows overall job status, not process status,
4304 * making it impossible to know 1st process status.
4308 /* for each process */
4311 if (mode & SHOW_PIDS)
4312 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4314 fprintf(out, "%s%*c%s%s",
4316 33 - col >= 0 ? 33 - col : 0, ' ',
4317 ps == jp->ps ? "" : "| ",
4320 } while (++ps != psend);
4321 newline_and_flush(out);
4325 if (jp->state == JOBDONE) {
4326 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4332 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4333 * statuses have changed since the last call to showjobs.
4340 TRACE(("showjobs(0x%x) called\n", mode));
4342 /* Handle all finished jobs */
4343 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4346 for (jp = curjob; jp; jp = jp->prev_job) {
4347 if (!(mode & SHOW_CHANGED) || jp->changed) {
4353 static int FAST_FUNC
4354 jobscmd(int argc UNUSED_PARAM, char **argv)
4359 while ((m = nextopt("lp")) != '\0') {
4363 mode |= SHOW_ONLY_PGID;
4369 showjob(getjob(*argv, 0), mode);
4379 /* Called only on finished or stopped jobs (no members are running) */
4381 getstatus(struct job *job)
4385 struct procstat *ps;
4387 /* Fetch last member's status */
4388 ps = job->ps + job->nprocs - 1;
4389 status = ps->ps_status;
4391 /* "set -o pipefail" mode: use last _nonzero_ status */
4392 while (status == 0 && --ps >= job->ps)
4393 status = ps->ps_status;
4396 retval = WEXITSTATUS(status);
4397 if (!WIFEXITED(status)) {
4399 retval = WSTOPSIG(status);
4400 if (!WIFSTOPPED(status))
4403 /* XXX: limits number of signals */
4404 retval = WTERMSIG(status);
4406 if (retval == SIGINT)
4412 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4413 jobno(job), job->nprocs, status, retval));
4417 static int FAST_FUNC
4418 waitcmd(int argc UNUSED_PARAM, char **argv)
4429 /* wait for all jobs */
4433 if (!jp) /* no running procs */
4435 if (jp->state == JOBRUNNING)
4441 * "When bash is waiting for an asynchronous command via
4442 * the wait builtin, the reception of a signal for which a trap
4443 * has been set will cause the wait builtin to return immediately
4444 * with an exit status greater than 128, immediately after which
4445 * the trap is executed."
4447 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4448 /* if child sends us a signal *and immediately exits*,
4449 * dowait() returns pid > 0. Check this case,
4450 * not "if (dowait() < 0)"!
4459 if (**argv != '%') {
4460 pid_t pid = number(*argv);
4465 if (job->ps[job->nprocs - 1].ps_pid == pid)
4467 job = job->prev_job;
4470 job = getjob(*argv, 0);
4472 /* loop until process terminated or stopped */
4473 while (job->state == JOBRUNNING) {
4474 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4479 retval = getstatus(job);
4486 retval = 128 + pending_sig;
4495 struct job *jp, *jq;
4497 len = njobs * sizeof(*jp);
4499 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4501 offset = (char *)jp - (char *)jq;
4503 /* Relocate pointers */
4506 jq = (struct job *)((char *)jq + l);
4510 #define joff(p) ((struct job *)((char *)(p) + l))
4511 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4512 if (joff(jp)->ps == &jq->ps0)
4513 jmove(joff(jp)->ps);
4514 if (joff(jp)->prev_job)
4515 jmove(joff(jp)->prev_job);
4525 jp = (struct job *)((char *)jp + len);
4529 } while (--jq >= jp);
4534 * Return a new job structure.
4535 * Called with interrupts off.
4538 makejob(/*union node *node,*/ int nprocs)
4543 for (i = njobs, jp = jobtab; ; jp++) {
4550 if (jp->state != JOBDONE || !jp->waited)
4559 memset(jp, 0, sizeof(*jp));
4561 /* jp->jobctl is a bitfield.
4562 * "jp->jobctl |= doing_jobctl" likely to give awful code */
4566 jp->prev_job = curjob;
4571 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4573 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4580 * Return a string identifying a command (to be printed by the
4583 static char *cmdnextc;
4586 cmdputs(const char *s)
4588 static const char vstype[VSTYPE + 1][3] = {
4589 "", "}", "-", "+", "?", "=",
4590 "%", "%%", "#", "##"
4591 IF_BASH_SUBSTR(, ":")
4592 IF_BASH_PATTERN_SUBST(, "/", "//")
4595 const char *p, *str;
4599 unsigned char subtype = 0;
4603 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4605 while ((c = *p++) != '\0') {
4613 if ((subtype & VSTYPE) == VSLENGTH)
4619 str = "\"}" + !(quoted & 1);
4626 #if ENABLE_FEATURE_SH_MATH
4641 if ((subtype & VSTYPE) != VSNORMAL)
4643 str = vstype[subtype & VSTYPE];
4644 if (subtype & VSNUL)
4653 /* These can only happen inside quotes */
4659 // [1]+ Done true ${\$} <<=== BUG: ${\$} is not a valid way to write $$ (${$} would be ok)
4670 while ((c = *str++) != '\0') {
4673 } /* while *p++ not NUL */
4676 USTPUTC('"', nextc);
4682 /* cmdtxt() and cmdlist() call each other */
4683 static void cmdtxt(union node *n);
4686 cmdlist(union node *np, int sep)
4688 for (; np; np = np->narg.next) {
4692 if (sep && np->narg.next)
4698 cmdtxt(union node *n)
4701 struct nodelist *lp;
4712 lp = n->npipe.cmdlist;
4730 cmdtxt(n->nbinary.ch1);
4746 cmdtxt(n->nif.test);
4748 if (n->nif.elsepart) {
4749 cmdtxt(n->nif.ifpart);
4751 n = n->nif.elsepart;
4769 cmdtxt(n->nbinary.ch1);
4779 cmdputs(n->nfor.var);
4781 cmdlist(n->nfor.args, 1);
4786 cmdputs(n->narg.text);
4790 cmdlist(n->ncmd.args, 1);
4791 cmdlist(n->ncmd.redirect, 0);
4804 cmdputs(n->ncase.expr->narg.text);
4806 for (np = n->ncase.cases; np; np = np->nclist.next) {
4807 cmdtxt(np->nclist.pattern);
4809 cmdtxt(np->nclist.body);
4823 #if BASH_REDIR_OUTPUT
4838 cmdputs(utoa(n->nfile.fd));
4840 if (n->type == NTOFD || n->type == NFROMFD) {
4841 if (n->ndup.dupfd >= 0)
4842 cmdputs(utoa(n->ndup.dupfd));
4853 commandtext(union node *n)
4857 STARTSTACKSTR(cmdnextc);
4859 name = stackblock();
4860 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4861 return ckstrdup(name);
4866 * Fork off a subshell. If we are doing job control, give the subshell its
4867 * own process group. Jp is a job structure that the job is to be added to.
4868 * N is the command that will be evaluated by the child. Both jp and n may
4869 * be NULL. The mode parameter can be one of the following:
4870 * FORK_FG - Fork off a foreground process.
4871 * FORK_BG - Fork off a background process.
4872 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4873 * process group even if job control is on.
4875 * When job control is turned off, background processes have their standard
4876 * input redirected to /dev/null (except for the second and later processes
4879 * Called with interrupts off.
4882 * Clear traps on a fork.
4890 for (tp = trap; tp < &trap[NSIG]; tp++) {
4891 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4892 if (trap_ptr == trap)
4894 /* else: it "belongs" to trap_ptr vector, don't free */
4896 if ((tp - trap) != 0)
4897 setsignal(tp - trap);
4904 /* Lives far away from here, needed for forkchild */
4905 static void closescript(void);
4907 /* Called after fork(), in child */
4908 /* jp and n are NULL when called by openhere() for heredoc support */
4909 static NOINLINE void
4910 forkchild(struct job *jp, union node *n, int mode)
4914 TRACE(("Child shell %d\n", getpid()));
4918 /* man bash: "Non-builtin commands run by bash have signal handlers
4919 * set to the values inherited by the shell from its parent".
4920 * Do we do it correctly? */
4924 if (mode == FORK_NOJOB /* is it `xxx` ? */
4925 && n && n->type == NCMD /* is it single cmd? */
4926 /* && n->ncmd.args->type == NARG - always true? */
4927 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4928 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4929 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4931 TRACE(("Trap hack\n"));
4932 /* Awful hack for `trap` or $(trap).
4934 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4935 * contains an example where "trap" is executed in a subshell:
4937 * save_traps=$(trap)
4939 * eval "$save_traps"
4941 * Standard does not say that "trap" in subshell shall print
4942 * parent shell's traps. It only says that its output
4943 * must have suitable form, but then, in the above example
4944 * (which is not supposed to be normative), it implies that.
4946 * bash (and probably other shell) does implement it
4947 * (traps are reset to defaults, but "trap" still shows them),
4948 * but as a result, "trap" logic is hopelessly messed up:
4951 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4952 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4953 * # true | trap <--- trap is in subshell - no output (ditto)
4954 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4955 * trap -- 'echo Ho' SIGWINCH
4956 * # echo `(trap)` <--- in subshell in subshell - output
4957 * trap -- 'echo Ho' SIGWINCH
4958 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4959 * trap -- 'echo Ho' SIGWINCH
4961 * The rules when to forget and when to not forget traps
4962 * get really complex and nonsensical.
4964 * Our solution: ONLY bare $(trap) or `trap` is special.
4966 /* Save trap handler strings for trap builtin to print */
4967 trap_ptr = xmemdup(trap, sizeof(trap));
4968 /* Fall through into clearing traps */
4972 /* do job control only in root shell */
4974 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4977 if (jp->nprocs == 0)
4980 pgrp = jp->ps[0].ps_pid;
4981 /* this can fail because we are doing it in the parent also */
4983 if (mode == FORK_FG)
4984 xtcsetpgrp(ttyfd, pgrp);
4989 if (mode == FORK_BG) {
4990 /* man bash: "When job control is not in effect,
4991 * asynchronous commands ignore SIGINT and SIGQUIT" */
4994 if (jp->nprocs == 0) {
4996 if (open(bb_dev_null, O_RDONLY) != 0)
4997 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
5001 if (iflag) { /* why if iflag only? */
5006 * "In all cases, bash ignores SIGQUIT. Non-builtin
5007 * commands run by bash have signal handlers
5008 * set to the values inherited by the shell
5010 * Take care of the second rule: */
5014 if (n && n->type == NCMD
5015 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
5017 TRACE(("Job hack\n"));
5018 /* "jobs": we do not want to clear job list for it,
5019 * instead we remove only _its_ own_ job from job list.
5020 * This makes "jobs .... | cat" more useful.
5026 for (jp = curjob; jp; jp = jp->prev_job)
5031 /* Called after fork(), in parent */
5033 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
5036 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
5038 TRACE(("In parent shell: child = %d\n", pid));
5040 /* jp is NULL when called by openhere() for heredoc support */
5041 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
5047 if (mode != FORK_NOJOB && jp->jobctl) {
5050 if (jp->nprocs == 0)
5053 pgrp = jp->ps[0].ps_pid;
5054 /* This can fail because we are doing it in the child also */
5058 if (mode == FORK_BG) {
5059 backgndpid = pid; /* set $! */
5060 set_curjob(jp, CUR_RUNNING);
5063 struct procstat *ps = &jp->ps[jp->nprocs++];
5066 ps->ps_cmd = nullstr;
5068 if (doing_jobctl && n)
5069 ps->ps_cmd = commandtext(n);
5074 /* jp and n are NULL when called by openhere() for heredoc support */
5076 forkshell(struct job *jp, union node *n, int mode)
5080 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
5083 TRACE(("Fork failed, errno=%d", errno));
5086 ash_msg_and_raise_error("can't fork");
5089 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
5090 forkchild(jp, n, mode);
5092 forkparent(jp, n, mode, pid);
5098 * Wait for job to finish.
5100 * Under job control we have the problem that while a child process
5101 * is running interrupts generated by the user are sent to the child
5102 * but not to the shell. This means that an infinite loop started by
5103 * an interactive user may be hard to kill. With job control turned off,
5104 * an interactive user may place an interactive program inside a loop.
5105 * If the interactive program catches interrupts, the user doesn't want
5106 * these interrupts to also abort the loop. The approach we take here
5107 * is to have the shell ignore interrupt signals while waiting for a
5108 * foreground process to terminate, and then send itself an interrupt
5109 * signal if the child process was terminated by an interrupt signal.
5110 * Unfortunately, some programs want to do a bit of cleanup and then
5111 * exit on interrupt; unless these processes terminate themselves by
5112 * sending a signal to themselves (instead of calling exit) they will
5113 * confuse this approach.
5115 * Called with interrupts off.
5118 waitforjob(struct job *jp)
5122 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
5125 while (jp->state == JOBRUNNING) {
5126 /* In non-interactive shells, we _can_ get
5127 * a keyboard signal here and be EINTRed,
5128 * but we just loop back, waiting for command to complete.
5131 * "If bash is waiting for a command to complete and receives
5132 * a signal for which a trap has been set, the trap
5133 * will not be executed until the command completes."
5135 * Reality is that even if trap is not set, bash
5136 * will not act on the signal until command completes.
5137 * Try this. sleep5intoff.c:
5138 * #include <signal.h>
5139 * #include <unistd.h>
5142 * sigemptyset(&set);
5143 * sigaddset(&set, SIGINT);
5144 * sigaddset(&set, SIGQUIT);
5145 * sigprocmask(SIG_BLOCK, &set, NULL);
5149 * $ bash -c './sleep5intoff; echo hi'
5150 * ^C^C^C^C <--- pressing ^C once a second
5152 * $ bash -c './sleep5intoff; echo hi'
5153 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
5156 dowait(DOWAIT_BLOCK, jp);
5163 xtcsetpgrp(ttyfd, rootpid);
5164 restore_tty_if_stopped_or_signaled(jp);
5167 * This is truly gross.
5168 * If we're doing job control, then we did a TIOCSPGRP which
5169 * caused us (the shell) to no longer be in the controlling
5170 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
5171 * intuit from the subprocess exit status whether a SIGINT
5172 * occurred, and if so interrupt ourselves. Yuck. - mycroft
5174 if (jp->sigint) /* TODO: do the same with all signals */
5175 raise(SIGINT); /* ... by raise(jp->sig) instead? */
5177 if (jp->state == JOBDONE)
5184 * return 1 if there are stopped jobs, otherwise 0
5196 if (jp && jp->state == JOBSTOPPED) {
5197 out2str("You have stopped jobs.\n");
5207 * Code for dealing with input/output redirection.
5212 #define EMPTY -2 /* marks an unused slot in redirtab */
5213 #define CLOSED -1 /* marks a slot of previously-closed fd */
5216 * Handle here documents. Normally we fork off a process to write the
5217 * data to a pipe. If the document is short, we can stuff the data in
5218 * the pipe without forking.
5220 /* openhere needs this forward reference */
5221 static void expandhere(union node *arg, int fd);
5223 openhere(union node *redir)
5229 ash_msg_and_raise_error("pipe call failed");
5230 if (redir->type == NHERE) {
5231 len = strlen(redir->nhere.doc->narg.text);
5232 if (len <= PIPE_BUF) {
5233 full_write(pip[1], redir->nhere.doc->narg.text, len);
5237 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5240 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5241 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5242 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5243 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5244 signal(SIGPIPE, SIG_DFL);
5245 if (redir->type == NHERE)
5246 full_write(pip[1], redir->nhere.doc->narg.text, len);
5248 expandhere(redir->nhere.doc, pip[1]);
5249 _exit(EXIT_SUCCESS);
5257 openredirect(union node *redir)
5263 switch (redir->nfile.type) {
5264 /* Can't happen, our single caller does this itself */
5270 return openhere(redir);
5273 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5274 * allocated space. Do it only when we know it is safe.
5276 fname = redir->nfile.expfname;
5278 switch (redir->nfile.type) {
5284 f = open(fname, O_RDONLY);
5289 f = open(fname, O_RDWR|O_CREAT, 0666);
5294 #if BASH_REDIR_OUTPUT
5297 /* Take care of noclobber mode. */
5299 if (stat(fname, &sb) < 0) {
5300 f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5303 } else if (!S_ISREG(sb.st_mode)) {
5304 f = open(fname, O_WRONLY, 0666);
5307 if (fstat(f, &sb) < 0 && S_ISREG(sb.st_mode)) {
5320 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5325 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5333 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5335 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5339 * Copy a file descriptor to be >= 10. Throws exception on error.
5347 newfd = fcntl(from, F_DUPFD, 10);
5348 err = newfd < 0 ? errno : 0;
5351 ash_msg_and_raise_perror("%d", from);
5353 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5359 dup2_or_raise(int from, int to)
5363 newfd = (from != to) ? dup2(from, to) : to;
5365 /* Happens when source fd is not open: try "echo >&99" */
5366 ash_msg_and_raise_perror("%d", from);
5371 fcntl_F_DUPFD(int fd, int avoid_fd)
5375 newfd = fcntl(fd, F_DUPFD, avoid_fd + 1);
5385 xdup_CLOEXEC_and_close(int fd, int avoid_fd)
5389 newfd = fcntl(fd, F_DUPFD, avoid_fd + 1);
5395 /* fd was not open? */
5398 ash_msg_and_raise_perror("%d", newfd);
5400 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5405 /* Struct def and variable are moved down to the first usage site */
5411 struct redirtab *next;
5413 struct squirrel two_fd[];
5415 #define redirlist (G_var.redirlist)
5418 add_squirrel_closed(struct redirtab *sq, int fd)
5425 for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
5426 /* If we collide with an already moved fd... */
5427 if (fd == sq->two_fd[i].orig_fd) {
5429 * "echo 3>FILE 3>&- 3>FILE"
5430 * "echo 3>&- 3>FILE"
5431 * No need for last redirect to insert
5432 * another "need to close 3" indicator.
5434 TRACE(("redirect_fd %d: already moved or closed\n", fd));
5438 TRACE(("redirect_fd %d: previous fd was closed\n", fd));
5439 sq->two_fd[i].orig_fd = fd;
5440 sq->two_fd[i].moved_to = CLOSED;
5444 save_fd_on_redirect(int fd, int avoid_fd, struct redirtab *sq)
5448 if (avoid_fd < 9) /* the important case here is that it can be -1 */
5453 /* Testcase: "ls -l /proc/$$/fd 10>&-" should work */
5454 ttyfd = xdup_CLOEXEC_and_close(ttyfd, avoid_fd);
5455 TRACE(("redirect_fd %d: matches ttyfd, moving it to %d\n", fd, ttyfd));
5456 return 1; /* "we closed fd" */
5459 /* Are we called from redirect(0)? E.g. redirect
5460 * in a forked child. No need to save fds,
5461 * we aren't going to use them anymore, ok to trash.
5466 /* If this one of script's fds? */
5468 struct parsefile *pf = g_parsefile;
5470 /* We skip fd == 0 case because of the following:
5471 * $ ash # running ash interactively
5473 * and in script.sh: "exec 9>&0".
5474 * Even though top-level pf_fd _is_ 0,
5475 * it's still ok to use it: "read" builtin uses it,
5476 * why should we cripple "exec" builtin?
5478 if (fd == pf->pf_fd) {
5479 pf->pf_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
5480 return 1; /* "we closed fd" */
5486 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
5488 /* First: do we collide with some already moved fds? */
5489 for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
5490 /* If we collide with an already moved fd... */
5491 if (fd == sq->two_fd[i].moved_to) {
5492 new_fd = fcntl_F_DUPFD(fd, avoid_fd);
5493 sq->two_fd[i].moved_to = new_fd;
5494 TRACE(("redirect_fd %d: already busy, moving to %d\n", fd, new_fd));
5495 if (new_fd < 0) /* what? */
5497 return 0; /* "we did not close fd" */
5499 if (fd == sq->two_fd[i].orig_fd) {
5500 /* Example: echo Hello >/dev/null 1>&2 */
5501 TRACE(("redirect_fd %d: already moved\n", fd));
5502 return 0; /* "we did not close fd" */
5506 /* If this fd is open, we move and remember it; if it's closed, new_fd = CLOSED (-1) */
5507 new_fd = fcntl_F_DUPFD(fd, avoid_fd);
5508 TRACE(("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, new_fd));
5512 /* new_fd = CLOSED; - already is -1 */
5514 sq->two_fd[i].moved_to = new_fd;
5515 sq->two_fd[i].orig_fd = fd;
5517 /* if we move stderr, let "set -x" code know */
5518 if (fd == preverrout_fd)
5519 preverrout_fd = new_fd;
5521 return 0; /* "we did not close fd" */
5525 internally_opened_fd(int fd, struct redirtab *sq)
5532 /* If this one of script's fds? */
5534 struct parsefile *pf = g_parsefile;
5536 if (fd == pf->pf_fd)
5542 if (sq) for (i = 0; i < sq->pair_count && sq->two_fd[i].orig_fd != EMPTY; i++) {
5543 if (fd == sq->two_fd[i].moved_to)
5550 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5551 * old file descriptors are stashed away so that the redirection can be
5552 * undone by calling popredir.
5554 /* flags passed to redirect */
5555 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5557 redirect(union node *redir, int flags)
5559 struct redirtab *sv;
5566 if (flags & REDIR_PUSH)
5574 fd = redir->nfile.fd;
5575 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5576 //bb_error_msg("doing %d > %d", fd, newfd);
5577 newfd = redir->ndup.dupfd;
5580 newfd = openredirect(redir); /* always >= 0 */
5582 /* open() gave us precisely the fd we wanted.
5583 * This means that this fd was not busy
5584 * (not opened to anywhere).
5585 * Remember to close it on restore:
5587 add_squirrel_closed(sv, fd);
5596 /* if "N>FILE": move newfd to fd */
5597 /* if "N>&M": dup newfd to fd */
5598 /* if "N>&-": close fd (newfd is -1) */
5600 IF_BASH_REDIR_OUTPUT(redirect_more:)
5602 closed = save_fd_on_redirect(fd, /*avoid:*/ newfd, sv);
5604 /* "N>&-" means "close me" */
5606 /* ^^^ optimization: saving may already
5607 * have closed it. If not... */
5611 /* if newfd is a script fd or saved fd, simulate EBADF */
5612 if (internally_opened_fd(newfd, sv)) {
5614 ash_msg_and_raise_perror("%d", newfd);
5616 dup2_or_raise(newfd, fd);
5617 if (close_fd >= 0) /* "N>FILE" or ">&FILE" or heredoc? */
5619 #if BASH_REDIR_OUTPUT
5620 if (redir->nfile.type == NTO2 && fd == 1) {
5621 /* ">&FILE". we already redirected to 1, now copy 1 to 2 */
5629 } while ((redir = redir->nfile.next) != NULL);
5632 //dash:#define REDIR_SAVEFD2 03 /* set preverrout */
5633 #define REDIR_SAVEFD2 0
5634 // dash has a bug: since REDIR_SAVEFD2=3 and REDIR_PUSH=1, this test
5635 // triggers for pure REDIR_PUSH too. Thus, this is done almost always,
5636 // not only for calls with flags containing REDIR_SAVEFD2.
5637 // We do this unconditionally (see save_fd_on_redirect()).
5638 //if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5639 // preverrout_fd = copied_fd2;
5643 redirectsafe(union node *redir, int flags)
5646 volatile int saveint;
5647 struct jmploc *volatile savehandler = exception_handler;
5648 struct jmploc jmploc;
5651 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5652 err = setjmp(jmploc.loc); /* was = setjmp(jmploc.loc) * 2; */
5654 exception_handler = &jmploc;
5655 redirect(redir, flags);
5657 exception_handler = savehandler;
5658 if (err && exception_type != EXERROR)
5659 longjmp(exception_handler->loc, 1);
5660 RESTORE_INT(saveint);
5664 static struct redirtab*
5665 pushredir(union node *redir)
5667 struct redirtab *sv;
5676 #if BASH_REDIR_OUTPUT
5677 if (redir->nfile.type == NTO2)
5680 redir = redir->nfile.next;
5683 sv = ckzalloc(sizeof(*sv) + i * sizeof(sv->two_fd[0]));
5686 sv->two_fd[i].orig_fd = sv->two_fd[i].moved_to = EMPTY;
5687 sv->next = redirlist;
5693 * Undo the effects of the last redirection.
5698 struct redirtab *rp;
5701 if (redirlist == NULL)
5705 for (i = 0; i < rp->pair_count; i++) {
5706 int fd = rp->two_fd[i].orig_fd;
5707 int copy = rp->two_fd[i].moved_to;
5708 if (copy == CLOSED) {
5713 if (copy != EMPTY) {
5716 dup2_or_raise(copy, fd);
5721 redirlist = rp->next;
5727 unwindredir(struct redirtab *stop)
5729 while (redirlist != stop)
5730 popredir(/*drop:*/ 0);
5734 /* ============ Routines to expand arguments to commands
5736 * We have to deal with backquotes, shell variables, and file metacharacters.
5739 #if ENABLE_FEATURE_SH_MATH
5741 ash_arith(const char *s)
5743 arith_state_t math_state;
5746 math_state.lookupvar = lookupvar;
5747 math_state.setvar = setvar0;
5748 //math_state.endofname = endofname;
5751 result = arith(&math_state, s);
5752 if (math_state.errmsg)
5753 ash_msg_and_raise_error(math_state.errmsg);
5763 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5764 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5765 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5766 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5767 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5768 * POSIX says for this case:
5769 * Pathname expansion shall not be performed on the word by a
5770 * non-interactive shell; an interactive shell may perform it, but shall
5771 * do so only when the expansion would result in one word.
5772 * Currently, our code complies to the above rule by never globbing
5773 * redirection filenames.
5774 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5775 * (this means that on a typical Linux distro, bash almost always
5776 * performs globbing, and thus diverges from what we do).
5778 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5779 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5780 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5781 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5782 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5786 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5787 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5788 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5789 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5790 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5792 /* Add CTLESC when necessary. */
5793 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT)
5794 /* Do not skip NUL characters. */
5795 #define QUOTES_KEEPNUL EXP_TILDE
5798 * Structure specifying which parts of the string should be searched
5799 * for IFS characters.
5802 struct ifsregion *next; /* next region in list */
5803 int begoff; /* offset of start of region */
5804 int endoff; /* offset of end of region */
5805 int nulonly; /* search for nul bytes only */
5809 struct strlist *list;
5810 struct strlist **lastp;
5813 /* output of current string */
5814 static char *expdest;
5815 /* list of back quote expressions */
5816 static struct nodelist *argbackq;
5817 /* first struct in list of ifs regions */
5818 static struct ifsregion ifsfirst;
5819 /* last struct in list */
5820 static struct ifsregion *ifslastp;
5821 /* holds expanded arg list */
5822 static struct arglist exparg;
5826 * cvtnum() is used even if math support is off (to prepare $? values and such).
5833 /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
5834 len = sizeof(arith_t) * 3;
5835 /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
5836 if (sizeof(arith_t) < 4) len += 2;
5838 expdest = makestrspace(len, expdest);
5839 len = fmtstr(expdest, len, ARITH_FMT, num);
5840 STADJUST(len, expdest);
5845 * Break the argument string into pieces based upon IFS and add the
5846 * strings to the argument list. The regions of the string to be
5847 * searched for IFS characters have been stored by recordregion.
5850 ifsbreakup(char *string, struct arglist *arglist)
5852 struct ifsregion *ifsp;
5857 const char *ifs, *realifs;
5862 if (ifslastp != NULL) {
5865 realifs = ifsset() ? ifsval() : defifs;
5868 p = string + ifsp->begoff;
5869 nulonly = ifsp->nulonly;
5870 ifs = nulonly ? nullstr : realifs;
5872 while (p < string + ifsp->endoff) {
5874 if ((unsigned char)*p == CTLESC)
5876 if (!strchr(ifs, *p)) {
5881 ifsspc = (strchr(defifs, *p) != NULL);
5882 /* Ignore IFS whitespace at start */
5883 if (q == start && ifsspc) {
5889 sp = stzalloc(sizeof(*sp));
5891 *arglist->lastp = sp;
5892 arglist->lastp = &sp->next;
5896 if (p >= string + ifsp->endoff) {
5900 if ((unsigned char)*p == CTLESC)
5902 if (strchr(ifs, *p) == NULL) {
5906 if (strchr(defifs, *p) == NULL) {
5921 } while (ifsp != NULL);
5930 sp = stzalloc(sizeof(*sp));
5932 *arglist->lastp = sp;
5933 arglist->lastp = &sp->next;
5939 struct ifsregion *p = ifsfirst.next;
5946 struct ifsregion *ifsp;
5951 ifsfirst.next = NULL;
5958 esclen(const char *start, const char *p)
5962 while (p > start && (unsigned char)*--p == CTLESC) {
5969 * Remove any CTLESC characters from a string.
5972 rmescapes(char *str, int flag)
5974 static const char qchars[] ALIGN1 = {
5975 IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
5979 unsigned protect_against_glob;
5981 IF_BASH_PATTERN_SUBST(unsigned slash = flag & RMESCAPE_SLASH;)
5983 p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash));
5989 if (flag & RMESCAPE_ALLOC) {
5990 size_t len = p - str;
5991 size_t fulllen = len + strlen(p) + 1;
5993 if (flag & RMESCAPE_GROW) {
5994 int strloc = str - (char *)stackblock();
5995 r = makestrspace(fulllen, expdest);
5996 /* p and str may be invalidated by makestrspace */
5997 str = (char *)stackblock() + strloc;
5999 } else if (flag & RMESCAPE_HEAP) {
6000 r = ckmalloc(fulllen);
6002 r = stalloc(fulllen);
6006 q = (char *)mempcpy(q, str, len);
6011 globbing = flag & RMESCAPE_GLOB;
6012 protect_against_glob = globbing;
6014 if ((unsigned char)*p == CTLQUOTEMARK) {
6015 // Note: both inquotes and protect_against_glob only affect whether
6016 // CTLESC,<ch> gets converted to <ch> or to \<ch>
6017 inquotes = ~inquotes;
6019 protect_against_glob = globbing;
6022 if ((unsigned char)*p == CTLESC) {
6026 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
6028 if (protect_against_glob) {
6030 * We used to trust glob() and fnmatch() to eat
6031 * superfluous escapes (\z where z has no
6032 * special meaning anyway). But this causes
6033 * bugs such as string of one greek letter rho
6034 * (unicode-encoded as two bytes "cf,81")
6035 * getting encoded as "cf,CTLESC,81"
6036 * and here, converted to "cf,\,81" -
6037 * which does not go well with some flavors
6038 * of fnmatch() in unicode locales
6039 * (for example, glibc <= 2.22).
6041 * Lets add "\" only on the chars which need it.
6042 * Testcases for less obvious chars are shown.
6047 || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
6048 || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
6049 || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
6050 || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
6051 /* Some libc support [^negate], that's why "^" also needs love */
6052 || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
6057 } else if (*p == '\\' && !inquotes) {
6058 /* naked back slash */
6059 protect_against_glob = 0;
6062 #if BASH_PATTERN_SUBST
6063 else if (*p == '/' && slash) {
6064 /* stop handling globbing and mark location of slash */
6065 globbing = slash = 0;
6069 protect_against_glob = globbing;
6074 if (flag & RMESCAPE_GROW) {
6076 STADJUST(q - r + 1, expdest);
6080 #define pmatch(a, b) !fnmatch((a), (b), 0)
6083 * Prepare a pattern for a expmeta (internal glob(3)) call.
6085 * Returns an stalloced string.
6088 preglob(const char *pattern, int flag)
6090 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
6094 * Put a string on the stack.
6097 memtodest(const char *p, size_t len, int syntax, int quotes)
6104 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
6107 unsigned char c = *p++;
6109 if (quotes & QUOTES_ESC) {
6110 int n = SIT(c, syntax);
6112 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
6119 } else if (!(quotes & QUOTES_KEEPNUL))
6128 strtodest(const char *p, int syntax, int quotes)
6130 size_t len = strlen(p);
6131 memtodest(p, len, syntax, quotes);
6136 * Record the fact that we have to scan this region of the
6137 * string for IFS characters.
6140 recordregion(int start, int end, int nulonly)
6142 struct ifsregion *ifsp;
6144 if (ifslastp == NULL) {
6148 ifsp = ckzalloc(sizeof(*ifsp));
6149 /*ifsp->next = NULL; - ckzalloc did it */
6150 ifslastp->next = ifsp;
6154 ifslastp->begoff = start;
6155 ifslastp->endoff = end;
6156 ifslastp->nulonly = nulonly;
6160 removerecordregions(int endoff)
6162 if (ifslastp == NULL)
6165 if (ifsfirst.endoff > endoff) {
6166 while (ifsfirst.next) {
6167 struct ifsregion *ifsp;
6169 ifsp = ifsfirst.next->next;
6170 free(ifsfirst.next);
6171 ifsfirst.next = ifsp;
6174 if (ifsfirst.begoff > endoff) {
6177 ifslastp = &ifsfirst;
6178 ifsfirst.endoff = endoff;
6183 ifslastp = &ifsfirst;
6184 while (ifslastp->next && ifslastp->next->begoff < endoff)
6185 ifslastp = ifslastp->next;
6186 while (ifslastp->next) {
6187 struct ifsregion *ifsp;
6189 ifsp = ifslastp->next->next;
6190 free(ifslastp->next);
6191 ifslastp->next = ifsp;
6194 if (ifslastp->endoff > endoff)
6195 ifslastp->endoff = endoff;
6199 exptilde(char *startp, char *p, int flags)
6205 int quotes = flags & QUOTES_ESC;
6209 while ((c = *++p) != '\0') {
6216 if (flags & EXP_VARTILDE)
6226 if (*name == '\0') {
6227 home = lookupvar("HOME");
6229 pw = getpwnam(name);
6234 if (!home || !*home)
6237 strtodest(home, SQSYNTAX, quotes);
6245 * Execute a command inside back quotes. If it's a builtin command, we
6246 * want to save its output in a block obtained from malloc. Otherwise
6247 * we fork off a subprocess and get the output of the command via a pipe.
6248 * Should be called with interrupts off.
6250 struct backcmd { /* result of evalbackcmd */
6251 int fd; /* file descriptor to read from */
6252 int nleft; /* number of chars in buffer */
6253 char *buf; /* buffer */
6254 struct job *jp; /* job structure for command */
6257 /* These forward decls are needed to use "eval" code for backticks handling: */
6258 /* flags in argument to evaltree */
6259 #define EV_EXIT 01 /* exit after evaluating tree */
6260 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
6261 static int evaltree(union node *, int);
6263 /* An evaltree() which is known to never return.
6264 * Used to use an alias:
6265 * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
6266 * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
6268 static ALWAYS_INLINE NORETURN void
6269 evaltreenr(union node *n, int flags)
6272 bb_unreachable(abort());
6276 static void FAST_FUNC
6277 evalbackcmd(union node *n, struct backcmd *result)
6291 ash_msg_and_raise_error("pipe call failed");
6292 jp = makejob(/*n,*/ 1);
6293 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6299 dup2_or_raise(pip[1], 1);
6302 /* TODO: eflag clearing makes the following not abort:
6303 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6304 * which is what bash does (unless it is in POSIX mode).
6305 * dash deleted "eflag = 0" line in the commit
6306 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6307 * [EVAL] Don't clear eflag in evalbackcmd
6308 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6312 evaltreenr(n, EV_EXIT);
6317 result->fd = pip[0];
6321 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6322 result->fd, result->buf, result->nleft, result->jp));
6326 * Expand stuff in backwards quotes.
6329 expbackq(union node *cmd, int flag)
6337 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6338 struct stackmark smark;
6341 startloc = expdest - (char *)stackblock();
6342 pushstackmark(&smark, startloc);
6343 evalbackcmd(cmd, &in);
6344 popstackmark(&smark);
6351 memtodest(p, i, syntax, flag & QUOTES_ESC);
6355 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6356 TRACE(("expbackq: read returns %d\n", i));
6365 back_exitstatus = waitforjob(in.jp);
6369 /* Eat all trailing newlines */
6371 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6375 if (!(flag & EXP_QUOTED))
6376 recordregion(startloc, dest - (char *)stackblock(), 0);
6377 TRACE(("evalbackq: size:%d:'%.*s'\n",
6378 (int)((dest - (char *)stackblock()) - startloc),
6379 (int)((dest - (char *)stackblock()) - startloc),
6380 stackblock() + startloc));
6383 #if ENABLE_FEATURE_SH_MATH
6385 * Expand arithmetic expression. Backup to start of expression,
6386 * evaluate, place result in (backed up) result, adjust string position.
6398 * This routine is slightly over-complicated for
6399 * efficiency. Next we scan backwards looking for the
6400 * start of arithmetic.
6402 start = stackblock();
6409 while ((unsigned char)*p != CTLARI) {
6413 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6418 esc = esclen(start, p);
6428 removerecordregions(begoff);
6432 if (flag & QUOTES_ESC)
6433 rmescapes(p + 1, 0);
6435 len = cvtnum(ash_arith(p + 1));
6437 if (!(flag & EXP_QUOTED))
6438 recordregion(begoff, begoff + len, 0);
6442 /* argstr needs it */
6443 static char *evalvar(char *p, int flags);
6446 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6447 * characters to allow for further processing. Otherwise treat
6448 * $@ like $* since no splitting will be performed.
6451 argstr(char *p, int flags)
6453 static const char spclchars[] ALIGN1 = {
6461 #if ENABLE_FEATURE_SH_MATH
6466 const char *reject = spclchars;
6467 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6472 if (!(flags & EXP_VARTILDE)) {
6474 } else if (flags & EXP_VARTILDE2) {
6479 if (flags & EXP_TILDE) {
6482 flags &= ~EXP_TILDE;
6486 p = exptilde(p, q, flags);
6489 startloc = expdest - (char *)stackblock();
6493 length += strcspn(p + length, reject);
6497 IF_FEATURE_SH_MATH(|| c == CTLENDARI)
6499 /* c == '=' || c == ':' || c == CTLENDARI */
6505 expdest = stack_nputstr(p, length, expdest);
6506 newloc = expdest - (char *)stackblock();
6507 if (breakall && !inquotes && newloc > startloc) {
6508 recordregion(startloc, newloc, 0);
6519 if (flags & EXP_VARTILDE2) {
6523 flags |= EXP_VARTILDE2;
6528 * sort of a hack - expand tildes in variable
6529 * assignments (after the first '=' and after ':'s).
6538 case CTLENDVAR: /* ??? */
6541 inquotes ^= EXP_QUOTED;
6542 /* "$@" syntax adherence hack */
6543 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6544 p = evalvar(p + 1, flags | inquotes) + 1;
6548 if (flags & QUOTES_ESC) {
6559 * Quoted parameter expansion pattern: remove quote
6560 * unless inside inner quotes or we have a literal
6563 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6564 EXP_QPAT && *p != '\\')
6569 TRACE(("argstr: evalvar('%s')\n", p));
6570 p = evalvar(p, flags | inquotes);
6571 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6574 expbackq(argbackq->n, flags | inquotes);
6575 argbackq = argbackq->next;
6577 #if ENABLE_FEATURE_SH_MATH
6580 expari(flags | inquotes);
6589 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6590 char *pattern, int quotes, int zero)
6599 const char *s = loc2;
6606 match = pmatch(pattern, s);
6611 if (quotes && (unsigned char)*loc == CTLESC)
6620 scanright(char *startp, char *rmesc, char *rmescend,
6621 char *pattern, int quotes, int match_at_start)
6623 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6624 int try2optimize = match_at_start;
6630 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6631 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6632 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6634 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6635 * and on each iteration they go back two/one char until they reach the beginning.
6636 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6638 /* TODO: document in what other circumstances we are called. */
6640 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6643 const char *s = loc2;
6644 if (match_at_start) {
6648 match = pmatch(pattern, s);
6649 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6653 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6655 /* Maybe we can optimize this:
6656 * if pattern ends with unescaped *, we can avoid checking
6657 * shorter strings: if "foo*" doesn't match "raw_value_of_v",
6658 * it won't match truncated "raw_value_of_" strings too.
6660 unsigned plen = strlen(pattern);
6661 /* Does it end with "*"? */
6662 if (plen != 0 && pattern[--plen] == '*') {
6663 /* "xxxx*" is not escaped */
6664 /* "xxx\*" is escaped */
6665 /* "xx\\*" is not escaped */
6666 /* "x\\\*" is escaped */
6668 while (plen != 0 && pattern[--plen] == '\\')
6671 break; /* ends with unescaped "*" */
6679 esc = esclen(startp, loc);
6690 static void varunset(const char *, const char *, const char *, int) NORETURN;
6692 varunset(const char *end, const char *var, const char *umsg, int varflags)
6698 msg = "parameter not set";
6700 if ((unsigned char)*end == CTLENDVAR) {
6701 if (varflags & VSNUL)
6707 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6711 subevalvar(char *p, char *varname, int strloc, int subtype,
6712 int startloc, int varflags, int flag)
6714 struct nodelist *saveargbackq = argbackq;
6715 int quotes = flag & QUOTES_ESC;
6718 char *rmesc, *rmescend;
6720 int amount, resetloc;
6721 IF_BASH_PATTERN_SUBST(int workloc;)
6722 IF_BASH_PATTERN_SUBST(char *repl = NULL;)
6724 char *(*scan)(char*, char*, char*, char*, int, int);
6726 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6727 // p, varname, strloc, subtype, startloc, varflags, quotes);
6729 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6730 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0)
6732 STPUTC('\0', expdest);
6733 argbackq = saveargbackq;
6734 startp = (char *)stackblock() + startloc;
6738 setvar0(varname, startp);
6739 amount = startp - expdest;
6740 STADJUST(amount, expdest);
6744 varunset(p, varname, startp, varflags);
6749 int pos, len, orig_len;
6752 loc = str = stackblock() + strloc;
6754 # if !ENABLE_FEATURE_SH_MATH
6755 # define ash_arith number
6757 /* Read POS in ${var:POS:LEN} */
6758 colon = strchr(loc, ':');
6759 if (colon) *colon = '\0';
6760 pos = ash_arith(loc);
6761 if (colon) *colon = ':';
6763 /* Read LEN in ${var:POS:LEN} */
6764 len = str - startp - 1;
6765 /* *loc != '\0', guaranteed by parser */
6769 /* Adjust the length by the number of escapes */
6770 for (ptr = startp; ptr < (str - 1); ptr++) {
6771 if ((unsigned char)*ptr == CTLESC) {
6778 if (*loc++ == ':') {
6780 len = ash_arith(loc);
6782 /* Skip POS in ${var:POS:LEN} */
6784 while (*loc && *loc != ':') {
6787 if (*loc++ == ':') {
6788 len = ash_arith(loc);
6794 /* ${VAR:$((-n)):l} starts n chars from the end */
6795 pos = orig_len + pos;
6797 if ((unsigned)pos >= orig_len) {
6798 /* apart from obvious ${VAR:999999:l},
6799 * covers ${VAR:$((-9999999)):l} - result is ""
6806 /* ${VAR:N:-M} sets LEN to strlen()-M */
6807 len = (orig_len - pos) + len;
6809 if ((unsigned)len > (orig_len - pos))
6810 len = orig_len - pos;
6812 for (str = startp; pos; str++, pos--) {
6813 if (quotes && (unsigned char)*str == CTLESC)
6816 for (loc = startp; len; len--) {
6817 if (quotes && (unsigned char)*str == CTLESC)
6822 amount = loc - expdest;
6823 STADJUST(amount, expdest);
6826 #endif /* BASH_SUBSTR */
6829 resetloc = expdest - (char *)stackblock();
6831 #if BASH_PATTERN_SUBST
6832 /* We'll comeback here if we grow the stack while handling
6833 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6834 * stack will need rebasing, and we'll need to remove our work
6840 amount = expdest - ((char *)stackblock() + resetloc);
6841 STADJUST(-amount, expdest);
6842 startp = (char *)stackblock() + startloc;
6845 rmescend = (char *)stackblock() + strloc;
6847 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6848 if (rmesc != startp) {
6850 startp = (char *)stackblock() + startloc;
6854 str = (char *)stackblock() + strloc;
6856 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6857 * The result is a_\_z_c (not a\_\_z_c)!
6859 * The search pattern and replace string treat backslashes differently!
6860 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6861 * and string. It's only used on the first call.
6863 preglob(str, IF_BASH_PATTERN_SUBST(
6864 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6865 RMESCAPE_SLASH : ) 0);
6867 #if BASH_PATTERN_SUBST
6868 workloc = expdest - (char *)stackblock();
6869 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6874 repl = strchr(str, CTLESC);
6880 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6882 /* If there's no pattern to match, return the expansion unmolested */
6891 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6892 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6894 /* No match, advance */
6895 char *restart_detect = stackblock();
6897 STPUTC(*idx, expdest);
6898 if (quotes && (unsigned char)*idx == CTLESC) {
6901 STPUTC(*idx, expdest);
6903 if (stackblock() != restart_detect)
6908 /* continue; - prone to quadratic behavior, smarter code: */
6911 if (str[0] == '*') {
6912 /* Pattern is "*foo". If "*foo" does not match "long_string",
6913 * it would never match "ong_string" etc, no point in trying.
6920 if (subtype == VSREPLACEALL) {
6922 if (quotes && (unsigned char)*idx == CTLESC)
6931 //bb_error_msg("repl:'%s'", repl);
6932 for (loc = (char*)repl; *loc; loc++) {
6933 char *restart_detect = stackblock();
6934 if (quotes && *loc == '\\') {
6935 STPUTC(CTLESC, expdest);
6938 STPUTC(*loc, expdest);
6939 if (stackblock() != restart_detect)
6944 if (subtype == VSREPLACE) {
6945 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6947 char *restart_detect = stackblock();
6948 STPUTC(*idx, expdest);
6949 if (stackblock() != restart_detect)
6958 /* We've put the replaced text into a buffer at workloc, now
6959 * move it to the right place and adjust the stack.
6961 STPUTC('\0', expdest);
6962 startp = (char *)stackblock() + startloc;
6963 memmove(startp, (char *)stackblock() + workloc, len + 1);
6964 //bb_error_msg("startp:'%s'", startp);
6965 amount = expdest - (startp + len);
6966 STADJUST(-amount, expdest);
6969 #endif /* BASH_PATTERN_SUBST */
6971 subtype -= VSTRIMRIGHT;
6973 if (subtype < 0 || subtype > 7)
6976 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6977 zero = subtype >> 1;
6978 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6979 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6981 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6984 memmove(startp, loc, str - loc);
6985 loc = startp + (str - loc) - 1;
6988 amount = loc - expdest;
6989 STADJUST(amount, expdest);
6995 * Add the value of a specialized variable to the stack string.
6996 * name parameter (examples):
6997 * ash -c 'echo $1' name:'1='
6998 * ash -c 'echo $qwe' name:'qwe='
6999 * ash -c 'echo $$' name:'$='
7000 * ash -c 'echo ${$}' name:'$='
7001 * ash -c 'echo ${$##q}' name:'$=q'
7002 * ash -c 'echo ${#$}' name:'$='
7003 * note: examples with bad shell syntax:
7004 * ash -c 'echo ${#$1}' name:'$=1'
7005 * ash -c 'echo ${#1#}' name:'1=#'
7007 static NOINLINE ssize_t
7008 varvalue(char *name, int varflags, int flags, int *quotedp)
7015 int quoted = *quotedp;
7016 int subtype = varflags & VSTYPE;
7017 int discard = subtype == VSPLUS || subtype == VSLENGTH;
7018 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
7021 sep = (flags & EXP_FULL) << CHAR_BIT;
7022 syntax = quoted ? DQSYNTAX : BASESYNTAX;
7032 num = shellparam.nparam;
7040 goto check_1char_name;
7042 expdest = makestrspace(NOPTS, expdest);
7043 for (i = NOPTS - 1; i >= 0; i--) {
7045 USTPUTC(optletters(i), expdest);
7051 /* handles cases similar to ${#$1} */
7052 if (name[2] != '\0')
7053 raise_error_syntax("bad substitution");
7066 sep |= ifsset() ? ifsval()[0] : ' ';
7073 while ((p = *ap++) != NULL) {
7074 len += strtodest(p, syntax, quotes);
7078 memtodest(&sepc, 1, syntax, quotes);
7093 num = atoi(name); /* number(name) fails on ${N#str} etc */
7094 if (num < 0 || num > shellparam.nparam)
7096 p = num ? shellparam.p[num - 1] : arg0;
7099 /* NB: name has form "VAR=..." */
7100 p = lookupvar(name);
7105 len = strtodest(p, syntax, quotes);
7106 #if ENABLE_UNICODE_SUPPORT
7107 if (subtype == VSLENGTH && len > 0) {
7108 reinit_unicode_for_ash();
7109 if (unicode_status == UNICODE_ON) {
7110 STADJUST(-len, expdest);
7112 len = unicode_strlen(p);
7120 STADJUST(-len, expdest);
7125 * Expand a variable, and return a pointer to the next character in the
7129 evalvar(char *p, int flag)
7140 varflags = (unsigned char) *p++;
7141 subtype = varflags & VSTYPE;
7144 raise_error_syntax("bad substitution");
7146 quoted = flag & EXP_QUOTED;
7148 easy = (!quoted || (*var == '@' && shellparam.nparam));
7149 startloc = expdest - (char *)stackblock();
7150 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
7153 varlen = varvalue(var, varflags, flag, "ed);
7154 if (varflags & VSNUL)
7157 if (subtype == VSPLUS) {
7158 varlen = -1 - varlen;
7162 if (subtype == VSMINUS) {
7167 flag | EXP_TILDE | EXP_WORD
7174 if (subtype == VSASSIGN || subtype == VSQUESTION) {
7178 subevalvar(p, var, 0, subtype, startloc, varflags,
7179 flag & ~QUOTES_ESC);
7182 * Remove any recorded regions beyond
7185 removerecordregions(startloc);
7189 if (varlen < 0 && uflag)
7190 varunset(p, var, 0, 0);
7192 if (subtype == VSLENGTH) {
7193 cvtnum(varlen > 0 ? varlen : 0);
7197 if (subtype == VSNORMAL) {
7201 recordregion(startloc, expdest - (char *)stackblock(), quoted);
7210 case VSTRIMRIGHTMAX:
7214 #if BASH_PATTERN_SUBST
7226 * Terminate the string and start recording the pattern
7229 STPUTC('\0', expdest);
7230 patloc = expdest - (char *)stackblock();
7231 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
7232 startloc, varflags, flag)) {
7233 int amount = expdest - (
7234 (char *)stackblock() + patloc - 1
7236 STADJUST(-amount, expdest);
7238 /* Remove any recorded regions beyond start of variable */
7239 removerecordregions(startloc);
7244 if (subtype != VSNORMAL) { /* skip to end of alternative */
7247 unsigned char c = *p++;
7250 else if (c == CTLBACKQ) {
7252 argbackq = argbackq->next;
7253 } else if (c == CTLVAR) {
7254 if ((*p++ & VSTYPE) != VSNORMAL)
7256 } else if (c == CTLENDVAR) {
7266 * Add a file name to the list.
7269 addfname(const char *name)
7273 sp = stzalloc(sizeof(*sp));
7274 sp->text = sstrdup(name);
7276 exparg.lastp = &sp->next;
7279 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7281 hasmeta(const char *p)
7283 static const char chars[] ALIGN1 = {
7284 '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
7288 p = strpbrk(p, chars);
7291 switch ((unsigned char) *p) {
7295 if (*p == CTLQUOTEMARK)
7299 if (*p == '\0') /* huh? */
7310 if (!strchr(p + 1, ']')) {
7311 /* It's not a properly closed [] pattern,
7312 * but other metas may follow. Continue checking.
7313 * my[file* _is_ globbed by bash
7314 * and matches filenames like "my[file1".
7330 /* If we want to use glob() from libc... */
7331 #if !ENABLE_ASH_INTERNAL_GLOB
7333 /* Add the result of glob() to the list */
7335 addglob(const glob_t *pglob)
7337 char **p = pglob->gl_pathv;
7344 expandmeta(struct strlist *str /*, int flag*/)
7346 /* TODO - EXP_REDIR */
7356 if (!hasmeta(str->text))
7360 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7361 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7362 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7364 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7365 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7366 // Which means you need to unescape the string, right? Not so fast:
7367 // if there _is_ a file named "file\?" (with backslash), it is returned
7368 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7369 // You DON'T KNOW by looking at the result whether you need to unescape it.
7371 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7372 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7373 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7374 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7375 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7376 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7377 i = glob(p, 0, NULL, &pglob);
7378 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7383 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7384 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7385 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7397 *exparg.lastp = str;
7398 rmescapes(str->text, 0);
7399 exparg.lastp = &str->next;
7401 default: /* GLOB_NOSPACE */
7404 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7411 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7414 * Do metacharacter (i.e. *, ?, [...]) expansion.
7417 expmeta(char *expdir, char *enddir, char *name)
7433 for (p = name; esc = 0, *p; p += esc + 1) {
7434 if (*p == '*' || *p == '?')
7436 else if (*p == '[') {
7443 if (*q == '/' || *q == '\0')
7453 if (p[esc] == '/') {
7456 start = p + esc + 1;
7460 if (metaflag == 0) { /* we've reached the end of the file name */
7461 if (enddir != expdir)
7469 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7480 } while (p < start);
7482 if (enddir == expdir) {
7484 } else if (enddir == expdir + 1 && *expdir == '/') {
7493 if (enddir != expdir)
7495 if (*endname == 0) {
7508 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7509 if (dp->d_name[0] == '.' && !matchdot)
7511 if (pmatch(start, dp->d_name)) {
7513 strcpy(enddir, dp->d_name);
7516 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7519 expmeta(expdir, p, endname);
7525 endname[-esc - 1] = esc ? '\\' : '/';
7528 static struct strlist *
7529 msort(struct strlist *list, int len)
7531 struct strlist *p, *q = NULL;
7532 struct strlist **lpp;
7540 for (n = half; --n >= 0;) {
7544 q->next = NULL; /* terminate first half of list */
7545 q = msort(list, half); /* sort first half of list */
7546 p = msort(p, len - half); /* sort second half */
7549 #if ENABLE_LOCALE_SUPPORT
7550 if (strcoll(p->text, q->text) < 0)
7552 if (strcmp(p->text, q->text) < 0)
7576 * Sort the results of file name expansion. It calculates the number of
7577 * strings to sort and then calls msort (short for merge sort) to do the
7580 static struct strlist *
7581 expsort(struct strlist *str)
7587 for (sp = str; sp; sp = sp->next)
7589 return msort(str, len);
7593 expandmeta(struct strlist *str /*, int flag*/)
7595 /* TODO - EXP_REDIR */
7599 struct strlist **savelastp;
7605 if (!hasmeta(str->text))
7607 savelastp = exparg.lastp;
7610 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7612 int i = strlen(str->text);
7613 //BUGGY estimation of how long expanded name can be
7614 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7616 expmeta(expdir, expdir, p);
7621 if (exparg.lastp == savelastp) {
7626 *exparg.lastp = str;
7627 rmescapes(str->text, 0);
7628 exparg.lastp = &str->next;
7630 *exparg.lastp = NULL;
7631 *savelastp = sp = expsort(*savelastp);
7632 while (sp->next != NULL)
7634 exparg.lastp = &sp->next;
7639 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7642 * Perform variable substitution and command substitution on an argument,
7643 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7644 * perform splitting and file name expansion. When arglist is NULL, perform
7645 * here document expansion.
7648 expandarg(union node *arg, struct arglist *arglist, int flag)
7653 argbackq = arg->narg.backquote;
7654 STARTSTACKSTR(expdest);
7655 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7656 argstr(arg->narg.text, flag);
7657 p = _STPUTC('\0', expdest);
7659 if (arglist == NULL) {
7660 /* here document expanded */
7663 p = grabstackstr(p);
7664 TRACE(("expandarg: p:'%s'\n", p));
7665 exparg.lastp = &exparg.list;
7669 if (flag & EXP_FULL) {
7670 ifsbreakup(p, &exparg);
7671 *exparg.lastp = NULL;
7672 exparg.lastp = &exparg.list;
7673 expandmeta(exparg.list /*, flag*/);
7675 sp = stzalloc(sizeof(*sp));
7678 exparg.lastp = &sp->next;
7680 *exparg.lastp = NULL;
7682 *arglist->lastp = exparg.list;
7683 arglist->lastp = exparg.lastp;
7691 * Expand shell variables and backquotes inside a here document.
7694 expandhere(union node *arg, int fd)
7696 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7697 full_write(fd, stackblock(), expdest - (char *)stackblock());
7701 * Returns true if the pattern matches the string.
7704 patmatch(char *pattern, const char *string)
7706 char *p = preglob(pattern, 0);
7707 //bb_error_msg("fnmatch(pattern:'%s',str:'%s')", p, string);
7708 return pmatch(p, string);
7712 * See if a pattern matches in a case statement.
7715 casematch(union node *pattern, char *val)
7717 struct stackmark smark;
7720 setstackmark(&smark);
7721 argbackq = pattern->narg.backquote;
7722 STARTSTACKSTR(expdest);
7723 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
7724 STACKSTRNUL(expdest);
7726 result = patmatch(stackblock(), val);
7727 popstackmark(&smark);
7732 /* ============ find_command */
7736 int (*builtin)(int, char **) FAST_FUNC;
7737 /* unsigned flags; */
7739 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7740 /* "regular" builtins always take precedence over commands,
7741 * regardless of PATH=....%builtin... position */
7742 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7743 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7746 smallint cmdtype; /* CMDxxx */
7749 /* index >= 0 for commands without path (slashes) */
7750 /* (TODO: what exactly does the value mean? PATH position?) */
7751 /* index == -1 for commands with slashes */
7752 /* index == (-2 - applet_no) for NOFORK applets */
7753 const struct builtincmd *cmd;
7754 struct funcnode *func;
7757 /* values of cmdtype */
7758 #define CMDUNKNOWN -1 /* no entry in table for command */
7759 #define CMDNORMAL 0 /* command is an executable program */
7760 #define CMDFUNCTION 1 /* command is a shell function */
7761 #define CMDBUILTIN 2 /* command is a shell builtin */
7763 /* action to find_command() */
7764 #define DO_ERR 0x01 /* prints errors */
7765 #define DO_ABS 0x02 /* checks absolute paths */
7766 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7767 #define DO_ALTPATH 0x08 /* using alternate path */
7768 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7770 static void find_command(char *, struct cmdentry *, int, const char *);
7773 /* ============ Hashing commands */
7776 * When commands are first encountered, they are entered in a hash table.
7777 * This ensures that a full path search will not have to be done for them
7778 * on each invocation.
7780 * We should investigate converting to a linear search, even though that
7781 * would make the command name "hash" a misnomer.
7785 struct tblentry *next; /* next entry in hash chain */
7786 union param param; /* definition of builtin function */
7787 smallint cmdtype; /* CMDxxx */
7788 char rehash; /* if set, cd done since entry created */
7789 char cmdname[1]; /* name of command */
7792 static struct tblentry **cmdtable;
7793 #define INIT_G_cmdtable() do { \
7794 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7797 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7801 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
7803 #if ENABLE_FEATURE_SH_STANDALONE
7804 if (applet_no >= 0) {
7805 if (APPLET_IS_NOEXEC(applet_no)) {
7809 popredir(/*drop:*/ 1);
7810 run_noexec_applet_and_exit(applet_no, cmd, argv);
7812 /* re-exec ourselves with the new arguments */
7813 execve(bb_busybox_exec_path, argv, envp);
7814 /* If they called chroot or otherwise made the binary no longer
7815 * executable, fall through */
7822 execve(cmd, argv, envp);
7823 } while (errno == EINTR);
7825 execve(cmd, argv, envp);
7827 if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
7828 /* Run "cmd" as a shell script:
7829 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7830 * "If the execve() function fails with ENOEXEC, the shell
7831 * shall execute a command equivalent to having a shell invoked
7832 * with the command name as its first operand,
7833 * with any remaining arguments passed to the new shell"
7835 * That is, do not use $SHELL, user's shell, or /bin/sh;
7836 * just call ourselves.
7838 * Note that bash reads ~80 chars of the file, and if it sees
7839 * a zero byte before it sees newline, it doesn't try to
7840 * interpret it, but fails with "cannot execute binary file"
7841 * message and exit code 126. For one, this prevents attempts
7842 * to interpret foreign ELF binaries as shell scripts.
7844 argv[0] = (char*) cmd;
7845 cmd = bb_busybox_exec_path;
7846 /* NB: this is only possible because all callers of shellexec()
7847 * ensure that the argv[-1] slot exists!
7850 argv[0] = (char*) "ash";
7856 * Exec a program. Never returns. If you change this routine, you may
7857 * have to change the find_command routine as well.
7858 * argv[-1] must exist and be writable! See tryexec() for why.
7860 static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
7861 static void shellexec(char *prog, char **argv, const char *path, int idx)
7867 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7869 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7870 if (strchr(prog, '/') != NULL
7871 #if ENABLE_FEATURE_SH_STANDALONE
7872 || (applet_no = find_applet_by_name(prog)) >= 0
7875 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
7876 if (applet_no >= 0) {
7877 /* We tried execing ourself, but it didn't work.
7878 * Maybe /proc/self/exe doesn't exist?
7887 while ((cmdname = path_advance(&path, prog)) != NULL) {
7888 if (--idx < 0 && pathopt == NULL) {
7889 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7890 if (errno != ENOENT && errno != ENOTDIR)
7897 /* Map to POSIX errors */
7909 exitstatus = exerrno;
7910 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7911 prog, e, suppress_int));
7912 ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
7917 printentry(struct tblentry *cmdp)
7923 idx = cmdp->param.index;
7926 name = path_advance(&path, cmdp->cmdname);
7928 } while (--idx >= 0);
7929 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7933 * Clear out command entries. The argument specifies the first entry in
7934 * PATH which has changed.
7937 clearcmdentry(int firstchange)
7939 struct tblentry **tblp;
7940 struct tblentry **pp;
7941 struct tblentry *cmdp;
7944 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7946 while ((cmdp = *pp) != NULL) {
7947 if ((cmdp->cmdtype == CMDNORMAL &&
7948 cmdp->param.index >= firstchange)
7949 || (cmdp->cmdtype == CMDBUILTIN &&
7950 builtinloc >= firstchange)
7963 * Locate a command in the command hash table. If "add" is nonzero,
7964 * add the command to the table if it is not already present. The
7965 * variable "lastcmdentry" is set to point to the address of the link
7966 * pointing to the entry, so that delete_cmd_entry can delete the
7969 * Interrupts must be off if called with add != 0.
7971 static struct tblentry **lastcmdentry;
7973 static struct tblentry *
7974 cmdlookup(const char *name, int add)
7976 unsigned int hashval;
7978 struct tblentry *cmdp;
7979 struct tblentry **pp;
7982 hashval = (unsigned char)*p << 4;
7984 hashval += (unsigned char)*p++;
7986 pp = &cmdtable[hashval % CMDTABLESIZE];
7987 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7988 if (strcmp(cmdp->cmdname, name) == 0)
7992 if (add && cmdp == NULL) {
7993 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7995 /* + 1 - already done because
7996 * tblentry::cmdname is char[1] */);
7997 /*cmdp->next = NULL; - ckzalloc did it */
7998 cmdp->cmdtype = CMDUNKNOWN;
7999 strcpy(cmdp->cmdname, name);
8006 * Delete the command entry returned on the last lookup.
8009 delete_cmd_entry(void)
8011 struct tblentry *cmdp;
8014 cmdp = *lastcmdentry;
8015 *lastcmdentry = cmdp->next;
8016 if (cmdp->cmdtype == CMDFUNCTION)
8017 freefunc(cmdp->param.func);
8023 * Add a new command entry, replacing any existing command entry for
8024 * the same name - except special builtins.
8027 addcmdentry(char *name, struct cmdentry *entry)
8029 struct tblentry *cmdp;
8031 cmdp = cmdlookup(name, 1);
8032 if (cmdp->cmdtype == CMDFUNCTION) {
8033 freefunc(cmdp->param.func);
8035 cmdp->cmdtype = entry->cmdtype;
8036 cmdp->param = entry->u;
8040 static int FAST_FUNC
8041 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8043 struct tblentry **pp;
8044 struct tblentry *cmdp;
8046 struct cmdentry entry;
8049 if (nextopt("r") != '\0') {
8054 if (*argptr == NULL) {
8055 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8056 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8057 if (cmdp->cmdtype == CMDNORMAL)
8065 while ((name = *argptr) != NULL) {
8066 cmdp = cmdlookup(name, 0);
8068 && (cmdp->cmdtype == CMDNORMAL
8069 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
8073 find_command(name, &entry, DO_ERR, pathval());
8074 if (entry.cmdtype == CMDUNKNOWN)
8082 * Called when a cd is done. Marks all commands so the next time they
8083 * are executed they will be rehashed.
8088 struct tblentry **pp;
8089 struct tblentry *cmdp;
8091 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8092 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8093 if (cmdp->cmdtype == CMDNORMAL
8094 || (cmdp->cmdtype == CMDBUILTIN
8095 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
8105 * Fix command hash table when PATH changed.
8106 * Called before PATH is changed. The argument is the new value of PATH;
8107 * pathval() still returns the old value at this point.
8108 * Called with interrupts off.
8110 static void FAST_FUNC
8111 changepath(const char *new)
8119 firstchange = 9999; /* assume no change */
8125 if ((*old == '\0' && *new == ':')
8126 || (*old == ':' && *new == '\0')
8130 old = new; /* ignore subsequent differences */
8134 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
8141 if (builtinloc < 0 && idx_bltin >= 0)
8142 builtinloc = idx_bltin; /* zap builtins */
8143 if (builtinloc >= 0 && idx_bltin < 0)
8145 clearcmdentry(firstchange);
8146 builtinloc = idx_bltin;
8182 typedef smallint token_id_t;
8184 /* Nth bit indicates if token marks the end of a list */
8187 /* 0 */ | (1u << TEOF)
8188 /* 1 */ | (0u << TNL)
8189 /* 2 */ | (0u << TREDIR)
8190 /* 3 */ | (0u << TWORD)
8191 /* 4 */ | (0u << TSEMI)
8192 /* 5 */ | (0u << TBACKGND)
8193 /* 6 */ | (0u << TAND)
8194 /* 7 */ | (0u << TOR)
8195 /* 8 */ | (0u << TPIPE)
8196 /* 9 */ | (0u << TLP)
8197 /* 10 */ | (1u << TRP)
8198 /* 11 */ | (1u << TENDCASE)
8199 /* 12 */ | (1u << TENDBQUOTE)
8200 /* 13 */ | (0u << TNOT)
8201 /* 14 */ | (0u << TCASE)
8202 /* 15 */ | (1u << TDO)
8203 /* 16 */ | (1u << TDONE)
8204 /* 17 */ | (1u << TELIF)
8205 /* 18 */ | (1u << TELSE)
8206 /* 19 */ | (1u << TESAC)
8207 /* 20 */ | (1u << TFI)
8208 /* 21 */ | (0u << TFOR)
8210 /* 22 */ | (0u << TFUNCTION)
8212 /* 23 */ | (0u << TIF)
8213 /* 24 */ | (0u << TIN)
8214 /* 25 */ | (1u << TTHEN)
8215 /* 26 */ | (0u << TUNTIL)
8216 /* 27 */ | (0u << TWHILE)
8217 /* 28 */ | (0u << TBEGIN)
8218 /* 29 */ | (1u << TEND)
8219 , /* thus far 29 bits used */
8222 static const char *const tokname_array[] = {
8236 #define KWDOFFSET 13
8237 /* the following are keywords */
8259 /* Wrapper around strcmp for qsort/bsearch/... */
8261 pstrcmp(const void *a, const void *b)
8263 return strcmp((char*)a, *(char**)b);
8266 static const char *const *
8267 findkwd(const char *s)
8269 return bsearch(s, tokname_array + KWDOFFSET,
8270 ARRAY_SIZE(tokname_array) - KWDOFFSET,
8271 sizeof(tokname_array[0]), pstrcmp);
8275 * Locate and print what a word is...
8278 describe_command(char *command, const char *path, int describe_command_verbose)
8280 struct cmdentry entry;
8281 #if ENABLE_ASH_ALIAS
8282 const struct alias *ap;
8285 path = path ? path : pathval();
8287 if (describe_command_verbose) {
8291 /* First look at the keywords */
8292 if (findkwd(command)) {
8293 out1str(describe_command_verbose ? " is a shell keyword" : command);
8297 #if ENABLE_ASH_ALIAS
8298 /* Then look at the aliases */
8299 ap = lookupalias(command, 0);
8301 if (!describe_command_verbose) {
8306 out1fmt(" is an alias for %s", ap->val);
8311 find_command(command, &entry, DO_ABS, path);
8313 switch (entry.cmdtype) {
8315 int j = entry.u.index;
8321 p = path_advance(&path, command);
8325 if (describe_command_verbose) {
8326 out1fmt(" is %s", p);
8334 if (describe_command_verbose) {
8335 out1str(" is a shell function");
8342 if (describe_command_verbose) {
8343 out1fmt(" is a %sshell builtin",
8344 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8345 "special " : nullstr
8353 if (describe_command_verbose) {
8354 out1str(": not found\n");
8363 static int FAST_FUNC
8364 typecmd(int argc UNUSED_PARAM, char **argv)
8370 /* type -p ... ? (we don't bother checking for 'p') */
8371 if (argv[1] && argv[1][0] == '-') {
8376 err |= describe_command(argv[i++], NULL, verbose);
8381 #if ENABLE_ASH_CMDCMD
8382 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8384 parse_command_args(char **argv, const char **path)
8397 if (c == '-' && !*cp) {
8405 *path = bb_default_path;
8408 /* run 'typecmd' for other options */
8417 static int FAST_FUNC
8418 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8426 const char *path = NULL;
8428 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8429 * never reaches this function.
8432 while ((c = nextopt("pvV")) != '\0')
8434 verify |= VERIFY_VERBOSE;
8436 /*verify |= VERIFY_BRIEF*/;
8442 path = bb_default_path;
8444 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8446 if (/*verify && */ cmd)
8447 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8454 /*static int funcblocksize; // size of structures in function */
8455 /*static int funcstringsize; // size of strings in node */
8456 static void *funcblock; /* block to allocate function from */
8457 static char *funcstring_end; /* end of block to allocate strings from */
8459 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8460 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8461 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8462 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8463 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8464 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8465 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8466 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8467 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8468 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8469 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8470 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8471 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8472 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8473 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8474 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8475 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8476 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8477 #if BASH_REDIR_OUTPUT
8478 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8480 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8481 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8482 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8483 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8484 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8485 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8486 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8487 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8488 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8491 static int calcsize(int funcblocksize, union node *n);
8494 sizenodelist(int funcblocksize, struct nodelist *lp)
8497 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8498 funcblocksize = calcsize(funcblocksize, lp->n);
8501 return funcblocksize;
8505 calcsize(int funcblocksize, union node *n)
8508 return funcblocksize;
8509 funcblocksize += nodesize[n->type];
8512 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8513 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8514 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8517 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8522 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8523 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8530 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8531 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8534 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8535 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8536 funcblocksize = calcsize(funcblocksize, n->nif.test);
8539 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8540 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8541 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8544 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8545 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8548 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8549 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8550 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8554 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8555 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8556 funcblocksize = calcsize(funcblocksize, n->narg.next);
8559 #if BASH_REDIR_OUTPUT
8566 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8567 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8571 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8572 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8576 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8577 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8580 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8583 return funcblocksize;
8587 nodeckstrdup(char *s)
8589 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8590 return strcpy(funcstring_end, s);
8593 static union node *copynode(union node *);
8595 static struct nodelist *
8596 copynodelist(struct nodelist *lp)
8598 struct nodelist *start;
8599 struct nodelist **lpp;
8604 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8605 (*lpp)->n = copynode(lp->n);
8607 lpp = &(*lpp)->next;
8614 copynode(union node *n)
8621 funcblock = (char *) funcblock + nodesize[n->type];
8625 new->ncmd.redirect = copynode(n->ncmd.redirect);
8626 new->ncmd.args = copynode(n->ncmd.args);
8627 new->ncmd.assign = copynode(n->ncmd.assign);
8630 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8631 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8636 new->nredir.redirect = copynode(n->nredir.redirect);
8637 new->nredir.n = copynode(n->nredir.n);
8644 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8645 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8648 new->nif.elsepart = copynode(n->nif.elsepart);
8649 new->nif.ifpart = copynode(n->nif.ifpart);
8650 new->nif.test = copynode(n->nif.test);
8653 new->nfor.var = nodeckstrdup(n->nfor.var);
8654 new->nfor.body = copynode(n->nfor.body);
8655 new->nfor.args = copynode(n->nfor.args);
8658 new->ncase.cases = copynode(n->ncase.cases);
8659 new->ncase.expr = copynode(n->ncase.expr);
8662 new->nclist.body = copynode(n->nclist.body);
8663 new->nclist.pattern = copynode(n->nclist.pattern);
8664 new->nclist.next = copynode(n->nclist.next);
8668 new->narg.backquote = copynodelist(n->narg.backquote);
8669 new->narg.text = nodeckstrdup(n->narg.text);
8670 new->narg.next = copynode(n->narg.next);
8673 #if BASH_REDIR_OUTPUT
8680 new->nfile.fname = copynode(n->nfile.fname);
8681 new->nfile.fd = n->nfile.fd;
8682 new->nfile.next = copynode(n->nfile.next);
8686 new->ndup.vname = copynode(n->ndup.vname);
8687 new->ndup.dupfd = n->ndup.dupfd;
8688 new->ndup.fd = n->ndup.fd;
8689 new->ndup.next = copynode(n->ndup.next);
8693 new->nhere.doc = copynode(n->nhere.doc);
8694 new->nhere.fd = n->nhere.fd;
8695 new->nhere.next = copynode(n->nhere.next);
8698 new->nnot.com = copynode(n->nnot.com);
8701 new->type = n->type;
8706 * Make a copy of a parse tree.
8708 static struct funcnode *
8709 copyfunc(union node *n)
8714 /*funcstringsize = 0;*/
8715 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8716 f = ckzalloc(blocksize /* + funcstringsize */);
8717 funcblock = (char *) f + offsetof(struct funcnode, n);
8718 funcstring_end = (char *) f + blocksize;
8720 /* f->count = 0; - ckzalloc did it */
8725 * Define a shell function.
8728 defun(union node *func)
8730 struct cmdentry entry;
8733 entry.cmdtype = CMDFUNCTION;
8734 entry.u.func = copyfunc(func);
8735 addcmdentry(func->narg.text, &entry);
8739 /* Reasons for skipping commands (see comment on breakcmd routine) */
8740 #define SKIPBREAK (1 << 0)
8741 #define SKIPCONT (1 << 1)
8742 #define SKIPFUNC (1 << 2)
8743 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8744 static int skipcount; /* number of levels to skip */
8745 static int funcnest; /* depth of function calls */
8746 static int loopnest; /* current loop nesting level */
8748 /* Forward decl way out to parsing code - dotrap needs it */
8749 static int evalstring(char *s, int flags);
8751 /* Called to execute a trap.
8752 * Single callsite - at the end of evaltree().
8753 * If we return non-zero, evaltree raises EXEXIT exception.
8755 * Perhaps we should avoid entering new trap handlers
8756 * while we are executing a trap handler. [is it a TODO?]
8763 uint8_t last_status;
8768 last_status = exitstatus;
8772 TRACE(("dotrap entered\n"));
8773 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8785 /* non-trapped SIGINT is handled separately by raise_interrupt,
8786 * don't upset it by resetting gotsig[SIGINT-1] */
8787 if (sig == SIGINT && !p)
8790 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8796 exitstatus = last_status;
8797 TRACE(("dotrap returns\n"));
8800 /* forward declarations - evaluation is fairly recursive business... */
8801 static int evalloop(union node *, int);
8802 static int evalfor(union node *, int);
8803 static int evalcase(union node *, int);
8804 static int evalsubshell(union node *, int);
8805 static void expredir(union node *);
8806 static int evalpipe(union node *, int);
8807 static int evalcommand(union node *, int);
8808 static int evalbltin(const struct builtincmd *, int, char **, int);
8809 static void prehash(union node *);
8812 * Evaluate a parse tree. The value is left in the global variable
8816 evaltree(union node *n, int flags)
8819 int (*evalfn)(union node *, int);
8823 TRACE(("evaltree(NULL) called\n"));
8826 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8833 out1fmt("Node type = %d\n", n->type);
8838 status = !evaltree(n->nnot.com, EV_TESTED);
8841 expredir(n->nredir.redirect);
8842 pushredir(n->nredir.redirect);
8843 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8845 status = evaltree(n->nredir.n, flags & EV_TESTED);
8847 if (n->nredir.redirect)
8848 popredir(/*drop:*/ 0);
8851 evalfn = evalcommand;
8853 if (eflag && !(flags & EV_TESTED))
8865 evalfn = evalsubshell;
8878 #error NAND + 1 != NOR
8880 #if NOR + 1 != NSEMI
8881 #error NOR + 1 != NSEMI
8883 unsigned is_or = n->type - NAND;
8886 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8888 if ((!status) == is_or || evalskip)
8894 status = evalfn(n, flags);
8898 status = evaltree(n->nif.test, EV_TESTED);
8905 if (n->nif.elsepart) {
8906 n = n->nif.elsepart;
8913 /* Not necessary. To test it:
8914 * "false; f() { qwerty; }; echo $?" should print 0.
8918 exitstatus = status;
8922 /* Order of checks below is important:
8923 * signal handlers trigger before exit caused by "set -e".
8927 if (checkexit & status)
8928 raise_exception(EXEXIT);
8929 if (flags & EV_EXIT)
8930 raise_exception(EXEXIT);
8932 TRACE(("leaving evaltree (no interrupts)\n"));
8939 int skip = evalskip;
8946 if (--skipcount <= 0) {
8957 evalloop(union node *n, int flags)
8968 i = evaltree(n->nbinary.ch1, EV_TESTED);
8970 if (skip == SKIPFUNC)
8974 if (n->type != NWHILE)
8978 status = evaltree(n->nbinary.ch2, flags);
8980 } while (!(skip & ~SKIPCONT));
8987 evalfor(union node *n, int flags)
8989 struct arglist arglist;
8992 struct stackmark smark;
8995 setstackmark(&smark);
8996 arglist.list = NULL;
8997 arglist.lastp = &arglist.list;
8998 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8999 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9001 *arglist.lastp = NULL;
9005 for (sp = arglist.list; sp; sp = sp->next) {
9006 setvar0(n->nfor.var, sp->text);
9007 status = evaltree(n->nfor.body, flags);
9008 if (skiploop() & ~SKIPCONT)
9012 popstackmark(&smark);
9018 evalcase(union node *n, int flags)
9022 struct arglist arglist;
9023 struct stackmark smark;
9026 setstackmark(&smark);
9027 arglist.list = NULL;
9028 arglist.lastp = &arglist.list;
9029 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
9030 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
9031 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
9032 if (casematch(patp, arglist.list->text)) {
9033 /* Ensure body is non-empty as otherwise
9034 * EV_EXIT may prevent us from setting the
9037 if (evalskip == 0 && cp->nclist.body) {
9038 status = evaltree(cp->nclist.body, flags);
9045 popstackmark(&smark);
9051 * Kick off a subshell to evaluate a tree.
9054 evalsubshell(union node *n, int flags)
9057 int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
9060 expredir(n->nredir.redirect);
9061 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
9064 if (backgnd == FORK_FG)
9066 jp = makejob(/*n,*/ 1);
9067 if (forkshell(jp, n, backgnd) == 0) {
9072 flags &= ~EV_TESTED;
9074 redirect(n->nredir.redirect, 0);
9075 evaltreenr(n->nredir.n, flags);
9080 if (backgnd == FORK_FG)
9081 status = waitforjob(jp);
9087 * Compute the names of the files in a redirection list.
9089 static void fixredir(union node *, const char *, int);
9091 expredir(union node *n)
9095 for (redir = n; redir; redir = redir->nfile.next) {
9099 fn.lastp = &fn.list;
9100 switch (redir->type) {
9104 #if BASH_REDIR_OUTPUT
9109 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
9110 TRACE(("expredir expanded to '%s'\n", fn.list->text));
9111 #if BASH_REDIR_OUTPUT
9115 // By the design of stack allocator, the loop of this kind:
9116 // while true; do while true; do break; done </dev/null; done
9117 // will look like a memory leak: ash plans to free expfname's
9118 // of "/dev/null" as soon as it finishes running the loop
9119 // (in this case, never).
9120 // This "fix" is wrong:
9121 if (redir->nfile.expfname)
9122 stunalloc(redir->nfile.expfname);
9123 // It results in corrupted state of stacked allocations.
9125 redir->nfile.expfname = fn.list->text;
9128 case NTOFD: /* >& */
9129 if (redir->ndup.vname) {
9130 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
9131 if (fn.list == NULL)
9132 ash_msg_and_raise_error("redir error");
9133 #if BASH_REDIR_OUTPUT
9134 //FIXME: we used expandarg with different args!
9135 if (!isdigit_str9(fn.list->text)) {
9136 /* >&file, not >&fd */
9137 if (redir->nfile.fd != 1) /* 123>&file - BAD */
9138 ash_msg_and_raise_error("redir error");
9140 goto store_expfname;
9143 fixredir(redir, fn.list->text, 1);
9151 * Evaluate a pipeline. All the processes in the pipeline are children
9152 * of the process creating the pipeline. (This differs from some versions
9153 * of the shell, which make the last process in a pipeline the parent
9157 evalpipe(union node *n, int flags)
9160 struct nodelist *lp;
9166 TRACE(("evalpipe(0x%lx) called\n", (long)n));
9168 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
9172 if (n->npipe.pipe_backgnd == 0)
9174 jp = makejob(/*n,*/ pipelen);
9176 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
9180 if (pipe(pip) < 0) {
9182 ash_msg_and_raise_error("pipe call failed");
9185 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
9199 evaltreenr(lp->n, flags);
9206 /* Don't want to trigger debugging */
9210 if (n->npipe.pipe_backgnd == 0) {
9211 status = waitforjob(jp);
9212 TRACE(("evalpipe: job done exit status %d\n", status));
9220 * Controls whether the shell is interactive or not.
9223 setinteractive(int on)
9225 static smallint is_interactive;
9227 if (++on == is_interactive)
9229 is_interactive = on;
9233 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9234 if (is_interactive > 1) {
9235 /* Looks like they want an interactive shell */
9236 static smallint did_banner;
9239 /* note: ash and hush share this string */
9240 out1fmt("\n\n%s %s\n"
9241 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
9244 "built-in shell (ash)"
9258 setinteractive(iflag);
9260 #if ENABLE_FEATURE_EDITING_VI
9262 line_input_state->flags |= VI_MODE;
9264 line_input_state->flags &= ~VI_MODE;
9266 viflag = 0; /* forcibly keep the option off */
9270 struct localvar_list {
9271 struct localvar_list *next;
9272 struct localvar *lv;
9275 static struct localvar_list *localvar_stack;
9278 * Called after a function returns.
9279 * Interrupts must be off.
9282 poplocalvars(int keep)
9284 struct localvar_list *ll;
9285 struct localvar *lvp, *next;
9289 ll = localvar_stack;
9290 localvar_stack = ll->next;
9295 while ((lvp = next) != NULL) {
9298 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9300 int bits = VSTRFIXED;
9302 if (lvp->flags != VUNSET) {
9303 if (vp->var_text == lvp->text)
9305 else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
9306 free((char*)lvp->text);
9310 vp->flags |= (lvp->flags & bits);
9313 (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
9314 unsetvar(vp->var_text);
9315 } else if (vp == NULL) { /* $- saved */
9316 memcpy(optlist, lvp->text, sizeof(optlist));
9317 free((char*)lvp->text);
9319 } else if (lvp->flags == VUNSET) {
9320 vp->flags &= ~(VSTRFIXED|VREADONLY);
9321 unsetvar(vp->var_text);
9324 vp->var_func(var_end(lvp->text));
9325 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9326 free((char*)vp->var_text);
9327 vp->flags = lvp->flags;
9328 vp->var_text = lvp->text;
9336 * Create a new localvar environment.
9338 static struct localvar_list *
9341 struct localvar_list *ll;
9344 ll = ckzalloc(sizeof(*ll));
9345 /*ll->lv = NULL; - zalloc did it */
9346 ll->next = localvar_stack;
9347 localvar_stack = ll;
9354 unwindlocalvars(struct localvar_list *stop)
9356 while (localvar_stack != stop)
9361 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9363 volatile struct shparam saveparam;
9364 struct jmploc *volatile savehandler;
9365 struct jmploc jmploc;
9368 saveparam = shellparam;
9369 savehandler = exception_handler;
9370 e = setjmp(jmploc.loc);
9375 exception_handler = &jmploc;
9376 shellparam.malloced = 0;
9380 shellparam.nparam = argc - 1;
9381 shellparam.p = argv + 1;
9382 #if ENABLE_ASH_GETOPTS
9383 shellparam.optind = 1;
9384 shellparam.optoff = -1;
9387 evaltree(func->n.narg.next, flags & EV_TESTED);
9393 freeparam(&shellparam);
9394 shellparam = saveparam;
9395 exception_handler = savehandler;
9397 evalskip &= ~SKIPFUNC;
9402 * Make a variable a local variable. When a variable is made local, it's
9403 * value and flags are saved in a localvar structure. The saved values
9404 * will be restored when the shell function returns. We handle the name
9405 * "-" as a special case: it makes changes to "set +-options" local
9406 * (options will be restored on return from the function).
9411 struct localvar *lvp;
9414 char *eq = strchr(name, '=');
9417 /* Cater for duplicate "local". Examples:
9418 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9419 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9421 lvp = localvar_stack->lv;
9423 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9427 * it's a duplicate "local VAR" declaration, do nothing
9434 lvp = ckzalloc(sizeof(*lvp));
9435 if (LONE_DASH(name)) {
9437 p = ckmalloc(sizeof(optlist));
9438 lvp->text = memcpy(p, optlist, sizeof(optlist));
9441 vpp = hashvar(name);
9442 vp = *findvar(vpp, name);
9444 /* variable did not exist yet */
9446 vp = setvareq(name, VSTRFIXED);
9448 vp = setvar(name, NULL, VSTRFIXED);
9449 lvp->flags = VUNSET;
9451 lvp->text = vp->var_text;
9452 lvp->flags = vp->flags;
9453 /* make sure neither "struct var" nor string gets freed
9454 * during (un)setting:
9456 vp->flags |= VSTRFIXED|VTEXTFIXED;
9460 /* "local VAR" unsets VAR: */
9461 setvar0(name, NULL);
9465 lvp->next = localvar_stack->lv;
9466 localvar_stack->lv = lvp;
9472 * The "local" command.
9474 static int FAST_FUNC
9475 localcmd(int argc UNUSED_PARAM, char **argv)
9479 if (!localvar_stack)
9480 ash_msg_and_raise_error("not in a function");
9483 while ((name = *argv++) != NULL) {
9489 static int FAST_FUNC
9490 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9495 static int FAST_FUNC
9496 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9501 static int FAST_FUNC
9502 execcmd(int argc UNUSED_PARAM, char **argv)
9505 while (nextopt("a:") != '\0')
9506 /* nextopt() sets optionarg to "-a ARGV0" */;
9512 iflag = 0; /* exit on error */
9515 /* We should set up signals for "exec CMD"
9516 * the same way as for "CMD" without "exec".
9517 * But optschanged->setinteractive->setsignal
9518 * still thought we are a root shell. Therefore, for example,
9519 * SIGQUIT is still set to IGN. Fix it:
9523 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9524 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9525 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9529 argv[0] = optionarg;
9530 shellexec(prog, argv, pathval(), 0);
9537 * The return command.
9539 static int FAST_FUNC
9540 returncmd(int argc UNUSED_PARAM, char **argv)
9543 * If called outside a function, do what ksh does;
9544 * skip the rest of the file.
9546 evalskip = SKIPFUNC;
9547 return argv[1] ? number(argv[1]) : exitstatus;
9550 /* Forward declarations for builtintab[] */
9551 static int breakcmd(int, char **) FAST_FUNC;
9552 static int dotcmd(int, char **) FAST_FUNC;
9553 static int evalcmd(int, char **, int) FAST_FUNC;
9554 static int exitcmd(int, char **) FAST_FUNC;
9555 static int exportcmd(int, char **) FAST_FUNC;
9556 #if ENABLE_ASH_GETOPTS
9557 static int getoptscmd(int, char **) FAST_FUNC;
9560 static int helpcmd(int, char **) FAST_FUNC;
9563 static int historycmd(int, char **) FAST_FUNC;
9565 #if ENABLE_FEATURE_SH_MATH
9566 static int letcmd(int, char **) FAST_FUNC;
9568 static int readcmd(int, char **) FAST_FUNC;
9569 static int setcmd(int, char **) FAST_FUNC;
9570 static int shiftcmd(int, char **) FAST_FUNC;
9571 static int timescmd(int, char **) FAST_FUNC;
9572 static int trapcmd(int, char **) FAST_FUNC;
9573 static int umaskcmd(int, char **) FAST_FUNC;
9574 static int unsetcmd(int, char **) FAST_FUNC;
9575 static int ulimitcmd(int, char **) FAST_FUNC;
9577 #define BUILTIN_NOSPEC "0"
9578 #define BUILTIN_SPECIAL "1"
9579 #define BUILTIN_REGULAR "2"
9580 #define BUILTIN_SPEC_REG "3"
9581 #define BUILTIN_ASSIGN "4"
9582 #define BUILTIN_SPEC_ASSG "5"
9583 #define BUILTIN_REG_ASSG "6"
9584 #define BUILTIN_SPEC_REG_ASSG "7"
9586 /* Stubs for calling non-FAST_FUNC's */
9588 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9590 #if ENABLE_ASH_PRINTF
9591 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9593 #if ENABLE_ASH_TEST || BASH_TEST2
9594 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9597 /* Keep these in proper order since it is searched via bsearch() */
9598 static const struct builtincmd builtintab[] = {
9599 { BUILTIN_SPEC_REG "." , dotcmd },
9600 { BUILTIN_SPEC_REG ":" , truecmd },
9602 { BUILTIN_REGULAR "[" , testcmd },
9605 { BUILTIN_REGULAR "[[" , testcmd },
9607 #if ENABLE_ASH_ALIAS
9608 { BUILTIN_REG_ASSG "alias" , aliascmd },
9611 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9613 { BUILTIN_SPEC_REG "break" , breakcmd },
9614 { BUILTIN_REGULAR "cd" , cdcmd },
9615 { BUILTIN_NOSPEC "chdir" , cdcmd },
9616 #if ENABLE_ASH_CMDCMD
9617 { BUILTIN_REGULAR "command" , commandcmd },
9619 { BUILTIN_SPEC_REG "continue", breakcmd },
9621 { BUILTIN_REGULAR "echo" , echocmd },
9623 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9624 { BUILTIN_SPEC_REG "exec" , execcmd },
9625 { BUILTIN_SPEC_REG "exit" , exitcmd },
9626 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9627 { BUILTIN_REGULAR "false" , falsecmd },
9629 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9631 #if ENABLE_ASH_GETOPTS
9632 { BUILTIN_REGULAR "getopts" , getoptscmd },
9634 { BUILTIN_NOSPEC "hash" , hashcmd },
9636 { BUILTIN_NOSPEC "help" , helpcmd },
9639 { BUILTIN_NOSPEC "history" , historycmd },
9642 { BUILTIN_REGULAR "jobs" , jobscmd },
9643 { BUILTIN_REGULAR "kill" , killcmd },
9645 #if ENABLE_FEATURE_SH_MATH
9646 { BUILTIN_NOSPEC "let" , letcmd },
9648 { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
9649 #if ENABLE_ASH_PRINTF
9650 { BUILTIN_REGULAR "printf" , printfcmd },
9652 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9653 { BUILTIN_REGULAR "read" , readcmd },
9654 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9655 { BUILTIN_SPEC_REG "return" , returncmd },
9656 { BUILTIN_SPEC_REG "set" , setcmd },
9657 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9659 { BUILTIN_SPEC_REG "source" , dotcmd },
9662 { BUILTIN_REGULAR "test" , testcmd },
9664 { BUILTIN_SPEC_REG "times" , timescmd },
9665 { BUILTIN_SPEC_REG "trap" , trapcmd },
9666 { BUILTIN_REGULAR "true" , truecmd },
9667 { BUILTIN_NOSPEC "type" , typecmd },
9668 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9669 { BUILTIN_REGULAR "umask" , umaskcmd },
9670 #if ENABLE_ASH_ALIAS
9671 { BUILTIN_REGULAR "unalias" , unaliascmd },
9673 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9674 { BUILTIN_REGULAR "wait" , waitcmd },
9677 /* Should match the above table! */
9678 #define COMMANDCMD (builtintab + \
9680 /* [ */ 1 * ENABLE_ASH_TEST + \
9681 /* [[ */ 1 * BASH_TEST2 + \
9682 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9683 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9684 /* break cd cddir */ 3)
9685 #define EVALCMD (COMMANDCMD + \
9686 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9687 /* continue */ 1 + \
9688 /* echo */ 1 * ENABLE_ASH_ECHO + \
9690 #define EXECCMD (EVALCMD + \
9694 * Search the table of builtin commands.
9697 pstrcmp1(const void *a, const void *b)
9699 return strcmp((char*)a, *(char**)b + 1);
9701 static struct builtincmd *
9702 find_builtin(const char *name)
9704 struct builtincmd *bp;
9707 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9714 * Execute a simple command.
9717 isassignment(const char *p)
9719 const char *q = endofname(p);
9724 static int FAST_FUNC
9725 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9727 /* Preserve exitstatus of a previous possible redirection
9728 * as POSIX mandates */
9729 return back_exitstatus;
9732 evalcommand(union node *cmd, int flags)
9734 static const struct builtincmd null_bltin = {
9735 "\0\0", bltincmd /* why three NULs? */
9737 struct localvar_list *localvar_stop;
9738 struct redirtab *redir_stop;
9739 struct stackmark smark;
9741 struct arglist arglist;
9742 struct arglist varlist;
9745 const struct strlist *sp;
9746 struct cmdentry cmdentry;
9753 smallint cmd_is_exec;
9755 /* First expand the arguments. */
9756 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9757 setstackmark(&smark);
9758 localvar_stop = pushlocalvars();
9759 back_exitstatus = 0;
9761 cmdentry.cmdtype = CMDBUILTIN;
9762 cmdentry.u.cmd = &null_bltin;
9763 varlist.lastp = &varlist.list;
9764 *varlist.lastp = NULL;
9765 arglist.lastp = &arglist.list;
9766 *arglist.lastp = NULL;
9769 if (cmd->ncmd.args) {
9770 struct builtincmd *bcmd;
9771 smallint pseudovarflag;
9773 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9774 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9776 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9777 struct strlist **spp;
9779 spp = arglist.lastp;
9780 if (pseudovarflag && isassignment(argp->narg.text))
9781 expandarg(argp, &arglist, EXP_VARTILDE);
9783 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9785 for (sp = *spp; sp; sp = sp->next)
9790 /* Reserve one extra spot at the front for shellexec. */
9791 nargv = stalloc(sizeof(char *) * (argc + 2));
9793 for (sp = arglist.list; sp; sp = sp->next) {
9794 TRACE(("evalcommand arg: %s\n", sp->text));
9795 *nargv++ = sp->text;
9800 if (iflag && funcnest == 0 && argc > 0)
9801 lastarg = nargv[-1];
9803 expredir(cmd->ncmd.redirect);
9804 redir_stop = pushredir(cmd->ncmd.redirect);
9806 if (BASH_XTRACEFD && xflag) {
9807 /* NB: bash closes fd == $BASH_XTRACEFD when it is changed.
9808 * we do not emulate this. We only use its value.
9810 const char *xtracefd = lookupvar("BASH_XTRACEFD");
9811 if (xtracefd && is_number(xtracefd))
9812 preverrout_fd = atoi(xtracefd);
9815 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9817 path = vpath.var_text;
9818 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9819 struct strlist **spp;
9822 spp = varlist.lastp;
9823 expandarg(argp, &varlist, EXP_VARTILDE);
9825 mklocal((*spp)->text);
9828 * Modify the command lookup path, if a PATH= assignment
9832 if (varcmp(p, path) == 0)
9836 /* Print the command if xflag is set. */
9838 const char *pfx = "";
9840 fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
9844 char *varval = sp->text;
9845 char *eq = strchrnul(varval, '=');
9848 fdprintf(preverrout_fd, "%s%.*s%s",
9850 (int)(eq - varval), varval,
9851 maybe_single_quote(eq)
9859 fdprintf(preverrout_fd, "%s%s",
9861 /* always quote if matches reserved word: */
9863 ? single_quote(sp->text)
9864 : maybe_single_quote(sp->text)
9869 safe_write(preverrout_fd, "\n", 1);
9875 /* Now locate the command. */
9877 int cmd_flag = DO_ERR;
9878 #if ENABLE_ASH_CMDCMD
9879 const char *oldpath = path + 5;
9883 find_command(argv[0], &cmdentry, cmd_flag, path);
9884 if (cmdentry.cmdtype == CMDUNKNOWN) {
9885 flush_stdout_stderr();
9890 /* implement bltin and command here */
9891 if (cmdentry.cmdtype != CMDBUILTIN)
9894 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9895 if (cmdentry.u.cmd == EXECCMD)
9897 #if ENABLE_ASH_CMDCMD
9898 if (cmdentry.u.cmd == COMMANDCMD) {
9900 nargv = parse_command_args(argv, &path);
9903 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9904 * nargv => "PROG". path is updated if -p.
9906 argc -= nargv - argv;
9908 cmd_flag |= DO_NOFUNC;
9917 exitstatus = status;
9919 /* We have a redirection error. */
9921 raise_exception(EXERROR);
9926 /* Execute the command. */
9927 switch (cmdentry.cmdtype) {
9930 #if ENABLE_FEATURE_SH_NOFORK
9931 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9932 * around run_nofork_applet() call.
9933 * (2) Should this check also be done in forkshell()?
9934 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9936 /* find_command() encodes applet_no as (-2 - applet_no) */
9937 int applet_no = (- cmdentry.u.index - 2);
9938 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9939 listsetvar(varlist.list, VEXPORT|VSTACK);
9941 * Run <applet>_main().
9942 * Signals (^C) can't interrupt here.
9943 * Otherwise we can mangle stdio or malloc internal state.
9944 * This makes applets which can run for a long time
9945 * and/or wait for user input ineligible for NOFORK:
9946 * for example, "yes" or "rm" (rm -i waits for input).
9949 status = run_nofork_applet(applet_no, argv);
9951 * Try enabling NOFORK for "yes" applet.
9952 * ^C _will_ stop it (write returns EINTR),
9953 * but this causes stdout FILE to be stuck
9954 * and needing clearerr(). What if other applets
9955 * also can get EINTRs? Do we need to switch
9956 * our signals to SA_RESTART?
9958 /*clearerr(stdout);*/
9963 /* Can we avoid forking? For example, very last command
9964 * in a script or a subshell does not need forking,
9965 * we can just exec it.
9967 if (!(flags & EV_EXIT) || may_have_traps) {
9968 /* No, forking off a child is necessary */
9971 jp = makejob(/*cmd,*/ 1);
9972 if (forkshell(jp, cmd, FORK_FG) != 0) {
9974 status = waitforjob(jp);
9976 TRACE(("forked child exited with %d\n", status));
9981 /* fall through to exec'ing external program */
9983 listsetvar(varlist.list, VEXPORT|VSTACK);
9984 shellexec(argv[0], argv, path, cmdentry.u.index);
9988 if (spclbltin > 0 || argc == 0) {
9990 if (cmd_is_exec && argc > 1)
9991 listsetvar(varlist.list, VEXPORT);
9994 /* Tight loop with builtins only:
9995 * "while kill -0 $child; do true; done"
9996 * will never exit even if $child died, unless we do this
9997 * to reap the zombie and make kill detect that it's gone: */
9998 dowait(DOWAIT_NONBLOCK, NULL);
10000 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
10001 if (exception_type == EXERROR && spclbltin <= 0) {
10006 longjmp(exception_handler->loc, 1);
10012 /* See above for the rationale */
10013 dowait(DOWAIT_NONBLOCK, NULL);
10014 if (evalfun(cmdentry.u.func, argc, argv, flags))
10017 status = exitstatus;
10022 if (cmd->ncmd.redirect)
10023 popredir(/*drop:*/ cmd_is_exec);
10024 unwindredir(redir_stop);
10025 unwindlocalvars(localvar_stop);
10027 /* dsl: I think this is intended to be used to support
10028 * '_' in 'vi' command mode during line editing...
10029 * However I implemented that within libedit itself.
10031 setvar0("_", lastarg);
10033 popstackmark(&smark);
10039 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
10041 char *volatile savecmdname;
10042 struct jmploc *volatile savehandler;
10043 struct jmploc jmploc;
10047 savecmdname = commandname;
10048 savehandler = exception_handler;
10049 i = setjmp(jmploc.loc);
10052 exception_handler = &jmploc;
10053 commandname = argv[0];
10055 optptr = NULL; /* initialize nextopt */
10056 if (cmd == EVALCMD)
10057 status = evalcmd(argc, argv, flags);
10059 status = (*cmd->builtin)(argc, argv);
10060 flush_stdout_stderr();
10061 status |= ferror(stdout);
10062 exitstatus = status;
10065 commandname = savecmdname;
10066 exception_handler = savehandler;
10072 goodname(const char *p)
10074 return endofname(p)[0] == '\0';
10079 * Search for a command. This is called before we fork so that the
10080 * location of the command will be available in the parent as well as
10081 * the child. The check for "goodname" is an overly conservative
10082 * check that the name will not be subject to expansion.
10085 prehash(union node *n)
10087 struct cmdentry entry;
10089 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
10090 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
10094 /* ============ Builtin commands
10096 * Builtin commands whose functions are closely tied to evaluation
10097 * are implemented here.
10101 * Handle break and continue commands. Break, continue, and return are
10102 * all handled by setting the evalskip flag. The evaluation routines
10103 * above all check this flag, and if it is set they start skipping
10104 * commands rather than executing them. The variable skipcount is
10105 * the number of loops to break/continue, or the number of function
10106 * levels to return. (The latter is always 1.) It should probably
10107 * be an error to break out of more loops than exist, but it isn't
10108 * in the standard shell so we don't make it one here.
10110 static int FAST_FUNC
10111 breakcmd(int argc UNUSED_PARAM, char **argv)
10113 int n = argv[1] ? number(argv[1]) : 1;
10116 ash_msg_and_raise_error(msg_illnum, argv[1]);
10120 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
10128 * This implements the input routines used by the parser.
10132 INPUT_PUSH_FILE = 1,
10133 INPUT_NOFILE_OK = 2,
10136 static smallint checkkwd;
10137 /* values of checkkwd variable */
10138 #define CHKALIAS 0x1
10141 #define CHKEOFMARK 0x8
10144 * Push a string back onto the input at this current parsefile level.
10145 * We handle aliases this way.
10147 #if !ENABLE_ASH_ALIAS
10148 #define pushstring(s, ap) pushstring(s)
10151 pushstring(char *s, struct alias *ap)
10153 struct strpush *sp;
10158 if (g_parsefile->strpush) {
10159 sp = ckzalloc(sizeof(*sp));
10160 sp->prev = g_parsefile->strpush;
10162 sp = &(g_parsefile->basestrpush);
10164 g_parsefile->strpush = sp;
10165 sp->prev_string = g_parsefile->next_to_pgetc;
10166 sp->prev_left_in_line = g_parsefile->left_in_line;
10167 sp->unget = g_parsefile->unget;
10168 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
10169 #if ENABLE_ASH_ALIAS
10172 ap->flag |= ALIASINUSE;
10176 g_parsefile->next_to_pgetc = s;
10177 g_parsefile->left_in_line = len;
10178 g_parsefile->unget = 0;
10185 struct strpush *sp = g_parsefile->strpush;
10188 #if ENABLE_ASH_ALIAS
10190 if (g_parsefile->next_to_pgetc[-1] == ' '
10191 || g_parsefile->next_to_pgetc[-1] == '\t'
10193 checkkwd |= CHKALIAS;
10195 if (sp->string != sp->ap->val) {
10198 sp->ap->flag &= ~ALIASINUSE;
10199 if (sp->ap->flag & ALIASDEAD) {
10200 unalias(sp->ap->name);
10204 g_parsefile->next_to_pgetc = sp->prev_string;
10205 g_parsefile->left_in_line = sp->prev_left_in_line;
10206 g_parsefile->unget = sp->unget;
10207 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
10208 g_parsefile->strpush = sp->prev;
10209 if (sp != &(g_parsefile->basestrpush))
10218 char *buf = g_parsefile->buf;
10220 g_parsefile->next_to_pgetc = buf;
10221 #if ENABLE_FEATURE_EDITING
10223 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
10224 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10226 # if ENABLE_ASH_IDLE_TIMEOUT
10229 const char *tmout_var = lookupvar("TMOUT");
10231 timeout = atoi(tmout_var) * 1000;
10236 line_input_state->timeout = timeout;
10238 # if ENABLE_FEATURE_TAB_COMPLETION
10239 line_input_state->path_lookup = pathval();
10241 reinit_unicode_for_ash();
10242 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ);
10244 /* ^C pressed, "convert" to SIGINT */
10245 write(STDOUT_FILENO, "^C", 2);
10246 if (trap[SIGINT]) {
10252 exitstatus = 128 + SIGINT;
10258 /* Ctrl+D pressed */
10261 # if ENABLE_ASH_IDLE_TIMEOUT
10262 else if (errno == EAGAIN && timeout > 0) {
10263 puts("\007timed out waiting for input: auto-logout");
10270 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10273 #if 0 /* disabled: nonblock_immune_read() handles this problem */
10275 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
10276 int flags = fcntl(0, F_GETFL);
10277 if (flags >= 0 && (flags & O_NONBLOCK)) {
10278 flags &= ~O_NONBLOCK;
10279 if (fcntl(0, F_SETFL, flags) >= 0) {
10280 out2str("sh: turning off NDELAY mode\n");
10291 * Refill the input buffer and return the next input character:
10293 * 1) If a string was pushed back on the input, pop it;
10294 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
10295 * or we are reading from a string so we can't refill the buffer,
10297 * 3) If there is more stuff in this buffer, use it else call read to fill it.
10298 * 4) Process input up to the next newline, deleting nul characters.
10300 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
10301 #define pgetc_debug(...) ((void)0)
10302 static int pgetc(void);
10309 if (g_parsefile->strpush) {
10310 #if ENABLE_ASH_ALIAS
10311 if (g_parsefile->left_in_line == -1
10312 && g_parsefile->strpush->ap
10313 && g_parsefile->next_to_pgetc[-1] != ' '
10314 && g_parsefile->next_to_pgetc[-1] != '\t'
10316 pgetc_debug("preadbuffer PEOA");
10323 /* on both branches above g_parsefile->left_in_line < 0.
10324 * "pgetc" needs refilling.
10327 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
10328 * pungetc() may increment it a few times.
10329 * Assuming it won't increment it to less than -90.
10331 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
10332 pgetc_debug("preadbuffer PEOF1");
10333 /* even in failure keep left_in_line and next_to_pgetc
10334 * in lock step, for correct multi-layer pungetc.
10335 * left_in_line was decremented before preadbuffer(),
10336 * must inc next_to_pgetc: */
10337 g_parsefile->next_to_pgetc++;
10341 more = g_parsefile->left_in_buffer;
10343 flush_stdout_stderr();
10347 /* don't try reading again */
10348 g_parsefile->left_in_line = -99;
10349 pgetc_debug("preadbuffer PEOF2");
10350 g_parsefile->next_to_pgetc++;
10355 /* Find out where's the end of line.
10356 * Set g_parsefile->left_in_line
10357 * and g_parsefile->left_in_buffer acordingly.
10358 * NUL chars are deleted.
10360 q = g_parsefile->next_to_pgetc;
10368 memmove(q, q + 1, more);
10372 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10378 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10379 if (g_parsefile->left_in_line < 0)
10384 g_parsefile->left_in_buffer = more;
10389 out2str(g_parsefile->next_to_pgetc);
10393 pgetc_debug("preadbuffer at %d:%p'%s'",
10394 g_parsefile->left_in_line,
10395 g_parsefile->next_to_pgetc,
10396 g_parsefile->next_to_pgetc);
10397 return (unsigned char)*g_parsefile->next_to_pgetc++;
10403 g_parsefile->linno++;
10404 setprompt_if(doprompt, 2);
10409 g_parsefile->linno++;
10410 needprompt = doprompt;
10418 pgetc_debug("pgetc at %d:%p'%s'",
10419 g_parsefile->left_in_line,
10420 g_parsefile->next_to_pgetc,
10421 g_parsefile->next_to_pgetc);
10422 if (g_parsefile->unget)
10423 return g_parsefile->lastc[--g_parsefile->unget];
10425 if (--g_parsefile->left_in_line >= 0)
10426 c = (unsigned char)*g_parsefile->next_to_pgetc++;
10430 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10431 g_parsefile->lastc[0] = c;
10436 #if ENABLE_ASH_ALIAS
10438 pgetc_without_PEOA(void)
10442 pgetc_debug("pgetc at %d:%p'%s'",
10443 g_parsefile->left_in_line,
10444 g_parsefile->next_to_pgetc,
10445 g_parsefile->next_to_pgetc);
10447 } while (c == PEOA);
10451 # define pgetc_without_PEOA() pgetc()
10455 * Undo a call to pgetc. Only two characters may be pushed back.
10456 * PEOF may be pushed back.
10461 g_parsefile->unget++;
10464 /* This one eats backslash+newline */
10470 while ((c = pgetc()) == '\\') {
10471 if (pgetc() != '\n') {
10483 * To handle the "." command, a stack of input files is used. Pushfile
10484 * adds a new entry to the stack and popfile restores the previous level.
10489 struct parsefile *pf;
10491 pf = ckzalloc(sizeof(*pf));
10492 pf->prev = g_parsefile;
10494 /*pf->strpush = NULL; - ckzalloc did it */
10495 /*pf->basestrpush.prev = NULL;*/
10503 struct parsefile *pf = g_parsefile;
10509 if (pf->pf_fd >= 0)
10512 while (pf->strpush)
10514 g_parsefile = pf->prev;
10520 * Return to top level.
10525 while (g_parsefile != &basepf)
10530 * Close the file(s) that the shell is reading commands from. Called
10531 * after a fork is done.
10537 if (g_parsefile->pf_fd > 0) {
10538 close(g_parsefile->pf_fd);
10539 g_parsefile->pf_fd = 0;
10544 * Like setinputfile, but takes an open file descriptor. Call this with
10548 setinputfd(int fd, int push)
10552 g_parsefile->buf = NULL;
10554 g_parsefile->pf_fd = fd;
10555 if (g_parsefile->buf == NULL)
10556 g_parsefile->buf = ckmalloc(IBUFSIZ);
10557 g_parsefile->left_in_buffer = 0;
10558 g_parsefile->left_in_line = 0;
10559 g_parsefile->linno = 1;
10563 * Set the input to take input from a file. If push is set, push the
10564 * old input onto the stack first.
10567 setinputfile(const char *fname, int flags)
10572 fd = open(fname, O_RDONLY);
10574 if (flags & INPUT_NOFILE_OK)
10577 ash_msg_and_raise_error("can't open '%s'", fname);
10582 close_on_exec_on(fd);
10583 setinputfd(fd, flags & INPUT_PUSH_FILE);
10590 * Like setinputfile, but takes input from a string.
10593 setinputstring(char *string)
10597 g_parsefile->next_to_pgetc = string;
10598 g_parsefile->left_in_line = strlen(string);
10599 g_parsefile->buf = NULL;
10600 g_parsefile->linno = 1;
10606 * Routines to check for mail.
10609 #if ENABLE_ASH_MAIL
10611 /* Hash of mtimes of mailboxes */
10612 static unsigned mailtime_hash;
10613 /* Set if MAIL or MAILPATH is changed. */
10614 static smallint mail_var_path_changed;
10617 * Print appropriate message(s) if mail has arrived.
10618 * If mail_var_path_changed is set,
10619 * then the value of MAIL has mail_var_path_changed,
10620 * so we just update the values.
10629 struct stackmark smark;
10632 setstackmark(&smark);
10633 mpath = mpathset() ? mpathval() : mailval();
10636 p = path_advance(&mpath, nullstr);
10641 for (q = p; *q; q++)
10647 q[-1] = '\0'; /* delete trailing '/' */
10648 if (stat(p, &statb) < 0) {
10651 /* Very simplistic "hash": just a sum of all mtimes */
10652 new_hash += (unsigned)statb.st_mtime;
10654 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10655 if (mailtime_hash != 0)
10656 out2str("you have mail\n");
10657 mailtime_hash = new_hash;
10659 mail_var_path_changed = 0;
10660 popstackmark(&smark);
10663 static void FAST_FUNC
10664 changemail(const char *val UNUSED_PARAM)
10666 mail_var_path_changed = 1;
10669 #endif /* ASH_MAIL */
10672 /* ============ ??? */
10675 * Set the shell parameters.
10678 setparam(char **argv)
10684 for (nparam = 0; argv[nparam]; nparam++)
10686 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10688 *ap++ = ckstrdup(*argv++);
10691 freeparam(&shellparam);
10692 shellparam.malloced = 1;
10693 shellparam.nparam = nparam;
10694 shellparam.p = newparam;
10695 #if ENABLE_ASH_GETOPTS
10696 shellparam.optind = 1;
10697 shellparam.optoff = -1;
10702 * Process shell options. The global variable argptr contains a pointer
10703 * to the argument list; we advance it past the options.
10705 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10706 * For a non-interactive shell, an error condition encountered
10707 * by a special built-in ... shall cause the shell to write a diagnostic message
10708 * to standard error and exit as shown in the following table:
10709 * Error Special Built-In
10711 * Utility syntax error (option or operand error) Shall exit
10713 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10714 * we see that bash does not do that (set "finishes" with error code 1 instead,
10715 * and shell continues), and people rely on this behavior!
10717 * set -o barfoo 2>/dev/null
10720 * Oh well. Let's mimic that.
10723 plus_minus_o(char *name, int val)
10728 for (i = 0; i < NOPTS; i++) {
10729 if (strcmp(name, optnames(i)) == 0) {
10734 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10737 for (i = 0; i < NOPTS; i++) {
10739 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10741 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10747 setoption(int flag, int val)
10751 for (i = 0; i < NOPTS; i++) {
10752 if (optletters(i) == flag) {
10757 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10761 options(int cmdline, int *login_sh)
10769 while ((p = *argptr) != NULL) {
10771 if (c != '-' && c != '+')
10774 val = 0; /* val = 0 if c == '+' */
10777 if (p[0] == '\0' || LONE_DASH(p)) {
10779 /* "-" means turn off -x and -v */
10782 /* "--" means reset params */
10783 else if (*argptr == NULL)
10786 break; /* "-" or "--" terminates options */
10789 /* first char was + or - */
10790 while ((c = *p++) != '\0') {
10791 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10792 if (c == 'c' && cmdline) {
10793 minusc = p; /* command is after shell args */
10794 } else if (c == 'o') {
10795 if (plus_minus_o(*argptr, val)) {
10796 /* it already printed err message */
10797 return 1; /* error */
10801 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10804 /* bash does not accept +-login, we also won't */
10805 } else if (cmdline && val && (c == '-')) { /* long options */
10806 if (strcmp(p, "login") == 0) {
10820 * The shift builtin command.
10822 static int FAST_FUNC
10823 shiftcmd(int argc UNUSED_PARAM, char **argv)
10830 n = number(argv[1]);
10831 if (n > shellparam.nparam)
10832 n = 0; /* bash compat, was = shellparam.nparam; */
10834 shellparam.nparam -= n;
10835 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10836 if (shellparam.malloced)
10839 ap2 = shellparam.p;
10840 while ((*ap2++ = *ap1++) != NULL)
10842 #if ENABLE_ASH_GETOPTS
10843 shellparam.optind = 1;
10844 shellparam.optoff = -1;
10851 * POSIX requires that 'set' (but not export or readonly) output the
10852 * variables in lexicographic order - by the locale's collating order (sigh).
10853 * Maybe we could keep them in an ordered balanced binary tree
10854 * instead of hashed lists.
10855 * For now just roll 'em through qsort for printing...
10858 showvars(const char *sep_prefix, int on, int off)
10861 char **ep, **epend;
10863 ep = listvars(on, off, &epend);
10864 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10866 sep = *sep_prefix ? " " : sep_prefix;
10868 for (; ep < epend; ep++) {
10872 p = strchrnul(*ep, '=');
10875 q = single_quote(++p);
10876 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10882 * The set command builtin.
10884 static int FAST_FUNC
10885 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10890 return showvars(nullstr, 0, VUNSET);
10893 retval = options(/*cmdline:*/ 0, NULL);
10894 if (retval == 0) { /* if no parse error... */
10896 if (*argptr != NULL) {
10904 #if ENABLE_ASH_RANDOM_SUPPORT
10905 static void FAST_FUNC
10906 change_random(const char *value)
10910 if (value == NULL) {
10911 /* "get", generate */
10912 t = next_random(&random_gen);
10913 /* set without recursion */
10914 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10915 vrandom.flags &= ~VNOFUNC;
10918 t = strtoul(value, NULL, 10);
10919 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10924 #if ENABLE_ASH_GETOPTS
10926 getopts(char *optstr, char *optvar, char **optfirst)
10933 int ind = shellparam.optind;
10934 int off = shellparam.optoff;
10938 shellparam.optind = -1;
10939 optnext = optfirst + ind - 1;
10941 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
10944 p = optnext[-1] + off;
10945 if (p == NULL || *p == '\0') {
10946 /* Current word is done, advance */
10948 if (p == NULL || *p != '-' || *++p == '\0') {
10955 if (LONE_DASH(p)) /* check for "--" */
10960 for (q = optstr; *q != c;) {
10962 if (optstr[0] == ':') {
10964 /*sbuf[1] = '\0'; - already is */
10965 setvar0("OPTARG", sbuf);
10967 fprintf(stderr, "Illegal option -%c\n", c);
10968 unsetvar("OPTARG");
10978 if (*p == '\0' && (p = *optnext) == NULL) {
10979 if (optstr[0] == ':') {
10981 /*sbuf[1] = '\0'; - already is */
10982 setvar0("OPTARG", sbuf);
10985 fprintf(stderr, "No arg for -%c option\n", c);
10986 unsetvar("OPTARG");
10994 setvar0("OPTARG", p);
10997 setvar0("OPTARG", nullstr);
10999 ind = optnext - optfirst + 1;
11000 setvar("OPTIND", itoa(ind), VNOFUNC);
11002 /*sbuf[1] = '\0'; - already is */
11003 setvar0(optvar, sbuf);
11005 shellparam.optoff = p ? p - *(optnext - 1) : -1;
11006 shellparam.optind = ind;
11012 * The getopts builtin. Shellparam.optnext points to the next argument
11013 * to be processed. Shellparam.optptr points to the next character to
11014 * be processed in the current argument. If shellparam.optnext is NULL,
11015 * then it's the first time getopts has been called.
11017 static int FAST_FUNC
11018 getoptscmd(int argc, char **argv)
11023 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
11025 optbase = shellparam.p;
11026 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
11027 shellparam.optind = 1;
11028 shellparam.optoff = -1;
11031 optbase = &argv[3];
11032 if ((unsigned)shellparam.optind > argc - 2) {
11033 shellparam.optind = 1;
11034 shellparam.optoff = -1;
11038 return getopts(argv[1], argv[2], optbase);
11040 #endif /* ASH_GETOPTS */
11043 /* ============ Shell parser */
11046 struct heredoc *next; /* next here document in list */
11047 union node *here; /* redirection node */
11048 char *eofmark; /* string indicating end of input */
11049 smallint striptabs; /* if set, strip leading tabs */
11052 static smallint tokpushback; /* last token pushed back */
11053 static smallint quoteflag; /* set if (part of) last token was quoted */
11054 static token_id_t lasttoken; /* last token read (integer id Txxx) */
11055 static struct heredoc *heredoclist; /* list of here documents to read */
11056 static char *wordtext; /* text of last word returned by readtoken */
11057 static struct nodelist *backquotelist;
11058 static union node *redirnode;
11059 static struct heredoc *heredoc;
11061 static const char *
11062 tokname(char *buf, int tok)
11065 return tokname_array[tok];
11066 sprintf(buf, "\"%s\"", tokname_array[tok]);
11070 /* raise_error_unexpected_syntax:
11071 * Called when an unexpected token is read during the parse. The argument
11072 * is the token that is expected, or -1 if more than one type of token can
11073 * occur at this point.
11075 static void raise_error_unexpected_syntax(int) NORETURN;
11077 raise_error_unexpected_syntax(int token)
11083 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
11085 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
11086 raise_error_syntax(msg);
11090 /* parsing is heavily cross-recursive, need these forward decls */
11091 static union node *andor(void);
11092 static union node *pipeline(void);
11093 static union node *parse_command(void);
11094 static void parseheredoc(void);
11095 static int peektoken(void);
11096 static int readtoken(void);
11098 static union node *
11101 union node *n1, *n2, *n3;
11106 switch (peektoken()) {
11114 if (!n1 && (nlflag & 1))
11120 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11121 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
11127 if (tok == TBACKGND) {
11128 if (n2->type == NPIPE) {
11129 n2->npipe.pipe_backgnd = 1;
11131 if (n2->type != NREDIR) {
11132 n3 = stzalloc(sizeof(struct nredir));
11134 /*n3->nredir.redirect = NULL; - stzalloc did it */
11137 n2->type = NBACKGND;
11143 n3 = stzalloc(sizeof(struct nbinary));
11145 n3->nbinary.ch1 = n1;
11146 n3->nbinary.ch2 = n2;
11159 raise_error_unexpected_syntax(-1);
11166 static union node *
11169 union node *n1, *n2, *n3;
11177 } else if (t == TOR) {
11183 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11185 n3 = stzalloc(sizeof(struct nbinary));
11187 n3->nbinary.ch1 = n1;
11188 n3->nbinary.ch2 = n2;
11193 static union node *
11196 union node *n1, *n2, *pipenode;
11197 struct nodelist *lp, *prev;
11201 TRACE(("pipeline: entered\n"));
11202 if (readtoken() == TNOT) {
11204 checkkwd = CHKKWD | CHKALIAS;
11207 n1 = parse_command();
11208 if (readtoken() == TPIPE) {
11209 pipenode = stzalloc(sizeof(struct npipe));
11210 pipenode->type = NPIPE;
11211 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
11212 lp = stzalloc(sizeof(struct nodelist));
11213 pipenode->npipe.cmdlist = lp;
11217 lp = stzalloc(sizeof(struct nodelist));
11218 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11219 lp->n = parse_command();
11221 } while (readtoken() == TPIPE);
11227 n2 = stzalloc(sizeof(struct nnot));
11235 static union node *
11240 n = stzalloc(sizeof(struct narg));
11242 /*n->narg.next = NULL; - stzalloc did it */
11243 n->narg.text = wordtext;
11244 n->narg.backquote = backquotelist;
11249 fixredir(union node *n, const char *text, int err)
11253 TRACE(("Fix redir %s %d\n", text, err));
11255 n->ndup.vname = NULL;
11257 fd = bb_strtou(text, NULL, 10);
11258 if (!errno && fd >= 0)
11259 n->ndup.dupfd = fd;
11260 else if (LONE_DASH(text))
11261 n->ndup.dupfd = -1;
11264 raise_error_syntax("bad fd number");
11265 n->ndup.vname = makename();
11272 union node *n = redirnode;
11274 if (n->type == NHERE)
11275 checkkwd = CHKEOFMARK;
11276 if (readtoken() != TWORD)
11277 raise_error_unexpected_syntax(-1);
11278 if (n->type == NHERE) {
11279 struct heredoc *here = heredoc;
11282 if (quoteflag == 0)
11284 TRACE(("Here document %d\n", n->type));
11285 rmescapes(wordtext, 0);
11286 here->eofmark = wordtext;
11288 if (heredoclist == NULL)
11289 heredoclist = here;
11291 for (p = heredoclist; p->next; p = p->next)
11295 } else if (n->type == NTOFD || n->type == NFROMFD) {
11296 fixredir(n, wordtext, 0);
11298 n->nfile.fname = makename();
11302 static union node *
11305 union node *args, **app;
11306 union node *n = NULL;
11307 union node *vars, **vpp;
11308 union node **rpp, *redir;
11311 smallint double_brackets_flag = 0;
11313 IF_BASH_FUNCTION(smallint function_flag = 0;)
11322 savecheckkwd = CHKALIAS;
11325 checkkwd = savecheckkwd;
11330 if (peektoken() != TWORD)
11331 raise_error_unexpected_syntax(TWORD);
11336 case TAND: /* "&&" */
11337 case TOR: /* "||" */
11338 if (!double_brackets_flag) {
11342 wordtext = (char *) (t == TAND ? "-a" : "-o");
11345 n = stzalloc(sizeof(struct narg));
11347 /*n->narg.next = NULL; - stzalloc did it */
11348 n->narg.text = wordtext;
11350 if (strcmp("[[", wordtext) == 0)
11351 double_brackets_flag = 1;
11352 else if (strcmp("]]", wordtext) == 0)
11353 double_brackets_flag = 0;
11355 n->narg.backquote = backquotelist;
11356 if (savecheckkwd && isassignment(wordtext)) {
11358 vpp = &n->narg.next;
11361 app = &n->narg.next;
11365 if (function_flag) {
11366 checkkwd = CHKNL | CHKKWD;
11367 switch (peektoken()) {
11379 if (strcmp("[[", wordtext) == 0)
11383 raise_error_unexpected_syntax(-1);
11389 *rpp = n = redirnode;
11390 rpp = &n->nfile.next;
11391 parsefname(); /* read name of redirection file */
11394 IF_BASH_FUNCTION(do_func:)
11395 if (args && app == &args->narg.next
11398 struct builtincmd *bcmd;
11401 /* We have a function */
11402 if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
11403 raise_error_unexpected_syntax(TRP);
11404 name = n->narg.text;
11405 if (!goodname(name)
11406 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11408 raise_error_syntax("bad function name");
11411 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11412 n->narg.next = parse_command();
11415 IF_BASH_FUNCTION(function_flag = 0;)
11426 n = stzalloc(sizeof(struct ncmd));
11428 n->ncmd.args = args;
11429 n->ncmd.assign = vars;
11430 n->ncmd.redirect = redir;
11434 static union node *
11435 parse_command(void)
11437 union node *n1, *n2;
11438 union node *ap, **app;
11439 union node *cp, **cpp;
11440 union node *redir, **rpp;
11447 switch (readtoken()) {
11449 raise_error_unexpected_syntax(-1);
11452 n1 = stzalloc(sizeof(struct nif));
11454 n1->nif.test = list(0);
11455 if (readtoken() != TTHEN)
11456 raise_error_unexpected_syntax(TTHEN);
11457 n1->nif.ifpart = list(0);
11459 while (readtoken() == TELIF) {
11460 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11461 n2 = n2->nif.elsepart;
11463 n2->nif.test = list(0);
11464 if (readtoken() != TTHEN)
11465 raise_error_unexpected_syntax(TTHEN);
11466 n2->nif.ifpart = list(0);
11468 if (lasttoken == TELSE)
11469 n2->nif.elsepart = list(0);
11471 n2->nif.elsepart = NULL;
11479 n1 = stzalloc(sizeof(struct nbinary));
11480 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11481 n1->nbinary.ch1 = list(0);
11484 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11485 got == TWORD ? wordtext : ""));
11486 raise_error_unexpected_syntax(TDO);
11488 n1->nbinary.ch2 = list(0);
11493 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11494 raise_error_syntax("bad for loop variable");
11495 n1 = stzalloc(sizeof(struct nfor));
11497 n1->nfor.var = wordtext;
11498 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11499 if (readtoken() == TIN) {
11501 while (readtoken() == TWORD) {
11502 n2 = stzalloc(sizeof(struct narg));
11504 /*n2->narg.next = NULL; - stzalloc did it */
11505 n2->narg.text = wordtext;
11506 n2->narg.backquote = backquotelist;
11508 app = &n2->narg.next;
11511 n1->nfor.args = ap;
11512 if (lasttoken != TNL && lasttoken != TSEMI)
11513 raise_error_unexpected_syntax(-1);
11515 n2 = stzalloc(sizeof(struct narg));
11517 /*n2->narg.next = NULL; - stzalloc did it */
11518 n2->narg.text = (char *)dolatstr;
11519 /*n2->narg.backquote = NULL;*/
11520 n1->nfor.args = n2;
11522 * Newline or semicolon here is optional (but note
11523 * that the original Bourne shell only allowed NL).
11525 if (lasttoken != TSEMI)
11528 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11529 if (readtoken() != TDO)
11530 raise_error_unexpected_syntax(TDO);
11531 n1->nfor.body = list(0);
11535 n1 = stzalloc(sizeof(struct ncase));
11537 if (readtoken() != TWORD)
11538 raise_error_unexpected_syntax(TWORD);
11539 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11541 /*n2->narg.next = NULL; - stzalloc did it */
11542 n2->narg.text = wordtext;
11543 n2->narg.backquote = backquotelist;
11544 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11545 if (readtoken() != TIN)
11546 raise_error_unexpected_syntax(TIN);
11547 cpp = &n1->ncase.cases;
11549 checkkwd = CHKNL | CHKKWD;
11551 while (t != TESAC) {
11552 if (lasttoken == TLP)
11554 *cpp = cp = stzalloc(sizeof(struct nclist));
11556 app = &cp->nclist.pattern;
11558 *app = ap = stzalloc(sizeof(struct narg));
11560 /*ap->narg.next = NULL; - stzalloc did it */
11561 ap->narg.text = wordtext;
11562 ap->narg.backquote = backquotelist;
11563 if (readtoken() != TPIPE)
11565 app = &ap->narg.next;
11568 //ap->narg.next = NULL;
11569 if (lasttoken != TRP)
11570 raise_error_unexpected_syntax(TRP);
11571 cp->nclist.body = list(2);
11573 cpp = &cp->nclist.next;
11575 checkkwd = CHKNL | CHKKWD;
11579 raise_error_unexpected_syntax(TENDCASE);
11586 n1 = stzalloc(sizeof(struct nredir));
11587 n1->type = NSUBSHELL;
11588 n1->nredir.n = list(0);
11589 /*n1->nredir.redirect = NULL; - stzalloc did it */
11596 IF_BASH_FUNCTION(case TFUNCTION:)
11600 return simplecmd();
11603 if (readtoken() != t)
11604 raise_error_unexpected_syntax(t);
11607 /* Now check for redirection which may follow command */
11608 checkkwd = CHKKWD | CHKALIAS;
11610 while (readtoken() == TREDIR) {
11611 *rpp = n2 = redirnode;
11612 rpp = &n2->nfile.next;
11618 if (n1->type != NSUBSHELL) {
11619 n2 = stzalloc(sizeof(struct nredir));
11624 n1->nredir.redirect = redir;
11629 #if BASH_DOLLAR_SQUOTE
11631 decode_dollar_squote(void)
11633 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11639 p = strchr(C_escapes, c);
11644 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11648 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11650 } else if (c == 'x') { /* \xHH */
11654 } while (isxdigit(c) && --cnt);
11656 if (cnt == 3) { /* \x but next char is "bad" */
11660 } else { /* simple seq like \\ or \t */
11665 c = bb_process_escape_sequence((void*)&p);
11666 } else { /* unrecognized "\z": print both chars unless ' or " */
11667 if (c != '\'' && c != '"') {
11669 c |= 0x100; /* "please encode \, then me" */
11676 /* Used by expandstr to get here-doc like behaviour. */
11677 #define FAKEEOFMARK ((char*)(uintptr_t)1)
11679 static ALWAYS_INLINE int
11680 realeofmark(const char *eofmark)
11682 return eofmark && eofmark != FAKEEOFMARK;
11686 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11687 * is not NULL, read a here document. In the latter case, eofmark is the
11688 * word which marks the end of the document and striptabs is true if
11689 * leading tabs should be stripped from the document. The argument c
11690 * is the first character of the input token or document.
11692 * Because C does not have internal subroutines, I have simulated them
11693 * using goto's to implement the subroutine linkage. The following macros
11694 * will run code that appears at the end of readtoken1.
11696 #define CHECKEND() {goto checkend; checkend_return:;}
11697 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11698 #define PARSESUB() {goto parsesub; parsesub_return:;}
11699 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11700 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11701 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11703 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11705 /* NB: syntax parameter fits into smallint */
11706 /* c parameter is an unsigned char or PEOF or PEOA */
11709 struct nodelist *bqlist;
11713 IF_FEATURE_SH_MATH(smallint prevsyntax;) /* syntax before arithmetic */
11714 smallint pssyntax; /* we are expanding a prompt string */
11715 int varnest; /* levels of variables expansion */
11716 IF_FEATURE_SH_MATH(int arinest;) /* levels of arithmetic expansion */
11717 IF_FEATURE_SH_MATH(int parenlevel;) /* levels of parens in arithmetic */
11718 int dqvarnest; /* levels of variables expansion within double quotes */
11720 IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
11722 startlinno = g_parsefile->linno;
11725 IF_FEATURE_SH_MATH(prevsyntax = 0;)
11726 #if ENABLE_ASH_EXPAND_PRMT
11727 pssyntax = (syntax == PSSYNTAX);
11731 pssyntax = 0; /* constant */
11733 dblquote = (syntax == DQSYNTAX);
11735 IF_FEATURE_SH_MATH(arinest = 0;)
11736 IF_FEATURE_SH_MATH(parenlevel = 0;)
11739 STARTSTACKSTR(out);
11741 /* For each line, until end of word */
11742 CHECKEND(); /* set c to PEOF if at end of here document */
11743 for (;;) { /* until end of line or end of word */
11744 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11745 switch (SIT(c, syntax)) {
11746 case CNL: /* '\n' */
11747 if (syntax == BASESYNTAX)
11748 goto endword; /* exit outer loop */
11752 goto loop; /* continue outer loop */
11757 #if BASH_DOLLAR_SQUOTE
11758 if (c == '\\' && bash_dollar_squote) {
11759 c = decode_dollar_squote();
11761 /* skip $'\000', $'\x00' (like bash) */
11765 /* Unknown escape. Encode as '\z' */
11766 c = (unsigned char)c;
11767 if (eofmark == NULL || dblquote)
11768 USTPUTC(CTLESC, out);
11769 USTPUTC('\\', out);
11773 if (eofmark == NULL || dblquote)
11774 USTPUTC(CTLESC, out);
11777 case CBACK: /* backslash */
11778 c = pgetc_without_PEOA();
11780 USTPUTC(CTLESC, out);
11781 USTPUTC('\\', out);
11783 } else if (c == '\n') {
11786 if (pssyntax && c == '$') {
11787 USTPUTC(CTLESC, out);
11788 USTPUTC('\\', out);
11790 /* Backslash is retained if we are in "str" and next char isn't special */
11795 && (c != '"' || eofmark != NULL)
11797 USTPUTC('\\', out);
11799 USTPUTC(CTLESC, out);
11807 if (eofmark == NULL) {
11808 USTPUTC(CTLQUOTEMARK, out);
11816 IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
11817 if (eofmark != NULL && varnest == 0) {
11820 if (dqvarnest == 0) {
11821 syntax = BASESYNTAX;
11828 case CVAR: /* '$' */
11829 PARSESUB(); /* parse substitution */
11831 case CENDVAR: /* '}' */
11834 if (dqvarnest > 0) {
11841 #if ENABLE_FEATURE_SH_MATH
11842 case CLP: /* '(' in arithmetic */
11846 case CRP: /* ')' in arithmetic */
11847 if (parenlevel > 0) {
11850 if (pgetc_eatbnl() == ')') {
11852 if (--arinest == 0) {
11853 syntax = prevsyntax;
11857 * unbalanced parens
11858 * (don't 2nd guess - no error)
11866 case CBQUOTE: /* '`' */
11870 goto endword; /* exit outer loop */
11874 if (varnest == 0) {
11875 #if BASH_REDIR_OUTPUT
11877 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11878 if (pgetc() == '>')
11879 c = 0x100 + '>'; /* flag &> */
11883 goto endword; /* exit outer loop */
11885 IF_ASH_ALIAS(if (c != PEOA))
11892 #if ENABLE_FEATURE_SH_MATH
11893 if (syntax == ARISYNTAX)
11894 raise_error_syntax("missing '))'");
11896 if (syntax != BASESYNTAX && eofmark == NULL)
11897 raise_error_syntax("unterminated quoted string");
11898 if (varnest != 0) {
11899 startlinno = g_parsefile->linno;
11901 raise_error_syntax("missing '}'");
11903 USTPUTC('\0', out);
11904 len = out - (char *)stackblock();
11905 out = stackblock();
11906 if (eofmark == NULL) {
11907 if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
11910 if (isdigit_str9(out)) {
11911 PARSEREDIR(); /* passed as params: out, c */
11912 lasttoken = TREDIR;
11915 /* else: non-number X seen, interpret it
11916 * as "NNNX>file" = "NNNX >file" */
11920 quoteflag = quotef;
11921 backquotelist = bqlist;
11922 grabstackblock(len);
11926 /* end of readtoken routine */
11929 * Check to see whether we are at the end of the here document. When this
11930 * is called, c is set to the first character of the next input line. If
11931 * we are at the end of the here document, this routine sets the c to PEOF.
11934 if (realeofmark(eofmark)) {
11938 #if ENABLE_ASH_ALIAS
11940 c = pgetc_without_PEOA();
11943 while (c == '\t') {
11944 c = pgetc_without_PEOA();
11948 markloc = out - (char *)stackblock();
11949 for (p = eofmark; STPUTC(c, out), *p; p++) {
11953 c = pgetc_without_PEOA();
11956 if (c == '\n' || c == PEOF) {
11958 g_parsefile->linno++;
11959 needprompt = doprompt;
11964 p = (char *)stackblock() + markloc + 1;
11965 len_here = out - p;
11968 len_here -= (c >= PEOF);
11974 str = alloca(len_here + 1);
11975 *(char *)mempcpy(str, p, len_here) = '\0';
11977 pushstring(str, NULL);
11982 STADJUST((char *)stackblock() + markloc - out, out);
11984 goto checkend_return;
11988 * Parse a redirection operator. The variable "out" points to a string
11989 * specifying the fd to be redirected. The variable "c" contains the
11990 * first character of the redirection operator.
11993 /* out is already checked to be a valid number or "" */
11994 int fd = (*out == '\0' ? -1 : atoi(out));
11997 np = stzalloc(sizeof(struct nfile));
12002 np->type = NAPPEND;
12004 np->type = NCLOBBER;
12007 /* it also can be NTO2 (>&file), but we can't figure it out yet */
12013 #if BASH_REDIR_OUTPUT
12014 else if (c == 0x100 + '>') { /* this flags &> redirection */
12016 pgetc(); /* this is '>', no need to check */
12020 else { /* c == '<' */
12021 /*np->nfile.fd = 0; - stzalloc did it */
12025 if (sizeof(struct nfile) != sizeof(struct nhere)) {
12026 np = stzalloc(sizeof(struct nhere));
12027 /*np->nfile.fd = 0; - stzalloc did it */
12030 heredoc = stzalloc(sizeof(struct heredoc));
12031 heredoc->here = np;
12034 heredoc->striptabs = 1;
12036 /*heredoc->striptabs = 0; - stzalloc did it */
12042 np->type = NFROMFD;
12046 np->type = NFROMTO;
12058 goto parseredir_return;
12062 * Parse a substitution. At this point, we have read the dollar sign
12063 * and nothing else.
12066 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
12067 * (assuming ascii char codes, as the original implementation did) */
12068 #define is_special(c) \
12069 (((unsigned)(c) - 33 < 32) \
12070 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
12072 unsigned char subtype;
12075 c = pgetc_eatbnl();
12076 if ((checkkwd & CHKEOFMARK)
12077 || c > 255 /* PEOA or PEOF */
12078 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
12080 #if BASH_DOLLAR_SQUOTE
12081 if (syntax != DQSYNTAX && c == '\'')
12082 bash_dollar_squote = 1;
12087 } else if (c == '(') {
12088 /* $(command) or $((arith)) */
12089 if (pgetc_eatbnl() == '(') {
12090 #if ENABLE_FEATURE_SH_MATH
12093 raise_error_syntax("support for $((arith)) is disabled");
12100 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
12101 USTPUTC(CTLVAR, out);
12102 typeloc = out - (char *)stackblock();
12104 subtype = VSNORMAL;
12106 c = pgetc_eatbnl();
12111 /* $[{[#]]NAME[}] */
12114 c = pgetc_eatbnl();
12115 } while (is_in_name(c));
12116 } else if (isdigit(c)) {
12117 /* $[{[#]]NUM[}] */
12120 c = pgetc_eatbnl();
12121 } while (isdigit(c));
12122 } else if (is_special(c)) {
12123 /* $[{[#]]<specialchar>[}] */
12126 c = pgetc_eatbnl();
12127 if (!subtype && cc == '#') {
12128 subtype = VSLENGTH;
12129 if (c == '_' || isalnum(c))
12132 c = pgetc_eatbnl();
12133 if (cc == '}' || c != '}') {
12144 if (c != '}' && subtype == VSLENGTH) {
12145 /* ${#VAR didn't end with } */
12149 if (subtype == 0) {
12150 static const char types[] ALIGN1 = "}-+?=";
12151 /* ${VAR...} but not $VAR or ${#VAR} */
12152 /* c == first char after VAR */
12155 c = pgetc_eatbnl();
12157 /* This check is only needed to not misinterpret
12158 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
12161 if (!strchr(types, c)) {
12162 subtype = VSSUBSTR;
12164 break; /* "goto badsub" is bigger (!) */
12170 const char *p = strchr(types, c);
12173 subtype |= p - types + VSNORMAL;
12179 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
12180 c = pgetc_eatbnl();
12186 #if BASH_PATTERN_SUBST
12188 /* ${v/[/]pattern/repl} */
12189 //TODO: encode pattern and repl separately.
12190 // Currently ${v/$var_with_slash/repl} is horribly broken
12191 subtype = VSREPLACE;
12192 c = pgetc_eatbnl();
12195 subtype++; /* VSREPLACEALL */
12203 ((unsigned char *)stackblock())[typeloc] = subtype;
12204 if (subtype != VSNORMAL) {
12211 goto parsesub_return;
12215 * Called to parse command substitutions. Newstyle is set if the command
12216 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
12217 * list of commands (passed by reference), and savelen is the number of
12218 * characters on the top of the stack which must be preserved.
12221 struct nodelist **nlpp;
12225 smallint saveprompt = 0;
12228 savelen = out - (char *)stackblock();
12231 * FIXME: this can allocate very large block on stack and SEGV.
12233 * echo "..<100kbytes>..`true` $(true) `true` ..."
12234 * allocates 100kb for every command subst. With about
12235 * a hundred command substitutions stack overflows.
12236 * With larger prepended string, SEGV happens sooner.
12238 str = alloca(savelen);
12239 memcpy(str, stackblock(), savelen);
12243 /* We must read until the closing backquote, giving special
12244 * treatment to some slashes, and then push the string and
12245 * reread it as input, interpreting it normally.
12251 STARTSTACKSTR(pout);
12255 setprompt_if(needprompt, 2);
12266 * If eating a newline, avoid putting
12267 * the newline into the new character
12268 * stream (via the STPUTC after the
12273 if (pc != '\\' && pc != '`' && pc != '$'
12274 && (!dblquote || pc != '"')
12276 STPUTC('\\', pout);
12278 if (pc <= 255 /* not PEOA or PEOF */) {
12284 IF_ASH_ALIAS(case PEOA:)
12285 startlinno = g_parsefile->linno;
12286 raise_error_syntax("EOF in backquote substitution");
12298 STPUTC('\0', pout);
12299 psavelen = pout - (char *)stackblock();
12300 if (psavelen > 0) {
12301 pstr = grabstackstr(pout);
12302 setinputstring(pstr);
12307 nlpp = &(*nlpp)->next;
12308 *nlpp = stzalloc(sizeof(**nlpp));
12309 /* (*nlpp)->next = NULL; - stzalloc did it */
12312 saveprompt = doprompt;
12319 doprompt = saveprompt;
12320 else if (readtoken() != TRP)
12321 raise_error_unexpected_syntax(TRP);
12326 * Start reading from old file again, ignoring any pushed back
12327 * tokens left from the backquote parsing
12332 while (stackblocksize() <= savelen)
12334 STARTSTACKSTR(out);
12336 memcpy(out, str, savelen);
12337 STADJUST(savelen, out);
12339 USTPUTC(CTLBACKQ, out);
12341 goto parsebackq_oldreturn;
12342 goto parsebackq_newreturn;
12345 #if ENABLE_FEATURE_SH_MATH
12347 * Parse an arithmetic expansion (indicate start of one and set state)
12350 if (++arinest == 1) {
12351 prevsyntax = syntax;
12352 syntax = ARISYNTAX;
12354 USTPUTC(CTLARI, out);
12355 goto parsearith_return;
12358 } /* end of readtoken */
12361 * Read the next input token.
12362 * If the token is a word, we set backquotelist to the list of cmds in
12363 * backquotes. We set quoteflag to true if any part of the word was
12365 * If the token is TREDIR, then we set redirnode to a structure containing
12367 * In all cases, the variable startlinno is set to the number of the line
12368 * on which the token starts.
12370 * [Change comment: here documents and internal procedures]
12371 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12372 * word parsing code into a separate routine. In this case, readtoken
12373 * doesn't need to have any internal procedures, but parseword does.
12374 * We could also make parseoperator in essence the main routine, and
12375 * have parseword (readtoken1?) handle both words and redirection.]
12377 #define NEW_xxreadtoken
12378 #ifdef NEW_xxreadtoken
12379 /* singles must be first! */
12380 static const char xxreadtoken_chars[7] ALIGN1 = {
12381 '\n', '(', ')', /* singles */
12382 '&', '|', ';', /* doubles */
12386 #define xxreadtoken_singles 3
12387 #define xxreadtoken_doubles 3
12389 static const char xxreadtoken_tokens[] ALIGN1 = {
12390 TNL, TLP, TRP, /* only single occurrence allowed */
12391 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12392 TEOF, /* corresponds to trailing nul */
12393 TAND, TOR, TENDCASE /* if double occurrence */
12405 setprompt_if(needprompt, 2);
12406 startlinno = g_parsefile->linno;
12407 for (;;) { /* until token or start of word found */
12409 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12413 while ((c = pgetc()) != '\n' && c != PEOF)
12416 } else if (c == '\\') {
12417 if (pgetc() != '\n') {
12419 break; /* return readtoken1(...) */
12425 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12431 p = strchr(xxreadtoken_chars, c);
12433 break; /* return readtoken1(...) */
12435 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12437 if (cc == c) { /* double occurrence? */
12438 p += xxreadtoken_doubles + 1;
12441 #if BASH_REDIR_OUTPUT
12442 if (c == '&' && cc == '>') /* &> */
12443 break; /* return readtoken1(...) */
12448 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12453 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12455 #else /* old xxreadtoken */
12456 #define RETURN(token) return lasttoken = token
12466 setprompt_if(needprompt, 2);
12467 startlinno = g_parsefile->linno;
12468 for (;;) { /* until token or start of word found */
12471 case ' ': case '\t':
12472 IF_ASH_ALIAS(case PEOA:)
12475 while ((c = pgetc()) != '\n' && c != PEOF)
12480 if (pgetc() == '\n') {
12492 if (pgetc() == '&')
12497 if (pgetc() == '|')
12502 if (pgetc() == ';')
12515 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12518 #endif /* old xxreadtoken */
12524 int kwd = checkkwd;
12526 smallint alreadyseen = tokpushback;
12529 #if ENABLE_ASH_ALIAS
12545 if (t != TWORD || quoteflag) {
12550 * check for keywords
12552 if (kwd & CHKKWD) {
12553 const char *const *pp;
12555 pp = findkwd(wordtext);
12557 lasttoken = t = pp - tokname_array;
12558 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12563 if (checkkwd & CHKALIAS) {
12564 #if ENABLE_ASH_ALIAS
12566 ap = lookupalias(wordtext, 1);
12569 pushstring(ap->val, ap);
12579 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12581 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12597 * Read and parse a command. Returns NODE_EOF on end of file.
12598 * (NULL is a valid parse tree indicating a blank line.)
12600 static union node *
12601 parsecmd(int interact)
12606 doprompt = interact;
12607 setprompt_if(doprompt, doprompt);
12613 * Input any here documents.
12618 struct heredoc *here;
12621 here = heredoclist;
12622 heredoclist = NULL;
12625 setprompt_if(needprompt, 2);
12626 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12627 here->eofmark, here->striptabs);
12628 n = stzalloc(sizeof(struct narg));
12629 n->narg.type = NARG;
12630 /*n->narg.next = NULL; - stzalloc did it */
12631 n->narg.text = wordtext;
12632 n->narg.backquote = backquotelist;
12633 here->here->nhere.doc = n;
12639 static const char *
12640 expandstr(const char *ps, int syntax_type)
12645 /* XXX Fix (char *) cast. */
12646 setinputstring((char *)ps);
12648 saveprompt = doprompt;
12650 readtoken1(pgetc(), syntax_type, FAKEEOFMARK, 0);
12651 doprompt = saveprompt;
12655 n.narg.type = NARG;
12656 n.narg.next = NULL;
12657 n.narg.text = wordtext;
12658 n.narg.backquote = backquotelist;
12660 expandarg(&n, NULL, EXP_QUOTED);
12661 return stackblock();
12667 return tokpushback && lasttoken == TEOF;
12671 * Execute a command or commands contained in a string.
12674 evalstring(char *s, int flags)
12676 struct jmploc *volatile savehandler;
12677 struct jmploc jmploc;
12681 struct stackmark smark;
12686 setstackmark(&smark);
12689 /* On exception inside execution loop, we must popfile().
12690 * Try interactively:
12692 * command eval "a=b" # throws "is read only" error
12693 * "command BLTIN" is not supposed to abort (even in non-interactive use).
12694 * But if we skip popfile(), we hit EOF in eval's string, and exit.
12696 savehandler = exception_handler;
12697 ex = setjmp(jmploc.loc);
12700 exception_handler = &jmploc;
12702 while ((n = parsecmd(0)) != NODE_EOF) {
12705 i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
12708 popstackmark(&smark);
12713 popstackmark(&smark);
12717 exception_handler = savehandler;
12719 longjmp(exception_handler->loc, ex);
12725 * The eval command.
12727 static int FAST_FUNC
12728 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12737 STARTSTACKSTR(concat);
12739 concat = stack_putstr(p, concat);
12743 STPUTC(' ', concat);
12745 STPUTC('\0', concat);
12746 p = grabstackstr(concat);
12748 return evalstring(p, flags & EV_TESTED);
12754 * Read and execute commands.
12755 * "Top" is nonzero for the top level command loop;
12756 * it turns on prompting if the shell is interactive.
12762 struct stackmark smark;
12767 TRACE(("cmdloop(%d) called\n", top));
12771 setstackmark(&smark);
12774 showjobs(SHOW_CHANGED|SHOW_STDERR);
12777 if (iflag && top) {
12781 n = parsecmd(inter);
12783 if (DEBUG > 2 && debug && (n != NODE_EOF))
12786 if (n == NODE_EOF) {
12787 if (!top || numeof >= 50)
12789 if (!stoppedjobs()) {
12792 out2str("\nUse \"exit\" to leave shell.\n");
12795 } else if (nflag == 0) {
12798 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12801 i = evaltree(n, 0);
12805 popstackmark(&smark);
12809 evalskip &= ~SKIPFUNC;
12817 * Take commands from a file. To be compatible we should do a path
12818 * search for the file, which is necessary to find sub-commands.
12821 find_dot_file(char *name)
12824 const char *path = pathval();
12827 /* don't try this for absolute or relative paths */
12828 if (strchr(name, '/'))
12831 while ((fullname = path_advance(&path, name)) != NULL) {
12832 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12834 * Don't bother freeing here, since it will
12835 * be freed by the caller.
12839 if (fullname != name)
12840 stunalloc(fullname);
12843 /* not found in the PATH */
12844 ash_msg_and_raise_error("%s: not found", name);
12848 static int FAST_FUNC
12849 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12851 /* "false; . empty_file; echo $?" should print 0, not 1: */
12855 char *args_need_save;
12856 volatile struct shparam saveparam;
12859 // struct strlist *sp;
12860 // for (sp = cmdenviron; sp; sp = sp->next)
12861 // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12863 nextopt(nullstr); /* handle possible "--" */
12867 /* bash says: "bash: .: filename argument required" */
12868 return 2; /* bash compat */
12871 /* This aborts if file isn't found, which is POSIXly correct.
12872 * bash returns exitcode 1 instead.
12874 fullname = find_dot_file(argv[0]);
12876 args_need_save = argv[0];
12877 if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
12879 saveparam = shellparam;
12880 shellparam.malloced = 0;
12884 shellparam.nparam = argc;
12885 shellparam.p = argv;
12888 /* This aborts if file can't be opened, which is POSIXly correct.
12889 * bash returns exitcode 1 instead.
12891 setinputfile(fullname, INPUT_PUSH_FILE);
12892 commandname = fullname;
12893 status = cmdloop(0);
12896 if (args_need_save) {
12897 freeparam(&shellparam);
12898 shellparam = saveparam;
12904 static int FAST_FUNC
12905 exitcmd(int argc UNUSED_PARAM, char **argv)
12910 exitstatus = number(argv[1]);
12911 raise_exception(EXEXIT);
12916 * Read a file containing shell functions.
12919 readcmdfile(char *name)
12921 setinputfile(name, INPUT_PUSH_FILE);
12927 /* ============ find_command inplementation */
12930 * Resolve a command name. If you change this routine, you may have to
12931 * change the shellexec routine as well.
12934 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12936 struct tblentry *cmdp;
12943 struct builtincmd *bcmd;
12945 /* If name contains a slash, don't use PATH or hash table */
12946 if (strchr(name, '/') != NULL) {
12947 entry->u.index = -1;
12948 if (act & DO_ABS) {
12949 while (stat(name, &statb) < 0) {
12951 if (errno == EINTR)
12954 entry->cmdtype = CMDUNKNOWN;
12958 entry->cmdtype = CMDNORMAL;
12962 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12964 updatetbl = (path == pathval());
12967 if (strstr(path, "%builtin") != NULL)
12968 act |= DO_ALTBLTIN;
12971 /* If name is in the table, check answer will be ok */
12972 cmdp = cmdlookup(name, 0);
12973 if (cmdp != NULL) {
12976 switch (cmdp->cmdtype) {
12994 } else if (cmdp->rehash == 0)
12995 /* if not invalidated by cd, we're done */
12999 /* If %builtin not in path, check for builtin next */
13000 bcmd = find_builtin(name);
13002 if (IS_BUILTIN_REGULAR(bcmd))
13003 goto builtin_success;
13004 if (act & DO_ALTPATH) {
13005 if (!(act & DO_ALTBLTIN))
13006 goto builtin_success;
13007 } else if (builtinloc <= 0) {
13008 goto builtin_success;
13012 #if ENABLE_FEATURE_SH_STANDALONE
13014 int applet_no = find_applet_by_name(name);
13015 if (applet_no >= 0) {
13016 entry->cmdtype = CMDNORMAL;
13017 entry->u.index = -2 - applet_no;
13023 /* We have to search path. */
13024 prev = -1; /* where to start */
13025 if (cmdp && cmdp->rehash) { /* doing a rehash */
13026 if (cmdp->cmdtype == CMDBUILTIN)
13029 prev = cmdp->param.index;
13035 while ((fullname = path_advance(&path, name)) != NULL) {
13036 stunalloc(fullname);
13037 /* NB: code below will still use fullname
13038 * despite it being "unallocated" */
13041 if (prefix(pathopt, "builtin")) {
13043 goto builtin_success;
13046 if ((act & DO_NOFUNC)
13047 || !prefix(pathopt, "func")
13048 ) { /* ignore unimplemented options */
13052 /* if rehash, don't redo absolute path names */
13053 if (fullname[0] == '/' && idx <= prev) {
13056 TRACE(("searchexec \"%s\": no change\n", name));
13059 while (stat(fullname, &statb) < 0) {
13061 if (errno == EINTR)
13064 if (errno != ENOENT && errno != ENOTDIR)
13068 e = EACCES; /* if we fail, this will be the error */
13069 if (!S_ISREG(statb.st_mode))
13071 if (pathopt) { /* this is a %func directory */
13072 stalloc(strlen(fullname) + 1);
13073 /* NB: stalloc will return space pointed by fullname
13074 * (because we don't have any intervening allocations
13075 * between stunalloc above and this stalloc) */
13076 readcmdfile(fullname);
13077 cmdp = cmdlookup(name, 0);
13078 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
13079 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
13080 stunalloc(fullname);
13083 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
13085 entry->cmdtype = CMDNORMAL;
13086 entry->u.index = idx;
13090 cmdp = cmdlookup(name, 1);
13091 cmdp->cmdtype = CMDNORMAL;
13092 cmdp->param.index = idx;
13097 /* We failed. If there was an entry for this command, delete it */
13098 if (cmdp && updatetbl)
13099 delete_cmd_entry();
13101 ash_msg("%s: %s", name, errmsg(e, "not found"));
13102 entry->cmdtype = CMDUNKNOWN;
13107 entry->cmdtype = CMDBUILTIN;
13108 entry->u.cmd = bcmd;
13112 cmdp = cmdlookup(name, 1);
13113 cmdp->cmdtype = CMDBUILTIN;
13114 cmdp->param.cmd = bcmd;
13118 entry->cmdtype = cmdp->cmdtype;
13119 entry->u = cmdp->param;
13124 * The trap builtin.
13126 static int FAST_FUNC
13127 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13131 int signo, exitcode;
13136 for (signo = 0; signo < NSIG; signo++) {
13137 char *tr = trap_ptr[signo];
13139 /* note: bash adds "SIG", but only if invoked
13140 * as "bash". If called as "sh", or if set -o posix,
13141 * then it prints short signal names.
13142 * We are printing short names: */
13143 out1fmt("trap -- %s %s\n",
13145 get_signame(signo));
13146 /* trap_ptr != trap only if we are in special-cased `trap` code.
13147 * In this case, we will exit very soon, no need to free(). */
13148 /* if (trap_ptr != trap && tp[0]) */
13153 if (trap_ptr != trap) {
13161 /* Why the second check?
13162 * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
13163 * In this case, NUM is signal no, not an action.
13166 if (ap[1] && !is_number(ap[0]))
13171 signo = get_signum(*ap);
13173 /* Mimic bash message exactly */
13174 ash_msg("%s: invalid signal specification", *ap);
13180 if (LONE_DASH(action))
13183 if (action[0]) /* not NULL and not "" and not "-" */
13184 may_have_traps = 1;
13185 action = ckstrdup(action);
13189 trap[signo] = action;
13200 /* ============ Builtins */
13202 #if ENABLE_ASH_HELP
13203 static int FAST_FUNC
13204 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13210 "Built-in commands:\n"
13211 "------------------\n");
13212 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
13213 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
13214 builtintab[i].name + 1);
13220 # if ENABLE_FEATURE_SH_STANDALONE
13222 const char *a = applet_names;
13224 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
13229 while (*a++ != '\0')
13234 newline_and_flush(stdout);
13235 return EXIT_SUCCESS;
13240 static int FAST_FUNC
13241 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13243 show_history(line_input_state);
13244 return EXIT_SUCCESS;
13249 * The export and readonly commands.
13251 static int FAST_FUNC
13252 exportcmd(int argc UNUSED_PARAM, char **argv)
13262 /* "readonly" in bash accepts, but ignores -n.
13263 * We do the same: it saves a conditional in nextopt's param.
13266 while ((opt = nextopt("np")) != '\0') {
13268 flag_off = VEXPORT;
13271 if (argv[0][0] == 'r') {
13273 flag_off = 0; /* readonly ignores -n */
13275 flag_off = ~flag_off;
13277 /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
13283 p = strchr(name, '=');
13287 vp = *findvar(hashvar(name), name);
13289 vp->flags = ((vp->flags | flag) & flag_off);
13293 setvar(name, p, (flag & flag_off));
13294 } while ((name = *++aptr) != NULL);
13299 /* No arguments. Show the list of exported or readonly vars.
13302 showvars(argv[0], flag, 0);
13307 * Delete a function if it exists.
13310 unsetfunc(const char *name)
13312 struct tblentry *cmdp;
13314 cmdp = cmdlookup(name, 0);
13315 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
13316 delete_cmd_entry();
13320 * The unset builtin command. We unset the function before we unset the
13321 * variable to allow a function to be unset when there is a readonly variable
13322 * with the same name.
13324 static int FAST_FUNC
13325 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13331 while ((i = nextopt("vf")) != 0) {
13335 for (ap = argptr; *ap; ap++) {
13346 static const unsigned char timescmd_str[] ALIGN1 = {
13347 ' ', offsetof(struct tms, tms_utime),
13348 '\n', offsetof(struct tms, tms_stime),
13349 ' ', offsetof(struct tms, tms_cutime),
13350 '\n', offsetof(struct tms, tms_cstime),
13353 static int FAST_FUNC
13354 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13357 const unsigned char *p;
13360 clk_tck = bb_clk_tck();
13365 unsigned sec, frac;
13367 t = *(clock_t *)(((char *) &buf) + p[1]);
13369 frac = t % clk_tck;
13370 out1fmt("%um%u.%03us%c",
13371 sec / 60, sec % 60,
13372 (frac * 1000) / clk_tck,
13380 #if ENABLE_FEATURE_SH_MATH
13382 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13383 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13385 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13387 static int FAST_FUNC
13388 letcmd(int argc UNUSED_PARAM, char **argv)
13394 ash_msg_and_raise_error("expression expected");
13396 i = ash_arith(*argv);
13404 * The read builtin. Options:
13405 * -r Do not interpret '\' specially
13406 * -s Turn off echo (tty only)
13407 * -n NCHARS Read NCHARS max
13408 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13409 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13410 * -u FD Read from given FD instead of fd 0
13411 * -d DELIM End on DELIM char, not newline
13412 * This uses unbuffered input, which may be avoidable in some cases.
13413 * TODO: bash also has:
13414 * -a ARRAY Read into array[0],[1],etc
13415 * -e Use line editing (tty only)
13417 static int FAST_FUNC
13418 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13420 char *opt_n = NULL;
13421 char *opt_p = NULL;
13422 char *opt_t = NULL;
13423 char *opt_u = NULL;
13424 char *opt_d = NULL; /* optimized out if !BASH */
13425 int read_flags = 0;
13429 while ((i = nextopt("p:u:rt:n:sd:")) != '\0') {
13438 read_flags |= BUILTIN_READ_SILENT;
13444 read_flags |= BUILTIN_READ_RAW;
13459 /* "read -s" needs to save/restore termios, can't allow ^C
13460 * to jump out of it.
13464 r = shell_builtin_read(setvar0,
13466 bltinlookup("IFS"), /* can be NULL */
13476 if ((uintptr_t)r == 1 && errno == EINTR) {
13477 /* To get SIGCHLD: sleep 1 & read x; echo $x
13478 * Correct behavior is to not exit "read"
13480 if (pending_sig == 0)
13484 if ((uintptr_t)r > 1)
13485 ash_msg_and_raise_error(r);
13487 return (uintptr_t)r;
13490 static int FAST_FUNC
13491 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13493 static const char permuser[3] ALIGN1 = "ogu";
13496 int symbolic_mode = 0;
13498 while (nextopt("S") != '\0') {
13507 if (*argptr == NULL) {
13508 if (symbolic_mode) {
13509 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13516 *p++ = permuser[i];
13518 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13519 if (!(mask & 0400)) *p++ = 'r';
13520 if (!(mask & 0200)) *p++ = 'w';
13521 if (!(mask & 0100)) *p++ = 'x';
13529 out1fmt("%04o\n", mask);
13532 char *modestr = *argptr;
13533 /* numeric umasks are taken as-is */
13534 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13535 if (!isdigit(modestr[0]))
13537 mask = bb_parse_mode(modestr, mask);
13538 if ((unsigned)mask > 0777) {
13539 ash_msg_and_raise_error("illegal mode: %s", modestr);
13541 if (!isdigit(modestr[0]))
13548 static int FAST_FUNC
13549 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13551 return shell_builtin_ulimit(argv);
13554 /* ============ main() and helpers */
13557 * Called to exit the shell.
13566 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13567 save_history(line_input_state);
13569 status = exitstatus;
13570 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13571 if (setjmp(loc.loc)) {
13572 if (exception_type == EXEXIT)
13573 status = exitstatus;
13576 exception_handler = &loc;
13582 /*free(p); - we'll exit soon */
13585 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13586 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13589 flush_stdout_stderr();
13594 /* Don't inline: conserve stack of caller from having our locals too */
13595 static NOINLINE void
13598 /* we will never free this */
13599 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13601 sigmode[SIGCHLD - 1] = S_DFL; /* ensure we install handler even if it is SIG_IGNed */
13602 setsignal(SIGCHLD);
13604 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13605 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13607 signal(SIGHUP, SIG_DFL);
13614 for (envp = environ; envp && *envp; envp++) {
13615 p = endofname(*envp);
13616 if (p != *envp && *p == '=') {
13617 setvareq(*envp, VEXPORT|VTEXTFIXED);
13621 setvareq((char*)defoptindvar, VTEXTFIXED);
13623 setvar0("PPID", utoa(getppid()));
13625 p = lookupvar("SHLVL");
13626 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13628 #if BASH_HOSTNAME_VAR
13629 if (!lookupvar("HOSTNAME")) {
13630 struct utsname uts;
13632 setvar0("HOSTNAME", uts.nodename);
13635 p = lookupvar("PWD");
13637 struct stat st1, st2;
13638 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13639 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13649 //usage:#define ash_trivial_usage
13650 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13651 //usage:#define ash_full_usage "\n\n"
13652 //usage: "Unix shell interpreter"
13655 * Process the shell command line arguments.
13658 procargs(char **argv)
13661 const char *xminusc;
13666 login_sh = xargv[0] && xargv[0][0] == '-';
13668 /* if (xargv[0]) - mmm, this is always true! */
13670 for (i = 0; i < NOPTS; i++)
13673 if (options(/*cmdline:*/ 1, &login_sh)) {
13674 /* it already printed err message */
13675 raise_exception(EXERROR);
13679 if (*xargv == NULL) {
13681 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13684 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13688 for (i = 0; i < NOPTS; i++)
13689 if (optlist[i] == 2)
13694 /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
13699 } else if (!sflag) {
13700 setinputfile(*xargv, 0);
13703 commandname = arg0;
13706 shellparam.p = xargv;
13707 #if ENABLE_ASH_GETOPTS
13708 shellparam.optind = 1;
13709 shellparam.optoff = -1;
13711 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13713 shellparam.nparam++;
13722 * Read /etc/profile, ~/.profile, $ENV.
13725 read_profile(const char *name)
13727 name = expandstr(name, DQSYNTAX);
13728 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13735 * This routine is called when an error or an interrupt occurs in an
13736 * interactive shell and control is returned to the main command loop.
13737 * (In dash, this function is auto-generated by build machinery).
13746 /* from expand.c: */
13749 /* from input.c: */
13750 g_parsefile->left_in_buffer = 0;
13751 g_parsefile->left_in_line = 0; /* clear input buffer */
13754 /* from redir.c: */
13758 unwindlocalvars(NULL);
13762 static short profile_buf[16384];
13763 extern int etext();
13767 * Main routine. We initialize things, parse the arguments, execute
13768 * profiles if we're a login shell, and then call cmdloop to execute
13769 * commands. The setjmp call sets up the location to jump to when an
13770 * exception occurs. When an exception occurs the variable "state"
13771 * is used to figure out how far we had gotten.
13773 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13774 int ash_main(int argc UNUSED_PARAM, char **argv)
13776 volatile smallint state;
13777 struct jmploc jmploc;
13778 struct stackmark smark;
13781 /* Initialize global data */
13785 #if ENABLE_ASH_ALIAS
13791 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13794 #if ENABLE_FEATURE_EDITING
13795 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13798 if (setjmp(jmploc.loc)) {
13804 e = exception_type;
13806 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13810 newline_and_flush(stderr);
13813 popstackmark(&smark);
13814 FORCE_INT_ON; /* enable interrupts */
13823 exception_handler = &jmploc;
13824 rootpid = getpid();
13827 setstackmark(&smark);
13828 login_sh = procargs(argv);
13830 TRACE(("Shell args: "));
13831 trace_puts_args(argv);
13838 read_profile("/etc/profile");
13841 hp = lookupvar("HOME");
13843 read_profile("$HOME/.profile");
13849 getuid() == geteuid() && getgid() == getegid() &&
13853 const char *shinit = lookupvar("ENV");
13854 if (shinit != NULL && *shinit != '\0')
13855 read_profile(shinit);
13857 popstackmark(&smark);
13861 /* evalstring pushes parsefile stack.
13862 * Ensure we don't falsely claim that 0 (stdin)
13863 * is one of stacked source fds.
13864 * Testcase: ash -c 'exec 1>&0' must not complain. */
13865 // if (!sflag) g_parsefile->pf_fd = -1;
13866 // ^^ not necessary since now we special-case fd 0
13867 // in save_fd_on_redirect()
13868 evalstring(minusc, sflag ? 0 : EV_EXIT);
13871 if (sflag || minusc == NULL) {
13872 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13874 const char *hp = lookupvar("HISTFILE");
13876 hp = lookupvar("HOME");
13879 hp = concat_path_file(hp, ".ash_history");
13880 setvar0("HISTFILE", hp);
13883 hp = lookupvar("HISTFILE");
13887 line_input_state->hist_file = hp;
13888 # if ENABLE_FEATURE_SH_HISTFILESIZE
13889 hp = lookupvar("HISTFILESIZE");
13890 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13894 state4: /* XXX ??? - why isn't this before the "if" statement */
13902 extern void _mcleanup(void);
13906 TRACE(("End of main reached\n"));
13913 * Copyright (c) 1989, 1991, 1993, 1994
13914 * The Regents of the University of California. All rights reserved.
13916 * This code is derived from software contributed to Berkeley by
13917 * Kenneth Almquist.
13919 * Redistribution and use in source and binary forms, with or without
13920 * modification, are permitted provided that the following conditions
13922 * 1. Redistributions of source code must retain the above copyright
13923 * notice, this list of conditions and the following disclaimer.
13924 * 2. Redistributions in binary form must reproduce the above copyright
13925 * notice, this list of conditions and the following disclaimer in the
13926 * documentation and/or other materials provided with the distribution.
13927 * 3. Neither the name of the University nor the names of its contributors
13928 * may be used to endorse or promote products derived from this software
13929 * without specific prior written permission.
13931 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
13932 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13933 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13934 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13935 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13936 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13937 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13938 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13939 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13940 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF