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 * The parsefile structure pointed to by the global variable parsefile
1234 * contains information about the current file being read.
1237 struct parsefile *prev; /* preceding file on stack */
1238 int linno; /* current line */
1239 int pf_fd; /* file descriptor (or -1 if string) */
1240 int left_in_line; /* number of chars left in this line */
1241 int left_in_buffer; /* number of chars left in this buffer past the line */
1242 char *next_to_pgetc; /* next char in buffer */
1243 char *buf; /* input buffer */
1244 struct strpush *strpush; /* for pushing strings at this level */
1245 struct strpush basestrpush; /* so pushing one is fast */
1247 /* Remember last two characters for pungetc. */
1250 /* Number of outstanding calls to pungetc. */
1254 static struct parsefile basepf; /* top level input file */
1255 static struct parsefile *g_parsefile = &basepf; /* current input file */
1256 static int startlinno; /* line # where last token started */
1257 static char *commandname; /* currently executing command */
1260 /* ============ Message printing */
1263 ash_vmsg(const char *msg, va_list ap)
1265 fprintf(stderr, "%s: ", arg0);
1267 if (strcmp(arg0, commandname))
1268 fprintf(stderr, "%s: ", commandname);
1269 if (!iflag || g_parsefile->pf_fd > 0)
1270 fprintf(stderr, "line %d: ", startlinno);
1272 vfprintf(stderr, msg, ap);
1273 newline_and_flush(stderr);
1277 * Exverror is called to raise the error exception. If the second argument
1278 * is not NULL then error prints an error message using printf style
1279 * formatting. It then raises the error exception.
1281 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1283 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1287 TRACE(("ash_vmsg_and_raise(%d):", cond));
1290 TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
1295 flush_stdout_stderr();
1296 raise_exception(cond);
1300 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1302 ash_msg_and_raise_error(const char *msg, ...)
1309 ash_vmsg_and_raise(EXERROR, msg, ap);
1315 * 'fmt' must be a string literal.
1317 #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": "STRERROR_FMT, ##__VA_ARGS__ STRERROR_ERRNO)
1319 static void raise_error_syntax(const char *) NORETURN;
1321 raise_error_syntax(const char *msg)
1323 ash_msg_and_raise_error("syntax error: %s", msg);
1327 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1329 ash_msg_and_raise(int cond, const char *msg, ...)
1334 ash_vmsg_and_raise(cond, msg, ap);
1340 * error/warning routines for external builtins
1343 ash_msg(const char *fmt, ...)
1353 * Return a string describing an error. The returned string may be a
1354 * pointer to a static buffer that will be overwritten on the next call.
1355 * Action describes the operation that got the error.
1358 errmsg(int e, const char *em)
1360 if (e == ENOENT || e == ENOTDIR) {
1367 /* ============ Memory allocation */
1370 /* I consider these wrappers nearly useless:
1371 * ok, they return you to nearest exception handler, but
1372 * how much memory do you leak in the process, making
1373 * memory starvation worse?
1376 ckrealloc(void * p, size_t nbytes)
1378 p = realloc(p, nbytes);
1380 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1385 ckmalloc(size_t nbytes)
1387 return ckrealloc(NULL, nbytes);
1391 ckzalloc(size_t nbytes)
1393 return memset(ckmalloc(nbytes), 0, nbytes);
1397 ckstrdup(const char *s)
1399 char *p = strdup(s);
1401 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1405 /* Using bbox equivalents. They exit if out of memory */
1406 # define ckrealloc xrealloc
1407 # define ckmalloc xmalloc
1408 # define ckzalloc xzalloc
1409 # define ckstrdup xstrdup
1413 * It appears that grabstackstr() will barf with such alignments
1414 * because stalloc() will return a string allocated in a new stackblock.
1416 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1418 /* Most machines require the value returned from malloc to be aligned
1419 * in some way. The following macro will get this right
1420 * on many machines. */
1421 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1422 /* Minimum size of a block */
1423 MINSIZE = SHELL_ALIGN(504),
1426 struct stack_block {
1427 struct stack_block *prev;
1428 char space[MINSIZE];
1432 struct stack_block *stackp;
1438 struct globals_memstack {
1439 struct stack_block *g_stackp; // = &stackbase;
1440 char *g_stacknxt; // = stackbase.space;
1441 char *sstrend; // = stackbase.space + MINSIZE;
1442 size_t g_stacknleft; // = MINSIZE;
1443 struct stack_block stackbase;
1445 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1446 #define G_memstack (*ash_ptr_to_globals_memstack)
1447 #define g_stackp (G_memstack.g_stackp )
1448 #define g_stacknxt (G_memstack.g_stacknxt )
1449 #define sstrend (G_memstack.sstrend )
1450 #define g_stacknleft (G_memstack.g_stacknleft)
1451 #define stackbase (G_memstack.stackbase )
1452 #define INIT_G_memstack() do { \
1453 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1455 g_stackp = &stackbase; \
1456 g_stacknxt = stackbase.space; \
1457 g_stacknleft = MINSIZE; \
1458 sstrend = stackbase.space + MINSIZE; \
1462 #define stackblock() ((void *)g_stacknxt)
1463 #define stackblocksize() g_stacknleft
1466 * Parse trees for commands are allocated in lifo order, so we use a stack
1467 * to make this more efficient, and also to avoid all sorts of exception
1468 * handling code to handle interrupts in the middle of a parse.
1470 * The size 504 was chosen because the Ultrix malloc handles that size
1474 stalloc(size_t nbytes)
1479 aligned = SHELL_ALIGN(nbytes);
1480 if (aligned > g_stacknleft) {
1483 struct stack_block *sp;
1485 blocksize = aligned;
1486 if (blocksize < MINSIZE)
1487 blocksize = MINSIZE;
1488 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1489 if (len < blocksize)
1490 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1493 sp->prev = g_stackp;
1494 g_stacknxt = sp->space;
1495 g_stacknleft = blocksize;
1496 sstrend = g_stacknxt + blocksize;
1501 g_stacknxt += aligned;
1502 g_stacknleft -= aligned;
1507 stzalloc(size_t nbytes)
1509 return memset(stalloc(nbytes), 0, nbytes);
1516 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1517 write(STDERR_FILENO, "stunalloc\n", 10);
1521 g_stacknleft += g_stacknxt - (char *)p;
1526 * Like strdup but works with the ash stack.
1529 sstrdup(const char *p)
1531 size_t len = strlen(p) + 1;
1532 return memcpy(stalloc(len), p, len);
1535 static ALWAYS_INLINE void
1536 grabstackblock(size_t len)
1542 pushstackmark(struct stackmark *mark, size_t len)
1544 mark->stackp = g_stackp;
1545 mark->stacknxt = g_stacknxt;
1546 mark->stacknleft = g_stacknleft;
1547 grabstackblock(len);
1551 setstackmark(struct stackmark *mark)
1553 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1557 popstackmark(struct stackmark *mark)
1559 struct stack_block *sp;
1565 while (g_stackp != mark->stackp) {
1567 g_stackp = sp->prev;
1570 g_stacknxt = mark->stacknxt;
1571 g_stacknleft = mark->stacknleft;
1572 sstrend = mark->stacknxt + mark->stacknleft;
1577 * When the parser reads in a string, it wants to stick the string on the
1578 * stack and only adjust the stack pointer when it knows how big the
1579 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1580 * of space on top of the stack and stackblocklen returns the length of
1581 * this block. Growstackblock will grow this space by at least one byte,
1582 * possibly moving it (like realloc). Grabstackblock actually allocates the
1583 * part of the block that has been used.
1586 growstackblock(void)
1590 newlen = g_stacknleft * 2;
1591 if (newlen < g_stacknleft)
1592 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1596 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1597 struct stack_block *sp;
1598 struct stack_block *prevstackp;
1603 prevstackp = sp->prev;
1604 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1605 sp = ckrealloc(sp, grosslen);
1606 sp->prev = prevstackp;
1608 g_stacknxt = sp->space;
1609 g_stacknleft = newlen;
1610 sstrend = sp->space + newlen;
1613 char *oldspace = g_stacknxt;
1614 size_t oldlen = g_stacknleft;
1615 char *p = stalloc(newlen);
1617 /* free the space we just allocated */
1618 g_stacknxt = memcpy(p, oldspace, oldlen);
1619 g_stacknleft += newlen;
1624 * The following routines are somewhat easier to use than the above.
1625 * The user declares a variable of type STACKSTR, which may be declared
1626 * to be a register. The macro STARTSTACKSTR initializes things. Then
1627 * the user uses the macro STPUTC to add characters to the string. In
1628 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1629 * grown as necessary. When the user is done, she can just leave the
1630 * string there and refer to it using stackblock(). Or she can allocate
1631 * the space for it using grabstackstr(). If it is necessary to allow
1632 * someone else to use the stack temporarily and then continue to grow
1633 * the string, the user should use grabstack to allocate the space, and
1634 * then call ungrabstr(p) to return to the previous mode of operation.
1636 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1637 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1638 * is space for at least one character.
1643 size_t len = stackblocksize();
1645 return (char *)stackblock() + len;
1649 * Called from CHECKSTRSPACE.
1652 makestrspace(size_t newlen, char *p)
1654 size_t len = p - g_stacknxt;
1660 size = stackblocksize();
1662 if (nleft >= newlen)
1666 return (char *)stackblock() + len;
1670 stack_nputstr(const char *s, size_t n, char *p)
1672 p = makestrspace(n, p);
1673 p = (char *)mempcpy(p, s, n);
1678 stack_putstr(const char *s, char *p)
1680 return stack_nputstr(s, strlen(s), p);
1684 _STPUTC(int c, char *p)
1692 #define STARTSTACKSTR(p) ((p) = stackblock())
1693 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1694 #define CHECKSTRSPACE(n, p) do { \
1697 size_t m = sstrend - q; \
1699 (p) = makestrspace(l, q); \
1701 #define USTPUTC(c, p) (*(p)++ = (c))
1702 #define STACKSTRNUL(p) do { \
1703 if ((p) == sstrend) \
1704 (p) = growstackstr(); \
1707 #define STUNPUTC(p) (--(p))
1708 #define STTOPC(p) ((p)[-1])
1709 #define STADJUST(amount, p) ((p) += (amount))
1711 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1712 #define ungrabstackstr(s, p) stunalloc(s)
1713 #define stackstrend() ((void *)sstrend)
1716 /* ============ String helpers */
1719 * prefix -- see if pfx is a prefix of string.
1722 prefix(const char *string, const char *pfx)
1725 if (*pfx++ != *string++)
1728 return (char *) string;
1732 * Check for a valid number. This should be elsewhere.
1735 is_number(const char *p)
1740 } while (*++p != '\0');
1745 * Convert a string of digits to an integer, printing an error message on
1749 number(const char *s)
1752 ash_msg_and_raise_error(msg_illnum, s);
1757 * Produce a single quoted string suitable as input to the shell.
1758 * The return string is allocated on the stack.
1761 single_quote(const char *s)
1771 len = strchrnul(s, '\'') - s;
1773 q = p = makestrspace(len + 3, p);
1776 q = (char *)mempcpy(q, s, len);
1785 do len++; while (*++s == '\'');
1787 q = p = makestrspace(len + 3, p);
1790 q = (char *)mempcpy(q, s - len, len);
1798 return stackblock();
1802 * Produce a possibly single quoted string suitable as input to the shell.
1803 * If quoting was done, the return string is allocated on the stack,
1804 * otherwise a pointer to the original string is returned.
1807 maybe_single_quote(const char *s)
1812 /* Assuming ACSII */
1813 /* quote ctrl_chars space !"#$%&'()* */
1817 if (*p >= ';' && *p <= '?')
1826 /* quote {|}~ DEL and high bytes */
1829 /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
1830 /* TODO: maybe avoid quoting % */
1836 return single_quote(s);
1840 /* ============ nextopt */
1842 static char **argptr; /* argument list for builtin commands */
1843 static char *optionarg; /* set by nextopt (like getopt) */
1844 static char *optptr; /* used by nextopt */
1847 * XXX - should get rid of. Have all builtins use getopt(3).
1848 * The library getopt must have the BSD extension static variable
1849 * "optreset", otherwise it can't be used within the shell safely.
1851 * Standard option processing (a la getopt) for builtin routines.
1852 * The only argument that is passed to nextopt is the option string;
1853 * the other arguments are unnecessary. It returns the character,
1854 * or '\0' on end of input.
1857 nextopt(const char *optstring)
1864 if (p == NULL || *p == '\0') {
1865 /* We ate entire "-param", take next one */
1871 if (*++p == '\0') /* just "-" ? */
1874 if (LONE_DASH(p)) /* "--" ? */
1876 /* p => next "-param" */
1878 /* p => some option char in the middle of a "-param" */
1880 for (q = optstring; *q != c;) {
1882 ash_msg_and_raise_error("illegal option -%c", c);
1890 ash_msg_and_raise_error("no arg for -%c option", c);
1900 /* ============ Shell variables */
1903 int nparam; /* # of positional parameters (without $0) */
1904 #if ENABLE_ASH_GETOPTS
1905 int optind; /* next parameter to be processed by getopts */
1906 int optoff; /* used by getopts */
1908 unsigned char malloced; /* if parameter list dynamically allocated */
1909 char **p; /* parameter list */
1913 * Free the list of positional parameters.
1916 freeparam(volatile struct shparam *param)
1918 if (param->malloced) {
1920 ap = ap1 = param->p;
1927 #if ENABLE_ASH_GETOPTS
1928 static void FAST_FUNC getoptsreset(const char *value);
1932 struct var *next; /* next entry in hash list */
1933 int flags; /* flags are defined above */
1934 const char *var_text; /* name=value */
1935 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1936 /* the variable gets set/unset */
1940 struct localvar *next; /* next local variable in list */
1941 struct var *vp; /* the variable that was made local */
1942 int flags; /* saved flags */
1943 const char *text; /* saved text */
1947 #define VEXPORT 0x01 /* variable is exported */
1948 #define VREADONLY 0x02 /* variable cannot be modified */
1949 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1950 #define VTEXTFIXED 0x08 /* text is statically allocated */
1951 #define VSTACK 0x10 /* text is allocated on the stack */
1952 #define VUNSET 0x20 /* the variable is not set */
1953 #define VNOFUNC 0x40 /* don't call the callback function */
1954 #define VNOSET 0x80 /* do not set variable - just readonly test */
1955 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1956 #if ENABLE_ASH_RANDOM_SUPPORT
1957 # define VDYNAMIC 0x200 /* dynamic variable */
1963 /* Need to be before varinit_data[] */
1964 #if ENABLE_LOCALE_SUPPORT
1965 static void FAST_FUNC
1966 change_lc_all(const char *value)
1968 if (value && *value != '\0')
1969 setlocale(LC_ALL, value);
1971 static void FAST_FUNC
1972 change_lc_ctype(const char *value)
1974 if (value && *value != '\0')
1975 setlocale(LC_CTYPE, value);
1979 static void chkmail(void);
1980 static void changemail(const char *var_value) FAST_FUNC;
1982 # define chkmail() ((void)0)
1984 static void changepath(const char *) FAST_FUNC;
1985 #if ENABLE_ASH_RANDOM_SUPPORT
1986 static void change_random(const char *) FAST_FUNC;
1989 static const struct {
1991 const char *var_text;
1992 void (*var_func)(const char *) FAST_FUNC;
1993 } varinit_data[] = {
1995 * Note: VEXPORT would not work correctly here for NOFORK applets:
1996 * some environment strings may be constant.
1998 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
2000 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
2001 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
2003 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
2004 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
2005 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
2006 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
2007 #if ENABLE_ASH_GETOPTS
2008 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
2010 #if ENABLE_ASH_RANDOM_SUPPORT
2011 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
2013 #if ENABLE_LOCALE_SUPPORT
2014 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
2015 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
2017 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
2018 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
2024 struct globals_var {
2025 struct shparam shellparam; /* $@ current positional parameters */
2026 struct redirtab *redirlist;
2027 int preverrout_fd; /* stderr fd: usually 2, unless redirect moved it */
2028 struct var *vartab[VTABSIZE];
2029 struct var varinit[ARRAY_SIZE(varinit_data)];
2031 extern struct globals_var *const ash_ptr_to_globals_var;
2032 #define G_var (*ash_ptr_to_globals_var)
2033 #define shellparam (G_var.shellparam )
2034 //#define redirlist (G_var.redirlist )
2035 #define preverrout_fd (G_var.preverrout_fd)
2036 #define vartab (G_var.vartab )
2037 #define varinit (G_var.varinit )
2038 #define INIT_G_var() do { \
2040 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
2042 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
2043 varinit[i].flags = varinit_data[i].flags; \
2044 varinit[i].var_text = varinit_data[i].var_text; \
2045 varinit[i].var_func = varinit_data[i].var_func; \
2049 #define vifs varinit[0]
2051 # define vmail (&vifs)[1]
2052 # define vmpath (&vmail)[1]
2053 # define vpath (&vmpath)[1]
2055 # define vpath (&vifs)[1]
2057 #define vps1 (&vpath)[1]
2058 #define vps2 (&vps1)[1]
2059 #define vps4 (&vps2)[1]
2060 #if ENABLE_ASH_GETOPTS
2061 # define voptind (&vps4)[1]
2062 # if ENABLE_ASH_RANDOM_SUPPORT
2063 # define vrandom (&voptind)[1]
2066 # if ENABLE_ASH_RANDOM_SUPPORT
2067 # define vrandom (&vps4)[1]
2072 * The following macros access the values of the above variables.
2073 * They have to skip over the name. They return the null string
2074 * for unset variables.
2076 #define ifsval() (vifs.var_text + 4)
2077 #define ifsset() ((vifs.flags & VUNSET) == 0)
2079 # define mailval() (vmail.var_text + 5)
2080 # define mpathval() (vmpath.var_text + 9)
2081 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2083 #define pathval() (vpath.var_text + 5)
2084 #define ps1val() (vps1.var_text + 4)
2085 #define ps2val() (vps2.var_text + 4)
2086 #define ps4val() (vps4.var_text + 4)
2087 #if ENABLE_ASH_GETOPTS
2088 # define optindval() (voptind.var_text + 7)
2091 #if ENABLE_ASH_GETOPTS
2092 static void FAST_FUNC
2093 getoptsreset(const char *value)
2095 shellparam.optind = 1;
2096 if (is_number(value))
2097 shellparam.optind = number(value) ?: 1;
2098 shellparam.optoff = -1;
2103 * Compares two strings up to the first = or '\0'. The first
2104 * string must be terminated by '='; the second may be terminated by
2105 * either '=' or '\0'.
2108 varcmp(const char *p, const char *q)
2112 while ((c = *p) == (d = *q)) {
2113 if (c == '\0' || c == '=')
2127 * Find the appropriate entry in the hash table from the name.
2129 static struct var **
2130 hashvar(const char *p)
2134 hashval = ((unsigned char) *p) << 4;
2135 while (*p && *p != '=')
2136 hashval += (unsigned char) *p++;
2137 return &vartab[hashval % VTABSIZE];
2141 vpcmp(const void *a, const void *b)
2143 return varcmp(*(const char **)a, *(const char **)b);
2147 * This routine initializes the builtin variables.
2157 * PS1 depends on uid
2159 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2160 vps1.var_text = "PS1=\\w \\$ ";
2163 vps1.var_text = "PS1=# ";
2166 end = vp + ARRAY_SIZE(varinit);
2168 vpp = hashvar(vp->var_text);
2171 } while (++vp < end);
2174 static struct var **
2175 findvar(struct var **vpp, const char *name)
2177 for (; *vpp; vpp = &(*vpp)->next) {
2178 if (varcmp((*vpp)->var_text, name) == 0) {
2186 * Find the value of a variable. Returns NULL if not set.
2188 static const char* FAST_FUNC
2189 lookupvar(const char *name)
2193 v = *findvar(hashvar(name), name);
2195 #if ENABLE_ASH_RANDOM_SUPPORT
2197 * Dynamic variables are implemented roughly the same way they are
2198 * in bash. Namely, they're "special" so long as they aren't unset.
2199 * As soon as they're unset, they're no longer dynamic, and dynamic
2200 * lookup will no longer happen at that point. -- PFM.
2202 if (v->flags & VDYNAMIC)
2205 if (!(v->flags & VUNSET))
2206 return var_end(v->var_text);
2211 #if ENABLE_UNICODE_SUPPORT
2213 reinit_unicode_for_ash(void)
2215 /* Unicode support should be activated even if LANG is set
2216 * _during_ shell execution, not only if it was set when
2217 * shell was started. Therefore, re-check LANG every time:
2219 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2220 || ENABLE_UNICODE_USING_LOCALE
2222 const char *s = lookupvar("LC_ALL");
2223 if (!s) s = lookupvar("LC_CTYPE");
2224 if (!s) s = lookupvar("LANG");
2229 # define reinit_unicode_for_ash() ((void)0)
2233 * Search the environment of a builtin command.
2235 static ALWAYS_INLINE const char *
2236 bltinlookup(const char *name)
2238 return lookupvar(name);
2242 * Same as setvar except that the variable and value are passed in
2243 * the first argument as name=value. Since the first argument will
2244 * be actually stored in the table, it should not be a string that
2246 * Called with interrupts off.
2249 setvareq(char *s, int flags)
2251 struct var *vp, **vpp;
2254 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2255 vpp = findvar(vpp, s);
2258 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2261 if (flags & VNOSAVE)
2265 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2271 if (vp->var_func && !(flags & VNOFUNC))
2272 vp->var_func(var_end(s));
2274 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2275 free((char*)vp->var_text);
2277 if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
2281 if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
2286 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2288 /* variable s is not found */
2291 if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
2293 vp = ckzalloc(sizeof(*vp));
2295 /*vp->func = NULL; - ckzalloc did it */
2298 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2308 * Set the value of a variable. The flags argument is ored with the
2309 * flags of the variable. If val is NULL, the variable is unset.
2312 setvar(const char *name, const char *val, int flags)
2321 q = endofname(name);
2322 p = strchrnul(q, '=');
2324 if (!namelen || p != q)
2325 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2330 vallen = strlen(val);
2334 nameeq = ckmalloc(namelen + vallen + 2);
2335 p = mempcpy(nameeq, name, namelen);
2338 p = mempcpy(p, val, vallen);
2341 vp = setvareq(nameeq, flags | VNOSAVE);
2347 static void FAST_FUNC
2348 setvar0(const char *name, const char *val)
2350 setvar(name, val, 0);
2354 * Unset the specified variable.
2357 unsetvar(const char *s)
2363 * Process a linked list of variable assignments.
2366 listsetvar(struct strlist *list_set_var, int flags)
2368 struct strlist *lp = list_set_var;
2374 setvareq(lp->text, flags);
2381 * Generate a list of variables satisfying the given conditions.
2383 #if !ENABLE_FEATURE_SH_NOFORK
2384 # define listvars(on, off, lp, end) listvars(on, off, end)
2387 listvars(int on, int off, struct strlist *lp, char ***end)
2398 for (vp = *vpp; vp; vp = vp->next) {
2399 if ((vp->flags & mask) == on) {
2400 #if ENABLE_FEATURE_SH_NOFORK
2401 /* If variable with the same name is both
2402 * exported and temporarily set for a command:
2405 * then "ZVAR=6" will be both in vartab and
2406 * lp lists. Do not pass it twice to printenv.
2408 struct strlist *lp1 = lp;
2410 if (strcmp(lp1->text, vp->var_text) == 0)
2415 if (ep == stackstrend())
2416 ep = growstackstr();
2417 *ep++ = (char*)vp->var_text;
2418 #if ENABLE_FEATURE_SH_NOFORK
2423 } while (++vpp < vartab + VTABSIZE);
2425 #if ENABLE_FEATURE_SH_NOFORK
2427 if (ep == stackstrend())
2428 ep = growstackstr();
2434 if (ep == stackstrend())
2435 ep = growstackstr();
2439 return grabstackstr(ep);
2443 /* ============ Path search helper
2445 * The variable path (passed by reference) should be set to the start
2446 * of the path before the first call; path_advance will update
2447 * this value as it proceeds. Successive calls to path_advance will return
2448 * the possible path expansions in sequence. If an option (indicated by
2449 * a percent sign) appears in the path entry then the global variable
2450 * pathopt will be set to point to it; otherwise pathopt will be set to
2453 static const char *pathopt; /* set by path_advance */
2456 path_advance(const char **path, const char *name)
2466 for (p = start; *p && *p != ':' && *p != '%'; p++)
2468 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2469 while (stackblocksize() < len)
2473 q = mempcpy(q, start, p - start);
2480 while (*p && *p != ':')
2487 return stalloc(len);
2491 /* ============ Prompt */
2493 static smallint doprompt; /* if set, prompt the user */
2494 static smallint needprompt; /* true if interactive and at start of line */
2496 #if ENABLE_FEATURE_EDITING
2497 static line_input_t *line_input_state;
2498 static const char *cmdedit_prompt;
2500 putprompt(const char *s)
2502 if (ENABLE_ASH_EXPAND_PRMT) {
2503 free((char*)cmdedit_prompt);
2504 cmdedit_prompt = ckstrdup(s);
2511 putprompt(const char *s)
2517 /* expandstr() needs parsing machinery, so it is far away ahead... */
2518 static const char *expandstr(const char *ps, int syntax_type);
2519 /* Values for syntax param */
2520 #define BASESYNTAX 0 /* not in quotes */
2521 #define DQSYNTAX 1 /* in double quotes */
2522 #define SQSYNTAX 2 /* in single quotes */
2523 #define ARISYNTAX 3 /* in arithmetic */
2524 #if ENABLE_ASH_EXPAND_PRMT
2525 # define PSSYNTAX 4 /* prompt. never passed to SIT() */
2527 /* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
2530 * called by editline -- any expansions to the prompt should be added here.
2533 setprompt_if(smallint do_set, int whichprompt)
2536 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2543 switch (whichprompt) {
2553 #if ENABLE_ASH_EXPAND_PRMT
2554 pushstackmark(&smark, stackblocksize());
2555 putprompt(expandstr(prompt, PSSYNTAX));
2556 popstackmark(&smark);
2563 /* ============ The cd and pwd commands */
2565 #define CD_PHYSICAL 1
2575 while ((i = nextopt("LP")) != '\0') {
2577 flags ^= CD_PHYSICAL;
2586 * Update curdir (the name of the current directory) in response to a
2590 updatepwd(const char *dir)
2597 cdcomppath = sstrdup(dir);
2600 if (curdir == nullstr)
2602 new = stack_putstr(curdir, new);
2604 new = makestrspace(strlen(dir) + 2, new);
2605 lim = (char *)stackblock() + 1;
2609 if (new > lim && *lim == '/')
2614 if (dir[1] == '/' && dir[2] != '/') {
2620 p = strtok(cdcomppath, "/");
2624 if (p[1] == '.' && p[2] == '\0') {
2636 new = stack_putstr(p, new);
2639 p = strtok(NULL, "/");
2644 return stackblock();
2648 * Find out what the current directory is. If we already know the current
2649 * directory, this routine returns immediately.
2654 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2655 return dir ? dir : nullstr;
2659 setpwd(const char *val, int setold)
2663 oldcur = dir = curdir;
2666 setvar("OLDPWD", oldcur, VEXPORT);
2669 if (physdir != nullstr) {
2670 if (physdir != oldcur)
2674 if (oldcur == val || !val) {
2680 dir = ckstrdup(val);
2681 if (oldcur != dir && oldcur != nullstr) {
2686 setvar("PWD", dir, VEXPORT);
2689 static void hashcd(void);
2692 * Actually do the chdir. We also call hashcd to let other routines
2693 * know that the current directory has changed.
2696 docd(const char *dest, int flags)
2698 const char *dir = NULL;
2701 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2704 if (!(flags & CD_PHYSICAL)) {
2705 dir = updatepwd(dest);
2719 static int FAST_FUNC
2720 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2732 dest = bltinlookup("HOME");
2733 else if (LONE_DASH(dest)) {
2734 dest = bltinlookup("OLDPWD");
2756 path = bltinlookup("CDPATH");
2759 p = path_advance(&path, dest);
2760 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2764 if (!docd(p, flags))
2775 ash_msg_and_raise_perror("can't cd to %s", dest);
2778 if (flags & CD_PRINT)
2779 out1fmt("%s\n", curdir);
2783 static int FAST_FUNC
2784 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2787 const char *dir = curdir;
2791 if (physdir == nullstr)
2795 out1fmt("%s\n", dir);
2800 /* ============ ... */
2803 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2805 /* Syntax classes */
2806 #define CWORD 0 /* character is nothing special */
2807 #define CNL 1 /* newline character */
2808 #define CBACK 2 /* a backslash character */
2809 #define CSQUOTE 3 /* single quote */
2810 #define CDQUOTE 4 /* double quote */
2811 #define CENDQUOTE 5 /* a terminating quote */
2812 #define CBQUOTE 6 /* backwards single quote */
2813 #define CVAR 7 /* a dollar sign */
2814 #define CENDVAR 8 /* a '}' character */
2815 #define CLP 9 /* a left paren in arithmetic */
2816 #define CRP 10 /* a right paren in arithmetic */
2817 #define CENDFILE 11 /* end of file */
2818 #define CCTL 12 /* like CWORD, except it must be escaped */
2819 #define CSPCL 13 /* these terminate a word */
2820 #define CIGN 14 /* character should be ignored */
2823 #if ENABLE_ASH_ALIAS
2827 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2829 #if ENABLE_FEATURE_SH_MATH
2830 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2832 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2834 static const uint16_t S_I_T[] ALIGN2 = {
2835 #if ENABLE_ASH_ALIAS
2836 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2838 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2839 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2840 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2841 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2842 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2843 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2844 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2845 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2846 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2847 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2848 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2849 #if !USE_SIT_FUNCTION
2850 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2851 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2852 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2856 /* Constants below must match table above */
2858 #if ENABLE_ASH_ALIAS
2859 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2861 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2862 CNL_CNL_CNL_CNL , /* 2 */
2863 CWORD_CCTL_CCTL_CWORD , /* 3 */
2864 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2865 CVAR_CVAR_CWORD_CVAR , /* 5 */
2866 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2867 CSPCL_CWORD_CWORD_CLP , /* 7 */
2868 CSPCL_CWORD_CWORD_CRP , /* 8 */
2869 CBACK_CBACK_CCTL_CBACK , /* 9 */
2870 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2871 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2872 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2873 CWORD_CWORD_CWORD_CWORD , /* 13 */
2874 CCTL_CCTL_CCTL_CCTL , /* 14 */
2877 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2878 * caller must ensure proper cast on it if c is *char_ptr!
2880 #if USE_SIT_FUNCTION
2883 SIT(int c, int syntax)
2885 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2886 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2888 * This causes '/' to be prepended with CTLESC in dquoted string,
2889 * making "./file"* treated incorrectly because we feed
2890 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2891 * The "homegrown" glob implementation is okay with that,
2892 * but glibc one isn't. With '/' always treated as CWORD,
2895 # if ENABLE_ASH_ALIAS
2896 static const uint8_t syntax_index_table[] ALIGN1 = {
2897 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2898 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2899 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2903 static const uint8_t syntax_index_table[] ALIGN1 = {
2904 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2905 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2906 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2915 # if ENABLE_ASH_ALIAS
2921 /* Cast is purely for paranoia here,
2922 * just in case someone passed signed char to us */
2923 if ((unsigned char)c >= CTL_FIRST
2924 && (unsigned char)c <= CTL_LAST
2928 s = strchrnul(spec_symbls, c);
2931 indx = syntax_index_table[s - spec_symbls];
2933 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2936 #else /* !USE_SIT_FUNCTION */
2938 static const uint8_t syntax_index_table[] ALIGN1 = {
2939 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2940 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2945 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2946 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2947 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2948 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2949 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2950 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2951 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2952 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2953 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2954 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2955 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2956 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2957 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2958 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2959 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2960 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2961 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2962 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2963 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2964 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2965 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2966 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2967 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2968 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2969 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2970 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2971 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2972 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2973 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2974 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2975 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2977 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2979 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2980 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2981 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2982 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2983 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2985 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2986 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2987 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2988 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2993 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
3000 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
3001 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
3002 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
3003 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
3004 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
3005 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
3006 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
3007 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
3008 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
3009 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
3010 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
3011 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
3012 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
3013 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
3014 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
3015 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
3016 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
3017 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
3018 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
3019 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
3020 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
3021 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
3022 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
3023 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
3024 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
3025 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
3026 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
3027 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
3028 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
3029 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
3030 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
3031 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
3032 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
3033 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
3034 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
3035 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
3036 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
3037 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
3038 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
3039 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
3040 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
3041 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
3042 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
3043 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
3044 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
3045 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
3046 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
3047 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
3048 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
3049 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
3050 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
3051 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
3052 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3053 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3054 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3055 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3056 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3057 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3058 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3059 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3060 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3061 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3062 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3063 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3064 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3065 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3066 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3067 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3068 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
3069 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
3071 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
3072 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
3073 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
3074 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
3075 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3076 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3077 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3078 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3113 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3114 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3115 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3116 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3117 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3118 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3119 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3120 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3121 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3122 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3123 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3124 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3125 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3126 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3127 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3128 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3129 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3130 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3131 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3132 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3133 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3134 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3135 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3136 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3137 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3138 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3139 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3140 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3141 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3142 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3143 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3144 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3145 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3146 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3147 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3148 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3149 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3150 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3151 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3152 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3153 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3154 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3155 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3156 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3157 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3158 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3159 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3160 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3161 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3162 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3163 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3164 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3165 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3166 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3167 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3168 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3169 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3170 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3171 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3172 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3173 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3174 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3175 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3176 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3177 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3178 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3179 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3180 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3181 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3182 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3183 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3184 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3185 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3186 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3187 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3188 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3189 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3190 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3191 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3192 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3193 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3194 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3195 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3196 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3197 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3198 # if ENABLE_ASH_ALIAS
3199 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3204 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3205 #else /* debug version, caught one signed char bug */
3206 # define SIT(c, syntax) \
3208 if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
3209 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3210 if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
3211 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3212 ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
3216 #endif /* !USE_SIT_FUNCTION */
3219 /* ============ Alias handling */
3221 #if ENABLE_ASH_ALIAS
3223 #define ALIASINUSE 1
3234 static struct alias **atab; // [ATABSIZE];
3235 #define INIT_G_alias() do { \
3236 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3240 static struct alias **
3241 __lookupalias(const char *name)
3243 unsigned int hashval;
3250 ch = (unsigned char)*p;
3254 ch = (unsigned char)*++p;
3256 app = &atab[hashval % ATABSIZE];
3258 for (; *app; app = &(*app)->next) {
3259 if (strcmp(name, (*app)->name) == 0) {
3267 static struct alias *
3268 lookupalias(const char *name, int check)
3270 struct alias *ap = *__lookupalias(name);
3272 if (check && ap && (ap->flag & ALIASINUSE))
3277 static struct alias *
3278 freealias(struct alias *ap)
3282 if (ap->flag & ALIASINUSE) {
3283 ap->flag |= ALIASDEAD;
3295 setalias(const char *name, const char *val)
3297 struct alias *ap, **app;
3299 app = __lookupalias(name);
3303 if (!(ap->flag & ALIASINUSE)) {
3306 ap->val = ckstrdup(val);
3307 ap->flag &= ~ALIASDEAD;
3310 ap = ckzalloc(sizeof(struct alias));
3311 ap->name = ckstrdup(name);
3312 ap->val = ckstrdup(val);
3313 /*ap->flag = 0; - ckzalloc did it */
3314 /*ap->next = NULL;*/
3321 unalias(const char *name)
3325 app = __lookupalias(name);
3329 *app = freealias(*app);
3340 struct alias *ap, **app;
3344 for (i = 0; i < ATABSIZE; i++) {
3346 for (ap = *app; ap; ap = *app) {
3347 *app = freealias(*app);
3357 printalias(const struct alias *ap)
3359 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3363 * TODO - sort output
3365 static int FAST_FUNC
3366 aliascmd(int argc UNUSED_PARAM, char **argv)
3375 for (i = 0; i < ATABSIZE; i++) {
3376 for (ap = atab[i]; ap; ap = ap->next) {
3382 while ((n = *++argv) != NULL) {
3383 v = strchr(n+1, '=');
3384 if (v == NULL) { /* n+1: funny ksh stuff */
3385 ap = *__lookupalias(n);
3387 fprintf(stderr, "%s: %s not found\n", "alias", n);
3400 static int FAST_FUNC
3401 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3405 while (nextopt("a") != '\0') {
3409 for (i = 0; *argptr; argptr++) {
3410 if (unalias(*argptr)) {
3411 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3419 #endif /* ASH_ALIAS */
3422 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3425 #define FORK_NOJOB 2
3427 /* mode flags for showjob(s) */
3428 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3429 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3430 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3431 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3434 * A job structure contains information about a job. A job is either a
3435 * single process or a set of processes contained in a pipeline. In the
3436 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3440 pid_t ps_pid; /* process id */
3441 int ps_status; /* last process status from wait() */
3442 char *ps_cmd; /* text of command being run */
3446 struct procstat ps0; /* status of process */
3447 struct procstat *ps; /* status or processes when more than one */
3449 int stopstatus; /* status of a stopped job */
3451 unsigned nprocs; /* number of processes */
3453 #define JOBRUNNING 0 /* at least one proc running */
3454 #define JOBSTOPPED 1 /* all procs are stopped */
3455 #define JOBDONE 2 /* all procs are completed */
3459 sigint: 1, /* job was killed by SIGINT */
3460 jobctl: 1, /* job running under job control */
3462 waited: 1, /* true if this entry has been waited for */
3463 used: 1, /* true if this entry is in used */
3464 changed: 1; /* true if status has changed */
3465 struct job *prev_job; /* previous job */
3468 static struct job *makejob(/*union node *,*/ int);
3469 static int forkshell(struct job *, union node *, int);
3470 static int waitforjob(struct job *);
3473 enum { doing_jobctl = 0 };
3474 #define setjobctl(on) do {} while (0)
3476 static smallint doing_jobctl; //references:8
3477 static void setjobctl(int);
3484 ignoresig(int signo)
3486 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3487 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3488 /* No, need to do it */
3489 signal(signo, SIG_IGN);
3491 sigmode[signo - 1] = S_HARD_IGN;
3495 * Only one usage site - in setsignal()
3498 signal_handler(int signo)
3500 if (signo == SIGCHLD) {
3506 gotsig[signo - 1] = 1;
3507 pending_sig = signo;
3509 if (signo == SIGINT && !trap[SIGINT]) {
3510 if (!suppress_int) {
3512 raise_interrupt(); /* does not return */
3519 * Set the signal handler for the specified signal. The routine figures
3520 * out what it should be set to.
3523 setsignal(int signo)
3526 char cur_act, new_act;
3527 struct sigaction act;
3531 if (t != NULL) { /* trap for this sig is set */
3533 if (t[0] == '\0') /* trap is "": ignore this sig */
3537 if (rootshell && new_act == S_DFL) {
3540 if (iflag || minusc || sflag == 0)
3549 * "In all cases, bash ignores SIGQUIT. Non-builtin
3550 * commands run by bash have signal handlers
3551 * set to the values inherited by the shell
3552 * from its parent". */
3568 /* if !rootshell, we reset SIGQUIT to DFL,
3569 * whereas we have to restore it to what shell got on entry.
3570 * This is handled by the fact that if signal was IGNored on entry,
3571 * then cur_act is S_HARD_IGN and we never change its sigaction
3575 if (signo == SIGCHLD)
3578 t = &sigmode[signo - 1];
3581 /* current setting is not yet known */
3582 if (sigaction(signo, NULL, &act)) {
3583 /* pretend it worked; maybe we should give a warning,
3584 * but other shells don't. We don't alter sigmode,
3585 * so we retry every time.
3586 * btw, in Linux it never fails. --vda */
3589 if (act.sa_handler == SIG_IGN) {
3590 cur_act = S_HARD_IGN;
3592 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3594 cur_act = S_IGN; /* don't hard ignore these */
3597 if (act.sa_handler == SIG_DFL && new_act == S_DFL) {
3598 /* installing SIG_DFL over SIG_DFL is a no-op */
3599 /* saves one sigaction call in each "sh -c SCRIPT" invocation */
3604 if (cur_act == S_HARD_IGN || cur_act == new_act)
3609 act.sa_handler = SIG_DFL;
3612 act.sa_handler = signal_handler;
3615 act.sa_handler = SIG_IGN;
3618 /* flags and mask matter only if !DFL and !IGN, but we do it
3619 * for all cases for more deterministic behavior:
3621 act.sa_flags = 0; //TODO: why not SA_RESTART?
3622 sigfillset(&act.sa_mask);
3624 sigaction_set(signo, &act);
3627 /* mode flags for set_curjob */
3628 #define CUR_DELETE 2
3629 #define CUR_RUNNING 1
3630 #define CUR_STOPPED 0
3633 /* pgrp of shell on invocation */
3634 static int initialpgrp; //references:2
3635 static int ttyfd = -1; //5
3638 static struct job *jobtab; //5
3640 static unsigned njobs; //4
3642 static struct job *curjob; //lots
3643 /* number of presumed living untracked jobs */
3644 static int jobless; //4
3647 /* Bash has a feature: it restores termios after a successful wait for
3648 * a foreground job which had at least one stopped or sigkilled member.
3649 * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
3650 * properly restoring tty state. Should we do this too?
3651 * A reproducer: ^Z an interactive python:
3654 * Python 2.7.12 (...)
3656 * { python leaves tty in -icanon -echo state. We do survive that... }
3657 * [1]+ Stopped python
3658 * { ...however, next program (python #2) does not survive it well: }
3660 * Python 2.7.12 (...)
3661 * >>> Traceback (most recent call last):
3662 * { above, I typed "qwerty<CR>", but -echo state is still in effect }
3663 * File "<stdin>", line 1, in <module>
3664 * NameError: name 'qwerty' is not defined
3666 * The implementation below is modeled on bash code and seems to work.
3667 * However, I'm not sure we should do this. For one: what if I'd fg
3668 * the stopped python instead? It'll be confused by "restored" tty state.
3670 static struct termios shell_tty_info;
3674 if (rootshell && ttyfd >= 0)
3675 tcgetattr(ttyfd, &shell_tty_info);
3680 /* if (rootshell) - caller ensures this */
3682 tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
3685 job_signal_status(struct job *jp)
3689 struct procstat *ps = jp->ps;
3690 for (i = 0; i < jp->nprocs; i++) {
3691 status = ps[i].ps_status;
3692 if (WIFSIGNALED(status) || WIFSTOPPED(status))
3698 restore_tty_if_stopped_or_signaled(struct job *jp)
3700 //TODO: check what happens if we come from waitforjob() in expbackq()
3702 int s = job_signal_status(jp);
3703 if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
3708 # define get_tty_state() ((void)0)
3709 # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
3713 set_curjob(struct job *jp, unsigned mode)
3716 struct job **jpp, **curp;
3718 /* first remove from list */
3719 jpp = curp = &curjob;
3724 jpp = &jp1->prev_job;
3726 *jpp = jp1->prev_job;
3728 /* Then re-insert in correct position */
3736 /* job being deleted */
3739 /* newly created job or backgrounded job,
3740 * put after all stopped jobs.
3745 if (!jp1 || jp1->state != JOBSTOPPED)
3748 jpp = &jp1->prev_job;
3754 /* newly stopped job - becomes curjob */
3755 jp->prev_job = *jpp;
3763 jobno(const struct job *jp)
3765 return jp - jobtab + 1;
3770 * Convert a job name to a job structure.
3773 #define getjob(name, getctl) getjob(name)
3776 getjob(const char *name, int getctl)
3780 const char *err_msg = "%s: no such job";
3784 char *(*match)(const char *, const char *);
3799 if (c == '+' || c == '%') {
3801 err_msg = "No current job";
3807 err_msg = "No previous job";
3817 if (num > 0 && num <= njobs) {
3818 jp = jobtab + num - 1;
3833 if (match(jp->ps[0].ps_cmd, p)) {
3837 err_msg = "%s: ambiguous";
3847 err_msg = "job %s not created under job control";
3848 if (getctl && jp->jobctl == 0)
3853 ash_msg_and_raise_error(err_msg, name);
3857 * Mark a job structure as unused.
3860 freejob(struct job *jp)
3862 struct procstat *ps;
3866 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3867 if (ps->ps_cmd != nullstr)
3870 if (jp->ps != &jp->ps0)
3873 set_curjob(jp, CUR_DELETE);
3879 xtcsetpgrp(int fd, pid_t pgrp)
3881 if (tcsetpgrp(fd, pgrp))
3882 ash_msg_and_raise_perror("can't set tty process group");
3886 * Turn job control on and off.
3888 * Note: This code assumes that the third arg to ioctl is a character
3889 * pointer, which is true on Berkeley systems but not System V. Since
3890 * System V doesn't have job control yet, this isn't a problem now.
3892 * Called with interrupts off.
3900 if (on == doing_jobctl || rootshell == 0)
3904 ofd = fd = open(_PATH_TTY, O_RDWR);
3906 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3907 * That sometimes helps to acquire controlling tty.
3908 * Obviously, a workaround for bugs when someone
3909 * failed to provide a controlling tty to bash! :) */
3915 /* fd is a tty at this point */
3916 fd = fcntl(fd, F_DUPFD, 10);
3917 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
3920 goto out; /* F_DUPFD failed */
3921 close_on_exec_on(fd);
3922 while (1) { /* while we are in the background */
3923 pgrp = tcgetpgrp(fd);
3926 ash_msg("can't access tty; job control turned off");
3930 if (pgrp == getpgrp())
3941 xtcsetpgrp(fd, pgrp);
3943 /* turning job control off */
3946 /* was xtcsetpgrp, but this can make exiting ash
3947 * loop forever if pty is already deleted */
3948 tcsetpgrp(fd, pgrp);
3962 static int FAST_FUNC
3963 killcmd(int argc, char **argv)
3965 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3968 if (argv[i][0] == '%') {
3970 * "kill %N" - job kill
3971 * Converting to pgrp / pid kill
3977 jp = getjob(argv[i], 0);
3979 * In jobs started under job control, we signal
3980 * entire process group by kill -PGRP_ID.
3981 * This happens, f.e., in interactive shell.
3983 * Otherwise, we signal each child via
3984 * kill PID1 PID2 PID3.
3986 * sh -c 'sleep 1|sleep 1 & kill %1'
3987 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3988 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3990 n = jp->nprocs; /* can't be 0 (I hope) */
3993 dst = alloca(n * sizeof(int)*4);
3995 for (j = 0; j < n; j++) {
3996 struct procstat *ps = &jp->ps[j];
3997 /* Skip non-running and not-stopped members
3998 * (i.e. dead members) of the job
4000 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
4003 * kill_main has matching code to expect
4004 * leading space. Needed to not confuse
4005 * negative pids with "kill -SIGNAL_NO" syntax
4007 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
4011 } while (argv[++i]);
4013 return kill_main(argc, argv);
4017 showpipe(struct job *jp /*, FILE *out*/)
4019 struct procstat *ps;
4020 struct procstat *psend;
4022 psend = jp->ps + jp->nprocs;
4023 for (ps = jp->ps + 1; ps < psend; ps++)
4024 printf(" | %s", ps->ps_cmd);
4025 newline_and_flush(stdout);
4026 flush_stdout_stderr();
4031 restartjob(struct job *jp, int mode)
4033 struct procstat *ps;
4039 if (jp->state == JOBDONE)
4041 jp->state = JOBRUNNING;
4042 pgid = jp->ps[0].ps_pid;
4043 if (mode == FORK_FG) {
4045 xtcsetpgrp(ttyfd, pgid);
4047 killpg(pgid, SIGCONT);
4051 if (WIFSTOPPED(ps->ps_status)) {
4057 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
4062 static int FAST_FUNC
4063 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
4069 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
4073 jp = getjob(*argv, 1);
4074 if (mode == FORK_BG) {
4075 set_curjob(jp, CUR_RUNNING);
4076 printf("[%d] ", jobno(jp));
4078 out1str(jp->ps[0].ps_cmd);
4079 showpipe(jp /*, stdout*/);
4080 retval = restartjob(jp, mode);
4081 } while (*argv && *++argv);
4087 sprint_status48(char *s, int status, int sigonly)
4093 if (!WIFEXITED(status)) {
4095 if (WIFSTOPPED(status))
4096 st = WSTOPSIG(status);
4099 st = WTERMSIG(status);
4101 if (st == SIGINT || st == SIGPIPE)
4104 if (WIFSTOPPED(status))
4109 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
4110 col = fmtstr(s, 32, strsignal(st));
4111 if (WCOREDUMP(status)) {
4112 strcpy(s + col, " (core dumped)");
4113 col += sizeof(" (core dumped)")-1;
4115 } else if (!sigonly) {
4116 st = WEXITSTATUS(status);
4117 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
4124 wait_block_or_sig(int *status)
4131 /* Poll all children for changes in their state */
4133 /* if job control is active, accept stopped processes too */
4134 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
4136 break; /* Error (e.g. EINTR, ECHILD) or pid */
4138 /* Children exist, but none are ready. Sleep until interesting signal */
4141 sigprocmask(SIG_SETMASK, &mask, &mask);
4142 while (!got_sigchld && !pending_sig)
4144 sigprocmask(SIG_SETMASK, &mask, NULL);
4145 #else /* unsafe: a signal can set pending_sig after check, but before pause() */
4146 while (!got_sigchld && !pending_sig)
4150 /* If it was SIGCHLD, poll children again */
4151 } while (got_sigchld);
4156 #define DOWAIT_NONBLOCK 0
4157 #define DOWAIT_BLOCK 1
4158 #define DOWAIT_BLOCK_OR_SIG 2
4161 dowait(int block, struct job *job)
4166 struct job *thisjob = NULL;
4168 TRACE(("dowait(0x%x) called\n", block));
4170 /* It's wrong to call waitpid() outside of INT_OFF region:
4171 * signal can arrive just after syscall return and handler can
4172 * longjmp away, losing stop/exit notification processing.
4173 * Thus, for "jobs" builtin, and for waiting for a fg job,
4174 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
4176 * However, for "wait" builtin it is wrong to simply call waitpid()
4177 * in INT_OFF region: "wait" needs to wait for any running job
4178 * to change state, but should exit on any trap too.
4179 * In INT_OFF region, a signal just before syscall entry can set
4180 * pending_sig variables, but we can't check them, and we would
4181 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
4183 * Because of this, we run inside INT_OFF, but use a special routine
4184 * which combines waitpid() and sigsuspend().
4185 * This is the reason why we need to have a handler for SIGCHLD:
4186 * SIG_DFL handler does not wake sigsuspend().
4189 if (block == DOWAIT_BLOCK_OR_SIG) {
4190 pid = wait_block_or_sig(&status);
4193 if (block == DOWAIT_NONBLOCK)
4194 wait_flags = WNOHANG;
4195 /* if job control is active, accept stopped processes too */
4197 wait_flags |= WUNTRACED;
4198 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4199 pid = waitpid(-1, &status, wait_flags);
4201 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4202 pid, status, errno, strerror(errno)));
4207 for (jp = curjob; jp; jp = jp->prev_job) {
4209 struct procstat *ps;
4210 struct procstat *psend;
4211 if (jp->state == JOBDONE)
4215 psend = ps + jp->nprocs;
4217 if (ps->ps_pid == pid) {
4218 TRACE(("Job %d: changing status of proc %d "
4219 "from 0x%x to 0x%x\n",
4220 jobno(jp), pid, ps->ps_status, status));
4221 ps->ps_status = status;
4224 if (ps->ps_status == -1)
4225 jobstate = JOBRUNNING;
4227 if (jobstate == JOBRUNNING)
4229 if (WIFSTOPPED(ps->ps_status)) {
4230 jp->stopstatus = ps->ps_status;
4231 jobstate = JOBSTOPPED;
4234 } while (++ps < psend);
4238 /* Found the job where one of its processes changed its state.
4239 * Is there at least one live and running process in this job? */
4240 if (jobstate != JOBRUNNING) {
4241 /* No. All live processes in the job are stopped
4242 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4244 thisjob->changed = 1;
4245 if (thisjob->state != jobstate) {
4246 TRACE(("Job %d: changing state from %d to %d\n",
4247 jobno(thisjob), thisjob->state, jobstate));
4248 thisjob->state = jobstate;
4250 if (jobstate == JOBSTOPPED)
4251 set_curjob(thisjob, CUR_STOPPED);
4257 /* The process wasn't found in job list */
4259 if (!WIFSTOPPED(status))
4265 if (thisjob && thisjob == job) {
4269 len = sprint_status48(s, status, 1);
4281 showjob(struct job *jp, int mode)
4283 struct procstat *ps;
4284 struct procstat *psend;
4287 char s[16 + 16 + 48];
4288 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4292 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4293 /* just output process (group) id of pipeline */
4294 fprintf(out, "%d\n", ps->ps_pid);
4298 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4303 else if (curjob && jp == curjob->prev_job)
4306 if (mode & SHOW_PIDS)
4307 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4309 psend = ps + jp->nprocs;
4311 if (jp->state == JOBRUNNING) {
4312 strcpy(s + col, "Running");
4313 col += sizeof("Running") - 1;
4315 int status = psend[-1].ps_status;
4316 if (jp->state == JOBSTOPPED)
4317 status = jp->stopstatus;
4318 col += sprint_status48(s + col, status, 0);
4320 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4322 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4323 * or prints several "PID | <cmdN>" lines,
4324 * depending on SHOW_PIDS bit.
4325 * We do not print status of individual processes
4326 * between PID and <cmdN>. bash does it, but not very well:
4327 * first line shows overall job status, not process status,
4328 * making it impossible to know 1st process status.
4332 /* for each process */
4335 if (mode & SHOW_PIDS)
4336 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4338 fprintf(out, "%s%*c%s%s",
4340 33 - col >= 0 ? 33 - col : 0, ' ',
4341 ps == jp->ps ? "" : "| ",
4344 } while (++ps != psend);
4345 newline_and_flush(out);
4349 if (jp->state == JOBDONE) {
4350 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4356 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4357 * statuses have changed since the last call to showjobs.
4364 TRACE(("showjobs(0x%x) called\n", mode));
4366 /* Handle all finished jobs */
4367 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4370 for (jp = curjob; jp; jp = jp->prev_job) {
4371 if (!(mode & SHOW_CHANGED) || jp->changed) {
4377 static int FAST_FUNC
4378 jobscmd(int argc UNUSED_PARAM, char **argv)
4383 while ((m = nextopt("lp")) != '\0') {
4387 mode |= SHOW_ONLY_PGID;
4393 showjob(getjob(*argv, 0), mode);
4403 /* Called only on finished or stopped jobs (no members are running) */
4405 getstatus(struct job *job)
4409 struct procstat *ps;
4411 /* Fetch last member's status */
4412 ps = job->ps + job->nprocs - 1;
4413 status = ps->ps_status;
4415 /* "set -o pipefail" mode: use last _nonzero_ status */
4416 while (status == 0 && --ps >= job->ps)
4417 status = ps->ps_status;
4420 retval = WEXITSTATUS(status);
4421 if (!WIFEXITED(status)) {
4423 retval = WSTOPSIG(status);
4424 if (!WIFSTOPPED(status))
4427 /* XXX: limits number of signals */
4428 retval = WTERMSIG(status);
4430 if (retval == SIGINT)
4436 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4437 jobno(job), job->nprocs, status, retval));
4441 static int FAST_FUNC
4442 waitcmd(int argc UNUSED_PARAM, char **argv)
4453 /* wait for all jobs */
4457 if (!jp) /* no running procs */
4459 if (jp->state == JOBRUNNING)
4465 * "When bash is waiting for an asynchronous command via
4466 * the wait builtin, the reception of a signal for which a trap
4467 * has been set will cause the wait builtin to return immediately
4468 * with an exit status greater than 128, immediately after which
4469 * the trap is executed."
4471 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4472 /* if child sends us a signal *and immediately exits*,
4473 * dowait() returns pid > 0. Check this case,
4474 * not "if (dowait() < 0)"!
4483 if (**argv != '%') {
4484 pid_t pid = number(*argv);
4489 if (job->ps[job->nprocs - 1].ps_pid == pid)
4491 job = job->prev_job;
4494 job = getjob(*argv, 0);
4496 /* loop until process terminated or stopped */
4497 while (job->state == JOBRUNNING) {
4498 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4503 retval = getstatus(job);
4510 retval = 128 + pending_sig;
4519 struct job *jp, *jq;
4521 len = njobs * sizeof(*jp);
4523 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4525 offset = (char *)jp - (char *)jq;
4527 /* Relocate pointers */
4530 jq = (struct job *)((char *)jq + l);
4534 #define joff(p) ((struct job *)((char *)(p) + l))
4535 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4536 if (joff(jp)->ps == &jq->ps0)
4537 jmove(joff(jp)->ps);
4538 if (joff(jp)->prev_job)
4539 jmove(joff(jp)->prev_job);
4549 jp = (struct job *)((char *)jp + len);
4553 } while (--jq >= jp);
4558 * Return a new job structure.
4559 * Called with interrupts off.
4562 makejob(/*union node *node,*/ int nprocs)
4567 for (i = njobs, jp = jobtab; ; jp++) {
4574 if (jp->state != JOBDONE || !jp->waited)
4583 memset(jp, 0, sizeof(*jp));
4585 /* jp->jobctl is a bitfield.
4586 * "jp->jobctl |= doing_jobctl" likely to give awful code */
4590 jp->prev_job = curjob;
4595 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4597 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4604 * Return a string identifying a command (to be printed by the
4607 static char *cmdnextc;
4610 cmdputs(const char *s)
4612 static const char vstype[VSTYPE + 1][3] = {
4613 "", "}", "-", "+", "?", "=",
4614 "%", "%%", "#", "##"
4615 IF_BASH_SUBSTR(, ":")
4616 IF_BASH_PATTERN_SUBST(, "/", "//")
4619 const char *p, *str;
4623 unsigned char subtype = 0;
4627 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4629 while ((c = *p++) != '\0') {
4637 if ((subtype & VSTYPE) == VSLENGTH)
4643 str = "\"}" + !(quoted & 1);
4650 #if ENABLE_FEATURE_SH_MATH
4665 if ((subtype & VSTYPE) != VSNORMAL)
4667 str = vstype[subtype & VSTYPE];
4668 if (subtype & VSNUL)
4677 /* These can only happen inside quotes */
4683 // [1]+ Done true ${\$} <<=== BUG: ${\$} is not a valid way to write $$ (${$} would be ok)
4694 while ((c = *str++) != '\0') {
4697 } /* while *p++ not NUL */
4700 USTPUTC('"', nextc);
4706 /* cmdtxt() and cmdlist() call each other */
4707 static void cmdtxt(union node *n);
4710 cmdlist(union node *np, int sep)
4712 for (; np; np = np->narg.next) {
4716 if (sep && np->narg.next)
4722 cmdtxt(union node *n)
4725 struct nodelist *lp;
4736 lp = n->npipe.cmdlist;
4754 cmdtxt(n->nbinary.ch1);
4770 cmdtxt(n->nif.test);
4772 if (n->nif.elsepart) {
4773 cmdtxt(n->nif.ifpart);
4775 n = n->nif.elsepart;
4793 cmdtxt(n->nbinary.ch1);
4803 cmdputs(n->nfor.var);
4805 cmdlist(n->nfor.args, 1);
4810 cmdputs(n->narg.text);
4814 cmdlist(n->ncmd.args, 1);
4815 cmdlist(n->ncmd.redirect, 0);
4828 cmdputs(n->ncase.expr->narg.text);
4830 for (np = n->ncase.cases; np; np = np->nclist.next) {
4831 cmdtxt(np->nclist.pattern);
4833 cmdtxt(np->nclist.body);
4847 #if BASH_REDIR_OUTPUT
4862 cmdputs(utoa(n->nfile.fd));
4864 if (n->type == NTOFD || n->type == NFROMFD) {
4865 if (n->ndup.dupfd >= 0)
4866 cmdputs(utoa(n->ndup.dupfd));
4877 commandtext(union node *n)
4881 STARTSTACKSTR(cmdnextc);
4883 name = stackblock();
4884 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4885 return ckstrdup(name);
4890 * Fork off a subshell. If we are doing job control, give the subshell its
4891 * own process group. Jp is a job structure that the job is to be added to.
4892 * N is the command that will be evaluated by the child. Both jp and n may
4893 * be NULL. The mode parameter can be one of the following:
4894 * FORK_FG - Fork off a foreground process.
4895 * FORK_BG - Fork off a background process.
4896 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4897 * process group even if job control is on.
4899 * When job control is turned off, background processes have their standard
4900 * input redirected to /dev/null (except for the second and later processes
4903 * Called with interrupts off.
4906 * Clear traps on a fork.
4914 for (tp = trap; tp < &trap[NSIG]; tp++) {
4915 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4916 if (trap_ptr == trap)
4918 /* else: it "belongs" to trap_ptr vector, don't free */
4920 if ((tp - trap) != 0)
4921 setsignal(tp - trap);
4928 /* Lives far away from here, needed for forkchild */
4929 static void closescript(void);
4931 /* Called after fork(), in child */
4932 /* jp and n are NULL when called by openhere() for heredoc support */
4933 static NOINLINE void
4934 forkchild(struct job *jp, union node *n, int mode)
4938 TRACE(("Child shell %d\n", getpid()));
4942 /* man bash: "Non-builtin commands run by bash have signal handlers
4943 * set to the values inherited by the shell from its parent".
4944 * Do we do it correctly? */
4948 if (mode == FORK_NOJOB /* is it `xxx` ? */
4949 && n && n->type == NCMD /* is it single cmd? */
4950 /* && n->ncmd.args->type == NARG - always true? */
4951 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4952 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4953 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4955 TRACE(("Trap hack\n"));
4956 /* Awful hack for `trap` or $(trap).
4958 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4959 * contains an example where "trap" is executed in a subshell:
4961 * save_traps=$(trap)
4963 * eval "$save_traps"
4965 * Standard does not say that "trap" in subshell shall print
4966 * parent shell's traps. It only says that its output
4967 * must have suitable form, but then, in the above example
4968 * (which is not supposed to be normative), it implies that.
4970 * bash (and probably other shell) does implement it
4971 * (traps are reset to defaults, but "trap" still shows them),
4972 * but as a result, "trap" logic is hopelessly messed up:
4975 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4976 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4977 * # true | trap <--- trap is in subshell - no output (ditto)
4978 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4979 * trap -- 'echo Ho' SIGWINCH
4980 * # echo `(trap)` <--- in subshell in subshell - output
4981 * trap -- 'echo Ho' SIGWINCH
4982 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4983 * trap -- 'echo Ho' SIGWINCH
4985 * The rules when to forget and when to not forget traps
4986 * get really complex and nonsensical.
4988 * Our solution: ONLY bare $(trap) or `trap` is special.
4990 /* Save trap handler strings for trap builtin to print */
4991 trap_ptr = xmemdup(trap, sizeof(trap));
4992 /* Fall through into clearing traps */
4996 /* do job control only in root shell */
4998 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
5001 if (jp->nprocs == 0)
5004 pgrp = jp->ps[0].ps_pid;
5005 /* this can fail because we are doing it in the parent also */
5007 if (mode == FORK_FG)
5008 xtcsetpgrp(ttyfd, pgrp);
5013 if (mode == FORK_BG) {
5014 /* man bash: "When job control is not in effect,
5015 * asynchronous commands ignore SIGINT and SIGQUIT" */
5018 if (jp->nprocs == 0) {
5020 if (open(bb_dev_null, O_RDONLY) != 0)
5021 ash_msg_and_raise_perror("can't open '%s'", bb_dev_null);
5025 if (iflag) { /* why if iflag only? */
5030 * "In all cases, bash ignores SIGQUIT. Non-builtin
5031 * commands run by bash have signal handlers
5032 * set to the values inherited by the shell
5034 * Take care of the second rule: */
5038 if (n && n->type == NCMD
5039 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
5041 TRACE(("Job hack\n"));
5042 /* "jobs": we do not want to clear job list for it,
5043 * instead we remove only _its_ own_ job from job list.
5044 * This makes "jobs .... | cat" more useful.
5050 for (jp = curjob; jp; jp = jp->prev_job)
5055 /* Called after fork(), in parent */
5057 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
5060 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
5062 TRACE(("In parent shell: child = %d\n", pid));
5064 /* jp is NULL when called by openhere() for heredoc support */
5065 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
5071 if (mode != FORK_NOJOB && jp->jobctl) {
5074 if (jp->nprocs == 0)
5077 pgrp = jp->ps[0].ps_pid;
5078 /* This can fail because we are doing it in the child also */
5082 if (mode == FORK_BG) {
5083 backgndpid = pid; /* set $! */
5084 set_curjob(jp, CUR_RUNNING);
5087 struct procstat *ps = &jp->ps[jp->nprocs++];
5090 ps->ps_cmd = nullstr;
5092 if (doing_jobctl && n)
5093 ps->ps_cmd = commandtext(n);
5098 /* jp and n are NULL when called by openhere() for heredoc support */
5100 forkshell(struct job *jp, union node *n, int mode)
5104 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
5107 TRACE(("Fork failed, errno=%d", errno));
5110 ash_msg_and_raise_perror("can't fork");
5113 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
5114 forkchild(jp, n, mode);
5116 forkparent(jp, n, mode, pid);
5122 * Wait for job to finish.
5124 * Under job control we have the problem that while a child process
5125 * is running interrupts generated by the user are sent to the child
5126 * but not to the shell. This means that an infinite loop started by
5127 * an interactive user may be hard to kill. With job control turned off,
5128 * an interactive user may place an interactive program inside a loop.
5129 * If the interactive program catches interrupts, the user doesn't want
5130 * these interrupts to also abort the loop. The approach we take here
5131 * is to have the shell ignore interrupt signals while waiting for a
5132 * foreground process to terminate, and then send itself an interrupt
5133 * signal if the child process was terminated by an interrupt signal.
5134 * Unfortunately, some programs want to do a bit of cleanup and then
5135 * exit on interrupt; unless these processes terminate themselves by
5136 * sending a signal to themselves (instead of calling exit) they will
5137 * confuse this approach.
5139 * Called with interrupts off.
5142 waitforjob(struct job *jp)
5146 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
5149 while (jp->state == JOBRUNNING) {
5150 /* In non-interactive shells, we _can_ get
5151 * a keyboard signal here and be EINTRed,
5152 * but we just loop back, waiting for command to complete.
5155 * "If bash is waiting for a command to complete and receives
5156 * a signal for which a trap has been set, the trap
5157 * will not be executed until the command completes."
5159 * Reality is that even if trap is not set, bash
5160 * will not act on the signal until command completes.
5161 * Try this. sleep5intoff.c:
5162 * #include <signal.h>
5163 * #include <unistd.h>
5166 * sigemptyset(&set);
5167 * sigaddset(&set, SIGINT);
5168 * sigaddset(&set, SIGQUIT);
5169 * sigprocmask(SIG_BLOCK, &set, NULL);
5173 * $ bash -c './sleep5intoff; echo hi'
5174 * ^C^C^C^C <--- pressing ^C once a second
5176 * $ bash -c './sleep5intoff; echo hi'
5177 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
5180 dowait(DOWAIT_BLOCK, jp);
5187 xtcsetpgrp(ttyfd, rootpid);
5188 restore_tty_if_stopped_or_signaled(jp);
5191 * This is truly gross.
5192 * If we're doing job control, then we did a TIOCSPGRP which
5193 * caused us (the shell) to no longer be in the controlling
5194 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
5195 * intuit from the subprocess exit status whether a SIGINT
5196 * occurred, and if so interrupt ourselves. Yuck. - mycroft
5198 if (jp->sigint) /* TODO: do the same with all signals */
5199 raise(SIGINT); /* ... by raise(jp->sig) instead? */
5201 if (jp->state == JOBDONE)
5208 * return 1 if there are stopped jobs, otherwise 0
5220 if (jp && jp->state == JOBSTOPPED) {
5221 out2str("You have stopped jobs.\n");
5231 * Code for dealing with input/output redirection.
5236 #define EMPTY -2 /* marks an unused slot in redirtab */
5237 #define CLOSED -1 /* marks a slot of previously-closed fd */
5240 * Handle here documents. Normally we fork off a process to write the
5241 * data to a pipe. If the document is short, we can stuff the data in
5242 * the pipe without forking.
5244 /* openhere needs this forward reference */
5245 static void expandhere(union node *arg, int fd);
5247 openhere(union node *redir)
5253 ash_msg_and_raise_perror("can't create pipe");
5254 if (redir->type == NHERE) {
5255 len = strlen(redir->nhere.doc->narg.text);
5256 if (len <= PIPE_BUF) {
5257 full_write(pip[1], redir->nhere.doc->narg.text, len);
5261 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5264 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5265 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5266 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5267 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5268 signal(SIGPIPE, SIG_DFL);
5269 if (redir->type == NHERE)
5270 full_write(pip[1], redir->nhere.doc->narg.text, len);
5272 expandhere(redir->nhere.doc, pip[1]);
5273 _exit(EXIT_SUCCESS);
5281 openredirect(union node *redir)
5287 switch (redir->nfile.type) {
5288 /* Can't happen, our single caller does this itself */
5294 return openhere(redir);
5297 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5298 * allocated space. Do it only when we know it is safe.
5300 fname = redir->nfile.expfname;
5302 switch (redir->nfile.type) {
5308 f = open(fname, O_RDONLY);
5313 f = open(fname, O_RDWR|O_CREAT, 0666);
5318 #if BASH_REDIR_OUTPUT
5321 /* Take care of noclobber mode. */
5323 if (stat(fname, &sb) < 0) {
5324 f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5327 } else if (!S_ISREG(sb.st_mode)) {
5328 f = open(fname, O_WRONLY, 0666);
5331 if (fstat(f, &sb) < 0 && S_ISREG(sb.st_mode)) {
5344 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5349 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5357 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5359 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5363 * Copy a file descriptor to be >= 10. Throws exception on error.
5371 newfd = fcntl(from, F_DUPFD, 10);
5372 err = newfd < 0 ? errno : 0;
5375 ash_msg_and_raise_perror("%d", from);
5377 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5383 dup2_or_raise(int from, int to)
5387 newfd = (from != to) ? dup2(from, to) : to;
5389 /* Happens when source fd is not open: try "echo >&99" */
5390 ash_msg_and_raise_perror("%d", from);
5395 fcntl_F_DUPFD(int fd, int avoid_fd)
5399 newfd = fcntl(fd, F_DUPFD, avoid_fd + 1);
5409 xdup_CLOEXEC_and_close(int fd, int avoid_fd)
5413 newfd = fcntl(fd, F_DUPFD, avoid_fd + 1);
5419 /* fd was not open? */
5422 ash_msg_and_raise_perror("%d", newfd);
5424 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5429 /* Struct def and variable are moved down to the first usage site */
5435 struct redirtab *next;
5437 struct squirrel two_fd[];
5439 #define redirlist (G_var.redirlist)
5442 add_squirrel_closed(struct redirtab *sq, int fd)
5449 for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
5450 /* If we collide with an already moved fd... */
5451 if (fd == sq->two_fd[i].orig_fd) {
5453 * "echo 3>FILE 3>&- 3>FILE"
5454 * "echo 3>&- 3>FILE"
5455 * No need for last redirect to insert
5456 * another "need to close 3" indicator.
5458 TRACE(("redirect_fd %d: already moved or closed\n", fd));
5462 TRACE(("redirect_fd %d: previous fd was closed\n", fd));
5463 sq->two_fd[i].orig_fd = fd;
5464 sq->two_fd[i].moved_to = CLOSED;
5468 save_fd_on_redirect(int fd, int avoid_fd, struct redirtab *sq)
5472 if (avoid_fd < 9) /* the important case here is that it can be -1 */
5477 /* Testcase: "ls -l /proc/$$/fd 10>&-" should work */
5478 ttyfd = xdup_CLOEXEC_and_close(ttyfd, avoid_fd);
5479 TRACE(("redirect_fd %d: matches ttyfd, moving it to %d\n", fd, ttyfd));
5480 return 1; /* "we closed fd" */
5483 /* Are we called from redirect(0)? E.g. redirect
5484 * in a forked child. No need to save fds,
5485 * we aren't going to use them anymore, ok to trash.
5490 /* If this one of script's fds? */
5492 struct parsefile *pf = g_parsefile;
5494 /* We skip fd == 0 case because of the following:
5495 * $ ash # running ash interactively
5497 * and in script.sh: "exec 9>&0".
5498 * Even though top-level pf_fd _is_ 0,
5499 * it's still ok to use it: "read" builtin uses it,
5500 * why should we cripple "exec" builtin?
5502 if (fd == pf->pf_fd) {
5503 pf->pf_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
5504 return 1; /* "we closed fd" */
5510 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
5512 /* First: do we collide with some already moved fds? */
5513 for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
5514 /* If we collide with an already moved fd... */
5515 if (fd == sq->two_fd[i].moved_to) {
5516 new_fd = fcntl_F_DUPFD(fd, avoid_fd);
5517 sq->two_fd[i].moved_to = new_fd;
5518 TRACE(("redirect_fd %d: already busy, moving to %d\n", fd, new_fd));
5519 if (new_fd < 0) /* what? */
5521 return 0; /* "we did not close fd" */
5523 if (fd == sq->two_fd[i].orig_fd) {
5524 /* Example: echo Hello >/dev/null 1>&2 */
5525 TRACE(("redirect_fd %d: already moved\n", fd));
5526 return 0; /* "we did not close fd" */
5530 /* If this fd is open, we move and remember it; if it's closed, new_fd = CLOSED (-1) */
5531 new_fd = fcntl_F_DUPFD(fd, avoid_fd);
5532 TRACE(("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, new_fd));
5536 /* new_fd = CLOSED; - already is -1 */
5538 sq->two_fd[i].moved_to = new_fd;
5539 sq->two_fd[i].orig_fd = fd;
5541 /* if we move stderr, let "set -x" code know */
5542 if (fd == preverrout_fd)
5543 preverrout_fd = new_fd;
5545 return 0; /* "we did not close fd" */
5549 internally_opened_fd(int fd, struct redirtab *sq)
5556 /* If this one of script's fds? */
5558 struct parsefile *pf = g_parsefile;
5560 if (fd == pf->pf_fd)
5566 if (sq) for (i = 0; i < sq->pair_count && sq->two_fd[i].orig_fd != EMPTY; i++) {
5567 if (fd == sq->two_fd[i].moved_to)
5574 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5575 * old file descriptors are stashed away so that the redirection can be
5576 * undone by calling popredir.
5578 /* flags passed to redirect */
5579 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5581 redirect(union node *redir, int flags)
5583 struct redirtab *sv;
5590 if (flags & REDIR_PUSH)
5598 fd = redir->nfile.fd;
5599 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5600 //bb_error_msg("doing %d > %d", fd, newfd);
5601 newfd = redir->ndup.dupfd;
5604 newfd = openredirect(redir); /* always >= 0 */
5606 /* open() gave us precisely the fd we wanted.
5607 * This means that this fd was not busy
5608 * (not opened to anywhere).
5609 * Remember to close it on restore:
5611 add_squirrel_closed(sv, fd);
5620 /* if "N>FILE": move newfd to fd */
5621 /* if "N>&M": dup newfd to fd */
5622 /* if "N>&-": close fd (newfd is -1) */
5624 IF_BASH_REDIR_OUTPUT(redirect_more:)
5626 closed = save_fd_on_redirect(fd, /*avoid:*/ newfd, sv);
5628 /* "N>&-" means "close me" */
5630 /* ^^^ optimization: saving may already
5631 * have closed it. If not... */
5635 /* if newfd is a script fd or saved fd, simulate EBADF */
5636 if (internally_opened_fd(newfd, sv)) {
5638 ash_msg_and_raise_perror("%d", newfd);
5640 dup2_or_raise(newfd, fd);
5641 if (close_fd >= 0) /* "N>FILE" or ">&FILE" or heredoc? */
5643 #if BASH_REDIR_OUTPUT
5644 if (redir->nfile.type == NTO2 && fd == 1) {
5645 /* ">&FILE". we already redirected to 1, now copy 1 to 2 */
5653 } while ((redir = redir->nfile.next) != NULL);
5656 //dash:#define REDIR_SAVEFD2 03 /* set preverrout */
5657 #define REDIR_SAVEFD2 0
5658 // dash has a bug: since REDIR_SAVEFD2=3 and REDIR_PUSH=1, this test
5659 // triggers for pure REDIR_PUSH too. Thus, this is done almost always,
5660 // not only for calls with flags containing REDIR_SAVEFD2.
5661 // We do this unconditionally (see save_fd_on_redirect()).
5662 //if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5663 // preverrout_fd = copied_fd2;
5667 redirectsafe(union node *redir, int flags)
5670 volatile int saveint;
5671 struct jmploc *volatile savehandler = exception_handler;
5672 struct jmploc jmploc;
5675 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5676 err = setjmp(jmploc.loc); /* was = setjmp(jmploc.loc) * 2; */
5678 exception_handler = &jmploc;
5679 redirect(redir, flags);
5681 exception_handler = savehandler;
5682 if (err && exception_type != EXERROR)
5683 longjmp(exception_handler->loc, 1);
5684 RESTORE_INT(saveint);
5688 static struct redirtab*
5689 pushredir(union node *redir)
5691 struct redirtab *sv;
5700 #if BASH_REDIR_OUTPUT
5701 if (redir->nfile.type == NTO2)
5704 redir = redir->nfile.next;
5707 sv = ckzalloc(sizeof(*sv) + i * sizeof(sv->two_fd[0]));
5710 sv->two_fd[i].orig_fd = sv->two_fd[i].moved_to = EMPTY;
5711 sv->next = redirlist;
5717 * Undo the effects of the last redirection.
5722 struct redirtab *rp;
5725 if (redirlist == NULL)
5729 for (i = 0; i < rp->pair_count; i++) {
5730 int fd = rp->two_fd[i].orig_fd;
5731 int copy = rp->two_fd[i].moved_to;
5732 if (copy == CLOSED) {
5737 if (copy != EMPTY) {
5740 dup2_or_raise(copy, fd);
5745 redirlist = rp->next;
5751 unwindredir(struct redirtab *stop)
5753 while (redirlist != stop)
5754 popredir(/*drop:*/ 0);
5758 /* ============ Routines to expand arguments to commands
5760 * We have to deal with backquotes, shell variables, and file metacharacters.
5763 #if ENABLE_FEATURE_SH_MATH
5765 ash_arith(const char *s)
5767 arith_state_t math_state;
5770 math_state.lookupvar = lookupvar;
5771 math_state.setvar = setvar0;
5772 //math_state.endofname = endofname;
5775 result = arith(&math_state, s);
5776 if (math_state.errmsg)
5777 ash_msg_and_raise_error(math_state.errmsg);
5784 # if ENABLE_FEATURE_SH_MATH
5785 static int substr_atoi(const char *s)
5787 arith_t t = ash_arith(s);
5788 if (sizeof(t) > sizeof(int)) {
5789 /* clamp very large or very large negative nums for ${v:N:M}:
5790 * else "${v:0:0x100000001}" would work as "${v:0:1}"
5800 # define substr_atoi(s) number(s)
5807 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5808 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5809 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5810 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5811 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5812 * POSIX says for this case:
5813 * Pathname expansion shall not be performed on the word by a
5814 * non-interactive shell; an interactive shell may perform it, but shall
5815 * do so only when the expansion would result in one word.
5816 * Currently, our code complies to the above rule by never globbing
5817 * redirection filenames.
5818 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5819 * (this means that on a typical Linux distro, bash almost always
5820 * performs globbing, and thus diverges from what we do).
5822 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5823 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5824 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5825 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5826 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5830 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5831 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5832 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5833 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5835 /* Add CTLESC when necessary. */
5836 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT)
5837 /* Do not skip NUL characters. */
5838 #define QUOTES_KEEPNUL EXP_TILDE
5841 * Structure specifying which parts of the string should be searched
5842 * for IFS characters.
5845 struct ifsregion *next; /* next region in list */
5846 int begoff; /* offset of start of region */
5847 int endoff; /* offset of end of region */
5848 int nulonly; /* search for nul bytes only */
5852 struct strlist *list;
5853 struct strlist **lastp;
5856 /* output of current string */
5857 static char *expdest;
5858 /* list of back quote expressions */
5859 static struct nodelist *argbackq;
5860 /* first struct in list of ifs regions */
5861 static struct ifsregion ifsfirst;
5862 /* last struct in list */
5863 static struct ifsregion *ifslastp;
5864 /* holds expanded arg list */
5865 static struct arglist exparg;
5869 * cvtnum() is used even if math support is off (to prepare $? values and such).
5876 /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
5877 len = sizeof(arith_t) * 3;
5878 /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
5879 if (sizeof(arith_t) < 4) len += 2;
5881 expdest = makestrspace(len, expdest);
5882 len = fmtstr(expdest, len, ARITH_FMT, num);
5883 STADJUST(len, expdest);
5888 * Break the argument string into pieces based upon IFS and add the
5889 * strings to the argument list. The regions of the string to be
5890 * searched for IFS characters have been stored by recordregion.
5893 ifsbreakup(char *string, struct arglist *arglist)
5895 struct ifsregion *ifsp;
5900 const char *ifs, *realifs;
5905 if (ifslastp != NULL) {
5908 realifs = ifsset() ? ifsval() : defifs;
5911 p = string + ifsp->begoff;
5912 nulonly = ifsp->nulonly;
5913 ifs = nulonly ? nullstr : realifs;
5915 while (p < string + ifsp->endoff) {
5917 if ((unsigned char)*p == CTLESC)
5919 if (!strchr(ifs, *p)) {
5924 ifsspc = (strchr(defifs, *p) != NULL);
5925 /* Ignore IFS whitespace at start */
5926 if (q == start && ifsspc) {
5932 sp = stzalloc(sizeof(*sp));
5934 *arglist->lastp = sp;
5935 arglist->lastp = &sp->next;
5939 if (p >= string + ifsp->endoff) {
5943 if ((unsigned char)*p == CTLESC)
5945 if (strchr(ifs, *p) == NULL) {
5949 if (strchr(defifs, *p) == NULL) {
5964 } while (ifsp != NULL);
5973 sp = stzalloc(sizeof(*sp));
5975 *arglist->lastp = sp;
5976 arglist->lastp = &sp->next;
5982 struct ifsregion *p = ifsfirst.next;
5989 struct ifsregion *ifsp;
5994 ifsfirst.next = NULL;
6001 esclen(const char *start, const char *p)
6005 while (p > start && (unsigned char)*--p == CTLESC) {
6012 * Remove any CTLESC characters from a string.
6014 #if !BASH_PATTERN_SUBST
6015 #define rmescapes(str, flag, slash_position) \
6016 rmescapes(str, flag)
6019 rmescapes(char *str, int flag, int *slash_position)
6021 static const char qchars[] ALIGN1 = {
6022 IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
6026 unsigned protect_against_glob;
6029 p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash_position));
6035 if (flag & RMESCAPE_ALLOC) {
6036 size_t len = p - str;
6037 size_t fulllen = len + strlen(p) + 1;
6039 if (flag & RMESCAPE_GROW) {
6040 int strloc = str - (char *)stackblock();
6041 r = makestrspace(fulllen, expdest);
6042 /* p and str may be invalidated by makestrspace */
6043 str = (char *)stackblock() + strloc;
6045 } else if (flag & RMESCAPE_HEAP) {
6046 r = ckmalloc(fulllen);
6048 r = stalloc(fulllen);
6052 q = (char *)mempcpy(q, str, len);
6057 globbing = flag & RMESCAPE_GLOB;
6058 protect_against_glob = globbing;
6060 if ((unsigned char)*p == CTLQUOTEMARK) {
6061 // Note: both inquotes and protect_against_glob only affect whether
6062 // CTLESC,<ch> gets converted to <ch> or to \<ch>
6063 inquotes = ~inquotes;
6065 protect_against_glob = globbing;
6068 if ((unsigned char)*p == CTLESC) {
6072 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
6074 if (protect_against_glob) {
6076 * We used to trust glob() and fnmatch() to eat
6077 * superfluous escapes (\z where z has no
6078 * special meaning anyway). But this causes
6079 * bugs such as string of one greek letter rho
6080 * (unicode-encoded as two bytes "cf,81")
6081 * getting encoded as "cf,CTLESC,81"
6082 * and here, converted to "cf,\,81" -
6083 * which does not go well with some flavors
6084 * of fnmatch() in unicode locales
6085 * (for example, glibc <= 2.22).
6087 * Lets add "\" only on the chars which need it.
6088 * Testcases for less obvious chars are shown.
6093 || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
6094 || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
6095 || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
6096 || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
6097 /* Some libc support [^negate], that's why "^" also needs love */
6098 || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
6103 } else if (*p == '\\' && !inquotes) {
6104 /* naked back slash */
6105 protect_against_glob = 0;
6108 #if BASH_PATTERN_SUBST
6109 else if (slash_position && p == str + *slash_position) {
6110 /* stop handling globbing */
6112 *slash_position = q - r;
6113 slash_position = NULL;
6116 protect_against_glob = globbing;
6121 if (flag & RMESCAPE_GROW) {
6123 STADJUST(q - r + 1, expdest);
6127 #define pmatch(a, b) !fnmatch((a), (b), 0)
6130 * Prepare a pattern for a expmeta (internal glob(3)) call.
6132 * Returns an stalloced string.
6135 preglob(const char *pattern, int flag)
6137 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB, NULL);
6141 * Put a string on the stack.
6144 memtodest(const char *p, size_t len, int syntax, int quotes)
6151 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
6154 unsigned char c = *p++;
6156 if (quotes & QUOTES_ESC) {
6157 int n = SIT(c, syntax);
6159 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
6166 } else if (!(quotes & QUOTES_KEEPNUL))
6175 strtodest(const char *p, int syntax, int quotes)
6177 size_t len = strlen(p);
6178 memtodest(p, len, syntax, quotes);
6183 * Record the fact that we have to scan this region of the
6184 * string for IFS characters.
6187 recordregion(int start, int end, int nulonly)
6189 struct ifsregion *ifsp;
6191 if (ifslastp == NULL) {
6195 ifsp = ckzalloc(sizeof(*ifsp));
6196 /*ifsp->next = NULL; - ckzalloc did it */
6197 ifslastp->next = ifsp;
6201 ifslastp->begoff = start;
6202 ifslastp->endoff = end;
6203 ifslastp->nulonly = nulonly;
6207 removerecordregions(int endoff)
6209 if (ifslastp == NULL)
6212 if (ifsfirst.endoff > endoff) {
6213 while (ifsfirst.next) {
6214 struct ifsregion *ifsp;
6216 ifsp = ifsfirst.next->next;
6217 free(ifsfirst.next);
6218 ifsfirst.next = ifsp;
6221 if (ifsfirst.begoff > endoff) {
6224 ifslastp = &ifsfirst;
6225 ifsfirst.endoff = endoff;
6230 ifslastp = &ifsfirst;
6231 while (ifslastp->next && ifslastp->next->begoff < endoff)
6232 ifslastp = ifslastp->next;
6233 while (ifslastp->next) {
6234 struct ifsregion *ifsp;
6236 ifsp = ifslastp->next->next;
6237 free(ifslastp->next);
6238 ifslastp->next = ifsp;
6241 if (ifslastp->endoff > endoff)
6242 ifslastp->endoff = endoff;
6246 exptilde(char *startp, char *p, int flags)
6252 int quotes = flags & QUOTES_ESC;
6256 while ((c = *++p) != '\0') {
6263 if (flags & EXP_VARTILDE)
6273 if (*name == '\0') {
6274 home = lookupvar("HOME");
6276 pw = getpwnam(name);
6281 if (!home || !*home)
6284 strtodest(home, SQSYNTAX, quotes);
6292 * Execute a command inside back quotes. If it's a builtin command, we
6293 * want to save its output in a block obtained from malloc. Otherwise
6294 * we fork off a subprocess and get the output of the command via a pipe.
6295 * Should be called with interrupts off.
6297 struct backcmd { /* result of evalbackcmd */
6298 int fd; /* file descriptor to read from */
6299 int nleft; /* number of chars in buffer */
6300 char *buf; /* buffer */
6301 struct job *jp; /* job structure for command */
6304 /* These forward decls are needed to use "eval" code for backticks handling: */
6305 /* flags in argument to evaltree */
6306 #define EV_EXIT 01 /* exit after evaluating tree */
6307 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
6308 static int evaltree(union node *, int);
6310 /* An evaltree() which is known to never return.
6311 * Used to use an alias:
6312 * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
6313 * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
6315 static ALWAYS_INLINE NORETURN void
6316 evaltreenr(union node *n, int flags)
6319 bb_unreachable(abort());
6323 static void FAST_FUNC
6324 evalbackcmd(union node *n, struct backcmd *result)
6338 ash_msg_and_raise_perror("can't create pipe");
6339 jp = makejob(/*n,*/ 1);
6340 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6346 dup2_or_raise(pip[1], 1);
6349 /* TODO: eflag clearing makes the following not abort:
6350 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6351 * which is what bash does (unless it is in POSIX mode).
6352 * dash deleted "eflag = 0" line in the commit
6353 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6354 * [EVAL] Don't clear eflag in evalbackcmd
6355 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6359 evaltreenr(n, EV_EXIT);
6364 result->fd = pip[0];
6368 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6369 result->fd, result->buf, result->nleft, result->jp));
6373 * Expand stuff in backwards quotes.
6376 expbackq(union node *cmd, int flag)
6384 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6385 struct stackmark smark;
6388 startloc = expdest - (char *)stackblock();
6389 pushstackmark(&smark, startloc);
6390 evalbackcmd(cmd, &in);
6391 popstackmark(&smark);
6398 memtodest(p, i, syntax, flag & QUOTES_ESC);
6402 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6403 TRACE(("expbackq: read returns %d\n", i));
6412 back_exitstatus = waitforjob(in.jp);
6416 /* Eat all trailing newlines */
6418 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6422 if (!(flag & EXP_QUOTED))
6423 recordregion(startloc, dest - (char *)stackblock(), 0);
6424 TRACE(("evalbackq: size:%d:'%.*s'\n",
6425 (int)((dest - (char *)stackblock()) - startloc),
6426 (int)((dest - (char *)stackblock()) - startloc),
6427 stackblock() + startloc));
6430 #if ENABLE_FEATURE_SH_MATH
6432 * Expand arithmetic expression. Backup to start of expression,
6433 * evaluate, place result in (backed up) result, adjust string position.
6445 * This routine is slightly over-complicated for
6446 * efficiency. Next we scan backwards looking for the
6447 * start of arithmetic.
6449 start = stackblock();
6456 while ((unsigned char)*p != CTLARI) {
6460 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6465 esc = esclen(start, p);
6475 removerecordregions(begoff);
6479 if (flag & QUOTES_ESC)
6480 rmescapes(p + 1, 0, NULL);
6482 len = cvtnum(ash_arith(p + 1));
6484 if (!(flag & EXP_QUOTED))
6485 recordregion(begoff, begoff + len, 0);
6489 /* argstr needs it */
6490 static char *evalvar(char *p, int flags);
6493 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6494 * characters to allow for further processing. Otherwise treat
6495 * $@ like $* since no splitting will be performed.
6498 argstr(char *p, int flags)
6500 static const char spclchars[] ALIGN1 = {
6508 #if ENABLE_FEATURE_SH_MATH
6513 const char *reject = spclchars;
6514 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6519 if (!(flags & EXP_VARTILDE)) {
6521 } else if (flags & EXP_VARTILDE2) {
6526 if (flags & EXP_TILDE) {
6529 flags &= ~EXP_TILDE;
6533 p = exptilde(p, q, flags);
6536 startloc = expdest - (char *)stackblock();
6540 length += strcspn(p + length, reject);
6544 IF_FEATURE_SH_MATH(|| c == CTLENDARI)
6546 /* c == '=' || c == ':' || c == CTLENDARI */
6552 expdest = stack_nputstr(p, length, expdest);
6553 newloc = expdest - (char *)stackblock();
6554 if (breakall && !inquotes && newloc > startloc) {
6555 recordregion(startloc, newloc, 0);
6566 if (flags & EXP_VARTILDE2) {
6570 flags |= EXP_VARTILDE2;
6575 * sort of a hack - expand tildes in variable
6576 * assignments (after the first '=' and after ':'s).
6585 case CTLENDVAR: /* ??? */
6588 inquotes ^= EXP_QUOTED;
6589 /* "$@" syntax adherence hack */
6590 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6591 p = evalvar(p + 1, flags | inquotes) + 1;
6595 if (flags & QUOTES_ESC) {
6606 * Quoted parameter expansion pattern: remove quote
6607 * unless inside inner quotes or we have a literal
6610 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6611 EXP_QPAT && *p != '\\')
6616 TRACE(("argstr: evalvar('%s')\n", p));
6617 p = evalvar(p, flags | inquotes);
6618 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6621 expbackq(argbackq->n, flags | inquotes);
6622 argbackq = argbackq->next;
6624 #if ENABLE_FEATURE_SH_MATH
6627 expari(flags | inquotes);
6636 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6637 char *pattern, int quotes, int zero)
6646 const char *s = loc2;
6653 match = pmatch(pattern, s);
6658 if (quotes && (unsigned char)*loc == CTLESC)
6667 scanright(char *startp, char *rmesc, char *rmescend,
6668 char *pattern, int quotes, int match_at_start)
6670 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6671 int try2optimize = match_at_start;
6677 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6678 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6679 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6681 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6682 * and on each iteration they go back two/one char until they reach the beginning.
6683 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6685 /* TODO: document in what other circumstances we are called. */
6687 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6690 const char *s = loc2;
6691 if (match_at_start) {
6695 match = pmatch(pattern, s);
6696 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6700 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6702 /* Maybe we can optimize this:
6703 * if pattern ends with unescaped *, we can avoid checking
6704 * shorter strings: if "foo*" doesn't match "raw_value_of_v",
6705 * it won't match truncated "raw_value_of_" strings too.
6707 unsigned plen = strlen(pattern);
6708 /* Does it end with "*"? */
6709 if (plen != 0 && pattern[--plen] == '*') {
6710 /* "xxxx*" is not escaped */
6711 /* "xxx\*" is escaped */
6712 /* "xx\\*" is not escaped */
6713 /* "x\\\*" is escaped */
6715 while (plen != 0 && pattern[--plen] == '\\')
6718 break; /* ends with unescaped "*" */
6726 esc = esclen(startp, loc);
6737 static void varunset(const char *, const char *, const char *, int) NORETURN;
6739 varunset(const char *end, const char *var, const char *umsg, int varflags)
6745 msg = "parameter not set";
6747 if ((unsigned char)*end == CTLENDVAR) {
6748 if (varflags & VSNUL)
6754 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6758 subevalvar(char *p, char *varname, int strloc, int subtype,
6759 int startloc, int varflags, int flag)
6761 struct nodelist *saveargbackq = argbackq;
6762 int quotes = flag & QUOTES_ESC;
6765 char *rmesc, *rmescend;
6767 int amount, resetloc;
6769 IF_BASH_PATTERN_SUBST(int workloc;)
6770 IF_BASH_PATTERN_SUBST(int slash_pos;)
6771 IF_BASH_PATTERN_SUBST(char *repl;)
6773 char *(*scan)(char*, char*, char*, char*, int, int);
6775 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6776 // p, varname, strloc, subtype, startloc, varflags, quotes);
6778 #if BASH_PATTERN_SUBST
6779 /* For "${v/pattern/repl}", we must find the delimiter _before_
6780 * argstr() call expands possible variable references in pattern:
6781 * think about "v=a; a=a/; echo ${v/$a/r}" case.
6784 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6785 /* Find '/' and replace with NUL */
6788 /* Handle escaped slashes, e.g. "${v/\//_}" (they are CTLESC'ed by this point) */
6789 if (*repl == '\0') {
6797 if ((unsigned char)*repl == CTLESC && repl[1])
6803 argstr_flags = EXP_TILDE;
6804 if (subtype != VSASSIGN && subtype != VSQUESTION)
6805 argstr_flags |= (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE);
6806 argstr(p, argstr_flags);
6807 #if BASH_PATTERN_SUBST
6810 slash_pos = expdest - ((char *)stackblock() + strloc);
6811 STPUTC('/', expdest);
6812 argstr(repl + 1, argstr_flags);
6816 STPUTC('\0', expdest);
6817 argbackq = saveargbackq;
6818 startp = (char *)stackblock() + startloc;
6819 //bb_error_msg("str1:'%s'", (char *)stackblock() + strloc);
6823 setvar0(varname, startp);
6824 amount = startp - expdest;
6825 STADJUST(amount, expdest);
6829 varunset(p, varname, startp, varflags);
6834 int pos, len, orig_len;
6837 loc = str = stackblock() + strloc;
6839 /* Read POS in ${var:POS:LEN} */
6840 colon = strchr(loc, ':');
6841 if (colon) *colon = '\0';
6842 pos = substr_atoi(loc);
6843 if (colon) *colon = ':';
6845 /* Read LEN in ${var:POS:LEN} */
6846 len = str - startp - 1;
6847 /* *loc != '\0', guaranteed by parser */
6850 /* Adjust the length by the number of escapes */
6851 for (ptr = startp; ptr < (str - 1); ptr++) {
6852 if ((unsigned char)*ptr == CTLESC) {
6859 if (*loc++ == ':') {
6861 len = substr_atoi(loc);
6863 /* Skip POS in ${var:POS:LEN} */
6865 while (*loc && *loc != ':')
6868 len = substr_atoi(loc);
6871 /* ${VAR:$((-n)):l} starts n chars from the end */
6872 pos = orig_len + pos;
6874 if ((unsigned)pos >= orig_len) {
6875 /* apart from obvious ${VAR:999999:l},
6876 * covers ${VAR:$((-9999999)):l} - result is ""
6883 /* ${VAR:N:-M} sets LEN to strlen()-M */
6884 len = (orig_len - pos) + len;
6886 if ((unsigned)len > (orig_len - pos))
6887 len = orig_len - pos;
6889 for (str = startp; pos; str++, pos--) {
6890 if (quotes && (unsigned char)*str == CTLESC)
6893 for (loc = startp; len; len--) {
6894 if (quotes && (unsigned char)*str == CTLESC)
6899 amount = loc - expdest;
6900 STADJUST(amount, expdest);
6903 #endif /* BASH_SUBSTR */
6906 resetloc = expdest - (char *)stackblock();
6908 #if BASH_PATTERN_SUBST
6911 /* We'll comeback here if we grow the stack while handling
6912 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6913 * stack will need rebasing, and we'll need to remove our work
6919 amount = expdest - ((char *)stackblock() + resetloc);
6920 STADJUST(-amount, expdest);
6921 startp = (char *)stackblock() + startloc;
6924 rmescend = (char *)stackblock() + strloc;
6925 //bb_error_msg("str7:'%s'", rmescend);
6927 //TODO: how to handle slash_pos here if string changes (shortens?)
6928 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW, NULL);
6929 if (rmesc != startp) {
6931 startp = (char *)stackblock() + startloc;
6935 str = (char *)stackblock() + strloc;
6937 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6938 * The result is a_\_z_c (not a\_\_z_c)!
6940 * The search pattern and replace string treat backslashes differently!
6941 * "&slash_pos" causes rmescapes() to work differently on the pattern
6942 * and string. It's only used on the first call.
6944 //bb_error_msg("str8:'%s' slash_pos:%d", str, slash_pos);
6945 rmescapes(str, RMESCAPE_GLOB,
6946 repl ? NULL : (slash_pos < 0 ? NULL : &slash_pos)
6949 #if BASH_PATTERN_SUBST
6950 workloc = expdest - (char *)stackblock();
6951 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6956 //bb_error_msg("str9:'%s' slash_pos:%d", str, slash_pos);
6958 if (slash_pos >= 0) {
6959 repl = str + slash_pos;
6963 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6965 /* If there's no pattern to match, return the expansion unmolested */
6974 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6975 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6977 /* No match, advance */
6978 char *restart_detect = stackblock();
6980 STPUTC(*idx, expdest);
6981 if (quotes && (unsigned char)*idx == CTLESC) {
6984 STPUTC(*idx, expdest);
6986 if (stackblock() != restart_detect)
6991 /* continue; - prone to quadratic behavior, smarter code: */
6994 if (str[0] == '*') {
6995 /* Pattern is "*foo". If "*foo" does not match "long_string",
6996 * it would never match "ong_string" etc, no point in trying.
7003 if (subtype == VSREPLACEALL) {
7005 if (quotes && (unsigned char)*idx == CTLESC)
7014 //bb_error_msg("repl:'%s'", repl);
7015 for (loc = (char*)repl; *loc; loc++) {
7016 char *restart_detect = stackblock();
7017 if (quotes && *loc == '\\') {
7018 STPUTC(CTLESC, expdest);
7021 STPUTC(*loc, expdest);
7022 if (stackblock() != restart_detect)
7027 if (subtype == VSREPLACE) {
7028 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
7030 char *restart_detect = stackblock();
7031 STPUTC(*idx, expdest);
7032 if (stackblock() != restart_detect)
7041 /* We've put the replaced text into a buffer at workloc, now
7042 * move it to the right place and adjust the stack.
7044 STPUTC('\0', expdest);
7045 startp = (char *)stackblock() + startloc;
7046 memmove(startp, (char *)stackblock() + workloc, len + 1);
7047 //bb_error_msg("startp:'%s'", startp);
7048 amount = expdest - (startp + len);
7049 STADJUST(-amount, expdest);
7052 #endif /* BASH_PATTERN_SUBST */
7054 subtype -= VSTRIMRIGHT;
7056 if (subtype < 0 || subtype > 7)
7059 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
7060 zero = subtype >> 1;
7061 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
7062 scan = (subtype & 1) ^ zero ? scanleft : scanright;
7064 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
7067 memmove(startp, loc, str - loc);
7068 loc = startp + (str - loc) - 1;
7071 amount = loc - expdest;
7072 STADJUST(amount, expdest);
7078 * Add the value of a specialized variable to the stack string.
7079 * name parameter (examples):
7080 * ash -c 'echo $1' name:'1='
7081 * ash -c 'echo $qwe' name:'qwe='
7082 * ash -c 'echo $$' name:'$='
7083 * ash -c 'echo ${$}' name:'$='
7084 * ash -c 'echo ${$##q}' name:'$=q'
7085 * ash -c 'echo ${#$}' name:'$='
7086 * note: examples with bad shell syntax:
7087 * ash -c 'echo ${#$1}' name:'$=1'
7088 * ash -c 'echo ${#1#}' name:'1=#'
7090 static NOINLINE ssize_t
7091 varvalue(char *name, int varflags, int flags, int *quotedp)
7098 int quoted = *quotedp;
7099 int subtype = varflags & VSTYPE;
7100 int discard = subtype == VSPLUS || subtype == VSLENGTH;
7101 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
7104 sep = (flags & EXP_FULL) << CHAR_BIT;
7105 syntax = quoted ? DQSYNTAX : BASESYNTAX;
7115 num = shellparam.nparam;
7123 goto check_1char_name;
7125 expdest = makestrspace(NOPTS, expdest);
7126 for (i = NOPTS - 1; i >= 0; i--) {
7128 USTPUTC(optletters(i), expdest);
7134 /* handles cases similar to ${#$1} */
7135 if (name[2] != '\0')
7136 raise_error_syntax("bad substitution");
7149 sep |= ifsset() ? ifsval()[0] : ' ';
7156 while ((p = *ap++) != NULL) {
7157 len += strtodest(p, syntax, quotes);
7161 memtodest(&sepc, 1, syntax, quotes);
7176 num = atoi(name); /* number(name) fails on ${N#str} etc */
7177 if (num < 0 || num > shellparam.nparam)
7179 p = num ? shellparam.p[num - 1] : arg0;
7182 /* NB: name has form "VAR=..." */
7183 p = lookupvar(name);
7188 len = strtodest(p, syntax, quotes);
7189 #if ENABLE_UNICODE_SUPPORT
7190 if (subtype == VSLENGTH && len > 0) {
7191 reinit_unicode_for_ash();
7192 if (unicode_status == UNICODE_ON) {
7193 STADJUST(-len, expdest);
7195 len = unicode_strlen(p);
7203 STADJUST(-len, expdest);
7208 * Expand a variable, and return a pointer to the next character in the
7212 evalvar(char *p, int flag)
7223 varflags = (unsigned char) *p++;
7224 subtype = varflags & VSTYPE;
7227 raise_error_syntax("bad substitution");
7229 quoted = flag & EXP_QUOTED;
7231 easy = (!quoted || (*var == '@' && shellparam.nparam));
7232 startloc = expdest - (char *)stackblock();
7233 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
7236 varlen = varvalue(var, varflags, flag, "ed);
7237 if (varflags & VSNUL)
7240 if (subtype == VSPLUS) {
7241 varlen = -1 - varlen;
7245 if (subtype == VSMINUS) {
7250 flag | EXP_TILDE | EXP_WORD
7257 if (subtype == VSASSIGN || subtype == VSQUESTION) {
7261 subevalvar(p, var, 0, subtype, startloc, varflags,
7262 flag & ~QUOTES_ESC);
7265 * Remove any recorded regions beyond
7268 removerecordregions(startloc);
7272 if (varlen < 0 && uflag)
7273 varunset(p, var, 0, 0);
7275 if (subtype == VSLENGTH) {
7276 cvtnum(varlen > 0 ? varlen : 0);
7280 if (subtype == VSNORMAL) {
7284 recordregion(startloc, expdest - (char *)stackblock(), quoted);
7293 case VSTRIMRIGHTMAX:
7297 #if BASH_PATTERN_SUBST
7309 * Terminate the string and start recording the pattern
7312 STPUTC('\0', expdest);
7313 patloc = expdest - (char *)stackblock();
7314 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
7315 startloc, varflags, flag)) {
7316 int amount = expdest - (
7317 (char *)stackblock() + patloc - 1
7319 STADJUST(-amount, expdest);
7321 /* Remove any recorded regions beyond start of variable */
7322 removerecordregions(startloc);
7327 if (subtype != VSNORMAL) { /* skip to end of alternative */
7330 unsigned char c = *p++;
7333 else if (c == CTLBACKQ) {
7335 argbackq = argbackq->next;
7336 } else if (c == CTLVAR) {
7337 if ((*p++ & VSTYPE) != VSNORMAL)
7339 } else if (c == CTLENDVAR) {
7349 * Add a file name to the list.
7352 addfname(const char *name)
7356 sp = stzalloc(sizeof(*sp));
7357 sp->text = sstrdup(name);
7359 exparg.lastp = &sp->next;
7362 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7364 hasmeta(const char *p)
7366 static const char chars[] ALIGN1 = {
7367 '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
7371 p = strpbrk(p, chars);
7374 switch ((unsigned char) *p) {
7378 if (*p == CTLQUOTEMARK)
7382 if (*p == '\0') /* huh? */
7393 if (!strchr(p + 1, ']')) {
7394 /* It's not a properly closed [] pattern,
7395 * but other metas may follow. Continue checking.
7396 * my[file* _is_ globbed by bash
7397 * and matches filenames like "my[file1".
7413 /* If we want to use glob() from libc... */
7414 #if !ENABLE_ASH_INTERNAL_GLOB
7416 /* Add the result of glob() to the list */
7418 addglob(const glob_t *pglob)
7420 char **p = pglob->gl_pathv;
7427 expandmeta(struct strlist *str /*, int flag*/)
7429 /* TODO - EXP_REDIR */
7439 if (!hasmeta(str->text))
7443 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7444 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7445 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7447 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7448 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7449 // Which means you need to unescape the string, right? Not so fast:
7450 // if there _is_ a file named "file\?" (with backslash), it is returned
7451 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7452 // You DON'T KNOW by looking at the result whether you need to unescape it.
7454 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7455 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7456 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7457 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7458 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7459 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7460 i = glob(p, 0, NULL, &pglob);
7461 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7466 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7467 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7468 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7480 *exparg.lastp = str;
7481 rmescapes(str->text, 0, NULL);
7482 exparg.lastp = &str->next;
7484 default: /* GLOB_NOSPACE */
7487 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7494 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7497 * Do metacharacter (i.e. *, ?, [...]) expansion.
7500 expmeta(char *expdir, char *enddir, char *name)
7516 for (p = name; esc = 0, *p; p += esc + 1) {
7517 if (*p == '*' || *p == '?')
7519 else if (*p == '[') {
7526 if (*q == '/' || *q == '\0')
7536 if (p[esc] == '/') {
7539 start = p + esc + 1;
7543 if (metaflag == 0) { /* we've reached the end of the file name */
7544 if (enddir != expdir)
7552 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7563 } while (p < start);
7565 if (enddir == expdir) {
7567 } else if (enddir == expdir + 1 && *expdir == '/') {
7576 if (enddir != expdir)
7578 if (*endname == 0) {
7591 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7592 if (dp->d_name[0] == '.' && !matchdot)
7594 if (pmatch(start, dp->d_name)) {
7596 strcpy(enddir, dp->d_name);
7599 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7602 expmeta(expdir, p, endname);
7608 endname[-esc - 1] = esc ? '\\' : '/';
7611 static struct strlist *
7612 msort(struct strlist *list, int len)
7614 struct strlist *p, *q = NULL;
7615 struct strlist **lpp;
7623 for (n = half; --n >= 0;) {
7627 q->next = NULL; /* terminate first half of list */
7628 q = msort(list, half); /* sort first half of list */
7629 p = msort(p, len - half); /* sort second half */
7632 #if ENABLE_LOCALE_SUPPORT
7633 if (strcoll(p->text, q->text) < 0)
7635 if (strcmp(p->text, q->text) < 0)
7659 * Sort the results of file name expansion. It calculates the number of
7660 * strings to sort and then calls msort (short for merge sort) to do the
7663 static struct strlist *
7664 expsort(struct strlist *str)
7670 for (sp = str; sp; sp = sp->next)
7672 return msort(str, len);
7676 expandmeta(struct strlist *str /*, int flag*/)
7678 /* TODO - EXP_REDIR */
7682 struct strlist **savelastp;
7688 if (!hasmeta(str->text))
7690 savelastp = exparg.lastp;
7693 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7695 int i = strlen(str->text);
7696 //BUGGY estimation of how long expanded name can be
7697 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7699 expmeta(expdir, expdir, p);
7704 if (exparg.lastp == savelastp) {
7709 *exparg.lastp = str;
7710 rmescapes(str->text, 0, NULL);
7711 exparg.lastp = &str->next;
7713 *exparg.lastp = NULL;
7714 *savelastp = sp = expsort(*savelastp);
7715 while (sp->next != NULL)
7717 exparg.lastp = &sp->next;
7722 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7725 * Perform variable substitution and command substitution on an argument,
7726 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7727 * perform splitting and file name expansion. When arglist is NULL, perform
7728 * here document expansion.
7731 expandarg(union node *arg, struct arglist *arglist, int flag)
7736 argbackq = arg->narg.backquote;
7737 STARTSTACKSTR(expdest);
7738 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7739 argstr(arg->narg.text, flag);
7740 p = _STPUTC('\0', expdest);
7742 if (arglist == NULL) {
7743 /* here document expanded */
7746 p = grabstackstr(p);
7747 TRACE(("expandarg: p:'%s'\n", p));
7748 exparg.lastp = &exparg.list;
7752 if (flag & EXP_FULL) {
7753 ifsbreakup(p, &exparg);
7754 *exparg.lastp = NULL;
7755 exparg.lastp = &exparg.list;
7756 expandmeta(exparg.list /*, flag*/);
7758 sp = stzalloc(sizeof(*sp));
7761 exparg.lastp = &sp->next;
7763 *exparg.lastp = NULL;
7765 *arglist->lastp = exparg.list;
7766 arglist->lastp = exparg.lastp;
7774 * Expand shell variables and backquotes inside a here document.
7777 expandhere(union node *arg, int fd)
7779 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7780 full_write(fd, stackblock(), expdest - (char *)stackblock());
7784 * Returns true if the pattern matches the string.
7787 patmatch(char *pattern, const char *string)
7789 char *p = preglob(pattern, 0);
7790 int r = pmatch(p, string);
7791 //bb_error_msg("!fnmatch(pattern:'%s',str:'%s',0):%d", p, string, r);
7796 * See if a pattern matches in a case statement.
7799 casematch(union node *pattern, char *val)
7801 struct stackmark smark;
7804 setstackmark(&smark);
7805 argbackq = pattern->narg.backquote;
7806 STARTSTACKSTR(expdest);
7807 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
7808 STACKSTRNUL(expdest);
7810 result = patmatch(stackblock(), val);
7811 popstackmark(&smark);
7816 /* ============ find_command */
7820 int (*builtin)(int, char **) FAST_FUNC;
7821 /* unsigned flags; */
7823 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7824 /* "regular" builtins always take precedence over commands,
7825 * regardless of PATH=....%builtin... position */
7826 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7827 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7830 smallint cmdtype; /* CMDxxx */
7833 /* index >= 0 for commands without path (slashes) */
7834 /* (TODO: what exactly does the value mean? PATH position?) */
7835 /* index == -1 for commands with slashes */
7836 /* index == (-2 - applet_no) for NOFORK applets */
7837 const struct builtincmd *cmd;
7838 struct funcnode *func;
7841 /* values of cmdtype */
7842 #define CMDUNKNOWN -1 /* no entry in table for command */
7843 #define CMDNORMAL 0 /* command is an executable program */
7844 #define CMDFUNCTION 1 /* command is a shell function */
7845 #define CMDBUILTIN 2 /* command is a shell builtin */
7847 /* action to find_command() */
7848 #define DO_ERR 0x01 /* prints errors */
7849 #define DO_ABS 0x02 /* checks absolute paths */
7850 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7851 #define DO_ALTPATH 0x08 /* using alternate path */
7852 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7854 static void find_command(char *, struct cmdentry *, int, const char *);
7857 /* ============ Hashing commands */
7860 * When commands are first encountered, they are entered in a hash table.
7861 * This ensures that a full path search will not have to be done for them
7862 * on each invocation.
7864 * We should investigate converting to a linear search, even though that
7865 * would make the command name "hash" a misnomer.
7869 struct tblentry *next; /* next entry in hash chain */
7870 union param param; /* definition of builtin function */
7871 smallint cmdtype; /* CMDxxx */
7872 char rehash; /* if set, cd done since entry created */
7873 char cmdname[1]; /* name of command */
7876 static struct tblentry **cmdtable;
7877 #define INIT_G_cmdtable() do { \
7878 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7881 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7885 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
7887 #if ENABLE_FEATURE_SH_STANDALONE
7888 if (applet_no >= 0) {
7889 if (APPLET_IS_NOEXEC(applet_no)) {
7893 popredir(/*drop:*/ 1);
7894 run_noexec_applet_and_exit(applet_no, cmd, argv);
7896 /* re-exec ourselves with the new arguments */
7897 execve(bb_busybox_exec_path, argv, envp);
7898 /* If they called chroot or otherwise made the binary no longer
7899 * executable, fall through */
7906 execve(cmd, argv, envp);
7907 } while (errno == EINTR);
7909 execve(cmd, argv, envp);
7911 if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
7912 /* Run "cmd" as a shell script:
7913 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7914 * "If the execve() function fails with ENOEXEC, the shell
7915 * shall execute a command equivalent to having a shell invoked
7916 * with the command name as its first operand,
7917 * with any remaining arguments passed to the new shell"
7919 * That is, do not use $SHELL, user's shell, or /bin/sh;
7920 * just call ourselves.
7922 * Note that bash reads ~80 chars of the file, and if it sees
7923 * a zero byte before it sees newline, it doesn't try to
7924 * interpret it, but fails with "cannot execute binary file"
7925 * message and exit code 126. For one, this prevents attempts
7926 * to interpret foreign ELF binaries as shell scripts.
7928 argv[0] = (char*) cmd;
7929 cmd = bb_busybox_exec_path;
7930 /* NB: this is only possible because all callers of shellexec()
7931 * ensure that the argv[-1] slot exists!
7934 argv[0] = (char*) "ash";
7940 * Exec a program. Never returns. If you change this routine, you may
7941 * have to change the find_command routine as well.
7942 * argv[-1] must exist and be writable! See tryexec() for why.
7944 static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
7945 static void shellexec(char *prog, char **argv, const char *path, int idx)
7951 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7953 envp = listvars(VEXPORT, VUNSET, /*strlist:*/ NULL, /*end:*/ NULL);
7954 if (strchr(prog, '/') != NULL
7955 #if ENABLE_FEATURE_SH_STANDALONE
7956 || (applet_no = find_applet_by_name(prog)) >= 0
7959 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
7960 if (applet_no >= 0) {
7961 /* We tried execing ourself, but it didn't work.
7962 * Maybe /proc/self/exe doesn't exist?
7971 while ((cmdname = path_advance(&path, prog)) != NULL) {
7972 if (--idx < 0 && pathopt == NULL) {
7973 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7974 if (errno != ENOENT && errno != ENOTDIR)
7981 /* Map to POSIX errors */
7993 exitstatus = exerrno;
7994 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7995 prog, e, suppress_int));
7996 ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
8001 printentry(struct tblentry *cmdp)
8007 idx = cmdp->param.index;
8010 name = path_advance(&path, cmdp->cmdname);
8012 } while (--idx >= 0);
8013 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
8017 * Clear out command entries. The argument specifies the first entry in
8018 * PATH which has changed.
8021 clearcmdentry(int firstchange)
8023 struct tblentry **tblp;
8024 struct tblentry **pp;
8025 struct tblentry *cmdp;
8028 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
8030 while ((cmdp = *pp) != NULL) {
8031 if ((cmdp->cmdtype == CMDNORMAL &&
8032 cmdp->param.index >= firstchange)
8033 || (cmdp->cmdtype == CMDBUILTIN &&
8034 builtinloc >= firstchange)
8047 * Locate a command in the command hash table. If "add" is nonzero,
8048 * add the command to the table if it is not already present. The
8049 * variable "lastcmdentry" is set to point to the address of the link
8050 * pointing to the entry, so that delete_cmd_entry can delete the
8053 * Interrupts must be off if called with add != 0.
8055 static struct tblentry **lastcmdentry;
8057 static struct tblentry *
8058 cmdlookup(const char *name, int add)
8060 unsigned int hashval;
8062 struct tblentry *cmdp;
8063 struct tblentry **pp;
8066 hashval = (unsigned char)*p << 4;
8068 hashval += (unsigned char)*p++;
8070 pp = &cmdtable[hashval % CMDTABLESIZE];
8071 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8072 if (strcmp(cmdp->cmdname, name) == 0)
8076 if (add && cmdp == NULL) {
8077 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
8079 /* + 1 - already done because
8080 * tblentry::cmdname is char[1] */);
8081 /*cmdp->next = NULL; - ckzalloc did it */
8082 cmdp->cmdtype = CMDUNKNOWN;
8083 strcpy(cmdp->cmdname, name);
8090 * Delete the command entry returned on the last lookup.
8093 delete_cmd_entry(void)
8095 struct tblentry *cmdp;
8098 cmdp = *lastcmdentry;
8099 *lastcmdentry = cmdp->next;
8100 if (cmdp->cmdtype == CMDFUNCTION)
8101 freefunc(cmdp->param.func);
8107 * Add a new command entry, replacing any existing command entry for
8108 * the same name - except special builtins.
8111 addcmdentry(char *name, struct cmdentry *entry)
8113 struct tblentry *cmdp;
8115 cmdp = cmdlookup(name, 1);
8116 if (cmdp->cmdtype == CMDFUNCTION) {
8117 freefunc(cmdp->param.func);
8119 cmdp->cmdtype = entry->cmdtype;
8120 cmdp->param = entry->u;
8124 static int FAST_FUNC
8125 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8127 struct tblentry **pp;
8128 struct tblentry *cmdp;
8130 struct cmdentry entry;
8133 if (nextopt("r") != '\0') {
8138 if (*argptr == NULL) {
8139 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8140 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8141 if (cmdp->cmdtype == CMDNORMAL)
8149 while ((name = *argptr) != NULL) {
8150 cmdp = cmdlookup(name, 0);
8152 && (cmdp->cmdtype == CMDNORMAL
8153 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
8157 find_command(name, &entry, DO_ERR, pathval());
8158 if (entry.cmdtype == CMDUNKNOWN)
8166 * Called when a cd is done. Marks all commands so the next time they
8167 * are executed they will be rehashed.
8172 struct tblentry **pp;
8173 struct tblentry *cmdp;
8175 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8176 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8177 if (cmdp->cmdtype == CMDNORMAL
8178 || (cmdp->cmdtype == CMDBUILTIN
8179 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
8189 * Fix command hash table when PATH changed.
8190 * Called before PATH is changed. The argument is the new value of PATH;
8191 * pathval() still returns the old value at this point.
8192 * Called with interrupts off.
8194 static void FAST_FUNC
8195 changepath(const char *new)
8203 firstchange = 9999; /* assume no change */
8209 if ((*old == '\0' && *new == ':')
8210 || (*old == ':' && *new == '\0')
8214 old = new; /* ignore subsequent differences */
8218 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
8225 if (builtinloc < 0 && idx_bltin >= 0)
8226 builtinloc = idx_bltin; /* zap builtins */
8227 if (builtinloc >= 0 && idx_bltin < 0)
8229 clearcmdentry(firstchange);
8230 builtinloc = idx_bltin;
8266 typedef smallint token_id_t;
8268 /* Nth bit indicates if token marks the end of a list */
8271 /* 0 */ | (1u << TEOF)
8272 /* 1 */ | (0u << TNL)
8273 /* 2 */ | (0u << TREDIR)
8274 /* 3 */ | (0u << TWORD)
8275 /* 4 */ | (0u << TSEMI)
8276 /* 5 */ | (0u << TBACKGND)
8277 /* 6 */ | (0u << TAND)
8278 /* 7 */ | (0u << TOR)
8279 /* 8 */ | (0u << TPIPE)
8280 /* 9 */ | (0u << TLP)
8281 /* 10 */ | (1u << TRP)
8282 /* 11 */ | (1u << TENDCASE)
8283 /* 12 */ | (1u << TENDBQUOTE)
8284 /* 13 */ | (0u << TNOT)
8285 /* 14 */ | (0u << TCASE)
8286 /* 15 */ | (1u << TDO)
8287 /* 16 */ | (1u << TDONE)
8288 /* 17 */ | (1u << TELIF)
8289 /* 18 */ | (1u << TELSE)
8290 /* 19 */ | (1u << TESAC)
8291 /* 20 */ | (1u << TFI)
8292 /* 21 */ | (0u << TFOR)
8294 /* 22 */ | (0u << TFUNCTION)
8296 /* 23 */ | (0u << TIF)
8297 /* 24 */ | (0u << TIN)
8298 /* 25 */ | (1u << TTHEN)
8299 /* 26 */ | (0u << TUNTIL)
8300 /* 27 */ | (0u << TWHILE)
8301 /* 28 */ | (0u << TBEGIN)
8302 /* 29 */ | (1u << TEND)
8303 , /* thus far 29 bits used */
8306 static const char *const tokname_array[] = {
8320 #define KWDOFFSET 13
8321 /* the following are keywords */
8343 /* Wrapper around strcmp for qsort/bsearch/... */
8345 pstrcmp(const void *a, const void *b)
8347 return strcmp((char*)a, *(char**)b);
8350 static const char *const *
8351 findkwd(const char *s)
8353 return bsearch(s, tokname_array + KWDOFFSET,
8354 ARRAY_SIZE(tokname_array) - KWDOFFSET,
8355 sizeof(tokname_array[0]), pstrcmp);
8359 * Locate and print what a word is...
8362 describe_command(char *command, const char *path, int describe_command_verbose)
8364 struct cmdentry entry;
8365 #if ENABLE_ASH_ALIAS
8366 const struct alias *ap;
8369 path = path ? path : pathval();
8371 if (describe_command_verbose) {
8375 /* First look at the keywords */
8376 if (findkwd(command)) {
8377 out1str(describe_command_verbose ? " is a shell keyword" : command);
8381 #if ENABLE_ASH_ALIAS
8382 /* Then look at the aliases */
8383 ap = lookupalias(command, 0);
8385 if (!describe_command_verbose) {
8390 out1fmt(" is an alias for %s", ap->val);
8395 find_command(command, &entry, DO_ABS, path);
8397 switch (entry.cmdtype) {
8399 int j = entry.u.index;
8405 p = path_advance(&path, command);
8409 if (describe_command_verbose) {
8410 out1fmt(" is %s", p);
8418 if (describe_command_verbose) {
8419 out1str(" is a shell function");
8426 if (describe_command_verbose) {
8427 out1fmt(" is a %sshell builtin",
8428 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8429 "special " : nullstr
8437 if (describe_command_verbose) {
8438 out1str(": not found\n");
8447 static int FAST_FUNC
8448 typecmd(int argc UNUSED_PARAM, char **argv)
8454 /* type -p ... ? (we don't bother checking for 'p') */
8455 if (argv[1] && argv[1][0] == '-') {
8460 err |= describe_command(argv[i++], NULL, verbose);
8465 #if ENABLE_ASH_CMDCMD
8466 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8468 parse_command_args(char **argv, const char **path)
8481 if (c == '-' && !*cp) {
8489 *path = bb_default_path;
8492 /* run 'typecmd' for other options */
8501 static int FAST_FUNC
8502 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8510 const char *path = NULL;
8512 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8513 * never reaches this function.
8516 while ((c = nextopt("pvV")) != '\0')
8518 verify |= VERIFY_VERBOSE;
8520 /*verify |= VERIFY_BRIEF*/;
8526 path = bb_default_path;
8528 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8530 if (/*verify && */ cmd)
8531 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8538 /*static int funcblocksize; // size of structures in function */
8539 /*static int funcstringsize; // size of strings in node */
8540 static void *funcblock; /* block to allocate function from */
8541 static char *funcstring_end; /* end of block to allocate strings from */
8543 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8544 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8545 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8546 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8547 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8548 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8549 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8550 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8551 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8552 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8553 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8554 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8555 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8556 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8557 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8558 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8559 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8560 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8561 #if BASH_REDIR_OUTPUT
8562 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8564 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8565 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8566 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8567 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8568 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8569 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8570 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8571 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8572 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8575 static int calcsize(int funcblocksize, union node *n);
8578 sizenodelist(int funcblocksize, struct nodelist *lp)
8581 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8582 funcblocksize = calcsize(funcblocksize, lp->n);
8585 return funcblocksize;
8589 calcsize(int funcblocksize, union node *n)
8592 return funcblocksize;
8593 funcblocksize += nodesize[n->type];
8596 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8597 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8598 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8601 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8606 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8607 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8614 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8615 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8618 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8619 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8620 funcblocksize = calcsize(funcblocksize, n->nif.test);
8623 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8624 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8625 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8628 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8629 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8632 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8633 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8634 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8638 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8639 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8640 funcblocksize = calcsize(funcblocksize, n->narg.next);
8643 #if BASH_REDIR_OUTPUT
8650 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8651 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8655 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8656 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8660 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8661 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8664 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8667 return funcblocksize;
8671 nodeckstrdup(char *s)
8673 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8674 return strcpy(funcstring_end, s);
8677 static union node *copynode(union node *);
8679 static struct nodelist *
8680 copynodelist(struct nodelist *lp)
8682 struct nodelist *start;
8683 struct nodelist **lpp;
8688 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8689 (*lpp)->n = copynode(lp->n);
8691 lpp = &(*lpp)->next;
8698 copynode(union node *n)
8705 funcblock = (char *) funcblock + nodesize[n->type];
8709 new->ncmd.redirect = copynode(n->ncmd.redirect);
8710 new->ncmd.args = copynode(n->ncmd.args);
8711 new->ncmd.assign = copynode(n->ncmd.assign);
8714 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8715 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8720 new->nredir.redirect = copynode(n->nredir.redirect);
8721 new->nredir.n = copynode(n->nredir.n);
8728 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8729 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8732 new->nif.elsepart = copynode(n->nif.elsepart);
8733 new->nif.ifpart = copynode(n->nif.ifpart);
8734 new->nif.test = copynode(n->nif.test);
8737 new->nfor.var = nodeckstrdup(n->nfor.var);
8738 new->nfor.body = copynode(n->nfor.body);
8739 new->nfor.args = copynode(n->nfor.args);
8742 new->ncase.cases = copynode(n->ncase.cases);
8743 new->ncase.expr = copynode(n->ncase.expr);
8746 new->nclist.body = copynode(n->nclist.body);
8747 new->nclist.pattern = copynode(n->nclist.pattern);
8748 new->nclist.next = copynode(n->nclist.next);
8752 new->narg.backquote = copynodelist(n->narg.backquote);
8753 new->narg.text = nodeckstrdup(n->narg.text);
8754 new->narg.next = copynode(n->narg.next);
8757 #if BASH_REDIR_OUTPUT
8764 new->nfile.fname = copynode(n->nfile.fname);
8765 new->nfile.fd = n->nfile.fd;
8766 new->nfile.next = copynode(n->nfile.next);
8770 new->ndup.vname = copynode(n->ndup.vname);
8771 new->ndup.dupfd = n->ndup.dupfd;
8772 new->ndup.fd = n->ndup.fd;
8773 new->ndup.next = copynode(n->ndup.next);
8777 new->nhere.doc = copynode(n->nhere.doc);
8778 new->nhere.fd = n->nhere.fd;
8779 new->nhere.next = copynode(n->nhere.next);
8782 new->nnot.com = copynode(n->nnot.com);
8785 new->type = n->type;
8790 * Make a copy of a parse tree.
8792 static struct funcnode *
8793 copyfunc(union node *n)
8798 /*funcstringsize = 0;*/
8799 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8800 f = ckzalloc(blocksize /* + funcstringsize */);
8801 funcblock = (char *) f + offsetof(struct funcnode, n);
8802 funcstring_end = (char *) f + blocksize;
8804 /* f->count = 0; - ckzalloc did it */
8809 * Define a shell function.
8812 defun(union node *func)
8814 struct cmdentry entry;
8817 entry.cmdtype = CMDFUNCTION;
8818 entry.u.func = copyfunc(func);
8819 addcmdentry(func->narg.text, &entry);
8823 /* Reasons for skipping commands (see comment on breakcmd routine) */
8824 #define SKIPBREAK (1 << 0)
8825 #define SKIPCONT (1 << 1)
8826 #define SKIPFUNC (1 << 2)
8827 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8828 static int skipcount; /* number of levels to skip */
8829 static int funcnest; /* depth of function calls */
8830 static int loopnest; /* current loop nesting level */
8832 /* Forward decl way out to parsing code - dotrap needs it */
8833 static int evalstring(char *s, int flags);
8835 /* Called to execute a trap.
8836 * Single callsite - at the end of evaltree().
8837 * If we return non-zero, evaltree raises EXEXIT exception.
8839 * Perhaps we should avoid entering new trap handlers
8840 * while we are executing a trap handler. [is it a TODO?]
8847 uint8_t last_status;
8852 last_status = exitstatus;
8856 TRACE(("dotrap entered\n"));
8857 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8869 /* non-trapped SIGINT is handled separately by raise_interrupt,
8870 * don't upset it by resetting gotsig[SIGINT-1] */
8871 if (sig == SIGINT && !p)
8874 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8880 exitstatus = last_status;
8881 TRACE(("dotrap returns\n"));
8884 /* forward declarations - evaluation is fairly recursive business... */
8885 static int evalloop(union node *, int);
8886 static int evalfor(union node *, int);
8887 static int evalcase(union node *, int);
8888 static int evalsubshell(union node *, int);
8889 static void expredir(union node *);
8890 static int evalpipe(union node *, int);
8891 static int evalcommand(union node *, int);
8892 static int evalbltin(const struct builtincmd *, int, char **, int);
8893 static void prehash(union node *);
8896 * Evaluate a parse tree. The value is left in the global variable
8900 evaltree(union node *n, int flags)
8903 int (*evalfn)(union node *, int);
8907 TRACE(("evaltree(NULL) called\n"));
8910 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8917 out1fmt("Node type = %d\n", n->type);
8922 status = !evaltree(n->nnot.com, EV_TESTED);
8925 expredir(n->nredir.redirect);
8926 pushredir(n->nredir.redirect);
8927 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8929 status = evaltree(n->nredir.n, flags & EV_TESTED);
8931 if (n->nredir.redirect)
8932 popredir(/*drop:*/ 0);
8935 evalfn = evalcommand;
8937 if (eflag && !(flags & EV_TESTED))
8949 evalfn = evalsubshell;
8962 #error NAND + 1 != NOR
8964 #if NOR + 1 != NSEMI
8965 #error NOR + 1 != NSEMI
8967 unsigned is_or = n->type - NAND;
8970 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8972 if ((!status) == is_or || evalskip)
8978 status = evalfn(n, flags);
8982 status = evaltree(n->nif.test, EV_TESTED);
8989 if (n->nif.elsepart) {
8990 n = n->nif.elsepart;
8997 /* Not necessary. To test it:
8998 * "false; f() { qwerty; }; echo $?" should print 0.
9002 exitstatus = status;
9006 /* Order of checks below is important:
9007 * signal handlers trigger before exit caused by "set -e".
9011 if (checkexit & status)
9012 raise_exception(EXEXIT);
9013 if (flags & EV_EXIT)
9014 raise_exception(EXEXIT);
9016 TRACE(("leaving evaltree (no interrupts)\n"));
9023 int skip = evalskip;
9030 if (--skipcount <= 0) {
9041 evalloop(union node *n, int flags)
9052 i = evaltree(n->nbinary.ch1, EV_TESTED);
9054 if (skip == SKIPFUNC)
9058 if (n->type != NWHILE)
9062 status = evaltree(n->nbinary.ch2, flags);
9064 } while (!(skip & ~SKIPCONT));
9071 evalfor(union node *n, int flags)
9073 struct arglist arglist;
9076 struct stackmark smark;
9079 setstackmark(&smark);
9080 arglist.list = NULL;
9081 arglist.lastp = &arglist.list;
9082 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
9083 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9085 *arglist.lastp = NULL;
9089 for (sp = arglist.list; sp; sp = sp->next) {
9090 setvar0(n->nfor.var, sp->text);
9091 status = evaltree(n->nfor.body, flags);
9092 if (skiploop() & ~SKIPCONT)
9096 popstackmark(&smark);
9102 evalcase(union node *n, int flags)
9106 struct arglist arglist;
9107 struct stackmark smark;
9110 setstackmark(&smark);
9111 arglist.list = NULL;
9112 arglist.lastp = &arglist.list;
9113 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
9114 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
9115 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
9116 if (casematch(patp, arglist.list->text)) {
9117 /* Ensure body is non-empty as otherwise
9118 * EV_EXIT may prevent us from setting the
9121 if (evalskip == 0 && cp->nclist.body) {
9122 status = evaltree(cp->nclist.body, flags);
9129 popstackmark(&smark);
9135 * Kick off a subshell to evaluate a tree.
9138 evalsubshell(union node *n, int flags)
9141 int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
9144 expredir(n->nredir.redirect);
9145 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
9148 if (backgnd == FORK_FG)
9150 jp = makejob(/*n,*/ 1);
9151 if (forkshell(jp, n, backgnd) == 0) {
9156 flags &= ~EV_TESTED;
9158 redirect(n->nredir.redirect, 0);
9159 evaltreenr(n->nredir.n, flags);
9164 if (backgnd == FORK_FG)
9165 status = waitforjob(jp);
9171 * Compute the names of the files in a redirection list.
9173 static void fixredir(union node *, const char *, int);
9175 expredir(union node *n)
9179 for (redir = n; redir; redir = redir->nfile.next) {
9183 fn.lastp = &fn.list;
9184 switch (redir->type) {
9188 #if BASH_REDIR_OUTPUT
9193 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
9194 TRACE(("expredir expanded to '%s'\n", fn.list->text));
9195 #if BASH_REDIR_OUTPUT
9199 // By the design of stack allocator, the loop of this kind:
9200 // while true; do while true; do break; done </dev/null; done
9201 // will look like a memory leak: ash plans to free expfname's
9202 // of "/dev/null" as soon as it finishes running the loop
9203 // (in this case, never).
9204 // This "fix" is wrong:
9205 if (redir->nfile.expfname)
9206 stunalloc(redir->nfile.expfname);
9207 // It results in corrupted state of stacked allocations.
9209 redir->nfile.expfname = fn.list->text;
9212 case NTOFD: /* >& */
9213 if (redir->ndup.vname) {
9214 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
9215 if (fn.list == NULL)
9216 ash_msg_and_raise_error("redir error");
9217 #if BASH_REDIR_OUTPUT
9218 //FIXME: we used expandarg with different args!
9219 if (!isdigit_str9(fn.list->text)) {
9220 /* >&file, not >&fd */
9221 if (redir->nfile.fd != 1) /* 123>&file - BAD */
9222 ash_msg_and_raise_error("redir error");
9224 goto store_expfname;
9227 fixredir(redir, fn.list->text, 1);
9235 * Evaluate a pipeline. All the processes in the pipeline are children
9236 * of the process creating the pipeline. (This differs from some versions
9237 * of the shell, which make the last process in a pipeline the parent
9241 evalpipe(union node *n, int flags)
9244 struct nodelist *lp;
9250 TRACE(("evalpipe(0x%lx) called\n", (long)n));
9252 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
9256 if (n->npipe.pipe_backgnd == 0)
9258 jp = makejob(/*n,*/ pipelen);
9260 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
9264 if (pipe(pip) < 0) {
9266 ash_msg_and_raise_perror("can't create pipe");
9269 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
9283 evaltreenr(lp->n, flags);
9290 /* Don't want to trigger debugging */
9294 if (n->npipe.pipe_backgnd == 0) {
9295 status = waitforjob(jp);
9296 TRACE(("evalpipe: job done exit status %d\n", status));
9304 * Controls whether the shell is interactive or not.
9307 setinteractive(int on)
9309 static smallint is_interactive;
9311 if (++on == is_interactive)
9313 is_interactive = on;
9317 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9318 if (is_interactive > 1) {
9319 /* Looks like they want an interactive shell */
9320 static smallint did_banner;
9323 /* note: ash and hush share this string */
9324 out1fmt("\n\n%s %s\n"
9325 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
9328 "built-in shell (ash)"
9342 setinteractive(iflag);
9344 #if ENABLE_FEATURE_EDITING_VI
9346 line_input_state->flags |= VI_MODE;
9348 line_input_state->flags &= ~VI_MODE;
9350 viflag = 0; /* forcibly keep the option off */
9354 struct localvar_list {
9355 struct localvar_list *next;
9356 struct localvar *lv;
9359 static struct localvar_list *localvar_stack;
9362 * Called after a function returns.
9363 * Interrupts must be off.
9366 poplocalvars(int keep)
9368 struct localvar_list *ll;
9369 struct localvar *lvp, *next;
9373 ll = localvar_stack;
9374 localvar_stack = ll->next;
9379 while ((lvp = next) != NULL) {
9382 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9384 int bits = VSTRFIXED;
9386 if (lvp->flags != VUNSET) {
9387 if (vp->var_text == lvp->text)
9389 else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
9390 free((char*)lvp->text);
9394 vp->flags |= (lvp->flags & bits);
9397 (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
9398 unsetvar(vp->var_text);
9399 } else if (vp == NULL) { /* $- saved */
9400 memcpy(optlist, lvp->text, sizeof(optlist));
9401 free((char*)lvp->text);
9403 } else if (lvp->flags == VUNSET) {
9404 vp->flags &= ~(VSTRFIXED|VREADONLY);
9405 unsetvar(vp->var_text);
9408 vp->var_func(var_end(lvp->text));
9409 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9410 free((char*)vp->var_text);
9411 vp->flags = lvp->flags;
9412 vp->var_text = lvp->text;
9420 * Create a new localvar environment.
9422 static struct localvar_list *
9425 struct localvar_list *ll;
9428 ll = ckzalloc(sizeof(*ll));
9429 /*ll->lv = NULL; - zalloc did it */
9430 ll->next = localvar_stack;
9431 localvar_stack = ll;
9438 unwindlocalvars(struct localvar_list *stop)
9440 while (localvar_stack != stop)
9445 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9447 volatile struct shparam saveparam;
9448 struct jmploc *volatile savehandler;
9449 struct jmploc jmploc;
9452 saveparam = shellparam;
9453 savehandler = exception_handler;
9454 e = setjmp(jmploc.loc);
9459 exception_handler = &jmploc;
9460 shellparam.malloced = 0;
9464 shellparam.nparam = argc - 1;
9465 shellparam.p = argv + 1;
9466 #if ENABLE_ASH_GETOPTS
9467 shellparam.optind = 1;
9468 shellparam.optoff = -1;
9471 evaltree(func->n.narg.next, flags & EV_TESTED);
9477 freeparam(&shellparam);
9478 shellparam = saveparam;
9479 exception_handler = savehandler;
9481 evalskip &= ~SKIPFUNC;
9486 * Make a variable a local variable. When a variable is made local, it's
9487 * value and flags are saved in a localvar structure. The saved values
9488 * will be restored when the shell function returns. We handle the name
9489 * "-" as a special case: it makes changes to "set +-options" local
9490 * (options will be restored on return from the function).
9495 struct localvar *lvp;
9498 char *eq = strchr(name, '=');
9501 /* Cater for duplicate "local". Examples:
9502 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9503 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9505 lvp = localvar_stack->lv;
9507 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9511 * it's a duplicate "local VAR" declaration, do nothing
9518 lvp = ckzalloc(sizeof(*lvp));
9519 if (LONE_DASH(name)) {
9521 p = ckmalloc(sizeof(optlist));
9522 lvp->text = memcpy(p, optlist, sizeof(optlist));
9525 vpp = hashvar(name);
9526 vp = *findvar(vpp, name);
9528 /* variable did not exist yet */
9530 vp = setvareq(name, VSTRFIXED);
9532 vp = setvar(name, NULL, VSTRFIXED);
9533 lvp->flags = VUNSET;
9535 lvp->text = vp->var_text;
9536 lvp->flags = vp->flags;
9537 /* make sure neither "struct var" nor string gets freed
9538 * during (un)setting:
9540 vp->flags |= VSTRFIXED|VTEXTFIXED;
9544 /* "local VAR" unsets VAR: */
9545 setvar0(name, NULL);
9549 lvp->next = localvar_stack->lv;
9550 localvar_stack->lv = lvp;
9556 * The "local" command.
9558 static int FAST_FUNC
9559 localcmd(int argc UNUSED_PARAM, char **argv)
9563 if (!localvar_stack)
9564 ash_msg_and_raise_error("not in a function");
9567 while ((name = *argv++) != NULL) {
9573 static int FAST_FUNC
9574 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9579 static int FAST_FUNC
9580 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9585 static int FAST_FUNC
9586 execcmd(int argc UNUSED_PARAM, char **argv)
9589 while (nextopt("a:") != '\0')
9590 /* nextopt() sets optionarg to "-a ARGV0" */;
9596 iflag = 0; /* exit on error */
9599 /* We should set up signals for "exec CMD"
9600 * the same way as for "CMD" without "exec".
9601 * But optschanged->setinteractive->setsignal
9602 * still thought we are a root shell. Therefore, for example,
9603 * SIGQUIT is still set to IGN. Fix it:
9607 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9608 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9609 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9613 argv[0] = optionarg;
9614 shellexec(prog, argv, pathval(), 0);
9621 * The return command.
9623 static int FAST_FUNC
9624 returncmd(int argc UNUSED_PARAM, char **argv)
9627 * If called outside a function, do what ksh does;
9628 * skip the rest of the file.
9630 evalskip = SKIPFUNC;
9631 return argv[1] ? number(argv[1]) : exitstatus;
9634 /* Forward declarations for builtintab[] */
9635 static int breakcmd(int, char **) FAST_FUNC;
9636 static int dotcmd(int, char **) FAST_FUNC;
9637 static int evalcmd(int, char **, int) FAST_FUNC;
9638 static int exitcmd(int, char **) FAST_FUNC;
9639 static int exportcmd(int, char **) FAST_FUNC;
9640 #if ENABLE_ASH_GETOPTS
9641 static int getoptscmd(int, char **) FAST_FUNC;
9644 static int helpcmd(int, char **) FAST_FUNC;
9647 static int historycmd(int, char **) FAST_FUNC;
9649 #if ENABLE_FEATURE_SH_MATH
9650 static int letcmd(int, char **) FAST_FUNC;
9652 static int readcmd(int, char **) FAST_FUNC;
9653 static int setcmd(int, char **) FAST_FUNC;
9654 static int shiftcmd(int, char **) FAST_FUNC;
9655 static int timescmd(int, char **) FAST_FUNC;
9656 static int trapcmd(int, char **) FAST_FUNC;
9657 static int umaskcmd(int, char **) FAST_FUNC;
9658 static int unsetcmd(int, char **) FAST_FUNC;
9659 static int ulimitcmd(int, char **) FAST_FUNC;
9661 #define BUILTIN_NOSPEC "0"
9662 #define BUILTIN_SPECIAL "1"
9663 #define BUILTIN_REGULAR "2"
9664 #define BUILTIN_SPEC_REG "3"
9665 #define BUILTIN_ASSIGN "4"
9666 #define BUILTIN_SPEC_ASSG "5"
9667 #define BUILTIN_REG_ASSG "6"
9668 #define BUILTIN_SPEC_REG_ASSG "7"
9670 /* Stubs for calling non-FAST_FUNC's */
9672 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9674 #if ENABLE_ASH_PRINTF
9675 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9677 #if ENABLE_ASH_TEST || BASH_TEST2
9678 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9681 /* Keep these in proper order since it is searched via bsearch() */
9682 static const struct builtincmd builtintab[] = {
9683 { BUILTIN_SPEC_REG "." , dotcmd },
9684 { BUILTIN_SPEC_REG ":" , truecmd },
9686 { BUILTIN_REGULAR "[" , testcmd },
9689 { BUILTIN_REGULAR "[[" , testcmd },
9691 #if ENABLE_ASH_ALIAS
9692 { BUILTIN_REG_ASSG "alias" , aliascmd },
9695 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9697 { BUILTIN_SPEC_REG "break" , breakcmd },
9698 { BUILTIN_REGULAR "cd" , cdcmd },
9699 { BUILTIN_NOSPEC "chdir" , cdcmd },
9700 #if ENABLE_ASH_CMDCMD
9701 { BUILTIN_REGULAR "command" , commandcmd },
9703 { BUILTIN_SPEC_REG "continue", breakcmd },
9705 { BUILTIN_REGULAR "echo" , echocmd },
9707 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9708 { BUILTIN_SPEC_REG "exec" , execcmd },
9709 { BUILTIN_SPEC_REG "exit" , exitcmd },
9710 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9711 { BUILTIN_REGULAR "false" , falsecmd },
9713 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9715 #if ENABLE_ASH_GETOPTS
9716 { BUILTIN_REGULAR "getopts" , getoptscmd },
9718 { BUILTIN_NOSPEC "hash" , hashcmd },
9720 { BUILTIN_NOSPEC "help" , helpcmd },
9723 { BUILTIN_NOSPEC "history" , historycmd },
9726 { BUILTIN_REGULAR "jobs" , jobscmd },
9727 { BUILTIN_REGULAR "kill" , killcmd },
9729 #if ENABLE_FEATURE_SH_MATH
9730 { BUILTIN_NOSPEC "let" , letcmd },
9732 { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
9733 #if ENABLE_ASH_PRINTF
9734 { BUILTIN_REGULAR "printf" , printfcmd },
9736 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9737 { BUILTIN_REGULAR "read" , readcmd },
9738 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9739 { BUILTIN_SPEC_REG "return" , returncmd },
9740 { BUILTIN_SPEC_REG "set" , setcmd },
9741 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9743 { BUILTIN_SPEC_REG "source" , dotcmd },
9746 { BUILTIN_REGULAR "test" , testcmd },
9748 { BUILTIN_SPEC_REG "times" , timescmd },
9749 { BUILTIN_SPEC_REG "trap" , trapcmd },
9750 { BUILTIN_REGULAR "true" , truecmd },
9751 { BUILTIN_NOSPEC "type" , typecmd },
9752 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9753 { BUILTIN_REGULAR "umask" , umaskcmd },
9754 #if ENABLE_ASH_ALIAS
9755 { BUILTIN_REGULAR "unalias" , unaliascmd },
9757 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9758 { BUILTIN_REGULAR "wait" , waitcmd },
9761 /* Should match the above table! */
9762 #define COMMANDCMD (builtintab + \
9764 /* [ */ 1 * ENABLE_ASH_TEST + \
9765 /* [[ */ 1 * BASH_TEST2 + \
9766 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9767 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9768 /* break cd cddir */ 3)
9769 #define EVALCMD (COMMANDCMD + \
9770 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9771 /* continue */ 1 + \
9772 /* echo */ 1 * ENABLE_ASH_ECHO + \
9774 #define EXECCMD (EVALCMD + \
9778 * Search the table of builtin commands.
9781 pstrcmp1(const void *a, const void *b)
9783 return strcmp((char*)a, *(char**)b + 1);
9785 static struct builtincmd *
9786 find_builtin(const char *name)
9788 struct builtincmd *bp;
9791 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9798 * Execute a simple command.
9801 isassignment(const char *p)
9803 const char *q = endofname(p);
9808 static int FAST_FUNC
9809 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9811 /* Preserve exitstatus of a previous possible redirection
9812 * as POSIX mandates */
9813 return back_exitstatus;
9816 evalcommand(union node *cmd, int flags)
9818 static const struct builtincmd null_bltin = {
9819 "\0\0", bltincmd /* why three NULs? */
9821 struct localvar_list *localvar_stop;
9822 struct redirtab *redir_stop;
9823 struct stackmark smark;
9825 struct arglist arglist;
9826 struct arglist varlist;
9829 const struct strlist *sp;
9830 struct cmdentry cmdentry;
9837 smallint cmd_is_exec;
9839 /* First expand the arguments. */
9840 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9841 setstackmark(&smark);
9842 localvar_stop = pushlocalvars();
9843 back_exitstatus = 0;
9845 cmdentry.cmdtype = CMDBUILTIN;
9846 cmdentry.u.cmd = &null_bltin;
9847 varlist.lastp = &varlist.list;
9848 *varlist.lastp = NULL;
9849 arglist.lastp = &arglist.list;
9850 *arglist.lastp = NULL;
9853 if (cmd->ncmd.args) {
9854 struct builtincmd *bcmd;
9855 smallint pseudovarflag;
9857 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9858 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9860 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9861 struct strlist **spp;
9863 spp = arglist.lastp;
9864 if (pseudovarflag && isassignment(argp->narg.text))
9865 expandarg(argp, &arglist, EXP_VARTILDE);
9867 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9869 for (sp = *spp; sp; sp = sp->next)
9874 /* Reserve one extra spot at the front for shellexec. */
9875 nargv = stalloc(sizeof(char *) * (argc + 2));
9877 for (sp = arglist.list; sp; sp = sp->next) {
9878 TRACE(("evalcommand arg: %s\n", sp->text));
9879 *nargv++ = sp->text;
9884 if (iflag && funcnest == 0 && argc > 0)
9885 lastarg = nargv[-1];
9887 expredir(cmd->ncmd.redirect);
9888 redir_stop = pushredir(cmd->ncmd.redirect);
9890 if (BASH_XTRACEFD && xflag) {
9891 /* NB: bash closes fd == $BASH_XTRACEFD when it is changed.
9892 * we do not emulate this. We only use its value.
9894 const char *xtracefd = lookupvar("BASH_XTRACEFD");
9895 if (xtracefd && is_number(xtracefd))
9896 preverrout_fd = atoi(xtracefd);
9899 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9901 path = vpath.var_text;
9902 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9903 struct strlist **spp;
9906 spp = varlist.lastp;
9907 expandarg(argp, &varlist, EXP_VARTILDE);
9909 mklocal((*spp)->text);
9912 * Modify the command lookup path, if a PATH= assignment
9916 if (varcmp(p, path) == 0)
9920 /* Print the command if xflag is set. */
9922 const char *pfx = "";
9924 fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
9928 char *varval = sp->text;
9929 char *eq = strchrnul(varval, '=');
9932 fdprintf(preverrout_fd, "%s%.*s%s",
9934 (int)(eq - varval), varval,
9935 maybe_single_quote(eq)
9943 fdprintf(preverrout_fd, "%s%s",
9945 /* always quote if matches reserved word: */
9947 ? single_quote(sp->text)
9948 : maybe_single_quote(sp->text)
9953 safe_write(preverrout_fd, "\n", 1);
9959 /* Now locate the command. */
9961 int cmd_flag = DO_ERR;
9962 #if ENABLE_ASH_CMDCMD
9963 const char *oldpath = path + 5;
9967 find_command(argv[0], &cmdentry, cmd_flag, path);
9968 if (cmdentry.cmdtype == CMDUNKNOWN) {
9969 flush_stdout_stderr();
9974 /* implement bltin and command here */
9975 if (cmdentry.cmdtype != CMDBUILTIN)
9978 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9979 if (cmdentry.u.cmd == EXECCMD)
9981 #if ENABLE_ASH_CMDCMD
9982 if (cmdentry.u.cmd == COMMANDCMD) {
9984 nargv = parse_command_args(argv, &path);
9987 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9988 * nargv => "PROG". path is updated if -p.
9990 argc -= nargv - argv;
9992 cmd_flag |= DO_NOFUNC;
10001 exitstatus = status;
10003 /* We have a redirection error. */
10005 raise_exception(EXERROR);
10010 /* Execute the command. */
10011 switch (cmdentry.cmdtype) {
10014 #if ENABLE_FEATURE_SH_STANDALONE \
10015 && ENABLE_FEATURE_SH_NOFORK \
10017 /* (1) BUG: if variables are set, we need to fork, or save/restore them
10018 * around run_nofork_applet() call.
10019 * (2) Should this check also be done in forkshell()?
10020 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
10022 /* find_command() encodes applet_no as (-2 - applet_no) */
10023 int applet_no = (- cmdentry.u.index - 2);
10024 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
10028 sv_environ = environ;
10029 environ = listvars(VEXPORT, VUNSET, varlist.list, /*end:*/ NULL);
10031 * Run <applet>_main().
10032 * Signals (^C) can't interrupt here.
10033 * Otherwise we can mangle stdio or malloc internal state.
10034 * This makes applets which can run for a long time
10035 * and/or wait for user input ineligible for NOFORK:
10036 * for example, "yes" or "rm" (rm -i waits for input).
10038 status = run_nofork_applet(applet_no, argv);
10039 environ = sv_environ;
10041 * Try enabling NOFORK for "yes" applet.
10042 * ^C _will_ stop it (write returns EINTR),
10043 * but this causes stdout FILE to be stuck
10044 * and needing clearerr(). What if other applets
10045 * also can get EINTRs? Do we need to switch
10046 * our signals to SA_RESTART?
10048 /*clearerr(stdout);*/
10053 /* Can we avoid forking? For example, very last command
10054 * in a script or a subshell does not need forking,
10055 * we can just exec it.
10057 if (!(flags & EV_EXIT) || may_have_traps) {
10058 /* No, forking off a child is necessary */
10061 jp = makejob(/*cmd,*/ 1);
10062 if (forkshell(jp, cmd, FORK_FG) != 0) {
10064 status = waitforjob(jp);
10066 TRACE(("forked child exited with %d\n", status));
10071 /* fall through to exec'ing external program */
10073 listsetvar(varlist.list, VEXPORT|VSTACK);
10074 shellexec(argv[0], argv, path, cmdentry.u.index);
10078 if (spclbltin > 0 || argc == 0) {
10080 if (cmd_is_exec && argc > 1)
10081 listsetvar(varlist.list, VEXPORT);
10084 /* Tight loop with builtins only:
10085 * "while kill -0 $child; do true; done"
10086 * will never exit even if $child died, unless we do this
10087 * to reap the zombie and make kill detect that it's gone: */
10088 dowait(DOWAIT_NONBLOCK, NULL);
10090 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
10091 if (exception_type == EXERROR && spclbltin <= 0) {
10096 longjmp(exception_handler->loc, 1);
10102 /* See above for the rationale */
10103 dowait(DOWAIT_NONBLOCK, NULL);
10104 if (evalfun(cmdentry.u.func, argc, argv, flags))
10107 status = exitstatus;
10112 if (cmd->ncmd.redirect)
10113 popredir(/*drop:*/ cmd_is_exec);
10114 unwindredir(redir_stop);
10115 unwindlocalvars(localvar_stop);
10117 /* dsl: I think this is intended to be used to support
10118 * '_' in 'vi' command mode during line editing...
10119 * However I implemented that within libedit itself.
10121 setvar0("_", lastarg);
10123 popstackmark(&smark);
10129 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
10131 char *volatile savecmdname;
10132 struct jmploc *volatile savehandler;
10133 struct jmploc jmploc;
10137 savecmdname = commandname;
10138 savehandler = exception_handler;
10139 i = setjmp(jmploc.loc);
10142 exception_handler = &jmploc;
10143 commandname = argv[0];
10145 optptr = NULL; /* initialize nextopt */
10146 if (cmd == EVALCMD)
10147 status = evalcmd(argc, argv, flags);
10149 status = (*cmd->builtin)(argc, argv);
10150 flush_stdout_stderr();
10151 status |= ferror(stdout);
10152 exitstatus = status;
10155 commandname = savecmdname;
10156 exception_handler = savehandler;
10162 goodname(const char *p)
10164 return endofname(p)[0] == '\0';
10169 * Search for a command. This is called before we fork so that the
10170 * location of the command will be available in the parent as well as
10171 * the child. The check for "goodname" is an overly conservative
10172 * check that the name will not be subject to expansion.
10175 prehash(union node *n)
10177 struct cmdentry entry;
10179 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
10180 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
10184 /* ============ Builtin commands
10186 * Builtin commands whose functions are closely tied to evaluation
10187 * are implemented here.
10191 * Handle break and continue commands. Break, continue, and return are
10192 * all handled by setting the evalskip flag. The evaluation routines
10193 * above all check this flag, and if it is set they start skipping
10194 * commands rather than executing them. The variable skipcount is
10195 * the number of loops to break/continue, or the number of function
10196 * levels to return. (The latter is always 1.) It should probably
10197 * be an error to break out of more loops than exist, but it isn't
10198 * in the standard shell so we don't make it one here.
10200 static int FAST_FUNC
10201 breakcmd(int argc UNUSED_PARAM, char **argv)
10203 int n = argv[1] ? number(argv[1]) : 1;
10206 ash_msg_and_raise_error(msg_illnum, argv[1]);
10210 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
10218 * This implements the input routines used by the parser.
10222 INPUT_PUSH_FILE = 1,
10223 INPUT_NOFILE_OK = 2,
10226 static smallint checkkwd;
10227 /* values of checkkwd variable */
10228 #define CHKALIAS 0x1
10231 #define CHKEOFMARK 0x8
10234 * Push a string back onto the input at this current parsefile level.
10235 * We handle aliases this way.
10237 #if !ENABLE_ASH_ALIAS
10238 #define pushstring(s, ap) pushstring(s)
10241 pushstring(char *s, struct alias *ap)
10243 struct strpush *sp;
10248 if (g_parsefile->strpush) {
10249 sp = ckzalloc(sizeof(*sp));
10250 sp->prev = g_parsefile->strpush;
10252 sp = &(g_parsefile->basestrpush);
10254 g_parsefile->strpush = sp;
10255 sp->prev_string = g_parsefile->next_to_pgetc;
10256 sp->prev_left_in_line = g_parsefile->left_in_line;
10257 sp->unget = g_parsefile->unget;
10258 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
10259 #if ENABLE_ASH_ALIAS
10262 ap->flag |= ALIASINUSE;
10266 g_parsefile->next_to_pgetc = s;
10267 g_parsefile->left_in_line = len;
10268 g_parsefile->unget = 0;
10275 struct strpush *sp = g_parsefile->strpush;
10278 #if ENABLE_ASH_ALIAS
10280 if (g_parsefile->next_to_pgetc[-1] == ' '
10281 || g_parsefile->next_to_pgetc[-1] == '\t'
10283 checkkwd |= CHKALIAS;
10285 if (sp->string != sp->ap->val) {
10288 sp->ap->flag &= ~ALIASINUSE;
10289 if (sp->ap->flag & ALIASDEAD) {
10290 unalias(sp->ap->name);
10294 g_parsefile->next_to_pgetc = sp->prev_string;
10295 g_parsefile->left_in_line = sp->prev_left_in_line;
10296 g_parsefile->unget = sp->unget;
10297 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
10298 g_parsefile->strpush = sp->prev;
10299 if (sp != &(g_parsefile->basestrpush))
10308 char *buf = g_parsefile->buf;
10310 g_parsefile->next_to_pgetc = buf;
10311 #if ENABLE_FEATURE_EDITING
10313 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
10314 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10316 # if ENABLE_ASH_IDLE_TIMEOUT
10319 const char *tmout_var = lookupvar("TMOUT");
10321 timeout = atoi(tmout_var) * 1000;
10326 line_input_state->timeout = timeout;
10328 # if ENABLE_FEATURE_TAB_COMPLETION
10329 line_input_state->path_lookup = pathval();
10331 reinit_unicode_for_ash();
10332 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ);
10334 /* ^C pressed, "convert" to SIGINT */
10335 write(STDOUT_FILENO, "^C", 2);
10336 if (trap[SIGINT]) {
10342 exitstatus = 128 + SIGINT;
10348 /* Ctrl+D pressed */
10351 # if ENABLE_ASH_IDLE_TIMEOUT
10352 else if (errno == EAGAIN && timeout > 0) {
10353 puts("\007timed out waiting for input: auto-logout");
10360 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10363 #if 0 /* disabled: nonblock_immune_read() handles this problem */
10365 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
10366 int flags = fcntl(0, F_GETFL);
10367 if (flags >= 0 && (flags & O_NONBLOCK)) {
10368 flags &= ~O_NONBLOCK;
10369 if (fcntl(0, F_SETFL, flags) >= 0) {
10370 out2str("sh: turning off NDELAY mode\n");
10381 * Refill the input buffer and return the next input character:
10383 * 1) If a string was pushed back on the input, pop it;
10384 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
10385 * or we are reading from a string so we can't refill the buffer,
10387 * 3) If there is more stuff in this buffer, use it else call read to fill it.
10388 * 4) Process input up to the next newline, deleting nul characters.
10390 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
10391 #define pgetc_debug(...) ((void)0)
10392 static int pgetc(void);
10399 if (g_parsefile->strpush) {
10400 #if ENABLE_ASH_ALIAS
10401 if (g_parsefile->left_in_line == -1
10402 && g_parsefile->strpush->ap
10403 && g_parsefile->next_to_pgetc[-1] != ' '
10404 && g_parsefile->next_to_pgetc[-1] != '\t'
10406 pgetc_debug("preadbuffer PEOA");
10413 /* on both branches above g_parsefile->left_in_line < 0.
10414 * "pgetc" needs refilling.
10417 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
10418 * pungetc() may increment it a few times.
10419 * Assuming it won't increment it to less than -90.
10421 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
10422 pgetc_debug("preadbuffer PEOF1");
10423 /* even in failure keep left_in_line and next_to_pgetc
10424 * in lock step, for correct multi-layer pungetc.
10425 * left_in_line was decremented before preadbuffer(),
10426 * must inc next_to_pgetc: */
10427 g_parsefile->next_to_pgetc++;
10431 more = g_parsefile->left_in_buffer;
10433 flush_stdout_stderr();
10437 /* don't try reading again */
10438 g_parsefile->left_in_line = -99;
10439 pgetc_debug("preadbuffer PEOF2");
10440 g_parsefile->next_to_pgetc++;
10445 /* Find out where's the end of line.
10446 * Set g_parsefile->left_in_line
10447 * and g_parsefile->left_in_buffer acordingly.
10448 * NUL chars are deleted.
10450 q = g_parsefile->next_to_pgetc;
10458 memmove(q, q + 1, more);
10462 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10468 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10469 if (g_parsefile->left_in_line < 0)
10474 g_parsefile->left_in_buffer = more;
10479 out2str(g_parsefile->next_to_pgetc);
10483 pgetc_debug("preadbuffer at %d:%p'%s'",
10484 g_parsefile->left_in_line,
10485 g_parsefile->next_to_pgetc,
10486 g_parsefile->next_to_pgetc);
10487 return (unsigned char)*g_parsefile->next_to_pgetc++;
10493 g_parsefile->linno++;
10494 setprompt_if(doprompt, 2);
10499 g_parsefile->linno++;
10500 needprompt = doprompt;
10508 pgetc_debug("pgetc at %d:%p'%s'",
10509 g_parsefile->left_in_line,
10510 g_parsefile->next_to_pgetc,
10511 g_parsefile->next_to_pgetc);
10512 if (g_parsefile->unget)
10513 return g_parsefile->lastc[--g_parsefile->unget];
10515 if (--g_parsefile->left_in_line >= 0)
10516 c = (unsigned char)*g_parsefile->next_to_pgetc++;
10520 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10521 g_parsefile->lastc[0] = c;
10526 #if ENABLE_ASH_ALIAS
10528 pgetc_without_PEOA(void)
10532 pgetc_debug("pgetc at %d:%p'%s'",
10533 g_parsefile->left_in_line,
10534 g_parsefile->next_to_pgetc,
10535 g_parsefile->next_to_pgetc);
10537 } while (c == PEOA);
10541 # define pgetc_without_PEOA() pgetc()
10545 * Undo a call to pgetc. Only two characters may be pushed back.
10546 * PEOF may be pushed back.
10551 g_parsefile->unget++;
10554 /* This one eats backslash+newline */
10560 while ((c = pgetc()) == '\\') {
10561 if (pgetc() != '\n') {
10573 * To handle the "." command, a stack of input files is used. Pushfile
10574 * adds a new entry to the stack and popfile restores the previous level.
10579 struct parsefile *pf;
10581 pf = ckzalloc(sizeof(*pf));
10582 pf->prev = g_parsefile;
10584 /*pf->strpush = NULL; - ckzalloc did it */
10585 /*pf->basestrpush.prev = NULL;*/
10593 struct parsefile *pf = g_parsefile;
10599 if (pf->pf_fd >= 0)
10602 while (pf->strpush)
10604 g_parsefile = pf->prev;
10610 * Return to top level.
10615 while (g_parsefile != &basepf)
10620 * Close the file(s) that the shell is reading commands from. Called
10621 * after a fork is done.
10627 if (g_parsefile->pf_fd > 0) {
10628 close(g_parsefile->pf_fd);
10629 g_parsefile->pf_fd = 0;
10634 * Like setinputfile, but takes an open file descriptor. Call this with
10638 setinputfd(int fd, int push)
10642 g_parsefile->buf = NULL;
10644 g_parsefile->pf_fd = fd;
10645 if (g_parsefile->buf == NULL)
10646 g_parsefile->buf = ckmalloc(IBUFSIZ);
10647 g_parsefile->left_in_buffer = 0;
10648 g_parsefile->left_in_line = 0;
10649 g_parsefile->linno = 1;
10653 * Set the input to take input from a file. If push is set, push the
10654 * old input onto the stack first.
10657 setinputfile(const char *fname, int flags)
10662 fd = open(fname, O_RDONLY);
10664 if (flags & INPUT_NOFILE_OK)
10667 ash_msg_and_raise_perror("can't open '%s'", fname);
10672 close_on_exec_on(fd);
10673 setinputfd(fd, flags & INPUT_PUSH_FILE);
10680 * Like setinputfile, but takes input from a string.
10683 setinputstring(char *string)
10687 g_parsefile->next_to_pgetc = string;
10688 g_parsefile->left_in_line = strlen(string);
10689 g_parsefile->buf = NULL;
10690 g_parsefile->linno = 1;
10696 * Routines to check for mail.
10699 #if ENABLE_ASH_MAIL
10701 /* Hash of mtimes of mailboxes */
10702 static unsigned mailtime_hash;
10703 /* Set if MAIL or MAILPATH is changed. */
10704 static smallint mail_var_path_changed;
10707 * Print appropriate message(s) if mail has arrived.
10708 * If mail_var_path_changed is set,
10709 * then the value of MAIL has mail_var_path_changed,
10710 * so we just update the values.
10719 struct stackmark smark;
10722 setstackmark(&smark);
10723 mpath = mpathset() ? mpathval() : mailval();
10726 p = path_advance(&mpath, nullstr);
10731 for (q = p; *q; q++)
10737 q[-1] = '\0'; /* delete trailing '/' */
10738 if (stat(p, &statb) < 0) {
10741 /* Very simplistic "hash": just a sum of all mtimes */
10742 new_hash += (unsigned)statb.st_mtime;
10744 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10745 if (mailtime_hash != 0)
10746 out2str("you have mail\n");
10747 mailtime_hash = new_hash;
10749 mail_var_path_changed = 0;
10750 popstackmark(&smark);
10753 static void FAST_FUNC
10754 changemail(const char *val UNUSED_PARAM)
10756 mail_var_path_changed = 1;
10759 #endif /* ASH_MAIL */
10762 /* ============ ??? */
10765 * Set the shell parameters.
10768 setparam(char **argv)
10774 for (nparam = 0; argv[nparam]; nparam++)
10776 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10778 *ap++ = ckstrdup(*argv++);
10781 freeparam(&shellparam);
10782 shellparam.malloced = 1;
10783 shellparam.nparam = nparam;
10784 shellparam.p = newparam;
10785 #if ENABLE_ASH_GETOPTS
10786 shellparam.optind = 1;
10787 shellparam.optoff = -1;
10792 * Process shell options. The global variable argptr contains a pointer
10793 * to the argument list; we advance it past the options.
10795 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10796 * For a non-interactive shell, an error condition encountered
10797 * by a special built-in ... shall cause the shell to write a diagnostic message
10798 * to standard error and exit as shown in the following table:
10799 * Error Special Built-In
10801 * Utility syntax error (option or operand error) Shall exit
10803 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10804 * we see that bash does not do that (set "finishes" with error code 1 instead,
10805 * and shell continues), and people rely on this behavior!
10807 * set -o barfoo 2>/dev/null
10810 * Oh well. Let's mimic that.
10813 plus_minus_o(char *name, int val)
10818 for (i = 0; i < NOPTS; i++) {
10819 if (strcmp(name, optnames(i)) == 0) {
10824 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10827 for (i = 0; i < NOPTS; i++) {
10829 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10831 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10837 setoption(int flag, int val)
10841 for (i = 0; i < NOPTS; i++) {
10842 if (optletters(i) == flag) {
10847 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10851 options(int cmdline, int *login_sh)
10859 while ((p = *argptr) != NULL) {
10861 if (c != '-' && c != '+')
10864 val = 0; /* val = 0 if c == '+' */
10867 if (p[0] == '\0' || LONE_DASH(p)) {
10869 /* "-" means turn off -x and -v */
10872 /* "--" means reset params */
10873 else if (*argptr == NULL)
10876 break; /* "-" or "--" terminates options */
10879 /* first char was + or - */
10880 while ((c = *p++) != '\0') {
10881 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10882 if (c == 'c' && cmdline) {
10883 minusc = p; /* command is after shell args */
10884 } else if (c == 'o') {
10885 if (plus_minus_o(*argptr, val)) {
10886 /* it already printed err message */
10887 return 1; /* error */
10891 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10894 /* bash does not accept +-login, we also won't */
10895 } else if (cmdline && val && (c == '-')) { /* long options */
10896 if (strcmp(p, "login") == 0) {
10910 * The shift builtin command.
10912 static int FAST_FUNC
10913 shiftcmd(int argc UNUSED_PARAM, char **argv)
10920 n = number(argv[1]);
10921 if (n > shellparam.nparam)
10924 shellparam.nparam -= n;
10925 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10926 if (shellparam.malloced)
10929 ap2 = shellparam.p;
10930 while ((*ap2++ = *ap1++) != NULL)
10932 #if ENABLE_ASH_GETOPTS
10933 shellparam.optind = 1;
10934 shellparam.optoff = -1;
10941 * POSIX requires that 'set' (but not export or readonly) output the
10942 * variables in lexicographic order - by the locale's collating order (sigh).
10943 * Maybe we could keep them in an ordered balanced binary tree
10944 * instead of hashed lists.
10945 * For now just roll 'em through qsort for printing...
10948 showvars(const char *sep_prefix, int on, int off)
10951 char **ep, **epend;
10953 ep = listvars(on, off, /*strlist:*/ NULL, &epend);
10954 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10956 sep = *sep_prefix ? " " : sep_prefix;
10958 for (; ep < epend; ep++) {
10962 p = endofname(*ep);
10963 /* Used to have simple "p = strchrnul(*ep, '=')" here instead, but this
10964 * makes "export -p" to have output not suitable for "eval":
10966 * os.environ["test-test"]="test"
10967 * if os.fork() == 0:
10968 * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
10969 * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ])
10973 q = single_quote(++p);
10974 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10980 * The set command builtin.
10982 static int FAST_FUNC
10983 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10988 return showvars(nullstr, 0, VUNSET);
10991 retval = options(/*cmdline:*/ 0, NULL);
10992 if (retval == 0) { /* if no parse error... */
10994 if (*argptr != NULL) {
11002 #if ENABLE_ASH_RANDOM_SUPPORT
11003 static void FAST_FUNC
11004 change_random(const char *value)
11008 if (value == NULL) {
11009 /* "get", generate */
11010 t = next_random(&random_gen);
11011 /* set without recursion */
11012 setvar(vrandom.var_text, utoa(t), VNOFUNC);
11013 vrandom.flags &= ~VNOFUNC;
11016 t = strtoul(value, NULL, 10);
11017 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
11022 #if ENABLE_ASH_GETOPTS
11024 getopts(char *optstr, char *optvar, char **optfirst)
11031 int ind = shellparam.optind;
11032 int off = shellparam.optoff;
11036 shellparam.optind = -1;
11037 optnext = optfirst + ind - 1;
11039 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
11042 p = optnext[-1] + off;
11043 if (p == NULL || *p == '\0') {
11044 /* Current word is done, advance */
11046 if (p == NULL || *p != '-' || *++p == '\0') {
11048 unsetvar("OPTARG");
11054 if (LONE_DASH(p)) /* check for "--" */
11059 for (q = optstr; *q != c;) {
11061 /* OPTERR is a bashism */
11062 const char *cp = lookupvar("OPTERR");
11063 if ((cp && LONE_CHAR(cp, '0'))
11064 || (optstr[0] == ':')
11067 /*sbuf[1] = '\0'; - already is */
11068 setvar0("OPTARG", sbuf);
11070 fprintf(stderr, "Illegal option -%c\n", c);
11071 unsetvar("OPTARG");
11081 if (*p == '\0' && (p = *optnext) == NULL) {
11082 /* OPTERR is a bashism */
11083 const char *cp = lookupvar("OPTERR");
11084 if ((cp && LONE_CHAR(cp, '0'))
11085 || (optstr[0] == ':')
11088 /*sbuf[1] = '\0'; - already is */
11089 setvar0("OPTARG", sbuf);
11092 fprintf(stderr, "No arg for -%c option\n", c);
11093 unsetvar("OPTARG");
11101 setvar0("OPTARG", p);
11104 setvar0("OPTARG", nullstr);
11106 ind = optnext - optfirst + 1;
11107 setvar("OPTIND", itoa(ind), VNOFUNC);
11109 /*sbuf[1] = '\0'; - already is */
11110 setvar0(optvar, sbuf);
11112 shellparam.optoff = p ? p - *(optnext - 1) : -1;
11113 shellparam.optind = ind;
11119 * The getopts builtin. Shellparam.optnext points to the next argument
11120 * to be processed. Shellparam.optptr points to the next character to
11121 * be processed in the current argument. If shellparam.optnext is NULL,
11122 * then it's the first time getopts has been called.
11124 static int FAST_FUNC
11125 getoptscmd(int argc, char **argv)
11130 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
11132 optbase = shellparam.p;
11133 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
11134 shellparam.optind = 1;
11135 shellparam.optoff = -1;
11138 optbase = &argv[3];
11139 if ((unsigned)shellparam.optind > argc - 2) {
11140 shellparam.optind = 1;
11141 shellparam.optoff = -1;
11145 return getopts(argv[1], argv[2], optbase);
11147 #endif /* ASH_GETOPTS */
11150 /* ============ Shell parser */
11153 struct heredoc *next; /* next here document in list */
11154 union node *here; /* redirection node */
11155 char *eofmark; /* string indicating end of input */
11156 smallint striptabs; /* if set, strip leading tabs */
11159 static smallint tokpushback; /* last token pushed back */
11160 static smallint quoteflag; /* set if (part of) last token was quoted */
11161 static token_id_t lasttoken; /* last token read (integer id Txxx) */
11162 static struct heredoc *heredoclist; /* list of here documents to read */
11163 static char *wordtext; /* text of last word returned by readtoken */
11164 static struct nodelist *backquotelist;
11165 static union node *redirnode;
11166 static struct heredoc *heredoc;
11168 static const char *
11169 tokname(char *buf, int tok)
11172 return tokname_array[tok];
11173 sprintf(buf, "\"%s\"", tokname_array[tok]);
11177 /* raise_error_unexpected_syntax:
11178 * Called when an unexpected token is read during the parse. The argument
11179 * is the token that is expected, or -1 if more than one type of token can
11180 * occur at this point.
11182 static void raise_error_unexpected_syntax(int) NORETURN;
11184 raise_error_unexpected_syntax(int token)
11190 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
11192 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
11193 raise_error_syntax(msg);
11197 /* parsing is heavily cross-recursive, need these forward decls */
11198 static union node *andor(void);
11199 static union node *pipeline(void);
11200 static union node *parse_command(void);
11201 static void parseheredoc(void);
11202 static int peektoken(void);
11203 static int readtoken(void);
11205 static union node *
11208 union node *n1, *n2, *n3;
11213 switch (peektoken()) {
11221 if (!n1 && (nlflag & 1))
11227 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11228 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
11234 if (tok == TBACKGND) {
11235 if (n2->type == NPIPE) {
11236 n2->npipe.pipe_backgnd = 1;
11238 if (n2->type != NREDIR) {
11239 n3 = stzalloc(sizeof(struct nredir));
11241 /*n3->nredir.redirect = NULL; - stzalloc did it */
11244 n2->type = NBACKGND;
11250 n3 = stzalloc(sizeof(struct nbinary));
11252 n3->nbinary.ch1 = n1;
11253 n3->nbinary.ch2 = n2;
11266 raise_error_unexpected_syntax(-1);
11273 static union node *
11276 union node *n1, *n2, *n3;
11284 } else if (t == TOR) {
11290 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11292 n3 = stzalloc(sizeof(struct nbinary));
11294 n3->nbinary.ch1 = n1;
11295 n3->nbinary.ch2 = n2;
11300 static union node *
11303 union node *n1, *n2, *pipenode;
11304 struct nodelist *lp, *prev;
11308 TRACE(("pipeline: entered\n"));
11309 if (readtoken() == TNOT) {
11311 checkkwd = CHKKWD | CHKALIAS;
11314 n1 = parse_command();
11315 if (readtoken() == TPIPE) {
11316 pipenode = stzalloc(sizeof(struct npipe));
11317 pipenode->type = NPIPE;
11318 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
11319 lp = stzalloc(sizeof(struct nodelist));
11320 pipenode->npipe.cmdlist = lp;
11324 lp = stzalloc(sizeof(struct nodelist));
11325 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11326 lp->n = parse_command();
11328 } while (readtoken() == TPIPE);
11334 n2 = stzalloc(sizeof(struct nnot));
11342 static union node *
11347 n = stzalloc(sizeof(struct narg));
11349 /*n->narg.next = NULL; - stzalloc did it */
11350 n->narg.text = wordtext;
11351 n->narg.backquote = backquotelist;
11356 fixredir(union node *n, const char *text, int err)
11360 TRACE(("Fix redir %s %d\n", text, err));
11362 n->ndup.vname = NULL;
11364 fd = bb_strtou(text, NULL, 10);
11365 if (!errno && fd >= 0)
11366 n->ndup.dupfd = fd;
11367 else if (LONE_DASH(text))
11368 n->ndup.dupfd = -1;
11371 raise_error_syntax("bad fd number");
11372 n->ndup.vname = makename();
11379 union node *n = redirnode;
11381 if (n->type == NHERE)
11382 checkkwd = CHKEOFMARK;
11383 if (readtoken() != TWORD)
11384 raise_error_unexpected_syntax(-1);
11385 if (n->type == NHERE) {
11386 struct heredoc *here = heredoc;
11389 if (quoteflag == 0)
11391 TRACE(("Here document %d\n", n->type));
11392 rmescapes(wordtext, 0, NULL);
11393 here->eofmark = wordtext;
11395 if (heredoclist == NULL)
11396 heredoclist = here;
11398 for (p = heredoclist; p->next; p = p->next)
11402 } else if (n->type == NTOFD || n->type == NFROMFD) {
11403 fixredir(n, wordtext, 0);
11405 n->nfile.fname = makename();
11409 static union node *
11412 union node *args, **app;
11413 union node *n = NULL;
11414 union node *vars, **vpp;
11415 union node **rpp, *redir;
11418 smallint double_brackets_flag = 0;
11420 IF_BASH_FUNCTION(smallint function_flag = 0;)
11429 savecheckkwd = CHKALIAS;
11432 checkkwd = savecheckkwd;
11437 if (peektoken() != TWORD)
11438 raise_error_unexpected_syntax(TWORD);
11443 case TAND: /* "&&" */
11444 case TOR: /* "||" */
11445 if (!double_brackets_flag) {
11449 wordtext = (char *) (t == TAND ? "-a" : "-o");
11452 n = stzalloc(sizeof(struct narg));
11454 /*n->narg.next = NULL; - stzalloc did it */
11455 n->narg.text = wordtext;
11457 if (strcmp("[[", wordtext) == 0)
11458 double_brackets_flag = 1;
11459 else if (strcmp("]]", wordtext) == 0)
11460 double_brackets_flag = 0;
11462 n->narg.backquote = backquotelist;
11463 if (savecheckkwd && isassignment(wordtext)) {
11465 vpp = &n->narg.next;
11468 app = &n->narg.next;
11472 if (function_flag) {
11473 checkkwd = CHKNL | CHKKWD;
11474 switch (peektoken()) {
11486 if (strcmp("[[", wordtext) == 0)
11490 raise_error_unexpected_syntax(-1);
11496 *rpp = n = redirnode;
11497 rpp = &n->nfile.next;
11498 parsefname(); /* read name of redirection file */
11501 IF_BASH_FUNCTION(do_func:)
11502 if (args && app == &args->narg.next
11505 struct builtincmd *bcmd;
11508 /* We have a function */
11509 if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
11510 raise_error_unexpected_syntax(TRP);
11511 name = n->narg.text;
11512 if (!goodname(name)
11513 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11515 raise_error_syntax("bad function name");
11518 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11519 n->narg.next = parse_command();
11522 IF_BASH_FUNCTION(function_flag = 0;)
11533 n = stzalloc(sizeof(struct ncmd));
11535 n->ncmd.args = args;
11536 n->ncmd.assign = vars;
11537 n->ncmd.redirect = redir;
11541 static union node *
11542 parse_command(void)
11544 union node *n1, *n2;
11545 union node *ap, **app;
11546 union node *cp, **cpp;
11547 union node *redir, **rpp;
11554 switch (readtoken()) {
11556 raise_error_unexpected_syntax(-1);
11559 n1 = stzalloc(sizeof(struct nif));
11561 n1->nif.test = list(0);
11562 if (readtoken() != TTHEN)
11563 raise_error_unexpected_syntax(TTHEN);
11564 n1->nif.ifpart = list(0);
11566 while (readtoken() == TELIF) {
11567 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11568 n2 = n2->nif.elsepart;
11570 n2->nif.test = list(0);
11571 if (readtoken() != TTHEN)
11572 raise_error_unexpected_syntax(TTHEN);
11573 n2->nif.ifpart = list(0);
11575 if (lasttoken == TELSE)
11576 n2->nif.elsepart = list(0);
11578 n2->nif.elsepart = NULL;
11586 n1 = stzalloc(sizeof(struct nbinary));
11587 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11588 n1->nbinary.ch1 = list(0);
11591 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11592 got == TWORD ? wordtext : ""));
11593 raise_error_unexpected_syntax(TDO);
11595 n1->nbinary.ch2 = list(0);
11600 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11601 raise_error_syntax("bad for loop variable");
11602 n1 = stzalloc(sizeof(struct nfor));
11604 n1->nfor.var = wordtext;
11605 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11606 if (readtoken() == TIN) {
11608 while (readtoken() == TWORD) {
11609 n2 = stzalloc(sizeof(struct narg));
11611 /*n2->narg.next = NULL; - stzalloc did it */
11612 n2->narg.text = wordtext;
11613 n2->narg.backquote = backquotelist;
11615 app = &n2->narg.next;
11618 n1->nfor.args = ap;
11619 if (lasttoken != TNL && lasttoken != TSEMI)
11620 raise_error_unexpected_syntax(-1);
11622 n2 = stzalloc(sizeof(struct narg));
11624 /*n2->narg.next = NULL; - stzalloc did it */
11625 n2->narg.text = (char *)dolatstr;
11626 /*n2->narg.backquote = NULL;*/
11627 n1->nfor.args = n2;
11629 * Newline or semicolon here is optional (but note
11630 * that the original Bourne shell only allowed NL).
11632 if (lasttoken != TSEMI)
11635 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11636 if (readtoken() != TDO)
11637 raise_error_unexpected_syntax(TDO);
11638 n1->nfor.body = list(0);
11642 n1 = stzalloc(sizeof(struct ncase));
11644 if (readtoken() != TWORD)
11645 raise_error_unexpected_syntax(TWORD);
11646 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11648 /*n2->narg.next = NULL; - stzalloc did it */
11649 n2->narg.text = wordtext;
11650 n2->narg.backquote = backquotelist;
11651 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11652 if (readtoken() != TIN)
11653 raise_error_unexpected_syntax(TIN);
11654 cpp = &n1->ncase.cases;
11656 checkkwd = CHKNL | CHKKWD;
11658 while (t != TESAC) {
11659 if (lasttoken == TLP)
11661 *cpp = cp = stzalloc(sizeof(struct nclist));
11663 app = &cp->nclist.pattern;
11665 *app = ap = stzalloc(sizeof(struct narg));
11667 /*ap->narg.next = NULL; - stzalloc did it */
11668 ap->narg.text = wordtext;
11669 ap->narg.backquote = backquotelist;
11670 if (readtoken() != TPIPE)
11672 app = &ap->narg.next;
11675 //ap->narg.next = NULL;
11676 if (lasttoken != TRP)
11677 raise_error_unexpected_syntax(TRP);
11678 cp->nclist.body = list(2);
11680 cpp = &cp->nclist.next;
11682 checkkwd = CHKNL | CHKKWD;
11686 raise_error_unexpected_syntax(TENDCASE);
11693 n1 = stzalloc(sizeof(struct nredir));
11694 n1->type = NSUBSHELL;
11695 n1->nredir.n = list(0);
11696 /*n1->nredir.redirect = NULL; - stzalloc did it */
11703 IF_BASH_FUNCTION(case TFUNCTION:)
11707 return simplecmd();
11710 if (readtoken() != t)
11711 raise_error_unexpected_syntax(t);
11714 /* Now check for redirection which may follow command */
11715 checkkwd = CHKKWD | CHKALIAS;
11717 while (readtoken() == TREDIR) {
11718 *rpp = n2 = redirnode;
11719 rpp = &n2->nfile.next;
11725 if (n1->type != NSUBSHELL) {
11726 n2 = stzalloc(sizeof(struct nredir));
11731 n1->nredir.redirect = redir;
11736 #if BASH_DOLLAR_SQUOTE
11738 decode_dollar_squote(void)
11740 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11746 p = strchr(C_escapes, c);
11751 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11755 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11757 } else if (c == 'x') { /* \xHH */
11761 } while (isxdigit(c) && --cnt);
11763 if (cnt == 3) { /* \x but next char is "bad" */
11767 } else { /* simple seq like \\ or \t */
11772 c = bb_process_escape_sequence((void*)&p);
11773 } else { /* unrecognized "\z": print both chars unless ' or " */
11774 if (c != '\'' && c != '"') {
11776 c |= 0x100; /* "please encode \, then me" */
11783 /* Used by expandstr to get here-doc like behaviour. */
11784 #define FAKEEOFMARK ((char*)(uintptr_t)1)
11786 static ALWAYS_INLINE int
11787 realeofmark(const char *eofmark)
11789 return eofmark && eofmark != FAKEEOFMARK;
11793 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11794 * is not NULL, read a here document. In the latter case, eofmark is the
11795 * word which marks the end of the document and striptabs is true if
11796 * leading tabs should be stripped from the document. The argument c
11797 * is the first character of the input token or document.
11799 * Because C does not have internal subroutines, I have simulated them
11800 * using goto's to implement the subroutine linkage. The following macros
11801 * will run code that appears at the end of readtoken1.
11803 #define CHECKEND() {goto checkend; checkend_return:;}
11804 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11805 #define PARSESUB() {goto parsesub; parsesub_return:;}
11806 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11807 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11808 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11810 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11812 /* NB: syntax parameter fits into smallint */
11813 /* c parameter is an unsigned char or PEOF or PEOA */
11816 struct nodelist *bqlist;
11820 IF_FEATURE_SH_MATH(smallint prevsyntax;) /* syntax before arithmetic */
11821 smallint pssyntax; /* we are expanding a prompt string */
11822 int varnest; /* levels of variables expansion */
11823 IF_FEATURE_SH_MATH(int arinest;) /* levels of arithmetic expansion */
11824 IF_FEATURE_SH_MATH(int parenlevel;) /* levels of parens in arithmetic */
11825 int dqvarnest; /* levels of variables expansion within double quotes */
11827 IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
11829 startlinno = g_parsefile->linno;
11832 IF_FEATURE_SH_MATH(prevsyntax = 0;)
11833 #if ENABLE_ASH_EXPAND_PRMT
11834 pssyntax = (syntax == PSSYNTAX);
11838 pssyntax = 0; /* constant */
11840 dblquote = (syntax == DQSYNTAX);
11842 IF_FEATURE_SH_MATH(arinest = 0;)
11843 IF_FEATURE_SH_MATH(parenlevel = 0;)
11846 STARTSTACKSTR(out);
11848 /* For each line, until end of word */
11849 CHECKEND(); /* set c to PEOF if at end of here document */
11850 for (;;) { /* until end of line or end of word */
11851 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11852 switch (SIT(c, syntax)) {
11853 case CNL: /* '\n' */
11854 if (syntax == BASESYNTAX)
11855 goto endword; /* exit outer loop */
11859 goto loop; /* continue outer loop */
11864 #if BASH_DOLLAR_SQUOTE
11865 if (c == '\\' && bash_dollar_squote) {
11866 c = decode_dollar_squote();
11868 /* skip $'\000', $'\x00' (like bash) */
11872 /* Unknown escape. Encode as '\z' */
11873 c = (unsigned char)c;
11874 if (eofmark == NULL || dblquote)
11875 USTPUTC(CTLESC, out);
11876 USTPUTC('\\', out);
11880 if (eofmark == NULL || dblquote)
11881 USTPUTC(CTLESC, out);
11884 case CBACK: /* backslash */
11885 c = pgetc_without_PEOA();
11887 USTPUTC(CTLESC, out);
11888 USTPUTC('\\', out);
11890 } else if (c == '\n') {
11893 if (pssyntax && c == '$') {
11894 USTPUTC(CTLESC, out);
11895 USTPUTC('\\', out);
11897 /* Backslash is retained if we are in "str" and next char isn't special */
11902 && (c != '"' || eofmark != NULL)
11904 USTPUTC('\\', out);
11906 USTPUTC(CTLESC, out);
11914 if (eofmark == NULL) {
11915 USTPUTC(CTLQUOTEMARK, out);
11923 IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
11924 if (eofmark != NULL && varnest == 0) {
11927 if (dqvarnest == 0) {
11928 syntax = BASESYNTAX;
11935 case CVAR: /* '$' */
11936 PARSESUB(); /* parse substitution */
11938 case CENDVAR: /* '}' */
11941 if (dqvarnest > 0) {
11948 #if ENABLE_FEATURE_SH_MATH
11949 case CLP: /* '(' in arithmetic */
11953 case CRP: /* ')' in arithmetic */
11954 if (parenlevel > 0) {
11957 if (pgetc_eatbnl() == ')') {
11959 if (--arinest == 0) {
11960 syntax = prevsyntax;
11964 * unbalanced parens
11965 * (don't 2nd guess - no error)
11973 case CBQUOTE: /* '`' */
11977 goto endword; /* exit outer loop */
11981 if (varnest == 0) {
11982 #if BASH_REDIR_OUTPUT
11984 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11985 if (pgetc() == '>')
11986 c = 0x100 + '>'; /* flag &> */
11990 goto endword; /* exit outer loop */
11992 IF_ASH_ALIAS(if (c != PEOA))
11999 #if ENABLE_FEATURE_SH_MATH
12000 if (syntax == ARISYNTAX)
12001 raise_error_syntax("missing '))'");
12003 if (syntax != BASESYNTAX && eofmark == NULL)
12004 raise_error_syntax("unterminated quoted string");
12005 if (varnest != 0) {
12006 startlinno = g_parsefile->linno;
12008 raise_error_syntax("missing '}'");
12010 USTPUTC('\0', out);
12011 len = out - (char *)stackblock();
12012 out = stackblock();
12013 if (eofmark == NULL) {
12014 if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
12017 if (isdigit_str9(out)) {
12018 PARSEREDIR(); /* passed as params: out, c */
12019 lasttoken = TREDIR;
12022 /* else: non-number X seen, interpret it
12023 * as "NNNX>file" = "NNNX >file" */
12027 quoteflag = quotef;
12028 backquotelist = bqlist;
12029 grabstackblock(len);
12033 /* end of readtoken routine */
12036 * Check to see whether we are at the end of the here document. When this
12037 * is called, c is set to the first character of the next input line. If
12038 * we are at the end of the here document, this routine sets the c to PEOF.
12041 if (realeofmark(eofmark)) {
12045 #if ENABLE_ASH_ALIAS
12047 c = pgetc_without_PEOA();
12050 while (c == '\t') {
12051 c = pgetc_without_PEOA();
12055 markloc = out - (char *)stackblock();
12056 for (p = eofmark; STPUTC(c, out), *p; p++) {
12060 c = pgetc_without_PEOA();
12063 if (c == '\n' || c == PEOF) {
12065 g_parsefile->linno++;
12066 needprompt = doprompt;
12071 p = (char *)stackblock() + markloc + 1;
12072 len_here = out - p;
12075 len_here -= (c >= PEOF);
12081 str = alloca(len_here + 1);
12082 *(char *)mempcpy(str, p, len_here) = '\0';
12084 pushstring(str, NULL);
12089 STADJUST((char *)stackblock() + markloc - out, out);
12091 goto checkend_return;
12095 * Parse a redirection operator. The variable "out" points to a string
12096 * specifying the fd to be redirected. The variable "c" contains the
12097 * first character of the redirection operator.
12100 /* out is already checked to be a valid number or "" */
12101 int fd = (*out == '\0' ? -1 : atoi(out));
12104 np = stzalloc(sizeof(struct nfile));
12109 np->type = NAPPEND;
12111 np->type = NCLOBBER;
12114 /* it also can be NTO2 (>&file), but we can't figure it out yet */
12120 #if BASH_REDIR_OUTPUT
12121 else if (c == 0x100 + '>') { /* this flags &> redirection */
12123 pgetc(); /* this is '>', no need to check */
12127 else { /* c == '<' */
12128 /*np->nfile.fd = 0; - stzalloc did it */
12132 if (sizeof(struct nfile) != sizeof(struct nhere)) {
12133 np = stzalloc(sizeof(struct nhere));
12134 /*np->nfile.fd = 0; - stzalloc did it */
12137 heredoc = stzalloc(sizeof(struct heredoc));
12138 heredoc->here = np;
12141 heredoc->striptabs = 1;
12143 /*heredoc->striptabs = 0; - stzalloc did it */
12149 np->type = NFROMFD;
12153 np->type = NFROMTO;
12165 goto parseredir_return;
12169 * Parse a substitution. At this point, we have read the dollar sign
12170 * and nothing else.
12173 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
12174 * (assuming ascii char codes, as the original implementation did) */
12175 #define is_special(c) \
12176 (((unsigned)(c) - 33 < 32) \
12177 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
12179 unsigned char subtype;
12182 c = pgetc_eatbnl();
12183 if ((checkkwd & CHKEOFMARK)
12184 || c > 255 /* PEOA or PEOF */
12185 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
12187 #if BASH_DOLLAR_SQUOTE
12188 if (syntax != DQSYNTAX && c == '\'')
12189 bash_dollar_squote = 1;
12194 } else if (c == '(') {
12195 /* $(command) or $((arith)) */
12196 if (pgetc_eatbnl() == '(') {
12197 #if ENABLE_FEATURE_SH_MATH
12200 raise_error_syntax("support for $((arith)) is disabled");
12207 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
12208 USTPUTC(CTLVAR, out);
12209 typeloc = out - (char *)stackblock();
12211 subtype = VSNORMAL;
12213 c = pgetc_eatbnl();
12218 /* $[{[#]]NAME[}] */
12221 c = pgetc_eatbnl();
12222 } while (is_in_name(c));
12223 } else if (isdigit(c)) {
12224 /* $[{[#]]NUM[}] */
12227 c = pgetc_eatbnl();
12228 } while (isdigit(c));
12230 /* $[{[#]]<specialchar>[}] */
12233 c = pgetc_eatbnl();
12234 if (!subtype && cc == '#') {
12235 subtype = VSLENGTH;
12236 if (c == '_' || isalnum(c))
12239 c = pgetc_eatbnl();
12240 if (cc == '}' || c != '}') {
12248 if (!is_special(cc)) {
12249 if (subtype == VSLENGTH)
12257 if (c != '}' && subtype == VSLENGTH) {
12258 /* ${#VAR didn't end with } */
12262 if (subtype == 0) {
12263 static const char types[] ALIGN1 = "}-+?=";
12264 /* ${VAR...} but not $VAR or ${#VAR} */
12265 /* c == first char after VAR */
12268 c = pgetc_eatbnl();
12270 /* This check is only needed to not misinterpret
12271 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
12274 if (!strchr(types, c)) {
12275 subtype = VSSUBSTR;
12277 break; /* "goto badsub" is bigger (!) */
12283 const char *p = strchr(types, c);
12286 subtype |= p - types + VSNORMAL;
12292 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
12293 c = pgetc_eatbnl();
12299 #if BASH_PATTERN_SUBST
12301 /* ${v/[/]pattern/repl} */
12302 //TODO: encode pattern and repl separately.
12303 // Currently ${v/$var_with_slash/repl} is horribly broken
12304 subtype = VSREPLACE;
12305 c = pgetc_eatbnl();
12308 subtype++; /* VSREPLACEALL */
12316 ((unsigned char *)stackblock())[typeloc] = subtype;
12317 if (subtype != VSNORMAL) {
12324 goto parsesub_return;
12328 * Called to parse command substitutions. Newstyle is set if the command
12329 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
12330 * list of commands (passed by reference), and savelen is the number of
12331 * characters on the top of the stack which must be preserved.
12334 struct nodelist **nlpp;
12338 smallint saveprompt = 0;
12341 savelen = out - (char *)stackblock();
12344 * FIXME: this can allocate very large block on stack and SEGV.
12346 * echo "..<100kbytes>..`true` $(true) `true` ..."
12347 * allocates 100kb for every command subst. With about
12348 * a hundred command substitutions stack overflows.
12349 * With larger prepended string, SEGV happens sooner.
12351 str = alloca(savelen);
12352 memcpy(str, stackblock(), savelen);
12356 /* We must read until the closing backquote, giving special
12357 * treatment to some slashes, and then push the string and
12358 * reread it as input, interpreting it normally.
12364 STARTSTACKSTR(pout);
12368 setprompt_if(needprompt, 2);
12379 * If eating a newline, avoid putting
12380 * the newline into the new character
12381 * stream (via the STPUTC after the
12386 if (pc != '\\' && pc != '`' && pc != '$'
12387 && (!dblquote || pc != '"')
12389 STPUTC('\\', pout);
12391 if (pc <= 255 /* not PEOA or PEOF */) {
12397 IF_ASH_ALIAS(case PEOA:)
12398 startlinno = g_parsefile->linno;
12399 raise_error_syntax("EOF in backquote substitution");
12411 STPUTC('\0', pout);
12412 psavelen = pout - (char *)stackblock();
12413 if (psavelen > 0) {
12414 pstr = grabstackstr(pout);
12415 setinputstring(pstr);
12420 nlpp = &(*nlpp)->next;
12421 *nlpp = stzalloc(sizeof(**nlpp));
12422 /* (*nlpp)->next = NULL; - stzalloc did it */
12425 saveprompt = doprompt;
12432 doprompt = saveprompt;
12433 else if (readtoken() != TRP)
12434 raise_error_unexpected_syntax(TRP);
12439 * Start reading from old file again, ignoring any pushed back
12440 * tokens left from the backquote parsing
12445 while (stackblocksize() <= savelen)
12447 STARTSTACKSTR(out);
12449 memcpy(out, str, savelen);
12450 STADJUST(savelen, out);
12452 USTPUTC(CTLBACKQ, out);
12454 goto parsebackq_oldreturn;
12455 goto parsebackq_newreturn;
12458 #if ENABLE_FEATURE_SH_MATH
12460 * Parse an arithmetic expansion (indicate start of one and set state)
12463 if (++arinest == 1) {
12464 prevsyntax = syntax;
12465 syntax = ARISYNTAX;
12467 USTPUTC(CTLARI, out);
12468 goto parsearith_return;
12471 } /* end of readtoken */
12474 * Read the next input token.
12475 * If the token is a word, we set backquotelist to the list of cmds in
12476 * backquotes. We set quoteflag to true if any part of the word was
12478 * If the token is TREDIR, then we set redirnode to a structure containing
12480 * In all cases, the variable startlinno is set to the number of the line
12481 * on which the token starts.
12483 * [Change comment: here documents and internal procedures]
12484 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12485 * word parsing code into a separate routine. In this case, readtoken
12486 * doesn't need to have any internal procedures, but parseword does.
12487 * We could also make parseoperator in essence the main routine, and
12488 * have parseword (readtoken1?) handle both words and redirection.]
12490 #define NEW_xxreadtoken
12491 #ifdef NEW_xxreadtoken
12492 /* singles must be first! */
12493 static const char xxreadtoken_chars[7] ALIGN1 = {
12494 '\n', '(', ')', /* singles */
12495 '&', '|', ';', /* doubles */
12499 #define xxreadtoken_singles 3
12500 #define xxreadtoken_doubles 3
12502 static const char xxreadtoken_tokens[] ALIGN1 = {
12503 TNL, TLP, TRP, /* only single occurrence allowed */
12504 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12505 TEOF, /* corresponds to trailing nul */
12506 TAND, TOR, TENDCASE /* if double occurrence */
12518 setprompt_if(needprompt, 2);
12519 startlinno = g_parsefile->linno;
12520 for (;;) { /* until token or start of word found */
12522 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12526 while ((c = pgetc()) != '\n' && c != PEOF)
12529 } else if (c == '\\') {
12530 if (pgetc() != '\n') {
12532 break; /* return readtoken1(...) */
12538 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12544 p = strchr(xxreadtoken_chars, c);
12546 break; /* return readtoken1(...) */
12548 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12550 if (cc == c) { /* double occurrence? */
12551 p += xxreadtoken_doubles + 1;
12554 #if BASH_REDIR_OUTPUT
12555 if (c == '&' && cc == '>') /* &> */
12556 break; /* return readtoken1(...) */
12561 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12566 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12568 #else /* old xxreadtoken */
12569 #define RETURN(token) return lasttoken = token
12579 setprompt_if(needprompt, 2);
12580 startlinno = g_parsefile->linno;
12581 for (;;) { /* until token or start of word found */
12584 case ' ': case '\t':
12585 IF_ASH_ALIAS(case PEOA:)
12588 while ((c = pgetc()) != '\n' && c != PEOF)
12593 if (pgetc() == '\n') {
12605 if (pgetc() == '&')
12610 if (pgetc() == '|')
12615 if (pgetc() == ';')
12628 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12631 #endif /* old xxreadtoken */
12637 int kwd = checkkwd;
12639 smallint alreadyseen = tokpushback;
12642 #if ENABLE_ASH_ALIAS
12658 if (t != TWORD || quoteflag) {
12663 * check for keywords
12665 if (kwd & CHKKWD) {
12666 const char *const *pp;
12668 pp = findkwd(wordtext);
12670 lasttoken = t = pp - tokname_array;
12671 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12676 if (checkkwd & CHKALIAS) {
12677 #if ENABLE_ASH_ALIAS
12679 ap = lookupalias(wordtext, 1);
12682 pushstring(ap->val, ap);
12692 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12694 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12710 * Read and parse a command. Returns NODE_EOF on end of file.
12711 * (NULL is a valid parse tree indicating a blank line.)
12713 static union node *
12714 parsecmd(int interact)
12719 doprompt = interact;
12720 setprompt_if(doprompt, doprompt);
12726 * Input any here documents.
12731 struct heredoc *here;
12734 here = heredoclist;
12735 heredoclist = NULL;
12738 setprompt_if(needprompt, 2);
12739 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12740 here->eofmark, here->striptabs);
12741 n = stzalloc(sizeof(struct narg));
12742 n->narg.type = NARG;
12743 /*n->narg.next = NULL; - stzalloc did it */
12744 n->narg.text = wordtext;
12745 n->narg.backquote = backquotelist;
12746 here->here->nhere.doc = n;
12752 static const char *
12753 expandstr(const char *ps, int syntax_type)
12758 /* XXX Fix (char *) cast. */
12759 setinputstring((char *)ps);
12761 saveprompt = doprompt;
12764 /* readtoken1() might die horribly.
12765 * Try a prompt with syntactically wrong command:
12766 * PS1='$(date "+%H:%M:%S) > '
12769 volatile int saveint;
12770 struct jmploc *volatile savehandler = exception_handler;
12771 struct jmploc jmploc;
12773 if (setjmp(jmploc.loc) == 0) {
12774 exception_handler = &jmploc;
12775 readtoken1(pgetc(), syntax_type, FAKEEOFMARK, 0);
12777 exception_handler = savehandler;
12778 RESTORE_INT(saveint);
12781 doprompt = saveprompt;
12785 n.narg.type = NARG;
12786 n.narg.next = NULL;
12787 n.narg.text = wordtext;
12788 n.narg.backquote = backquotelist;
12790 expandarg(&n, NULL, EXP_QUOTED);
12791 return stackblock();
12797 return tokpushback && lasttoken == TEOF;
12801 * Execute a command or commands contained in a string.
12804 evalstring(char *s, int flags)
12806 struct jmploc *volatile savehandler;
12807 struct jmploc jmploc;
12811 struct stackmark smark;
12816 setstackmark(&smark);
12819 /* On exception inside execution loop, we must popfile().
12820 * Try interactively:
12822 * command eval "a=b" # throws "is read only" error
12823 * "command BLTIN" is not supposed to abort (even in non-interactive use).
12824 * But if we skip popfile(), we hit EOF in eval's string, and exit.
12826 savehandler = exception_handler;
12827 ex = setjmp(jmploc.loc);
12830 exception_handler = &jmploc;
12832 while ((n = parsecmd(0)) != NODE_EOF) {
12835 i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
12838 popstackmark(&smark);
12843 popstackmark(&smark);
12847 exception_handler = savehandler;
12849 longjmp(exception_handler->loc, ex);
12855 * The eval command.
12857 static int FAST_FUNC
12858 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12867 STARTSTACKSTR(concat);
12869 concat = stack_putstr(p, concat);
12873 STPUTC(' ', concat);
12875 STPUTC('\0', concat);
12876 p = grabstackstr(concat);
12878 return evalstring(p, flags & EV_TESTED);
12884 * Read and execute commands.
12885 * "Top" is nonzero for the top level command loop;
12886 * it turns on prompting if the shell is interactive.
12892 struct stackmark smark;
12897 TRACE(("cmdloop(%d) called\n", top));
12901 setstackmark(&smark);
12904 showjobs(SHOW_CHANGED|SHOW_STDERR);
12907 if (iflag && top) {
12911 n = parsecmd(inter);
12913 if (DEBUG > 2 && debug && (n != NODE_EOF))
12916 if (n == NODE_EOF) {
12917 if (!top || numeof >= 50)
12919 if (!stoppedjobs()) {
12922 out2str("\nUse \"exit\" to leave shell.\n");
12925 } else if (nflag == 0) {
12928 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12931 i = evaltree(n, 0);
12935 popstackmark(&smark);
12939 evalskip &= ~SKIPFUNC;
12947 * Take commands from a file. To be compatible we should do a path
12948 * search for the file, which is necessary to find sub-commands.
12951 find_dot_file(char *name)
12954 const char *path = pathval();
12957 /* don't try this for absolute or relative paths */
12958 if (strchr(name, '/'))
12961 while ((fullname = path_advance(&path, name)) != NULL) {
12962 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12964 * Don't bother freeing here, since it will
12965 * be freed by the caller.
12969 if (fullname != name)
12970 stunalloc(fullname);
12973 /* not found in the PATH */
12974 ash_msg_and_raise_error("%s: not found", name);
12978 static int FAST_FUNC
12979 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12981 /* "false; . empty_file; echo $?" should print 0, not 1: */
12985 char *args_need_save;
12986 volatile struct shparam saveparam;
12989 // struct strlist *sp;
12990 // for (sp = cmdenviron; sp; sp = sp->next)
12991 // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12993 nextopt(nullstr); /* handle possible "--" */
12997 /* bash says: "bash: .: filename argument required" */
12998 return 2; /* bash compat */
13001 /* This aborts if file isn't found, which is POSIXly correct.
13002 * bash returns exitcode 1 instead.
13004 fullname = find_dot_file(argv[0]);
13006 args_need_save = argv[0];
13007 if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
13009 saveparam = shellparam;
13010 shellparam.malloced = 0;
13014 shellparam.nparam = argc;
13015 shellparam.p = argv;
13018 /* This aborts if file can't be opened, which is POSIXly correct.
13019 * bash returns exitcode 1 instead.
13021 setinputfile(fullname, INPUT_PUSH_FILE);
13022 commandname = fullname;
13023 status = cmdloop(0);
13026 if (args_need_save) {
13027 freeparam(&shellparam);
13028 shellparam = saveparam;
13034 static int FAST_FUNC
13035 exitcmd(int argc UNUSED_PARAM, char **argv)
13040 exitstatus = number(argv[1]);
13041 raise_exception(EXEXIT);
13046 * Read a file containing shell functions.
13049 readcmdfile(char *name)
13051 setinputfile(name, INPUT_PUSH_FILE);
13057 /* ============ find_command inplementation */
13060 * Resolve a command name. If you change this routine, you may have to
13061 * change the shellexec routine as well.
13064 find_command(char *name, struct cmdentry *entry, int act, const char *path)
13066 struct tblentry *cmdp;
13073 struct builtincmd *bcmd;
13075 /* If name contains a slash, don't use PATH or hash table */
13076 if (strchr(name, '/') != NULL) {
13077 entry->u.index = -1;
13078 if (act & DO_ABS) {
13079 while (stat(name, &statb) < 0) {
13081 if (errno == EINTR)
13084 entry->cmdtype = CMDUNKNOWN;
13088 entry->cmdtype = CMDNORMAL;
13092 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
13094 updatetbl = (path == pathval());
13097 if (strstr(path, "%builtin") != NULL)
13098 act |= DO_ALTBLTIN;
13101 /* If name is in the table, check answer will be ok */
13102 cmdp = cmdlookup(name, 0);
13103 if (cmdp != NULL) {
13106 switch (cmdp->cmdtype) {
13124 } else if (cmdp->rehash == 0)
13125 /* if not invalidated by cd, we're done */
13129 /* If %builtin not in path, check for builtin next */
13130 bcmd = find_builtin(name);
13132 if (IS_BUILTIN_REGULAR(bcmd))
13133 goto builtin_success;
13134 if (act & DO_ALTPATH) {
13135 if (!(act & DO_ALTBLTIN))
13136 goto builtin_success;
13137 } else if (builtinloc <= 0) {
13138 goto builtin_success;
13142 #if ENABLE_FEATURE_SH_STANDALONE
13144 int applet_no = find_applet_by_name(name);
13145 if (applet_no >= 0) {
13146 entry->cmdtype = CMDNORMAL;
13147 entry->u.index = -2 - applet_no;
13153 /* We have to search path. */
13154 prev = -1; /* where to start */
13155 if (cmdp && cmdp->rehash) { /* doing a rehash */
13156 if (cmdp->cmdtype == CMDBUILTIN)
13159 prev = cmdp->param.index;
13165 while ((fullname = path_advance(&path, name)) != NULL) {
13166 stunalloc(fullname);
13167 /* NB: code below will still use fullname
13168 * despite it being "unallocated" */
13171 if (prefix(pathopt, "builtin")) {
13173 goto builtin_success;
13176 if ((act & DO_NOFUNC)
13177 || !prefix(pathopt, "func")
13178 ) { /* ignore unimplemented options */
13182 /* if rehash, don't redo absolute path names */
13183 if (fullname[0] == '/' && idx <= prev) {
13186 TRACE(("searchexec \"%s\": no change\n", name));
13189 while (stat(fullname, &statb) < 0) {
13191 if (errno == EINTR)
13194 if (errno != ENOENT && errno != ENOTDIR)
13198 e = EACCES; /* if we fail, this will be the error */
13199 if (!S_ISREG(statb.st_mode))
13201 if (pathopt) { /* this is a %func directory */
13202 stalloc(strlen(fullname) + 1);
13203 /* NB: stalloc will return space pointed by fullname
13204 * (because we don't have any intervening allocations
13205 * between stunalloc above and this stalloc) */
13206 readcmdfile(fullname);
13207 cmdp = cmdlookup(name, 0);
13208 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
13209 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
13210 stunalloc(fullname);
13213 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
13215 entry->cmdtype = CMDNORMAL;
13216 entry->u.index = idx;
13220 cmdp = cmdlookup(name, 1);
13221 cmdp->cmdtype = CMDNORMAL;
13222 cmdp->param.index = idx;
13227 /* We failed. If there was an entry for this command, delete it */
13228 if (cmdp && updatetbl)
13229 delete_cmd_entry();
13231 ash_msg("%s: %s", name, errmsg(e, "not found"));
13232 entry->cmdtype = CMDUNKNOWN;
13237 entry->cmdtype = CMDBUILTIN;
13238 entry->u.cmd = bcmd;
13242 cmdp = cmdlookup(name, 1);
13243 cmdp->cmdtype = CMDBUILTIN;
13244 cmdp->param.cmd = bcmd;
13248 entry->cmdtype = cmdp->cmdtype;
13249 entry->u = cmdp->param;
13254 * The trap builtin.
13256 static int FAST_FUNC
13257 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13261 int signo, exitcode;
13266 for (signo = 0; signo < NSIG; signo++) {
13267 char *tr = trap_ptr[signo];
13269 /* note: bash adds "SIG", but only if invoked
13270 * as "bash". If called as "sh", or if set -o posix,
13271 * then it prints short signal names.
13272 * We are printing short names: */
13273 out1fmt("trap -- %s %s\n",
13275 get_signame(signo));
13276 /* trap_ptr != trap only if we are in special-cased `trap` code.
13277 * In this case, we will exit very soon, no need to free(). */
13278 /* if (trap_ptr != trap && tp[0]) */
13283 if (trap_ptr != trap) {
13291 /* Why the second check?
13292 * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
13293 * In this case, NUM is signal no, not an action.
13296 if (ap[1] && !is_number(ap[0]))
13301 signo = get_signum(*ap);
13303 /* Mimic bash message exactly */
13304 ash_msg("%s: invalid signal specification", *ap);
13310 if (LONE_DASH(action))
13313 if (action[0]) /* not NULL and not "" and not "-" */
13314 may_have_traps = 1;
13315 action = ckstrdup(action);
13319 trap[signo] = action;
13330 /* ============ Builtins */
13332 #if ENABLE_ASH_HELP
13333 static int FAST_FUNC
13334 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13340 "Built-in commands:\n"
13341 "------------------\n");
13342 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
13343 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
13344 builtintab[i].name + 1);
13350 # if ENABLE_FEATURE_SH_STANDALONE
13352 const char *a = applet_names;
13354 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
13359 while (*a++ != '\0')
13364 newline_and_flush(stdout);
13365 return EXIT_SUCCESS;
13370 static int FAST_FUNC
13371 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13373 show_history(line_input_state);
13374 return EXIT_SUCCESS;
13379 * The export and readonly commands.
13381 static int FAST_FUNC
13382 exportcmd(int argc UNUSED_PARAM, char **argv)
13392 /* "readonly" in bash accepts, but ignores -n.
13393 * We do the same: it saves a conditional in nextopt's param.
13396 while ((opt = nextopt("np")) != '\0') {
13398 flag_off = VEXPORT;
13401 if (argv[0][0] == 'r') {
13403 flag_off = 0; /* readonly ignores -n */
13405 flag_off = ~flag_off;
13407 /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
13413 p = strchr(name, '=');
13417 vp = *findvar(hashvar(name), name);
13419 vp->flags = ((vp->flags | flag) & flag_off);
13423 setvar(name, p, (flag & flag_off));
13424 } while ((name = *++aptr) != NULL);
13429 /* No arguments. Show the list of exported or readonly vars.
13432 showvars(argv[0], flag, 0);
13437 * Delete a function if it exists.
13440 unsetfunc(const char *name)
13442 struct tblentry *cmdp;
13444 cmdp = cmdlookup(name, 0);
13445 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
13446 delete_cmd_entry();
13450 * The unset builtin command. We unset the function before we unset the
13451 * variable to allow a function to be unset when there is a readonly variable
13452 * with the same name.
13454 static int FAST_FUNC
13455 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13461 while ((i = nextopt("vf")) != 0) {
13465 for (ap = argptr; *ap; ap++) {
13476 static const unsigned char timescmd_str[] ALIGN1 = {
13477 ' ', offsetof(struct tms, tms_utime),
13478 '\n', offsetof(struct tms, tms_stime),
13479 ' ', offsetof(struct tms, tms_cutime),
13480 '\n', offsetof(struct tms, tms_cstime),
13483 static int FAST_FUNC
13484 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13487 const unsigned char *p;
13490 clk_tck = bb_clk_tck();
13495 unsigned sec, frac;
13497 t = *(clock_t *)(((char *) &buf) + p[1]);
13499 frac = t % clk_tck;
13500 out1fmt("%um%u.%03us%c",
13501 sec / 60, sec % 60,
13502 (frac * 1000) / clk_tck,
13510 #if ENABLE_FEATURE_SH_MATH
13512 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13513 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13515 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13517 static int FAST_FUNC
13518 letcmd(int argc UNUSED_PARAM, char **argv)
13524 ash_msg_and_raise_error("expression expected");
13526 i = ash_arith(*argv);
13534 * The read builtin. Options:
13535 * -r Do not interpret '\' specially
13536 * -s Turn off echo (tty only)
13537 * -n NCHARS Read NCHARS max
13538 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13539 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13540 * -u FD Read from given FD instead of fd 0
13541 * -d DELIM End on DELIM char, not newline
13542 * This uses unbuffered input, which may be avoidable in some cases.
13543 * TODO: bash also has:
13544 * -a ARRAY Read into array[0],[1],etc
13545 * -e Use line editing (tty only)
13547 static int FAST_FUNC
13548 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13550 char *opt_n = NULL;
13551 char *opt_p = NULL;
13552 char *opt_t = NULL;
13553 char *opt_u = NULL;
13554 char *opt_d = NULL; /* optimized out if !BASH */
13555 int read_flags = 0;
13559 while ((i = nextopt("p:u:rt:n:sd:")) != '\0') {
13568 read_flags |= BUILTIN_READ_SILENT;
13574 read_flags |= BUILTIN_READ_RAW;
13589 /* "read -s" needs to save/restore termios, can't allow ^C
13590 * to jump out of it.
13594 r = shell_builtin_read(setvar0,
13596 bltinlookup("IFS"), /* can be NULL */
13606 if ((uintptr_t)r == 1 && errno == EINTR) {
13607 /* To get SIGCHLD: sleep 1 & read x; echo $x
13608 * Correct behavior is to not exit "read"
13610 if (pending_sig == 0)
13614 if ((uintptr_t)r > 1)
13615 ash_msg_and_raise_error(r);
13617 return (uintptr_t)r;
13620 static int FAST_FUNC
13621 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13623 static const char permuser[3] ALIGN1 = "ogu";
13626 int symbolic_mode = 0;
13628 while (nextopt("S") != '\0') {
13637 if (*argptr == NULL) {
13638 if (symbolic_mode) {
13639 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13646 *p++ = permuser[i];
13648 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13649 if (!(mask & 0400)) *p++ = 'r';
13650 if (!(mask & 0200)) *p++ = 'w';
13651 if (!(mask & 0100)) *p++ = 'x';
13659 out1fmt("%04o\n", mask);
13662 char *modestr = *argptr;
13663 /* numeric umasks are taken as-is */
13664 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13665 if (!isdigit(modestr[0]))
13667 mask = bb_parse_mode(modestr, mask);
13668 if ((unsigned)mask > 0777) {
13669 ash_msg_and_raise_error("illegal mode: %s", modestr);
13671 if (!isdigit(modestr[0]))
13678 static int FAST_FUNC
13679 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13681 return shell_builtin_ulimit(argv);
13684 /* ============ main() and helpers */
13687 * Called to exit the shell.
13696 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13697 save_history(line_input_state);
13699 status = exitstatus;
13700 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13701 if (setjmp(loc.loc)) {
13702 if (exception_type == EXEXIT)
13703 status = exitstatus;
13706 exception_handler = &loc;
13712 /*free(p); - we'll exit soon */
13715 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13716 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13719 flush_stdout_stderr();
13724 /* Don't inline: conserve stack of caller from having our locals too */
13725 static NOINLINE void
13728 /* we will never free this */
13729 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13732 sigmode[SIGCHLD - 1] = S_DFL; /* ensure we install handler even if it is SIG_IGNed */
13733 setsignal(SIGCHLD);
13735 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13736 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13738 signal(SIGHUP, SIG_DFL);
13745 for (envp = environ; envp && *envp; envp++) {
13747 * p = endofname(*envp);
13748 * if (p != *envp && *p == '=') {
13749 * here to weed out badly-named variables, but this breaks
13750 * scenarios where people do want them passed to children:
13752 * os.environ["test-test"]="test"
13753 * if os.fork() == 0:
13754 * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
13755 * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ]) # breaks this
13757 if (strchr(*envp, '=')) {
13758 setvareq(*envp, VEXPORT|VTEXTFIXED);
13762 setvareq((char*)defoptindvar, VTEXTFIXED);
13764 setvar0("PPID", utoa(getppid()));
13766 p = lookupvar("SHLVL");
13767 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13769 #if BASH_HOSTNAME_VAR
13770 if (!lookupvar("HOSTNAME")) {
13771 struct utsname uts;
13773 setvar0("HOSTNAME", uts.nodename);
13776 p = lookupvar("PWD");
13778 struct stat st1, st2;
13779 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13780 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13790 //usage:#define ash_trivial_usage
13791 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13792 //usage:#define ash_full_usage "\n\n"
13793 //usage: "Unix shell interpreter"
13796 * Process the shell command line arguments.
13799 procargs(char **argv)
13802 const char *xminusc;
13807 login_sh = xargv[0] && xargv[0][0] == '-';
13809 /* if (xargv[0]) - mmm, this is always true! */
13811 for (i = 0; i < NOPTS; i++)
13814 if (options(/*cmdline:*/ 1, &login_sh)) {
13815 /* it already printed err message */
13816 raise_exception(EXERROR);
13820 if (*xargv == NULL) {
13822 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13825 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13829 for (i = 0; i < NOPTS; i++)
13830 if (optlist[i] == 2)
13835 /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
13840 } else if (!sflag) {
13841 setinputfile(*xargv, 0);
13844 commandname = arg0;
13847 shellparam.p = xargv;
13848 #if ENABLE_ASH_GETOPTS
13849 shellparam.optind = 1;
13850 shellparam.optoff = -1;
13852 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13854 shellparam.nparam++;
13863 * Read /etc/profile, ~/.profile, $ENV.
13866 read_profile(const char *name)
13868 name = expandstr(name, DQSYNTAX);
13869 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13876 * This routine is called when an error or an interrupt occurs in an
13877 * interactive shell and control is returned to the main command loop.
13878 * (In dash, this function is auto-generated by build machinery).
13887 /* from expand.c: */
13890 /* from input.c: */
13891 g_parsefile->left_in_buffer = 0;
13892 g_parsefile->left_in_line = 0; /* clear input buffer */
13895 /* from redir.c: */
13899 unwindlocalvars(NULL);
13903 static short profile_buf[16384];
13904 extern int etext();
13908 * Main routine. We initialize things, parse the arguments, execute
13909 * profiles if we're a login shell, and then call cmdloop to execute
13910 * commands. The setjmp call sets up the location to jump to when an
13911 * exception occurs. When an exception occurs the variable "state"
13912 * is used to figure out how far we had gotten.
13914 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13915 int ash_main(int argc UNUSED_PARAM, char **argv)
13917 volatile smallint state;
13918 struct jmploc jmploc;
13919 struct stackmark smark;
13922 /* Initialize global data */
13926 #if ENABLE_ASH_ALIAS
13932 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13935 #if ENABLE_FEATURE_EDITING
13936 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13939 if (setjmp(jmploc.loc)) {
13945 e = exception_type;
13947 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13951 newline_and_flush(stderr);
13954 popstackmark(&smark);
13955 FORCE_INT_ON; /* enable interrupts */
13964 exception_handler = &jmploc;
13965 rootpid = getpid();
13968 setstackmark(&smark);
13969 login_sh = procargs(argv);
13971 TRACE(("Shell args: "));
13972 trace_puts_args(argv);
13979 read_profile("/etc/profile");
13982 hp = lookupvar("HOME");
13984 read_profile("$HOME/.profile");
13990 getuid() == geteuid() && getgid() == getegid() &&
13994 const char *shinit = lookupvar("ENV");
13995 if (shinit != NULL && *shinit != '\0')
13996 read_profile(shinit);
13998 popstackmark(&smark);
14002 /* evalstring pushes parsefile stack.
14003 * Ensure we don't falsely claim that 0 (stdin)
14004 * is one of stacked source fds.
14005 * Testcase: ash -c 'exec 1>&0' must not complain. */
14006 // if (!sflag) g_parsefile->pf_fd = -1;
14007 // ^^ not necessary since now we special-case fd 0
14008 // in save_fd_on_redirect()
14009 evalstring(minusc, sflag ? 0 : EV_EXIT);
14012 if (sflag || minusc == NULL) {
14013 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
14015 const char *hp = lookupvar("HISTFILE");
14017 hp = lookupvar("HOME");
14020 hp = concat_path_file(hp, ".ash_history");
14021 setvar0("HISTFILE", hp);
14024 hp = lookupvar("HISTFILE");
14028 line_input_state->hist_file = hp;
14029 # if ENABLE_FEATURE_SH_HISTFILESIZE
14030 hp = lookupvar("HISTFILESIZE");
14031 line_input_state->max_history = size_from_HISTFILESIZE(hp);
14035 state4: /* XXX ??? - why isn't this before the "if" statement */
14043 extern void _mcleanup(void);
14047 TRACE(("End of main reached\n"));
14054 * Copyright (c) 1989, 1991, 1993, 1994
14055 * The Regents of the University of California. All rights reserved.
14057 * This code is derived from software contributed to Berkeley by
14058 * Kenneth Almquist.
14060 * Redistribution and use in source and binary forms, with or without
14061 * modification, are permitted provided that the following conditions
14063 * 1. Redistributions of source code must retain the above copyright
14064 * notice, this list of conditions and the following disclaimer.
14065 * 2. Redistributions in binary form must reproduce the above copyright
14066 * notice, this list of conditions and the following disclaimer in the
14067 * documentation and/or other materials provided with the distribution.
14068 * 3. Neither the name of the University nor the names of its contributors
14069 * may be used to endorse or promote products derived from this software
14070 * without specific prior written permission.
14072 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
14073 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
14074 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
14075 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
14076 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
14077 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
14078 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
14079 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
14080 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
14081 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF