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.
21 //config: depends on !NOMMU
23 //config: Tha 'ash' shell adds about 60k in the default configuration and is
24 //config: the most complete and most pedantically correct shell included with
25 //config: busybox. This shell is actually a derivative of the Debian 'dash'
26 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
27 //config: (written by Kenneth Almquist) from NetBSD.
29 //config:# ash options
30 //config:# note: Don't remove !NOMMU part in the next line; it would break
31 //config:# menuconfig's indenting.
32 //config:if !NOMMU && (ASH || SH_IS_ASH || BASH_IS_ASH)
34 //config:config ASH_OPTIMIZE_FOR_SIZE
35 //config: bool "Optimize for size instead of speed"
37 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
39 //config:config ASH_INTERNAL_GLOB
40 //config: bool "Use internal glob() implementation"
41 //config: default y # Y is bigger, but because of uclibc glob() bug, let Y be default for now
42 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
44 //config: Do not use glob() function from libc, use internal implementation.
45 //config: Use this if you are getting "glob.h: No such file or directory"
46 //config: or similar build errors.
47 //config: Note that as of now (2017-01), uclibc and musl glob() both have bugs
48 //config: which would break ash if you select N here.
50 //config:config ASH_BASH_COMPAT
51 //config: bool "bash-compatible extensions"
53 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
55 //config:config ASH_JOB_CONTROL
56 //config: bool "Job control"
58 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
60 //config:config ASH_ALIAS
61 //config: bool "Alias support"
63 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
65 //config:config ASH_RANDOM_SUPPORT
66 //config: bool "Pseudorandom generator and $RANDOM variable"
68 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
70 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
71 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
72 //config: You can reset the generator by using a specified start value.
73 //config: After "unset RANDOM" the generator will switch off and this
74 //config: variable will no longer have special treatment.
76 //config:config ASH_EXPAND_PRMT
77 //config: bool "Expand prompt string"
79 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
81 //config: $PS# may contain volatile content, such as backquote commands.
82 //config: This option recreates the prompt string from the environment
83 //config: variable each time it is displayed.
85 //config:config ASH_IDLE_TIMEOUT
86 //config: bool "Idle timeout variable $TMOUT"
88 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
90 //config: Enable bash-like auto-logout after $TMOUT seconds of idle time.
92 //config:config ASH_MAIL
93 //config: bool "Check for new mail in interactive shell"
95 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
97 //config: Enable "check for new mail" function:
98 //config: if set, $MAIL file and $MAILPATH list of files
99 //config: are checked for mtime changes, and "you have mail"
100 //config: message is printed if change is detected.
102 //config:config ASH_ECHO
103 //config: bool "echo builtin"
105 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
107 //config:config ASH_PRINTF
108 //config: bool "printf builtin"
110 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
112 //config:config ASH_TEST
113 //config: bool "test builtin"
115 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
117 //config:config ASH_HELP
118 //config: bool "help builtin"
120 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
122 //config:config ASH_GETOPTS
123 //config: bool "getopts builtin"
125 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
127 //config:config ASH_CMDCMD
128 //config: bool "command builtin"
130 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
132 //config: Enable support for the 'command' builtin, which allows
133 //config: you to run the specified command or builtin,
134 //config: even when there is a function with the same name.
136 //config:endif # ash options
138 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
139 // APPLET_ODDNAME:name main location suid_type help
140 //applet:IF_SH_IS_ASH( APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
141 //applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
143 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
144 //kbuild:lib-$(CONFIG_SH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
145 //kbuild:lib-$(CONFIG_BASH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
146 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
149 * DEBUG=1 to compile in debugging ('set -o debug' turns on)
150 * DEBUG=2 to compile in and turn on debugging.
151 * When debugging is on ("set -o debug" was executed, or DEBUG=2),
152 * debugging info is written to ./trace, quit signal generates core dump.
155 /* Tweak debug output verbosity here */
159 #define DEBUG_INTONOFF 0
163 #define JOBS ENABLE_ASH_JOB_CONTROL
167 #include <sys/times.h>
168 #include <sys/utsname.h> /* for setting $HOSTNAME */
169 #include "busybox.h" /* for applet_names */
171 /* So far, all bash compat is controlled by one config option */
172 /* Separate defines document which part of code implements what */
173 /* function keyword */
174 #define BASH_FUNCTION ENABLE_ASH_BASH_COMPAT
175 #define IF_BASH_FUNCTION IF_ASH_BASH_COMPAT
177 #define BASH_REDIR_OUTPUT ENABLE_ASH_BASH_COMPAT
178 #define IF_BASH_REDIR_OUTPUT IF_ASH_BASH_COMPAT
180 #define BASH_DOLLAR_SQUOTE ENABLE_ASH_BASH_COMPAT
181 #define IF_BASH_DOLLAR_SQUOTE IF_ASH_BASH_COMPAT
182 #define BASH_PATTERN_SUBST ENABLE_ASH_BASH_COMPAT
183 #define IF_BASH_PATTERN_SUBST IF_ASH_BASH_COMPAT
184 #define BASH_SUBSTR ENABLE_ASH_BASH_COMPAT
185 #define IF_BASH_SUBSTR IF_ASH_BASH_COMPAT
187 #define BASH_TEST2 (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)
188 #define BASH_SOURCE ENABLE_ASH_BASH_COMPAT
189 #define BASH_PIPEFAIL ENABLE_ASH_BASH_COMPAT
190 #define BASH_HOSTNAME_VAR ENABLE_ASH_BASH_COMPAT
191 #define BASH_SHLVL_VAR ENABLE_ASH_BASH_COMPAT
193 #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
194 /* Bionic at least up to version 24 has no glob() */
195 # undef ENABLE_ASH_INTERNAL_GLOB
196 # define ENABLE_ASH_INTERNAL_GLOB 1
199 #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
200 # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
201 # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
202 # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
203 # error glob() should unbackslash them and match. uClibc does not unbackslash,
204 # error fails to match dirname, subsequently not expanding <pattern> in it.
206 // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
207 // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
210 #if !ENABLE_ASH_INTERNAL_GLOB
215 #include "shell_common.h"
216 #if ENABLE_FEATURE_SH_MATH
219 #if ENABLE_ASH_RANDOM_SUPPORT
222 # define CLEAR_RANDOM_T(rnd) ((void)0)
225 #include "NUM_APPLETS.h"
227 /* STANDALONE does not make sense, and won't compile */
228 # undef CONFIG_FEATURE_SH_STANDALONE
229 # undef ENABLE_FEATURE_SH_STANDALONE
230 # undef IF_FEATURE_SH_STANDALONE
231 # undef IF_NOT_FEATURE_SH_STANDALONE
232 # define ENABLE_FEATURE_SH_STANDALONE 0
233 # define IF_FEATURE_SH_STANDALONE(...)
234 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
238 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
242 # error "Do not even bother, ash will not run on NOMMU machine"
246 /* ============ Hash table sizes. Configurable. */
250 #define CMDTABLESIZE 31 /* should be prime */
253 /* ============ Shell options */
255 static const char *const optletters_optnames[] = {
279 #define optletters(n) optletters_optnames[n][0]
280 #define optnames(n) (optletters_optnames[n] + 1)
282 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
285 /* ============ Misc data */
287 #define msg_illnum "Illegal number: %s"
290 * We enclose jmp_buf in a structure so that we can declare pointers to
291 * jump locations. The global variable handler contains the location to
292 * jump to when an exception occurs, and the global variable exception_type
293 * contains a code identifying the exception. To implement nested
294 * exception handlers, the user should save the value of handler on entry
295 * to an inner scope, set handler to point to a jmploc structure for the
296 * inner scope, and restore handler on exit from the scope.
302 struct globals_misc {
303 uint8_t exitstatus; /* exit status of last command */
304 uint8_t back_exitstatus;/* exit status of backquoted command */
305 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
306 int rootpid; /* pid of main shell */
307 /* shell level: 0 for the main shell, 1 for its children, and so on */
309 #define rootshell (!shlvl)
310 char *minusc; /* argument to -c option */
312 char *curdir; // = nullstr; /* current working directory */
313 char *physdir; // = nullstr; /* physical working directory */
315 char *arg0; /* value of $0 */
317 struct jmploc *exception_handler;
319 volatile int suppress_int; /* counter */
320 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
321 volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
322 volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
323 smallint exception_type; /* kind of exception (0..5) */
325 #define EXINT 0 /* SIGINT received */
326 #define EXERROR 1 /* a generic error */
327 #define EXEXIT 4 /* exit the shell */
330 char nullstr[1]; /* zero length string */
333 #define eflag optlist[0]
334 #define fflag optlist[1]
335 #define Iflag optlist[2]
336 #define iflag optlist[3]
337 #define mflag optlist[4]
338 #define nflag optlist[5]
339 #define sflag optlist[6]
340 #define xflag optlist[7]
341 #define vflag optlist[8]
342 #define Cflag optlist[9]
343 #define aflag optlist[10]
344 #define bflag optlist[11]
345 #define uflag optlist[12]
346 #define viflag optlist[13]
348 # define pipefail optlist[14]
353 # define nolog optlist[14 + BASH_PIPEFAIL]
354 # define debug optlist[15 + BASH_PIPEFAIL]
357 /* trap handler commands */
359 * Sigmode records the current value of the signal handlers for the various
360 * modes. A value of zero means that the current handler is not known.
361 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
363 char sigmode[NSIG - 1];
364 #define S_DFL 1 /* default signal handling (SIG_DFL) */
365 #define S_CATCH 2 /* signal is caught */
366 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
367 #define S_HARD_IGN 4 /* signal is ignored permanently */
369 /* indicates specified signal received */
370 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
371 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
373 char **trap_ptr; /* used only by "trap hack" */
375 /* Rarely referenced stuff */
376 #if ENABLE_ASH_RANDOM_SUPPORT
379 pid_t backgndpid; /* pid of last background process */
381 extern struct globals_misc *const ash_ptr_to_globals_misc;
382 #define G_misc (*ash_ptr_to_globals_misc)
383 #define exitstatus (G_misc.exitstatus )
384 #define back_exitstatus (G_misc.back_exitstatus )
385 #define job_warning (G_misc.job_warning)
386 #define rootpid (G_misc.rootpid )
387 #define shlvl (G_misc.shlvl )
388 #define minusc (G_misc.minusc )
389 #define curdir (G_misc.curdir )
390 #define physdir (G_misc.physdir )
391 #define arg0 (G_misc.arg0 )
392 #define exception_handler (G_misc.exception_handler)
393 #define exception_type (G_misc.exception_type )
394 #define suppress_int (G_misc.suppress_int )
395 #define pending_int (G_misc.pending_int )
396 #define got_sigchld (G_misc.got_sigchld )
397 #define pending_sig (G_misc.pending_sig )
398 #define isloginsh (G_misc.isloginsh )
399 #define nullstr (G_misc.nullstr )
400 #define optlist (G_misc.optlist )
401 #define sigmode (G_misc.sigmode )
402 #define gotsig (G_misc.gotsig )
403 #define may_have_traps (G_misc.may_have_traps )
404 #define trap (G_misc.trap )
405 #define trap_ptr (G_misc.trap_ptr )
406 #define random_gen (G_misc.random_gen )
407 #define backgndpid (G_misc.backgndpid )
408 #define INIT_G_misc() do { \
409 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
417 /* ============ DEBUG */
419 static void trace_printf(const char *fmt, ...);
420 static void trace_vprintf(const char *fmt, va_list va);
421 # define TRACE(param) trace_printf param
422 # define TRACEV(param) trace_vprintf param
423 # define close(fd) do { \
425 if (close(dfd) < 0) \
426 bb_error_msg("bug on %d: closing %d(0x%x)", \
427 __LINE__, dfd, dfd); \
430 # define TRACE(param)
431 # define TRACEV(param)
435 /* ============ Utility functions */
436 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
437 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
440 isdigit_str9(const char *str)
442 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
443 while (--maxlen && isdigit(*str))
445 return (*str == '\0');
449 var_end(const char *var)
458 /* ============ Interrupts / exceptions */
460 static void exitshell(void) NORETURN;
463 * These macros allow the user to suspend the handling of interrupt signals
464 * over a period of time. This is similar to SIGHOLD or to sigblock, but
465 * much more efficient and portable. (But hacking the kernel is so much
466 * more fun than worrying about efficiency and portability. :-))
469 # define INT_OFF do { \
470 TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
475 # define INT_OFF do { \
482 * Called to raise an exception. Since C doesn't include exceptions, we
483 * just do a longjmp to the exception handler. The type of exception is
484 * stored in the global variable "exception_type".
486 static void raise_exception(int) NORETURN;
488 raise_exception(int e)
491 if (exception_handler == NULL)
496 longjmp(exception_handler->loc, 1);
499 #define raise_exception(e) do { \
500 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
501 raise_exception(e); \
506 * Called when a SIGINT is received. (If the user specifies
507 * that SIGINT is to be trapped or ignored using the trap builtin, then
508 * this routine is not called.) Suppressint is nonzero when interrupts
509 * are held using the INT_OFF macro. (The test for iflag is just
510 * defensive programming.)
512 static void raise_interrupt(void) NORETURN;
514 raise_interrupt(void)
517 /* Signal is not automatically unmasked after it is raised,
518 * do it ourself - unmask all signals */
519 sigprocmask_allsigs(SIG_UNBLOCK);
520 /* pending_sig = 0; - now done in signal_handler() */
522 if (!(rootshell && iflag)) {
523 /* Kill ourself with SIGINT */
524 signal(SIGINT, SIG_DFL);
527 /* bash: ^C even on empty command line sets $? */
528 exitstatus = SIGINT + 128;
529 raise_exception(EXINT);
533 #define raise_interrupt() do { \
534 TRACE(("raising interrupt on line %d\n", __LINE__)); \
539 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
543 if (--suppress_int == 0 && pending_int) {
548 # define INT_ON do { \
549 TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
553 # define INT_ON int_on()
555 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
563 #define FORCE_INT_ON force_int_on()
565 #define SAVE_INT(v) ((v) = suppress_int)
567 #define RESTORE_INT(v) do { \
569 suppress_int = (v); \
570 if (suppress_int == 0 && pending_int) \
575 /* ============ Stdout/stderr output */
578 outstr(const char *p, FILE *file)
586 flush_stdout_stderr(void)
593 /* Was called outcslow(c,FILE*), but c was always '\n' */
595 newline_and_flush(FILE *dest)
603 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
605 out1fmt(const char *fmt, ...)
612 r = vprintf(fmt, ap);
618 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
620 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
627 ret = vsnprintf(outbuf, length, fmt, ap);
634 out1str(const char *p)
640 out2str(const char *p)
643 flush_stdout_stderr();
647 /* ============ Parser structures */
649 /* control characters in argument strings */
650 #define CTL_FIRST CTLESC
651 #define CTLESC ((unsigned char)'\201') /* escape next character */
652 #define CTLVAR ((unsigned char)'\202') /* variable defn */
653 #define CTLENDVAR ((unsigned char)'\203')
654 #define CTLBACKQ ((unsigned char)'\204')
655 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
656 #define CTLENDARI ((unsigned char)'\207')
657 #define CTLQUOTEMARK ((unsigned char)'\210')
658 #define CTL_LAST CTLQUOTEMARK
660 /* variable substitution byte (follows CTLVAR) */
661 #define VSTYPE 0x0f /* type of variable substitution */
662 #define VSNUL 0x10 /* colon--treat the empty string as unset */
664 /* values of VSTYPE field */
665 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
666 #define VSMINUS 0x2 /* ${var-text} */
667 #define VSPLUS 0x3 /* ${var+text} */
668 #define VSQUESTION 0x4 /* ${var?message} */
669 #define VSASSIGN 0x5 /* ${var=text} */
670 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
671 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
672 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
673 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
674 #define VSLENGTH 0xa /* ${#var} */
676 #define VSSUBSTR 0xc /* ${var:position:length} */
678 #if BASH_PATTERN_SUBST
679 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
680 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
683 static const char dolatstr[] ALIGN1 = {
684 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
686 #define DOLATSTRLEN 6
705 #if BASH_REDIR_OUTPUT
722 smallint type; /* Nxxxx */
725 union node *redirect;
730 smallint pipe_backgnd;
731 struct nodelist *cmdlist;
737 union node *redirect;
750 union node *elsepart;
777 struct nodelist *backquote;
780 /* nfile and ndup layout must match!
781 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
782 * that it is actually NTO2 (>&file), and change its type.
799 char *_unused_expfname;
818 struct nredir nredir;
819 struct nbinary nbinary;
823 struct nclist nclist;
832 * NODE_EOF is returned by parsecmd when it encounters an end of file.
833 * It must be distinct from NULL.
835 #define NODE_EOF ((union node *) -1L)
838 struct nodelist *next;
851 freefunc(struct funcnode *f)
853 if (f && --f->count < 0)
858 /* ============ Debugging output */
862 static FILE *tracefile;
865 trace_printf(const char *fmt, ...)
872 fprintf(tracefile, "%u ", (int) time(NULL));
874 fprintf(tracefile, "[%u] ", (int) getpid());
876 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
878 vfprintf(tracefile, fmt, va);
883 trace_vprintf(const char *fmt, va_list va)
887 vfprintf(tracefile, fmt, va);
888 fprintf(tracefile, "\n");
892 trace_puts(const char *s)
900 trace_puts_quoted(char *s)
907 putc('"', tracefile);
908 for (p = s; *p; p++) {
909 switch ((unsigned char)*p) {
910 case '\n': c = 'n'; goto backslash;
911 case '\t': c = 't'; goto backslash;
912 case '\r': c = 'r'; goto backslash;
913 case '\"': c = '\"'; goto backslash;
914 case '\\': c = '\\'; goto backslash;
915 case CTLESC: c = 'e'; goto backslash;
916 case CTLVAR: c = 'v'; goto backslash;
917 case CTLBACKQ: c = 'q'; goto backslash;
919 putc('\\', tracefile);
923 if (*p >= ' ' && *p <= '~')
926 putc('\\', tracefile);
927 putc((*p >> 6) & 03, tracefile);
928 putc((*p >> 3) & 07, tracefile);
929 putc(*p & 07, tracefile);
934 putc('"', tracefile);
938 trace_puts_args(char **ap)
945 trace_puts_quoted(*ap);
947 putc('\n', tracefile);
950 putc(' ', tracefile);
965 /* leave open because libedit might be using it */
968 strcpy(s, "./trace");
970 if (!freopen(s, "a", tracefile)) {
971 fprintf(stderr, "Can't re-open %s\n", s);
976 tracefile = fopen(s, "a");
977 if (tracefile == NULL) {
978 fprintf(stderr, "Can't open %s\n", s);
984 flags = fcntl(fileno(tracefile), F_GETFL);
986 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
988 setlinebuf(tracefile);
989 fputs("\nTracing started.\n", tracefile);
993 indent(int amount, char *pfx, FILE *fp)
997 for (i = 0; i < amount; i++) {
998 if (pfx && i == amount - 1)
1004 /* little circular references here... */
1005 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
1008 sharg(union node *arg, FILE *fp)
1011 struct nodelist *bqlist;
1012 unsigned char subtype;
1014 if (arg->type != NARG) {
1015 out1fmt("<node type %d>\n", arg->type);
1018 bqlist = arg->narg.backquote;
1019 for (p = arg->narg.text; *p; p++) {
1020 switch ((unsigned char)*p) {
1029 if (subtype == VSLENGTH)
1037 if (subtype & VSNUL)
1040 switch (subtype & VSTYPE) {
1066 case VSTRIMRIGHTMAX:
1073 out1fmt("<subtype %d>", subtype);
1082 shtree(bqlist->n, -1, NULL, fp);
1093 shcmd(union node *cmd, FILE *fp)
1101 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1107 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1111 switch (np->nfile.type) {
1112 case NTO: s = ">>"+1; dftfd = 1; break;
1113 case NCLOBBER: s = ">|"; dftfd = 1; break;
1114 case NAPPEND: s = ">>"; dftfd = 1; break;
1115 #if BASH_REDIR_OUTPUT
1118 case NTOFD: s = ">&"; dftfd = 1; break;
1119 case NFROM: s = "<"; break;
1120 case NFROMFD: s = "<&"; break;
1121 case NFROMTO: s = "<>"; break;
1122 default: s = "*error*"; break;
1124 if (np->nfile.fd != dftfd)
1125 fprintf(fp, "%d", np->nfile.fd);
1127 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1128 fprintf(fp, "%d", np->ndup.dupfd);
1130 sharg(np->nfile.fname, fp);
1137 shtree(union node *n, int ind, char *pfx, FILE *fp)
1139 struct nodelist *lp;
1145 indent(ind, pfx, fp);
1147 if (n == NODE_EOF) {
1162 shtree(n->nbinary.ch1, ind, NULL, fp);
1165 shtree(n->nbinary.ch2, ind, NULL, fp);
1173 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1174 shtree(lp->n, 0, NULL, fp);
1178 if (n->npipe.pipe_backgnd)
1184 fprintf(fp, "<node type %d>", n->type);
1192 showtree(union node *n)
1194 trace_puts("showtree called\n");
1195 shtree(n, 1, NULL, stderr);
1201 /* ============ Parser data */
1204 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1207 struct strlist *next;
1214 struct strpush *prev; /* preceding string on stack */
1216 int prev_left_in_line;
1217 #if ENABLE_ASH_ALIAS
1218 struct alias *ap; /* if push was associated with an alias */
1220 char *string; /* remember the string since it may change */
1222 /* Remember last two characters for pungetc. */
1225 /* Number of outstanding calls to pungetc. */
1230 struct parsefile *prev; /* preceding file on stack */
1231 int linno; /* current line */
1232 int pf_fd; /* file descriptor (or -1 if string) */
1233 int left_in_line; /* number of chars left in this line */
1234 int left_in_buffer; /* number of chars left in this buffer past the line */
1235 char *next_to_pgetc; /* next char in buffer */
1236 char *buf; /* input buffer */
1237 struct strpush *strpush; /* for pushing strings at this level */
1238 struct strpush basestrpush; /* so pushing one is fast */
1240 /* Remember last two characters for pungetc. */
1243 /* Number of outstanding calls to pungetc. */
1247 static struct parsefile basepf; /* top level input file */
1248 static struct parsefile *g_parsefile = &basepf; /* current input file */
1249 static int startlinno; /* line # where last token started */
1250 static char *commandname; /* currently executing command */
1251 static struct strlist *cmdenviron; /* environment for builtin command */
1254 /* ============ Message printing */
1257 ash_vmsg(const char *msg, va_list ap)
1259 fprintf(stderr, "%s: ", arg0);
1261 if (strcmp(arg0, commandname))
1262 fprintf(stderr, "%s: ", commandname);
1263 if (!iflag || g_parsefile->pf_fd > 0)
1264 fprintf(stderr, "line %d: ", startlinno);
1266 vfprintf(stderr, msg, ap);
1267 newline_and_flush(stderr);
1271 * Exverror is called to raise the error exception. If the second argument
1272 * is not NULL then error prints an error message using printf style
1273 * formatting. It then raises the error exception.
1275 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1277 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1281 TRACE(("ash_vmsg_and_raise(%d):", cond));
1284 TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
1289 flush_stdout_stderr();
1290 raise_exception(cond);
1294 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1296 ash_msg_and_raise_error(const char *msg, ...)
1303 ash_vmsg_and_raise(EXERROR, msg, ap);
1308 static void raise_error_syntax(const char *) NORETURN;
1310 raise_error_syntax(const char *msg)
1312 ash_msg_and_raise_error("syntax error: %s", msg);
1316 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1318 ash_msg_and_raise(int cond, const char *msg, ...)
1323 ash_vmsg_and_raise(cond, msg, ap);
1329 * error/warning routines for external builtins
1332 ash_msg(const char *fmt, ...)
1342 * Return a string describing an error. The returned string may be a
1343 * pointer to a static buffer that will be overwritten on the next call.
1344 * Action describes the operation that got the error.
1347 errmsg(int e, const char *em)
1349 if (e == ENOENT || e == ENOTDIR) {
1356 /* ============ Memory allocation */
1359 /* I consider these wrappers nearly useless:
1360 * ok, they return you to nearest exception handler, but
1361 * how much memory do you leak in the process, making
1362 * memory starvation worse?
1365 ckrealloc(void * p, size_t nbytes)
1367 p = realloc(p, nbytes);
1369 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1374 ckmalloc(size_t nbytes)
1376 return ckrealloc(NULL, nbytes);
1380 ckzalloc(size_t nbytes)
1382 return memset(ckmalloc(nbytes), 0, nbytes);
1386 ckstrdup(const char *s)
1388 char *p = strdup(s);
1390 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1394 /* Using bbox equivalents. They exit if out of memory */
1395 # define ckrealloc xrealloc
1396 # define ckmalloc xmalloc
1397 # define ckzalloc xzalloc
1398 # define ckstrdup xstrdup
1402 * It appears that grabstackstr() will barf with such alignments
1403 * because stalloc() will return a string allocated in a new stackblock.
1405 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1407 /* Most machines require the value returned from malloc to be aligned
1408 * in some way. The following macro will get this right
1409 * on many machines. */
1410 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1411 /* Minimum size of a block */
1412 MINSIZE = SHELL_ALIGN(504),
1415 struct stack_block {
1416 struct stack_block *prev;
1417 char space[MINSIZE];
1421 struct stack_block *stackp;
1427 struct globals_memstack {
1428 struct stack_block *g_stackp; // = &stackbase;
1429 char *g_stacknxt; // = stackbase.space;
1430 char *sstrend; // = stackbase.space + MINSIZE;
1431 size_t g_stacknleft; // = MINSIZE;
1432 struct stack_block stackbase;
1434 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1435 #define G_memstack (*ash_ptr_to_globals_memstack)
1436 #define g_stackp (G_memstack.g_stackp )
1437 #define g_stacknxt (G_memstack.g_stacknxt )
1438 #define sstrend (G_memstack.sstrend )
1439 #define g_stacknleft (G_memstack.g_stacknleft)
1440 #define stackbase (G_memstack.stackbase )
1441 #define INIT_G_memstack() do { \
1442 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1444 g_stackp = &stackbase; \
1445 g_stacknxt = stackbase.space; \
1446 g_stacknleft = MINSIZE; \
1447 sstrend = stackbase.space + MINSIZE; \
1451 #define stackblock() ((void *)g_stacknxt)
1452 #define stackblocksize() g_stacknleft
1455 * Parse trees for commands are allocated in lifo order, so we use a stack
1456 * to make this more efficient, and also to avoid all sorts of exception
1457 * handling code to handle interrupts in the middle of a parse.
1459 * The size 504 was chosen because the Ultrix malloc handles that size
1463 stalloc(size_t nbytes)
1468 aligned = SHELL_ALIGN(nbytes);
1469 if (aligned > g_stacknleft) {
1472 struct stack_block *sp;
1474 blocksize = aligned;
1475 if (blocksize < MINSIZE)
1476 blocksize = MINSIZE;
1477 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1478 if (len < blocksize)
1479 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1482 sp->prev = g_stackp;
1483 g_stacknxt = sp->space;
1484 g_stacknleft = blocksize;
1485 sstrend = g_stacknxt + blocksize;
1490 g_stacknxt += aligned;
1491 g_stacknleft -= aligned;
1496 stzalloc(size_t nbytes)
1498 return memset(stalloc(nbytes), 0, nbytes);
1505 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1506 write(STDERR_FILENO, "stunalloc\n", 10);
1510 g_stacknleft += g_stacknxt - (char *)p;
1515 * Like strdup but works with the ash stack.
1518 sstrdup(const char *p)
1520 size_t len = strlen(p) + 1;
1521 return memcpy(stalloc(len), p, len);
1525 grabstackblock(size_t len)
1531 pushstackmark(struct stackmark *mark, size_t len)
1533 mark->stackp = g_stackp;
1534 mark->stacknxt = g_stacknxt;
1535 mark->stacknleft = g_stacknleft;
1536 grabstackblock(len);
1540 setstackmark(struct stackmark *mark)
1542 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1546 popstackmark(struct stackmark *mark)
1548 struct stack_block *sp;
1554 while (g_stackp != mark->stackp) {
1556 g_stackp = sp->prev;
1559 g_stacknxt = mark->stacknxt;
1560 g_stacknleft = mark->stacknleft;
1561 sstrend = mark->stacknxt + mark->stacknleft;
1566 * When the parser reads in a string, it wants to stick the string on the
1567 * stack and only adjust the stack pointer when it knows how big the
1568 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1569 * of space on top of the stack and stackblocklen returns the length of
1570 * this block. Growstackblock will grow this space by at least one byte,
1571 * possibly moving it (like realloc). Grabstackblock actually allocates the
1572 * part of the block that has been used.
1575 growstackblock(void)
1579 newlen = g_stacknleft * 2;
1580 if (newlen < g_stacknleft)
1581 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1585 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1586 struct stack_block *sp;
1587 struct stack_block *prevstackp;
1592 prevstackp = sp->prev;
1593 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1594 sp = ckrealloc(sp, grosslen);
1595 sp->prev = prevstackp;
1597 g_stacknxt = sp->space;
1598 g_stacknleft = newlen;
1599 sstrend = sp->space + newlen;
1602 char *oldspace = g_stacknxt;
1603 size_t oldlen = g_stacknleft;
1604 char *p = stalloc(newlen);
1606 /* free the space we just allocated */
1607 g_stacknxt = memcpy(p, oldspace, oldlen);
1608 g_stacknleft += newlen;
1613 * The following routines are somewhat easier to use than the above.
1614 * The user declares a variable of type STACKSTR, which may be declared
1615 * to be a register. The macro STARTSTACKSTR initializes things. Then
1616 * the user uses the macro STPUTC to add characters to the string. In
1617 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1618 * grown as necessary. When the user is done, she can just leave the
1619 * string there and refer to it using stackblock(). Or she can allocate
1620 * the space for it using grabstackstr(). If it is necessary to allow
1621 * someone else to use the stack temporarily and then continue to grow
1622 * the string, the user should use grabstack to allocate the space, and
1623 * then call ungrabstr(p) to return to the previous mode of operation.
1625 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1626 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1627 * is space for at least one character.
1632 size_t len = stackblocksize();
1634 return (char *)stackblock() + len;
1638 * Called from CHECKSTRSPACE.
1641 makestrspace(size_t newlen, char *p)
1643 size_t len = p - g_stacknxt;
1649 size = stackblocksize();
1651 if (nleft >= newlen)
1655 return (char *)stackblock() + len;
1659 stack_nputstr(const char *s, size_t n, char *p)
1661 p = makestrspace(n, p);
1662 p = (char *)memcpy(p, s, n) + n;
1667 stack_putstr(const char *s, char *p)
1669 return stack_nputstr(s, strlen(s), p);
1673 _STPUTC(int c, char *p)
1681 #define STARTSTACKSTR(p) ((p) = stackblock())
1682 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1683 #define CHECKSTRSPACE(n, p) do { \
1686 size_t m = sstrend - q; \
1688 (p) = makestrspace(l, q); \
1690 #define USTPUTC(c, p) (*(p)++ = (c))
1691 #define STACKSTRNUL(p) do { \
1692 if ((p) == sstrend) \
1693 (p) = growstackstr(); \
1696 #define STUNPUTC(p) (--(p))
1697 #define STTOPC(p) ((p)[-1])
1698 #define STADJUST(amount, p) ((p) += (amount))
1700 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1701 #define ungrabstackstr(s, p) stunalloc(s)
1702 #define stackstrend() ((void *)sstrend)
1705 /* ============ String helpers */
1708 * prefix -- see if pfx is a prefix of string.
1711 prefix(const char *string, const char *pfx)
1714 if (*pfx++ != *string++)
1717 return (char *) string;
1721 * Check for a valid number. This should be elsewhere.
1724 is_number(const char *p)
1729 } while (*++p != '\0');
1734 * Convert a string of digits to an integer, printing an error message on
1738 number(const char *s)
1741 ash_msg_and_raise_error(msg_illnum, s);
1746 * Produce a possibly single quoted string suitable as input to the shell.
1747 * The return string is allocated on the stack.
1750 single_quote(const char *s)
1760 len = strchrnul(s, '\'') - s;
1762 q = p = makestrspace(len + 3, p);
1765 q = (char *)memcpy(q, s, len) + len;
1774 do len++; while (*++s == '\'');
1776 q = p = makestrspace(len + 3, p);
1779 q = (char *)memcpy(q, s - len, len) + len;
1787 return stackblock();
1791 /* ============ nextopt */
1793 static char **argptr; /* argument list for builtin commands */
1794 static char *optionarg; /* set by nextopt (like getopt) */
1795 static char *optptr; /* used by nextopt */
1798 * XXX - should get rid of. Have all builtins use getopt(3).
1799 * The library getopt must have the BSD extension static variable
1800 * "optreset", otherwise it can't be used within the shell safely.
1802 * Standard option processing (a la getopt) for builtin routines.
1803 * The only argument that is passed to nextopt is the option string;
1804 * the other arguments are unnecessary. It returns the character,
1805 * or '\0' on end of input.
1808 nextopt(const char *optstring)
1815 if (p == NULL || *p == '\0') {
1816 /* We ate entire "-param", take next one */
1822 if (*++p == '\0') /* just "-" ? */
1825 if (LONE_DASH(p)) /* "--" ? */
1827 /* p => next "-param" */
1829 /* p => some option char in the middle of a "-param" */
1831 for (q = optstring; *q != c;) {
1833 ash_msg_and_raise_error("illegal option -%c", c);
1841 ash_msg_and_raise_error("no arg for -%c option", c);
1851 /* ============ Shell variables */
1854 * The parsefile structure pointed to by the global variable parsefile
1855 * contains information about the current file being read.
1858 int nparam; /* # of positional parameters (without $0) */
1859 #if ENABLE_ASH_GETOPTS
1860 int optind; /* next parameter to be processed by getopts */
1861 int optoff; /* used by getopts */
1863 unsigned char malloced; /* if parameter list dynamically allocated */
1864 char **p; /* parameter list */
1868 * Free the list of positional parameters.
1871 freeparam(volatile struct shparam *param)
1873 if (param->malloced) {
1875 ap = ap1 = param->p;
1882 #if ENABLE_ASH_GETOPTS
1883 static void FAST_FUNC getoptsreset(const char *value);
1887 struct var *next; /* next entry in hash list */
1888 int flags; /* flags are defined above */
1889 const char *var_text; /* name=value */
1890 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1891 /* the variable gets set/unset */
1895 struct localvar *next; /* next local variable in list */
1896 struct var *vp; /* the variable that was made local */
1897 int flags; /* saved flags */
1898 const char *text; /* saved text */
1902 #define VEXPORT 0x01 /* variable is exported */
1903 #define VREADONLY 0x02 /* variable cannot be modified */
1904 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1905 #define VTEXTFIXED 0x08 /* text is statically allocated */
1906 #define VSTACK 0x10 /* text is allocated on the stack */
1907 #define VUNSET 0x20 /* the variable is not set */
1908 #define VNOFUNC 0x40 /* don't call the callback function */
1909 #define VNOSET 0x80 /* do not set variable - just readonly test */
1910 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1911 #if ENABLE_ASH_RANDOM_SUPPORT
1912 # define VDYNAMIC 0x200 /* dynamic variable */
1918 /* Need to be before varinit_data[] */
1919 #if ENABLE_LOCALE_SUPPORT
1920 static void FAST_FUNC
1921 change_lc_all(const char *value)
1923 if (value && *value != '\0')
1924 setlocale(LC_ALL, value);
1926 static void FAST_FUNC
1927 change_lc_ctype(const char *value)
1929 if (value && *value != '\0')
1930 setlocale(LC_CTYPE, value);
1934 static void chkmail(void);
1935 static void changemail(const char *var_value) FAST_FUNC;
1937 # define chkmail() ((void)0)
1939 static void changepath(const char *) FAST_FUNC;
1940 #if ENABLE_ASH_RANDOM_SUPPORT
1941 static void change_random(const char *) FAST_FUNC;
1944 static const struct {
1946 const char *var_text;
1947 void (*var_func)(const char *) FAST_FUNC;
1948 } varinit_data[] = {
1950 * Note: VEXPORT would not work correctly here for NOFORK applets:
1951 * some environment strings may be constant.
1953 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1955 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1956 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1958 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1959 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1960 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1961 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
1962 #if ENABLE_ASH_GETOPTS
1963 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
1965 #if ENABLE_ASH_RANDOM_SUPPORT
1966 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
1968 #if ENABLE_LOCALE_SUPPORT
1969 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1970 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
1972 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
1973 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
1979 struct globals_var {
1980 struct shparam shellparam; /* $@ current positional parameters */
1981 struct redirtab *redirlist;
1982 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1983 struct var *vartab[VTABSIZE];
1984 struct var varinit[ARRAY_SIZE(varinit_data)];
1986 extern struct globals_var *const ash_ptr_to_globals_var;
1987 #define G_var (*ash_ptr_to_globals_var)
1988 #define shellparam (G_var.shellparam )
1989 //#define redirlist (G_var.redirlist )
1990 #define preverrout_fd (G_var.preverrout_fd)
1991 #define vartab (G_var.vartab )
1992 #define varinit (G_var.varinit )
1993 #define INIT_G_var() do { \
1995 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1997 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1998 varinit[i].flags = varinit_data[i].flags; \
1999 varinit[i].var_text = varinit_data[i].var_text; \
2000 varinit[i].var_func = varinit_data[i].var_func; \
2004 #define vifs varinit[0]
2006 # define vmail (&vifs)[1]
2007 # define vmpath (&vmail)[1]
2008 # define vpath (&vmpath)[1]
2010 # define vpath (&vifs)[1]
2012 #define vps1 (&vpath)[1]
2013 #define vps2 (&vps1)[1]
2014 #define vps4 (&vps2)[1]
2015 #if ENABLE_ASH_GETOPTS
2016 # define voptind (&vps4)[1]
2017 # if ENABLE_ASH_RANDOM_SUPPORT
2018 # define vrandom (&voptind)[1]
2021 # if ENABLE_ASH_RANDOM_SUPPORT
2022 # define vrandom (&vps4)[1]
2027 * The following macros access the values of the above variables.
2028 * They have to skip over the name. They return the null string
2029 * for unset variables.
2031 #define ifsval() (vifs.var_text + 4)
2032 #define ifsset() ((vifs.flags & VUNSET) == 0)
2034 # define mailval() (vmail.var_text + 5)
2035 # define mpathval() (vmpath.var_text + 9)
2036 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2038 #define pathval() (vpath.var_text + 5)
2039 #define ps1val() (vps1.var_text + 4)
2040 #define ps2val() (vps2.var_text + 4)
2041 #define ps4val() (vps4.var_text + 4)
2042 #if ENABLE_ASH_GETOPTS
2043 # define optindval() (voptind.var_text + 7)
2046 #if ENABLE_ASH_GETOPTS
2047 static void FAST_FUNC
2048 getoptsreset(const char *value)
2050 shellparam.optind = number(value) ?: 1;
2051 shellparam.optoff = -1;
2056 * Compares two strings up to the first = or '\0'. The first
2057 * string must be terminated by '='; the second may be terminated by
2058 * either '=' or '\0'.
2061 varcmp(const char *p, const char *q)
2065 while ((c = *p) == (d = *q)) {
2066 if (c == '\0' || c == '=')
2080 * Find the appropriate entry in the hash table from the name.
2082 static struct var **
2083 hashvar(const char *p)
2087 hashval = ((unsigned char) *p) << 4;
2088 while (*p && *p != '=')
2089 hashval += (unsigned char) *p++;
2090 return &vartab[hashval % VTABSIZE];
2094 vpcmp(const void *a, const void *b)
2096 return varcmp(*(const char **)a, *(const char **)b);
2100 * This routine initializes the builtin variables.
2110 * PS1 depends on uid
2112 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2113 vps1.var_text = "PS1=\\w \\$ ";
2116 vps1.var_text = "PS1=# ";
2119 end = vp + ARRAY_SIZE(varinit);
2121 vpp = hashvar(vp->var_text);
2124 } while (++vp < end);
2127 static struct var **
2128 findvar(struct var **vpp, const char *name)
2130 for (; *vpp; vpp = &(*vpp)->next) {
2131 if (varcmp((*vpp)->var_text, name) == 0) {
2139 * Find the value of a variable. Returns NULL if not set.
2141 static const char* FAST_FUNC
2142 lookupvar(const char *name)
2146 v = *findvar(hashvar(name), name);
2148 #if ENABLE_ASH_RANDOM_SUPPORT
2150 * Dynamic variables are implemented roughly the same way they are
2151 * in bash. Namely, they're "special" so long as they aren't unset.
2152 * As soon as they're unset, they're no longer dynamic, and dynamic
2153 * lookup will no longer happen at that point. -- PFM.
2155 if (v->flags & VDYNAMIC)
2158 if (!(v->flags & VUNSET))
2159 return var_end(v->var_text);
2164 #if ENABLE_UNICODE_SUPPORT
2166 reinit_unicode_for_ash(void)
2168 /* Unicode support should be activated even if LANG is set
2169 * _during_ shell execution, not only if it was set when
2170 * shell was started. Therefore, re-check LANG every time:
2172 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2173 || ENABLE_UNICODE_USING_LOCALE
2175 const char *s = lookupvar("LC_ALL");
2176 if (!s) s = lookupvar("LC_CTYPE");
2177 if (!s) s = lookupvar("LANG");
2182 # define reinit_unicode_for_ash() ((void)0)
2186 * Search the environment of a builtin command.
2189 bltinlookup(const char *name)
2193 for (sp = cmdenviron; sp; sp = sp->next) {
2194 if (varcmp(sp->text, name) == 0)
2195 return var_end(sp->text);
2197 return lookupvar(name);
2201 * Same as setvar except that the variable and value are passed in
2202 * the first argument as name=value. Since the first argument will
2203 * be actually stored in the table, it should not be a string that
2205 * Called with interrupts off.
2208 setvareq(char *s, int flags)
2210 struct var *vp, **vpp;
2213 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2214 vp = *findvar(vpp, s);
2216 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2219 if (flags & VNOSAVE)
2223 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2229 if (vp->var_func && !(flags & VNOFUNC))
2230 vp->var_func(var_end(s));
2232 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2233 free((char*)vp->var_text);
2235 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2237 /* variable s is not found */
2240 vp = ckzalloc(sizeof(*vp));
2242 /*vp->func = NULL; - ckzalloc did it */
2245 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2252 * Set the value of a variable. The flags argument is ored with the
2253 * flags of the variable. If val is NULL, the variable is unset.
2256 setvar(const char *name, const char *val, int flags)
2264 q = endofname(name);
2265 p = strchrnul(q, '=');
2267 if (!namelen || p != q)
2268 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2273 vallen = strlen(val);
2277 nameeq = ckmalloc(namelen + vallen + 2);
2278 p = memcpy(nameeq, name, namelen) + namelen;
2281 p = memcpy(p, val, vallen) + vallen;
2284 setvareq(nameeq, flags | VNOSAVE);
2288 static void FAST_FUNC
2289 setvar0(const char *name, const char *val)
2291 setvar(name, val, 0);
2295 * Unset the specified variable.
2298 unsetvar(const char *s)
2304 vpp = findvar(hashvar(s), s);
2308 int flags = vp->flags;
2311 if (flags & VREADONLY)
2313 #if ENABLE_ASH_RANDOM_SUPPORT
2314 vp->flags &= ~VDYNAMIC;
2318 if ((flags & VSTRFIXED) == 0) {
2320 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2321 free((char*)vp->var_text);
2327 vp->flags &= ~VEXPORT;
2337 * Process a linked list of variable assignments.
2340 listsetvar(struct strlist *list_set_var, int flags)
2342 struct strlist *lp = list_set_var;
2348 setvareq(lp->text, flags);
2355 * Generate a list of variables satisfying the given conditions.
2358 listvars(int on, int off, char ***end)
2369 for (vp = *vpp; vp; vp = vp->next) {
2370 if ((vp->flags & mask) == on) {
2371 if (ep == stackstrend())
2372 ep = growstackstr();
2373 *ep++ = (char*)vp->var_text;
2376 } while (++vpp < vartab + VTABSIZE);
2377 if (ep == stackstrend())
2378 ep = growstackstr();
2382 return grabstackstr(ep);
2386 /* ============ Path search helper
2388 * The variable path (passed by reference) should be set to the start
2389 * of the path before the first call; path_advance will update
2390 * this value as it proceeds. Successive calls to path_advance will return
2391 * the possible path expansions in sequence. If an option (indicated by
2392 * a percent sign) appears in the path entry then the global variable
2393 * pathopt will be set to point to it; otherwise pathopt will be set to
2396 static const char *pathopt; /* set by path_advance */
2399 path_advance(const char **path, const char *name)
2409 for (p = start; *p && *p != ':' && *p != '%'; p++)
2411 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2412 while (stackblocksize() < len)
2416 memcpy(q, start, p - start);
2424 while (*p && *p != ':')
2431 return stalloc(len);
2435 /* ============ Prompt */
2437 static smallint doprompt; /* if set, prompt the user */
2438 static smallint needprompt; /* true if interactive and at start of line */
2440 #if ENABLE_FEATURE_EDITING
2441 static line_input_t *line_input_state;
2442 static const char *cmdedit_prompt;
2444 putprompt(const char *s)
2446 if (ENABLE_ASH_EXPAND_PRMT) {
2447 free((char*)cmdedit_prompt);
2448 cmdedit_prompt = ckstrdup(s);
2455 putprompt(const char *s)
2461 #if ENABLE_ASH_EXPAND_PRMT
2462 /* expandstr() needs parsing machinery, so it is far away ahead... */
2463 static const char *expandstr(const char *ps);
2465 #define expandstr(s) s
2469 setprompt_if(smallint do_set, int whichprompt)
2472 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2479 switch (whichprompt) {
2489 #if ENABLE_ASH_EXPAND_PRMT
2490 pushstackmark(&smark, stackblocksize());
2492 putprompt(expandstr(prompt));
2493 #if ENABLE_ASH_EXPAND_PRMT
2494 popstackmark(&smark);
2499 /* ============ The cd and pwd commands */
2501 #define CD_PHYSICAL 1
2511 while ((i = nextopt("LP")) != '\0') {
2513 flags ^= CD_PHYSICAL;
2522 * Update curdir (the name of the current directory) in response to a
2526 updatepwd(const char *dir)
2533 cdcomppath = sstrdup(dir);
2536 if (curdir == nullstr)
2538 new = stack_putstr(curdir, new);
2540 new = makestrspace(strlen(dir) + 2, new);
2541 lim = (char *)stackblock() + 1;
2545 if (new > lim && *lim == '/')
2550 if (dir[1] == '/' && dir[2] != '/') {
2556 p = strtok(cdcomppath, "/");
2560 if (p[1] == '.' && p[2] == '\0') {
2572 new = stack_putstr(p, new);
2575 p = strtok(NULL, "/");
2580 return stackblock();
2584 * Find out what the current directory is. If we already know the current
2585 * directory, this routine returns immediately.
2590 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2591 return dir ? dir : nullstr;
2595 setpwd(const char *val, int setold)
2599 oldcur = dir = curdir;
2602 setvar("OLDPWD", oldcur, VEXPORT);
2605 if (physdir != nullstr) {
2606 if (physdir != oldcur)
2610 if (oldcur == val || !val) {
2616 dir = ckstrdup(val);
2617 if (oldcur != dir && oldcur != nullstr) {
2622 setvar("PWD", dir, VEXPORT);
2625 static void hashcd(void);
2628 * Actually do the chdir. We also call hashcd to let other routines
2629 * know that the current directory has changed.
2632 docd(const char *dest, int flags)
2634 const char *dir = NULL;
2637 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2640 if (!(flags & CD_PHYSICAL)) {
2641 dir = updatepwd(dest);
2655 static int FAST_FUNC
2656 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2668 dest = bltinlookup("HOME");
2669 else if (LONE_DASH(dest)) {
2670 dest = bltinlookup("OLDPWD");
2692 path = bltinlookup("CDPATH");
2695 p = path_advance(&path, dest);
2696 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2700 if (!docd(p, flags))
2711 ash_msg_and_raise_error("can't cd to %s", dest);
2714 if (flags & CD_PRINT)
2715 out1fmt("%s\n", curdir);
2719 static int FAST_FUNC
2720 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2723 const char *dir = curdir;
2727 if (physdir == nullstr)
2731 out1fmt("%s\n", dir);
2736 /* ============ ... */
2739 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2741 /* Syntax classes */
2742 #define CWORD 0 /* character is nothing special */
2743 #define CNL 1 /* newline character */
2744 #define CBACK 2 /* a backslash character */
2745 #define CSQUOTE 3 /* single quote */
2746 #define CDQUOTE 4 /* double quote */
2747 #define CENDQUOTE 5 /* a terminating quote */
2748 #define CBQUOTE 6 /* backwards single quote */
2749 #define CVAR 7 /* a dollar sign */
2750 #define CENDVAR 8 /* a '}' character */
2751 #define CLP 9 /* a left paren in arithmetic */
2752 #define CRP 10 /* a right paren in arithmetic */
2753 #define CENDFILE 11 /* end of file */
2754 #define CCTL 12 /* like CWORD, except it must be escaped */
2755 #define CSPCL 13 /* these terminate a word */
2756 #define CIGN 14 /* character should be ignored */
2759 #if ENABLE_ASH_ALIAS
2763 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2765 #if ENABLE_FEATURE_SH_MATH
2766 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2768 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2770 static const uint16_t S_I_T[] ALIGN2 = {
2771 #if ENABLE_ASH_ALIAS
2772 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2774 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2775 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2776 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2777 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2778 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2779 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2780 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2781 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2782 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2783 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2784 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2785 #if !USE_SIT_FUNCTION
2786 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2787 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2788 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2792 /* Constants below must match table above */
2794 #if ENABLE_ASH_ALIAS
2795 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2797 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2798 CNL_CNL_CNL_CNL , /* 2 */
2799 CWORD_CCTL_CCTL_CWORD , /* 3 */
2800 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2801 CVAR_CVAR_CWORD_CVAR , /* 5 */
2802 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2803 CSPCL_CWORD_CWORD_CLP , /* 7 */
2804 CSPCL_CWORD_CWORD_CRP , /* 8 */
2805 CBACK_CBACK_CCTL_CBACK , /* 9 */
2806 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2807 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2808 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2809 CWORD_CWORD_CWORD_CWORD , /* 13 */
2810 CCTL_CCTL_CCTL_CCTL , /* 14 */
2813 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2814 * caller must ensure proper cast on it if c is *char_ptr!
2816 /* Values for syntax param */
2817 #define BASESYNTAX 0 /* not in quotes */
2818 #define DQSYNTAX 1 /* in double quotes */
2819 #define SQSYNTAX 2 /* in single quotes */
2820 #define ARISYNTAX 3 /* in arithmetic */
2821 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2823 #if USE_SIT_FUNCTION
2826 SIT(int c, int syntax)
2828 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2829 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2831 * This causes '/' to be prepended with CTLESC in dquoted string,
2832 * making "./file"* treated incorrectly because we feed
2833 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2834 * The "homegrown" glob implementation is okay with that,
2835 * but glibc one isn't. With '/' always treated as CWORD,
2838 # if ENABLE_ASH_ALIAS
2839 static const uint8_t syntax_index_table[] ALIGN1 = {
2840 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2841 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2842 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2846 static const uint8_t syntax_index_table[] ALIGN1 = {
2847 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2848 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2849 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2858 # if ENABLE_ASH_ALIAS
2864 /* Cast is purely for paranoia here,
2865 * just in case someone passed signed char to us */
2866 if ((unsigned char)c >= CTL_FIRST
2867 && (unsigned char)c <= CTL_LAST
2871 s = strchrnul(spec_symbls, c);
2874 indx = syntax_index_table[s - spec_symbls];
2876 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2879 #else /* !USE_SIT_FUNCTION */
2881 static const uint8_t syntax_index_table[] ALIGN1 = {
2882 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2883 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2893 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2894 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2916 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2917 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2918 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2919 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2920 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2921 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2922 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2923 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2924 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2925 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2926 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2927 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2928 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2929 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2930 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2931 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2943 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2944 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2945 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2946 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2947 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2948 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2976 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2977 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2978 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2981 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2993 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3004 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3005 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3006 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3007 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3008 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3009 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3010 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3011 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
3012 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
3013 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
3014 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
3015 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
3016 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
3017 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
3018 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3019 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3020 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3021 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3022 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3023 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3024 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3025 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3027 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3028 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3029 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3030 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3031 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3032 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3033 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3034 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3113 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3114 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3115 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3116 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3117 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3118 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3119 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3120 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3121 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3122 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3123 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3124 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3125 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3126 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3127 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3128 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3129 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3130 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3131 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3132 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3133 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3134 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3135 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3136 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3137 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3138 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3139 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3140 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3141 # if ENABLE_ASH_ALIAS
3142 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3147 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3148 #else /* debug version, caught one signed char bug */
3149 # define SIT(c, syntax) \
3151 if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
3152 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3153 if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
3154 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3155 ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
3159 #endif /* !USE_SIT_FUNCTION */
3162 /* ============ Alias handling */
3164 #if ENABLE_ASH_ALIAS
3166 #define ALIASINUSE 1
3177 static struct alias **atab; // [ATABSIZE];
3178 #define INIT_G_alias() do { \
3179 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3183 static struct alias **
3184 __lookupalias(const char *name)
3186 unsigned int hashval;
3193 ch = (unsigned char)*p;
3197 ch = (unsigned char)*++p;
3199 app = &atab[hashval % ATABSIZE];
3201 for (; *app; app = &(*app)->next) {
3202 if (strcmp(name, (*app)->name) == 0) {
3210 static struct alias *
3211 lookupalias(const char *name, int check)
3213 struct alias *ap = *__lookupalias(name);
3215 if (check && ap && (ap->flag & ALIASINUSE))
3220 static struct alias *
3221 freealias(struct alias *ap)
3225 if (ap->flag & ALIASINUSE) {
3226 ap->flag |= ALIASDEAD;
3238 setalias(const char *name, const char *val)
3240 struct alias *ap, **app;
3242 app = __lookupalias(name);
3246 if (!(ap->flag & ALIASINUSE)) {
3249 ap->val = ckstrdup(val);
3250 ap->flag &= ~ALIASDEAD;
3253 ap = ckzalloc(sizeof(struct alias));
3254 ap->name = ckstrdup(name);
3255 ap->val = ckstrdup(val);
3256 /*ap->flag = 0; - ckzalloc did it */
3257 /*ap->next = NULL;*/
3264 unalias(const char *name)
3268 app = __lookupalias(name);
3272 *app = freealias(*app);
3283 struct alias *ap, **app;
3287 for (i = 0; i < ATABSIZE; i++) {
3289 for (ap = *app; ap; ap = *app) {
3290 *app = freealias(*app);
3300 printalias(const struct alias *ap)
3302 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3306 * TODO - sort output
3308 static int FAST_FUNC
3309 aliascmd(int argc UNUSED_PARAM, char **argv)
3318 for (i = 0; i < ATABSIZE; i++) {
3319 for (ap = atab[i]; ap; ap = ap->next) {
3325 while ((n = *++argv) != NULL) {
3326 v = strchr(n+1, '=');
3327 if (v == NULL) { /* n+1: funny ksh stuff */
3328 ap = *__lookupalias(n);
3330 fprintf(stderr, "%s: %s not found\n", "alias", n);
3343 static int FAST_FUNC
3344 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3348 while (nextopt("a") != '\0') {
3352 for (i = 0; *argptr; argptr++) {
3353 if (unalias(*argptr)) {
3354 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3362 #endif /* ASH_ALIAS */
3365 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3368 #define FORK_NOJOB 2
3370 /* mode flags for showjob(s) */
3371 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3372 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3373 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3374 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3377 * A job structure contains information about a job. A job is either a
3378 * single process or a set of processes contained in a pipeline. In the
3379 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3383 pid_t ps_pid; /* process id */
3384 int ps_status; /* last process status from wait() */
3385 char *ps_cmd; /* text of command being run */
3389 struct procstat ps0; /* status of process */
3390 struct procstat *ps; /* status or processes when more than one */
3392 int stopstatus; /* status of a stopped job */
3394 unsigned nprocs; /* number of processes */
3396 #define JOBRUNNING 0 /* at least one proc running */
3397 #define JOBSTOPPED 1 /* all procs are stopped */
3398 #define JOBDONE 2 /* all procs are completed */
3402 sigint: 1, /* job was killed by SIGINT */
3403 jobctl: 1, /* job running under job control */
3405 waited: 1, /* true if this entry has been waited for */
3406 used: 1, /* true if this entry is in used */
3407 changed: 1; /* true if status has changed */
3408 struct job *prev_job; /* previous job */
3411 static struct job *makejob(/*union node *,*/ int);
3412 static int forkshell(struct job *, union node *, int);
3413 static int waitforjob(struct job *);
3416 enum { doing_jobctl = 0 };
3417 #define setjobctl(on) do {} while (0)
3419 static smallint doing_jobctl; //references:8
3420 static void setjobctl(int);
3427 ignoresig(int signo)
3429 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3430 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3431 /* No, need to do it */
3432 signal(signo, SIG_IGN);
3434 sigmode[signo - 1] = S_HARD_IGN;
3438 * Only one usage site - in setsignal()
3441 signal_handler(int signo)
3443 if (signo == SIGCHLD) {
3449 gotsig[signo - 1] = 1;
3450 pending_sig = signo;
3452 if (signo == SIGINT && !trap[SIGINT]) {
3453 if (!suppress_int) {
3455 raise_interrupt(); /* does not return */
3462 * Set the signal handler for the specified signal. The routine figures
3463 * out what it should be set to.
3466 setsignal(int signo)
3469 char cur_act, new_act;
3470 struct sigaction act;
3474 if (t != NULL) { /* trap for this sig is set */
3476 if (t[0] == '\0') /* trap is "": ignore this sig */
3480 if (rootshell && new_act == S_DFL) {
3483 if (iflag || minusc || sflag == 0)
3492 * "In all cases, bash ignores SIGQUIT. Non-builtin
3493 * commands run by bash have signal handlers
3494 * set to the values inherited by the shell
3495 * from its parent". */
3511 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3512 //whereas we have to restore it to what shell got on entry
3513 //from the parent. See comment above
3515 if (signo == SIGCHLD)
3518 t = &sigmode[signo - 1];
3521 /* current setting is not yet known */
3522 if (sigaction(signo, NULL, &act)) {
3523 /* pretend it worked; maybe we should give a warning,
3524 * but other shells don't. We don't alter sigmode,
3525 * so we retry every time.
3526 * btw, in Linux it never fails. --vda */
3529 if (act.sa_handler == SIG_IGN) {
3530 cur_act = S_HARD_IGN;
3532 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3534 cur_act = S_IGN; /* don't hard ignore these */
3538 if (cur_act == S_HARD_IGN || cur_act == new_act)
3541 act.sa_handler = SIG_DFL;
3544 act.sa_handler = signal_handler;
3547 act.sa_handler = SIG_IGN;
3551 /* flags and mask matter only if !DFL and !IGN, but we do it
3552 * for all cases for more deterministic behavior:
3555 sigfillset(&act.sa_mask);
3557 sigaction_set(signo, &act);
3562 /* mode flags for set_curjob */
3563 #define CUR_DELETE 2
3564 #define CUR_RUNNING 1
3565 #define CUR_STOPPED 0
3568 /* pgrp of shell on invocation */
3569 static int initialpgrp; //references:2
3570 static int ttyfd = -1; //5
3573 static struct job *jobtab; //5
3575 static unsigned njobs; //4
3577 static struct job *curjob; //lots
3578 /* number of presumed living untracked jobs */
3579 static int jobless; //4
3582 /* Bash has a feature: it restores termios after a successful wait for
3583 * a foreground job which had at least one stopped or sigkilled member.
3584 * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
3585 * properly restoring tty state. Should we do this too?
3586 * A reproducer: ^Z an interactive python:
3589 * Python 2.7.12 (...)
3591 * { python leaves tty in -icanon -echo state. We do survive that... }
3592 * [1]+ Stopped python
3593 * { ...however, next program (python #2) does not survive it well: }
3595 * Python 2.7.12 (...)
3596 * >>> Traceback (most recent call last):
3597 * { above, I typed "qwerty<CR>", but -echo state is still in effect }
3598 * File "<stdin>", line 1, in <module>
3599 * NameError: name 'qwerty' is not defined
3601 * The implementation below is modeled on bash code and seems to work.
3602 * However, I'm not sure we should do this. For one: what if I'd fg
3603 * the stopped python instead? It'll be confused by "restored" tty state.
3605 static struct termios shell_tty_info;
3609 if (rootshell && ttyfd >= 0)
3610 tcgetattr(ttyfd, &shell_tty_info);
3615 /* if (rootshell) - caller ensures this */
3617 tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
3620 job_signal_status(struct job *jp)
3624 struct procstat *ps = jp->ps;
3625 for (i = 0; i < jp->nprocs; i++) {
3626 status = ps[i].ps_status;
3627 if (WIFSIGNALED(status) || WIFSTOPPED(status))
3633 restore_tty_if_stopped_or_signaled(struct job *jp)
3635 //TODO: check what happens if we come from waitforjob() in expbackq()
3637 int s = job_signal_status(jp);
3638 if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
3643 # define get_tty_state() ((void)0)
3644 # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
3648 set_curjob(struct job *jp, unsigned mode)
3651 struct job **jpp, **curp;
3653 /* first remove from list */
3654 jpp = curp = &curjob;
3659 jpp = &jp1->prev_job;
3661 *jpp = jp1->prev_job;
3663 /* Then re-insert in correct position */
3671 /* job being deleted */
3674 /* newly created job or backgrounded job,
3675 * put after all stopped jobs.
3680 if (!jp1 || jp1->state != JOBSTOPPED)
3683 jpp = &jp1->prev_job;
3689 /* newly stopped job - becomes curjob */
3690 jp->prev_job = *jpp;
3698 jobno(const struct job *jp)
3700 return jp - jobtab + 1;
3705 * Convert a job name to a job structure.
3708 #define getjob(name, getctl) getjob(name)
3711 getjob(const char *name, int getctl)
3715 const char *err_msg = "%s: no such job";
3719 char *(*match)(const char *, const char *);
3734 if (c == '+' || c == '%') {
3736 err_msg = "No current job";
3742 err_msg = "No previous job";
3752 if (num > 0 && num <= njobs) {
3753 jp = jobtab + num - 1;
3768 if (match(jp->ps[0].ps_cmd, p)) {
3772 err_msg = "%s: ambiguous";
3782 err_msg = "job %s not created under job control";
3783 if (getctl && jp->jobctl == 0)
3788 ash_msg_and_raise_error(err_msg, name);
3792 * Mark a job structure as unused.
3795 freejob(struct job *jp)
3797 struct procstat *ps;
3801 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3802 if (ps->ps_cmd != nullstr)
3805 if (jp->ps != &jp->ps0)
3808 set_curjob(jp, CUR_DELETE);
3814 xtcsetpgrp(int fd, pid_t pgrp)
3816 if (tcsetpgrp(fd, pgrp))
3817 ash_msg_and_raise_error("can't set tty process group (%m)");
3821 * Turn job control on and off.
3823 * Note: This code assumes that the third arg to ioctl is a character
3824 * pointer, which is true on Berkeley systems but not System V. Since
3825 * System V doesn't have job control yet, this isn't a problem now.
3827 * Called with interrupts off.
3835 if (on == doing_jobctl || rootshell == 0)
3839 ofd = fd = open(_PATH_TTY, O_RDWR);
3841 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3842 * That sometimes helps to acquire controlling tty.
3843 * Obviously, a workaround for bugs when someone
3844 * failed to provide a controlling tty to bash! :) */
3850 /* fd is a tty at this point */
3851 fd = fcntl(fd, F_DUPFD, 10);
3852 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
3855 goto out; /* F_DUPFD failed */
3856 close_on_exec_on(fd);
3857 while (1) { /* while we are in the background */
3858 pgrp = tcgetpgrp(fd);
3861 ash_msg("can't access tty; job control turned off");
3865 if (pgrp == getpgrp())
3876 xtcsetpgrp(fd, pgrp);
3878 /* turning job control off */
3881 /* was xtcsetpgrp, but this can make exiting ash
3882 * loop forever if pty is already deleted */
3883 tcsetpgrp(fd, pgrp);
3897 static int FAST_FUNC
3898 killcmd(int argc, char **argv)
3900 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3903 if (argv[i][0] == '%') {
3905 * "kill %N" - job kill
3906 * Converting to pgrp / pid kill
3912 jp = getjob(argv[i], 0);
3914 * In jobs started under job control, we signal
3915 * entire process group by kill -PGRP_ID.
3916 * This happens, f.e., in interactive shell.
3918 * Otherwise, we signal each child via
3919 * kill PID1 PID2 PID3.
3921 * sh -c 'sleep 1|sleep 1 & kill %1'
3922 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3923 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3925 n = jp->nprocs; /* can't be 0 (I hope) */
3928 dst = alloca(n * sizeof(int)*4);
3930 for (j = 0; j < n; j++) {
3931 struct procstat *ps = &jp->ps[j];
3932 /* Skip non-running and not-stopped members
3933 * (i.e. dead members) of the job
3935 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3938 * kill_main has matching code to expect
3939 * leading space. Needed to not confuse
3940 * negative pids with "kill -SIGNAL_NO" syntax
3942 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3946 } while (argv[++i]);
3948 return kill_main(argc, argv);
3952 showpipe(struct job *jp /*, FILE *out*/)
3954 struct procstat *ps;
3955 struct procstat *psend;
3957 psend = jp->ps + jp->nprocs;
3958 for (ps = jp->ps + 1; ps < psend; ps++)
3959 printf(" | %s", ps->ps_cmd);
3960 newline_and_flush(stdout);
3961 flush_stdout_stderr();
3966 restartjob(struct job *jp, int mode)
3968 struct procstat *ps;
3974 if (jp->state == JOBDONE)
3976 jp->state = JOBRUNNING;
3977 pgid = jp->ps[0].ps_pid;
3978 if (mode == FORK_FG) {
3980 xtcsetpgrp(ttyfd, pgid);
3982 killpg(pgid, SIGCONT);
3986 if (WIFSTOPPED(ps->ps_status)) {
3992 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3997 static int FAST_FUNC
3998 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
4004 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
4008 jp = getjob(*argv, 1);
4009 if (mode == FORK_BG) {
4010 set_curjob(jp, CUR_RUNNING);
4011 printf("[%d] ", jobno(jp));
4013 out1str(jp->ps[0].ps_cmd);
4014 showpipe(jp /*, stdout*/);
4015 retval = restartjob(jp, mode);
4016 } while (*argv && *++argv);
4022 sprint_status48(char *s, int status, int sigonly)
4028 if (!WIFEXITED(status)) {
4029 if (JOBS && WIFSTOPPED(status))
4030 st = WSTOPSIG(status);
4032 st = WTERMSIG(status);
4034 if (st == SIGINT || st == SIGPIPE)
4036 if (JOBS && WIFSTOPPED(status))
4040 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
4041 col = fmtstr(s, 32, strsignal(st));
4042 if (WCOREDUMP(status)) {
4043 strcpy(s + col, " (core dumped)");
4044 col += sizeof(" (core dumped)")-1;
4046 } else if (!sigonly) {
4047 st = WEXITSTATUS(status);
4048 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
4055 wait_block_or_sig(int *status)
4062 /* Poll all children for changes in their state */
4064 /* if job control is active, accept stopped processes too */
4065 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
4067 break; /* Error (e.g. EINTR, ECHILD) or pid */
4069 /* Children exist, but none are ready. Sleep until interesting signal */
4072 sigprocmask(SIG_SETMASK, &mask, &mask);
4073 while (!got_sigchld && !pending_sig)
4075 sigprocmask(SIG_SETMASK, &mask, NULL);
4076 #else /* unsafe: a signal can set pending_sig after check, but before pause() */
4077 while (!got_sigchld && !pending_sig)
4081 /* If it was SIGCHLD, poll children again */
4082 } while (got_sigchld);
4087 #define DOWAIT_NONBLOCK 0
4088 #define DOWAIT_BLOCK 1
4089 #define DOWAIT_BLOCK_OR_SIG 2
4092 dowait(int block, struct job *job)
4097 struct job *thisjob = NULL;
4099 TRACE(("dowait(0x%x) called\n", block));
4101 /* It's wrong to call waitpid() outside of INT_OFF region:
4102 * signal can arrive just after syscall return and handler can
4103 * longjmp away, losing stop/exit notification processing.
4104 * Thus, for "jobs" builtin, and for waiting for a fg job,
4105 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
4107 * However, for "wait" builtin it is wrong to simply call waitpid()
4108 * in INT_OFF region: "wait" needs to wait for any running job
4109 * to change state, but should exit on any trap too.
4110 * In INT_OFF region, a signal just before syscall entry can set
4111 * pending_sig variables, but we can't check them, and we would
4112 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
4114 * Because of this, we run inside INT_OFF, but use a special routine
4115 * which combines waitpid() and sigsuspend().
4116 * This is the reason why we need to have a handler for SIGCHLD:
4117 * SIG_DFL handler does not wake sigsuspend().
4120 if (block == DOWAIT_BLOCK_OR_SIG) {
4121 pid = wait_block_or_sig(&status);
4124 if (block == DOWAIT_NONBLOCK)
4125 wait_flags = WNOHANG;
4126 /* if job control is active, accept stopped processes too */
4128 wait_flags |= WUNTRACED;
4129 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4130 pid = waitpid(-1, &status, wait_flags);
4132 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4133 pid, status, errno, strerror(errno)));
4138 for (jp = curjob; jp; jp = jp->prev_job) {
4140 struct procstat *ps;
4141 struct procstat *psend;
4142 if (jp->state == JOBDONE)
4146 psend = ps + jp->nprocs;
4148 if (ps->ps_pid == pid) {
4149 TRACE(("Job %d: changing status of proc %d "
4150 "from 0x%x to 0x%x\n",
4151 jobno(jp), pid, ps->ps_status, status));
4152 ps->ps_status = status;
4155 if (ps->ps_status == -1)
4156 jobstate = JOBRUNNING;
4158 if (jobstate == JOBRUNNING)
4160 if (WIFSTOPPED(ps->ps_status)) {
4161 jp->stopstatus = ps->ps_status;
4162 jobstate = JOBSTOPPED;
4165 } while (++ps < psend);
4169 /* Found the job where one of its processes changed its state.
4170 * Is there at least one live and running process in this job? */
4171 if (jobstate != JOBRUNNING) {
4172 /* No. All live processes in the job are stopped
4173 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4175 thisjob->changed = 1;
4176 if (thisjob->state != jobstate) {
4177 TRACE(("Job %d: changing state from %d to %d\n",
4178 jobno(thisjob), thisjob->state, jobstate));
4179 thisjob->state = jobstate;
4181 if (jobstate == JOBSTOPPED)
4182 set_curjob(thisjob, CUR_STOPPED);
4188 /* The process wasn't found in job list */
4189 if (JOBS && !WIFSTOPPED(status))
4194 if (thisjob && thisjob == job) {
4198 len = sprint_status48(s, status, 1);
4210 showjob(struct job *jp, int mode)
4212 struct procstat *ps;
4213 struct procstat *psend;
4216 char s[16 + 16 + 48];
4217 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4221 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4222 /* just output process (group) id of pipeline */
4223 fprintf(out, "%d\n", ps->ps_pid);
4227 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4232 else if (curjob && jp == curjob->prev_job)
4235 if (mode & SHOW_PIDS)
4236 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4238 psend = ps + jp->nprocs;
4240 if (jp->state == JOBRUNNING) {
4241 strcpy(s + col, "Running");
4242 col += sizeof("Running") - 1;
4244 int status = psend[-1].ps_status;
4245 if (jp->state == JOBSTOPPED)
4246 status = jp->stopstatus;
4247 col += sprint_status48(s + col, status, 0);
4249 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4251 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4252 * or prints several "PID | <cmdN>" lines,
4253 * depending on SHOW_PIDS bit.
4254 * We do not print status of individual processes
4255 * between PID and <cmdN>. bash does it, but not very well:
4256 * first line shows overall job status, not process status,
4257 * making it impossible to know 1st process status.
4261 /* for each process */
4264 if (mode & SHOW_PIDS)
4265 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4267 fprintf(out, "%s%*c%s%s",
4269 33 - col >= 0 ? 33 - col : 0, ' ',
4270 ps == jp->ps ? "" : "| ",
4273 } while (++ps != psend);
4274 newline_and_flush(out);
4278 if (jp->state == JOBDONE) {
4279 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4285 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4286 * statuses have changed since the last call to showjobs.
4293 TRACE(("showjobs(0x%x) called\n", mode));
4295 /* Handle all finished jobs */
4296 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4299 for (jp = curjob; jp; jp = jp->prev_job) {
4300 if (!(mode & SHOW_CHANGED) || jp->changed) {
4306 static int FAST_FUNC
4307 jobscmd(int argc UNUSED_PARAM, char **argv)
4312 while ((m = nextopt("lp")) != '\0') {
4316 mode |= SHOW_ONLY_PGID;
4322 showjob(getjob(*argv, 0), mode);
4332 /* Called only on finished or stopped jobs (no members are running) */
4334 getstatus(struct job *job)
4338 struct procstat *ps;
4340 /* Fetch last member's status */
4341 ps = job->ps + job->nprocs - 1;
4342 status = ps->ps_status;
4344 /* "set -o pipefail" mode: use last _nonzero_ status */
4345 while (status == 0 && --ps >= job->ps)
4346 status = ps->ps_status;
4349 retval = WEXITSTATUS(status);
4350 if (!WIFEXITED(status)) {
4352 retval = WSTOPSIG(status);
4353 if (!WIFSTOPPED(status))
4356 /* XXX: limits number of signals */
4357 retval = WTERMSIG(status);
4359 if (retval == SIGINT)
4365 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4366 jobno(job), job->nprocs, status, retval));
4370 static int FAST_FUNC
4371 waitcmd(int argc UNUSED_PARAM, char **argv)
4382 /* wait for all jobs */
4386 if (!jp) /* no running procs */
4388 if (jp->state == JOBRUNNING)
4394 * "When bash is waiting for an asynchronous command via
4395 * the wait builtin, the reception of a signal for which a trap
4396 * has been set will cause the wait builtin to return immediately
4397 * with an exit status greater than 128, immediately after which
4398 * the trap is executed."
4400 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4401 /* if child sends us a signal *and immediately exits*,
4402 * dowait() returns pid > 0. Check this case,
4403 * not "if (dowait() < 0)"!
4412 if (**argv != '%') {
4413 pid_t pid = number(*argv);
4418 if (job->ps[job->nprocs - 1].ps_pid == pid)
4420 job = job->prev_job;
4423 job = getjob(*argv, 0);
4425 /* loop until process terminated or stopped */
4426 while (job->state == JOBRUNNING) {
4427 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4432 retval = getstatus(job);
4439 retval = 128 + pending_sig;
4448 struct job *jp, *jq;
4450 len = njobs * sizeof(*jp);
4452 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4454 offset = (char *)jp - (char *)jq;
4456 /* Relocate pointers */
4459 jq = (struct job *)((char *)jq + l);
4463 #define joff(p) ((struct job *)((char *)(p) + l))
4464 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4465 if (joff(jp)->ps == &jq->ps0)
4466 jmove(joff(jp)->ps);
4467 if (joff(jp)->prev_job)
4468 jmove(joff(jp)->prev_job);
4478 jp = (struct job *)((char *)jp + len);
4482 } while (--jq >= jp);
4487 * Return a new job structure.
4488 * Called with interrupts off.
4491 makejob(/*union node *node,*/ int nprocs)
4496 for (i = njobs, jp = jobtab; ; jp++) {
4503 if (jp->state != JOBDONE || !jp->waited)
4512 memset(jp, 0, sizeof(*jp));
4514 /* jp->jobctl is a bitfield.
4515 * "jp->jobctl |= doing_jobctl" likely to give awful code */
4519 jp->prev_job = curjob;
4524 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4526 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4533 * Return a string identifying a command (to be printed by the
4536 static char *cmdnextc;
4539 cmdputs(const char *s)
4541 static const char vstype[VSTYPE + 1][3] = {
4542 "", "}", "-", "+", "?", "=",
4543 "%", "%%", "#", "##"
4544 IF_BASH_SUBSTR(, ":")
4545 IF_BASH_PATTERN_SUBST(, "/", "//")
4548 const char *p, *str;
4552 unsigned char subtype = 0;
4556 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4558 while ((c = *p++) != '\0') {
4566 if ((subtype & VSTYPE) == VSLENGTH)
4572 str = "\"}" + !(quoted & 1);
4579 #if ENABLE_FEATURE_SH_MATH
4594 if ((subtype & VSTYPE) != VSNORMAL)
4596 str = vstype[subtype & VSTYPE];
4597 if (subtype & VSNUL)
4606 /* These can only happen inside quotes */
4619 while ((c = *str++) != '\0') {
4622 } /* while *p++ not NUL */
4625 USTPUTC('"', nextc);
4631 /* cmdtxt() and cmdlist() call each other */
4632 static void cmdtxt(union node *n);
4635 cmdlist(union node *np, int sep)
4637 for (; np; np = np->narg.next) {
4641 if (sep && np->narg.next)
4647 cmdtxt(union node *n)
4650 struct nodelist *lp;
4661 lp = n->npipe.cmdlist;
4679 cmdtxt(n->nbinary.ch1);
4695 cmdtxt(n->nif.test);
4697 if (n->nif.elsepart) {
4698 cmdtxt(n->nif.ifpart);
4700 n = n->nif.elsepart;
4718 cmdtxt(n->nbinary.ch1);
4728 cmdputs(n->nfor.var);
4730 cmdlist(n->nfor.args, 1);
4735 cmdputs(n->narg.text);
4739 cmdlist(n->ncmd.args, 1);
4740 cmdlist(n->ncmd.redirect, 0);
4753 cmdputs(n->ncase.expr->narg.text);
4755 for (np = n->ncase.cases; np; np = np->nclist.next) {
4756 cmdtxt(np->nclist.pattern);
4758 cmdtxt(np->nclist.body);
4772 #if BASH_REDIR_OUTPUT
4787 cmdputs(utoa(n->nfile.fd));
4789 if (n->type == NTOFD || n->type == NFROMFD) {
4790 cmdputs(utoa(n->ndup.dupfd));
4799 commandtext(union node *n)
4803 STARTSTACKSTR(cmdnextc);
4805 name = stackblock();
4806 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4807 return ckstrdup(name);
4812 * Fork off a subshell. If we are doing job control, give the subshell its
4813 * own process group. Jp is a job structure that the job is to be added to.
4814 * N is the command that will be evaluated by the child. Both jp and n may
4815 * be NULL. The mode parameter can be one of the following:
4816 * FORK_FG - Fork off a foreground process.
4817 * FORK_BG - Fork off a background process.
4818 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4819 * process group even if job control is on.
4821 * When job control is turned off, background processes have their standard
4822 * input redirected to /dev/null (except for the second and later processes
4825 * Called with interrupts off.
4828 * Clear traps on a fork.
4836 for (tp = trap; tp < &trap[NSIG]; tp++) {
4837 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4838 if (trap_ptr == trap)
4840 /* else: it "belongs" to trap_ptr vector, don't free */
4842 if ((tp - trap) != 0)
4843 setsignal(tp - trap);
4850 /* Lives far away from here, needed for forkchild */
4851 static void closescript(void);
4853 /* Called after fork(), in child */
4854 /* jp and n are NULL when called by openhere() for heredoc support */
4855 static NOINLINE void
4856 forkchild(struct job *jp, union node *n, int mode)
4860 TRACE(("Child shell %d\n", getpid()));
4864 /* man bash: "Non-builtin commands run by bash have signal handlers
4865 * set to the values inherited by the shell from its parent".
4866 * Do we do it correctly? */
4870 if (mode == FORK_NOJOB /* is it `xxx` ? */
4871 && n && n->type == NCMD /* is it single cmd? */
4872 /* && n->ncmd.args->type == NARG - always true? */
4873 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4874 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4875 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4877 TRACE(("Trap hack\n"));
4878 /* Awful hack for `trap` or $(trap).
4880 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4881 * contains an example where "trap" is executed in a subshell:
4883 * save_traps=$(trap)
4885 * eval "$save_traps"
4887 * Standard does not say that "trap" in subshell shall print
4888 * parent shell's traps. It only says that its output
4889 * must have suitable form, but then, in the above example
4890 * (which is not supposed to be normative), it implies that.
4892 * bash (and probably other shell) does implement it
4893 * (traps are reset to defaults, but "trap" still shows them),
4894 * but as a result, "trap" logic is hopelessly messed up:
4897 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4898 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4899 * # true | trap <--- trap is in subshell - no output (ditto)
4900 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4901 * trap -- 'echo Ho' SIGWINCH
4902 * # echo `(trap)` <--- in subshell in subshell - output
4903 * trap -- 'echo Ho' SIGWINCH
4904 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4905 * trap -- 'echo Ho' SIGWINCH
4907 * The rules when to forget and when to not forget traps
4908 * get really complex and nonsensical.
4910 * Our solution: ONLY bare $(trap) or `trap` is special.
4912 /* Save trap handler strings for trap builtin to print */
4913 trap_ptr = xmemdup(trap, sizeof(trap));
4914 /* Fall through into clearing traps */
4918 /* do job control only in root shell */
4920 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4923 if (jp->nprocs == 0)
4926 pgrp = jp->ps[0].ps_pid;
4927 /* this can fail because we are doing it in the parent also */
4929 if (mode == FORK_FG)
4930 xtcsetpgrp(ttyfd, pgrp);
4935 if (mode == FORK_BG) {
4936 /* man bash: "When job control is not in effect,
4937 * asynchronous commands ignore SIGINT and SIGQUIT" */
4940 if (jp->nprocs == 0) {
4942 if (open(bb_dev_null, O_RDONLY) != 0)
4943 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4947 if (iflag) { /* why if iflag only? */
4952 * "In all cases, bash ignores SIGQUIT. Non-builtin
4953 * commands run by bash have signal handlers
4954 * set to the values inherited by the shell
4956 * Take care of the second rule: */
4960 if (n && n->type == NCMD
4961 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4963 TRACE(("Job hack\n"));
4964 /* "jobs": we do not want to clear job list for it,
4965 * instead we remove only _its_ own_ job from job list.
4966 * This makes "jobs .... | cat" more useful.
4972 for (jp = curjob; jp; jp = jp->prev_job)
4977 /* Called after fork(), in parent */
4979 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4982 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4984 TRACE(("In parent shell: child = %d\n", pid));
4986 /* jp is NULL when called by openhere() for heredoc support */
4987 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4993 if (mode != FORK_NOJOB && jp->jobctl) {
4996 if (jp->nprocs == 0)
4999 pgrp = jp->ps[0].ps_pid;
5000 /* This can fail because we are doing it in the child also */
5004 if (mode == FORK_BG) {
5005 backgndpid = pid; /* set $! */
5006 set_curjob(jp, CUR_RUNNING);
5009 struct procstat *ps = &jp->ps[jp->nprocs++];
5012 ps->ps_cmd = nullstr;
5014 if (doing_jobctl && n)
5015 ps->ps_cmd = commandtext(n);
5020 /* jp and n are NULL when called by openhere() for heredoc support */
5022 forkshell(struct job *jp, union node *n, int mode)
5026 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
5029 TRACE(("Fork failed, errno=%d", errno));
5032 ash_msg_and_raise_error("can't fork");
5035 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
5036 forkchild(jp, n, mode);
5038 forkparent(jp, n, mode, pid);
5044 * Wait for job to finish.
5046 * Under job control we have the problem that while a child process
5047 * is running interrupts generated by the user are sent to the child
5048 * but not to the shell. This means that an infinite loop started by
5049 * an interactive user may be hard to kill. With job control turned off,
5050 * an interactive user may place an interactive program inside a loop.
5051 * If the interactive program catches interrupts, the user doesn't want
5052 * these interrupts to also abort the loop. The approach we take here
5053 * is to have the shell ignore interrupt signals while waiting for a
5054 * foreground process to terminate, and then send itself an interrupt
5055 * signal if the child process was terminated by an interrupt signal.
5056 * Unfortunately, some programs want to do a bit of cleanup and then
5057 * exit on interrupt; unless these processes terminate themselves by
5058 * sending a signal to themselves (instead of calling exit) they will
5059 * confuse this approach.
5061 * Called with interrupts off.
5064 waitforjob(struct job *jp)
5068 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
5071 while (jp->state == JOBRUNNING) {
5072 /* In non-interactive shells, we _can_ get
5073 * a keyboard signal here and be EINTRed,
5074 * but we just loop back, waiting for command to complete.
5077 * "If bash is waiting for a command to complete and receives
5078 * a signal for which a trap has been set, the trap
5079 * will not be executed until the command completes."
5081 * Reality is that even if trap is not set, bash
5082 * will not act on the signal until command completes.
5083 * Try this. sleep5intoff.c:
5084 * #include <signal.h>
5085 * #include <unistd.h>
5088 * sigemptyset(&set);
5089 * sigaddset(&set, SIGINT);
5090 * sigaddset(&set, SIGQUIT);
5091 * sigprocmask(SIG_BLOCK, &set, NULL);
5095 * $ bash -c './sleep5intoff; echo hi'
5096 * ^C^C^C^C <--- pressing ^C once a second
5098 * $ bash -c './sleep5intoff; echo hi'
5099 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
5102 dowait(DOWAIT_BLOCK, jp);
5109 xtcsetpgrp(ttyfd, rootpid);
5110 restore_tty_if_stopped_or_signaled(jp);
5113 * This is truly gross.
5114 * If we're doing job control, then we did a TIOCSPGRP which
5115 * caused us (the shell) to no longer be in the controlling
5116 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
5117 * intuit from the subprocess exit status whether a SIGINT
5118 * occurred, and if so interrupt ourselves. Yuck. - mycroft
5120 if (jp->sigint) /* TODO: do the same with all signals */
5121 raise(SIGINT); /* ... by raise(jp->sig) instead? */
5123 if (jp->state == JOBDONE)
5130 * return 1 if there are stopped jobs, otherwise 0
5142 if (jp && jp->state == JOBSTOPPED) {
5143 out2str("You have stopped jobs.\n");
5153 * Code for dealing with input/output redirection.
5158 #define EMPTY -2 /* marks an unused slot in redirtab */
5159 #define CLOSED -3 /* marks a slot of previously-closed fd */
5162 * Open a file in noclobber mode.
5163 * The code was copied from bash.
5166 noclobberopen(const char *fname)
5169 struct stat finfo, finfo2;
5172 * If the file exists and is a regular file, return an error
5175 r = stat(fname, &finfo);
5176 if (r == 0 && S_ISREG(finfo.st_mode)) {
5182 * If the file was not present (r != 0), make sure we open it
5183 * exclusively so that if it is created before we open it, our open
5184 * will fail. Make sure that we do not truncate an existing file.
5185 * Note that we don't turn on O_EXCL unless the stat failed -- if the
5186 * file was not a regular file, we leave O_EXCL off.
5189 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5190 fd = open(fname, O_WRONLY|O_CREAT, 0666);
5192 /* If the open failed, return the file descriptor right away. */
5197 * OK, the open succeeded, but the file may have been changed from a
5198 * non-regular file to a regular file between the stat and the open.
5199 * We are assuming that the O_EXCL open handles the case where FILENAME
5200 * did not exist and is symlinked to an existing file between the stat
5205 * If we can open it and fstat the file descriptor, and neither check
5206 * revealed that it was a regular file, and the file has not been
5207 * replaced, return the file descriptor.
5209 if (fstat(fd, &finfo2) == 0
5210 && !S_ISREG(finfo2.st_mode)
5211 && finfo.st_dev == finfo2.st_dev
5212 && finfo.st_ino == finfo2.st_ino
5217 /* The file has been replaced. badness. */
5224 * Handle here documents. Normally we fork off a process to write the
5225 * data to a pipe. If the document is short, we can stuff the data in
5226 * the pipe without forking.
5228 /* openhere needs this forward reference */
5229 static void expandhere(union node *arg, int fd);
5231 openhere(union node *redir)
5237 ash_msg_and_raise_error("pipe call failed");
5238 if (redir->type == NHERE) {
5239 len = strlen(redir->nhere.doc->narg.text);
5240 if (len <= PIPE_BUF) {
5241 full_write(pip[1], redir->nhere.doc->narg.text, len);
5245 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5248 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5249 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5250 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5251 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5252 signal(SIGPIPE, SIG_DFL);
5253 if (redir->type == NHERE)
5254 full_write(pip[1], redir->nhere.doc->narg.text, len);
5256 expandhere(redir->nhere.doc, pip[1]);
5257 _exit(EXIT_SUCCESS);
5265 openredirect(union node *redir)
5270 switch (redir->nfile.type) {
5271 /* Can't happen, our single caller does this itself */
5277 return openhere(redir);
5280 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5281 * allocated space. Do it only when we know it is safe.
5283 fname = redir->nfile.expfname;
5285 switch (redir->nfile.type) {
5291 f = open(fname, O_RDONLY);
5296 f = open(fname, O_RDWR|O_CREAT, 0666);
5301 #if BASH_REDIR_OUTPUT
5304 /* Take care of noclobber mode. */
5306 f = noclobberopen(fname);
5313 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5318 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5326 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5328 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5332 * Copy a file descriptor to be >= 10. Throws exception on error.
5340 newfd = fcntl(from, F_DUPFD, 10);
5341 err = newfd < 0 ? errno : 0;
5344 ash_msg_and_raise_error("%d: %m", from);
5346 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5352 dup2_or_raise(int from, int to)
5356 newfd = (from != to) ? dup2(from, to) : to;
5358 /* Happens when source fd is not open: try "echo >&99" */
5359 ash_msg_and_raise_error("%d: %m", from);
5364 /* Struct def and variable are moved down to the first usage site */
5369 struct redirtab *next;
5371 struct two_fd_t two_fd[];
5373 #define redirlist (G_var.redirlist)
5375 COPYFD_RESTORE = (int)~(INT_MAX),
5379 need_to_remember(struct redirtab *rp, int fd)
5383 if (!rp) /* remembering was not requested */
5386 for (i = 0; i < rp->pair_count; i++) {
5387 if (rp->two_fd[i].orig == fd) {
5388 /* already remembered */
5395 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5397 is_hidden_fd(struct redirtab *rp, int fd)
5400 struct parsefile *pf;
5404 /* Check open scripts' fds */
5407 /* We skip pf_fd == 0 case because of the following case:
5408 * $ ash # running ash interactively
5410 * and in script.sh: "exec 9>&0".
5411 * Even though top-level pf_fd _is_ 0,
5412 * it's still ok to use it: "read" builtin uses it,
5413 * why should we cripple "exec" builtin?
5415 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5423 /* Check saved fds of redirects */
5424 fd |= COPYFD_RESTORE;
5425 for (i = 0; i < rp->pair_count; i++) {
5426 if (rp->two_fd[i].copy == fd) {
5434 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5435 * old file descriptors are stashed away so that the redirection can be
5436 * undone by calling popredir.
5438 /* flags passed to redirect */
5439 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5440 #define REDIR_SAVEFD2 03 /* set preverrout */
5442 redirect(union node *redir, int flags)
5444 struct redirtab *sv;
5449 int copied_fd2 = -1;
5458 if (flags & REDIR_PUSH) {
5459 union node *tmp = redir;
5462 #if BASH_REDIR_OUTPUT
5463 if (tmp->nfile.type == NTO2)
5466 tmp = tmp->nfile.next;
5468 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5469 sv->next = redirlist;
5470 sv->pair_count = sv_pos;
5472 while (sv_pos > 0) {
5474 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5480 fd = redir->nfile.fd;
5481 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5482 right_fd = redir->ndup.dupfd;
5483 //bb_error_msg("doing %d > %d", fd, right_fd);
5484 /* redirect from/to same file descriptor? */
5487 /* "echo >&10" and 10 is a fd opened to a sh script? */
5488 if (is_hidden_fd(sv, right_fd)) {
5489 errno = EBADF; /* as if it is closed */
5490 ash_msg_and_raise_error("%d: %m", right_fd);
5494 newfd = openredirect(redir); /* always >= 0 */
5496 /* Descriptor wasn't open before redirect.
5497 * Mark it for close in the future */
5498 if (need_to_remember(sv, fd)) {
5499 goto remember_to_close;
5504 #if BASH_REDIR_OUTPUT
5507 if (need_to_remember(sv, fd)) {
5508 /* Copy old descriptor */
5509 /* Careful to not accidentally "save"
5510 * to the same fd as right side fd in N>&M */
5511 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5512 #if defined(F_DUPFD_CLOEXEC)
5513 i = fcntl(fd, F_DUPFD_CLOEXEC, minfd);
5515 i = fcntl(fd, F_DUPFD, minfd);
5520 /* Strange error (e.g. "too many files" EMFILE?) */
5524 ash_msg_and_raise_error("%d: %m", fd);
5527 /* EBADF: it is not open - good, remember to close it */
5530 } else { /* fd is open, save its copy */
5531 #if !defined(F_DUPFD_CLOEXEC)
5532 fcntl(i, F_SETFD, FD_CLOEXEC);
5534 /* "exec fd>&-" should not close fds
5535 * which point to script file(s).
5536 * Force them to be restored afterwards */
5537 if (is_hidden_fd(sv, fd))
5538 i |= COPYFD_RESTORE;
5542 sv->two_fd[sv_pos].orig = fd;
5543 sv->two_fd[sv_pos].copy = i;
5547 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5548 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5549 /* Don't want to trigger debugging */
5553 dup2_or_raise(redir->ndup.dupfd, fd);
5555 } else if (fd != newfd) { /* move newfd to fd */
5556 dup2_or_raise(newfd, fd);
5557 #if BASH_REDIR_OUTPUT
5558 if (!(redir->nfile.type == NTO2 && fd == 2))
5562 #if BASH_REDIR_OUTPUT
5563 if (redir->nfile.type == NTO2 && fd == 1) {
5564 /* We already redirected it to fd 1, now copy it to 2 */
5570 } while ((redir = redir->nfile.next) != NULL);
5573 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5574 preverrout_fd = copied_fd2;
5578 * Undo the effects of the last redirection.
5581 popredir(int drop, int restore)
5583 struct redirtab *rp;
5586 if (redirlist == NULL)
5590 for (i = 0; i < rp->pair_count; i++) {
5591 int fd = rp->two_fd[i].orig;
5592 int copy = rp->two_fd[i].copy;
5593 if (copy == CLOSED) {
5598 if (copy != EMPTY) {
5599 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5600 copy &= ~COPYFD_RESTORE;
5602 dup2_or_raise(copy, fd);
5604 close(copy & ~COPYFD_RESTORE);
5607 redirlist = rp->next;
5613 * Undo all redirections. Called on error or interrupt.
5617 redirectsafe(union node *redir, int flags)
5620 volatile int saveint;
5621 struct jmploc *volatile savehandler = exception_handler;
5622 struct jmploc jmploc;
5625 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5626 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5628 exception_handler = &jmploc;
5629 redirect(redir, flags);
5631 exception_handler = savehandler;
5632 if (err && exception_type != EXERROR)
5633 longjmp(exception_handler->loc, 1);
5634 RESTORE_INT(saveint);
5639 /* ============ Routines to expand arguments to commands
5641 * We have to deal with backquotes, shell variables, and file metacharacters.
5644 #if ENABLE_FEATURE_SH_MATH
5646 ash_arith(const char *s)
5648 arith_state_t math_state;
5651 math_state.lookupvar = lookupvar;
5652 math_state.setvar = setvar0;
5653 //math_state.endofname = endofname;
5656 result = arith(&math_state, s);
5657 if (math_state.errmsg)
5658 ash_msg_and_raise_error(math_state.errmsg);
5668 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5669 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5670 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5671 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5672 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5673 * POSIX says for this case:
5674 * Pathname expansion shall not be performed on the word by a
5675 * non-interactive shell; an interactive shell may perform it, but shall
5676 * do so only when the expansion would result in one word.
5677 * Currently, our code complies to the above rule by never globbing
5678 * redirection filenames.
5679 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5680 * (this means that on a typical Linux distro, bash almost always
5681 * performs globbing, and thus diverges from what we do).
5683 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5684 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5685 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5686 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5687 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5691 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5692 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5693 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5694 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5695 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5697 /* Add CTLESC when necessary. */
5698 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
5699 /* Do not skip NUL characters. */
5700 #define QUOTES_KEEPNUL EXP_TILDE
5703 * Structure specifying which parts of the string should be searched
5704 * for IFS characters.
5707 struct ifsregion *next; /* next region in list */
5708 int begoff; /* offset of start of region */
5709 int endoff; /* offset of end of region */
5710 int nulonly; /* search for nul bytes only */
5714 struct strlist *list;
5715 struct strlist **lastp;
5718 /* output of current string */
5719 static char *expdest;
5720 /* list of back quote expressions */
5721 static struct nodelist *argbackq;
5722 /* first struct in list of ifs regions */
5723 static struct ifsregion ifsfirst;
5724 /* last struct in list */
5725 static struct ifsregion *ifslastp;
5726 /* holds expanded arg list */
5727 static struct arglist exparg;
5732 #if !ENABLE_FEATURE_SH_MATH
5733 /* cvtnum() is used even if math support is off (to prepare $? values and such) */
5734 typedef long arith_t;
5735 # define ARITH_FMT "%ld"
5742 expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
5743 len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
5744 STADJUST(len, expdest);
5749 * Break the argument string into pieces based upon IFS and add the
5750 * strings to the argument list. The regions of the string to be
5751 * searched for IFS characters have been stored by recordregion.
5754 ifsbreakup(char *string, struct arglist *arglist)
5756 struct ifsregion *ifsp;
5761 const char *ifs, *realifs;
5766 if (ifslastp != NULL) {
5769 realifs = ifsset() ? ifsval() : defifs;
5772 p = string + ifsp->begoff;
5773 nulonly = ifsp->nulonly;
5774 ifs = nulonly ? nullstr : realifs;
5776 while (p < string + ifsp->endoff) {
5778 if ((unsigned char)*p == CTLESC)
5780 if (!strchr(ifs, *p)) {
5785 ifsspc = (strchr(defifs, *p) != NULL);
5786 /* Ignore IFS whitespace at start */
5787 if (q == start && ifsspc) {
5793 sp = stzalloc(sizeof(*sp));
5795 *arglist->lastp = sp;
5796 arglist->lastp = &sp->next;
5800 if (p >= string + ifsp->endoff) {
5804 if ((unsigned char)*p == CTLESC)
5806 if (strchr(ifs, *p) == NULL) {
5810 if (strchr(defifs, *p) == NULL) {
5825 } while (ifsp != NULL);
5834 sp = stzalloc(sizeof(*sp));
5836 *arglist->lastp = sp;
5837 arglist->lastp = &sp->next;
5843 struct ifsregion *p = ifsfirst.next;
5850 struct ifsregion *ifsp;
5855 ifsfirst.next = NULL;
5862 esclen(const char *start, const char *p)
5866 while (p > start && (unsigned char)*--p == CTLESC) {
5873 * Remove any CTLESC characters from a string.
5876 rmescapes(char *str, int flag)
5878 static const char qchars[] ALIGN1 = {
5879 IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
5883 unsigned protect_against_glob;
5885 IF_BASH_PATTERN_SUBST(unsigned slash = flag & RMESCAPE_SLASH;)
5887 p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash));
5893 if (flag & RMESCAPE_ALLOC) {
5894 size_t len = p - str;
5895 size_t fulllen = len + strlen(p) + 1;
5897 if (flag & RMESCAPE_GROW) {
5898 int strloc = str - (char *)stackblock();
5899 r = makestrspace(fulllen, expdest);
5900 /* p and str may be invalidated by makestrspace */
5901 str = (char *)stackblock() + strloc;
5903 } else if (flag & RMESCAPE_HEAP) {
5904 r = ckmalloc(fulllen);
5906 r = stalloc(fulllen);
5910 q = (char *)memcpy(q, str, len) + len;
5915 globbing = flag & RMESCAPE_GLOB;
5916 protect_against_glob = globbing;
5918 if ((unsigned char)*p == CTLQUOTEMARK) {
5919 // Note: both inquotes and protect_against_glob only affect whether
5920 inquotes = ~inquotes;
5922 protect_against_glob = globbing;
5925 if ((unsigned char)*p == CTLESC) {
5929 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5931 if (protect_against_glob) {
5934 } else if (*p == '\\' && !inquotes) {
5935 /* naked back slash */
5936 protect_against_glob = 0;
5939 #if BASH_PATTERN_SUBST
5940 else if (*p == '/' && slash) {
5941 /* stop handling globbing and mark location of slash */
5942 globbing = slash = 0;
5946 protect_against_glob = globbing;
5951 if (flag & RMESCAPE_GROW) {
5953 STADJUST(q - r + 1, expdest);
5957 #define pmatch(a, b) !fnmatch((a), (b), 0)
5960 * Prepare a pattern for a expmeta (internal glob(3)) call.
5962 * Returns an stalloced string.
5965 preglob(const char *pattern, int flag)
5967 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5971 * Put a string on the stack.
5974 memtodest(const char *p, size_t len, int syntax, int quotes)
5981 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
5984 unsigned char c = *p++;
5986 if (quotes & QUOTES_ESC) {
5987 int n = SIT(c, syntax);
5989 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
5996 } else if (!(quotes & QUOTES_KEEPNUL))
6005 strtodest(const char *p, int syntax, int quotes)
6007 size_t len = strlen(p);
6008 memtodest(p, len, syntax, quotes);
6013 * Record the fact that we have to scan this region of the
6014 * string for IFS characters.
6017 recordregion(int start, int end, int nulonly)
6019 struct ifsregion *ifsp;
6021 if (ifslastp == NULL) {
6025 ifsp = ckzalloc(sizeof(*ifsp));
6026 /*ifsp->next = NULL; - ckzalloc did it */
6027 ifslastp->next = ifsp;
6031 ifslastp->begoff = start;
6032 ifslastp->endoff = end;
6033 ifslastp->nulonly = nulonly;
6037 removerecordregions(int endoff)
6039 if (ifslastp == NULL)
6042 if (ifsfirst.endoff > endoff) {
6043 while (ifsfirst.next) {
6044 struct ifsregion *ifsp;
6046 ifsp = ifsfirst.next->next;
6047 free(ifsfirst.next);
6048 ifsfirst.next = ifsp;
6051 if (ifsfirst.begoff > endoff) {
6054 ifslastp = &ifsfirst;
6055 ifsfirst.endoff = endoff;
6060 ifslastp = &ifsfirst;
6061 while (ifslastp->next && ifslastp->next->begoff < endoff)
6062 ifslastp = ifslastp->next;
6063 while (ifslastp->next) {
6064 struct ifsregion *ifsp;
6066 ifsp = ifslastp->next->next;
6067 free(ifslastp->next);
6068 ifslastp->next = ifsp;
6071 if (ifslastp->endoff > endoff)
6072 ifslastp->endoff = endoff;
6076 exptilde(char *startp, char *p, int flags)
6082 int quotes = flags & QUOTES_ESC;
6086 while ((c = *++p) != '\0') {
6093 if (flags & EXP_VARTILDE)
6103 if (*name == '\0') {
6104 home = lookupvar("HOME");
6106 pw = getpwnam(name);
6111 if (!home || !*home)
6114 strtodest(home, SQSYNTAX, quotes);
6122 * Execute a command inside back quotes. If it's a builtin command, we
6123 * want to save its output in a block obtained from malloc. Otherwise
6124 * we fork off a subprocess and get the output of the command via a pipe.
6125 * Should be called with interrupts off.
6127 struct backcmd { /* result of evalbackcmd */
6128 int fd; /* file descriptor to read from */
6129 int nleft; /* number of chars in buffer */
6130 char *buf; /* buffer */
6131 struct job *jp; /* job structure for command */
6134 /* These forward decls are needed to use "eval" code for backticks handling: */
6135 #define EV_EXIT 01 /* exit after evaluating tree */
6136 static int evaltree(union node *, int);
6138 static void FAST_FUNC
6139 evalbackcmd(union node *n, struct backcmd *result)
6153 ash_msg_and_raise_error("pipe call failed");
6154 jp = makejob(/*n,*/ 1);
6155 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6161 dup2_or_raise(pip[1], 1);
6164 /* TODO: eflag clearing makes the following not abort:
6165 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6166 * which is what bash does (unless it is in POSIX mode).
6167 * dash deleted "eflag = 0" line in the commit
6168 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6169 * [EVAL] Don't clear eflag in evalbackcmd
6170 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6174 evaltree(n, EV_EXIT); /* actually evaltreenr... */
6179 result->fd = pip[0];
6183 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6184 result->fd, result->buf, result->nleft, result->jp));
6188 * Expand stuff in backwards quotes.
6191 expbackq(union node *cmd, int flag)
6199 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6200 struct stackmark smark;
6203 startloc = expdest - (char *)stackblock();
6204 pushstackmark(&smark, startloc);
6205 evalbackcmd(cmd, &in);
6206 popstackmark(&smark);
6213 memtodest(p, i, syntax, flag & QUOTES_ESC);
6217 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6218 TRACE(("expbackq: read returns %d\n", i));
6227 back_exitstatus = waitforjob(in.jp);
6231 /* Eat all trailing newlines */
6233 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6237 if (!(flag & EXP_QUOTED))
6238 recordregion(startloc, dest - (char *)stackblock(), 0);
6239 TRACE(("evalbackq: size:%d:'%.*s'\n",
6240 (int)((dest - (char *)stackblock()) - startloc),
6241 (int)((dest - (char *)stackblock()) - startloc),
6242 stackblock() + startloc));
6245 #if ENABLE_FEATURE_SH_MATH
6247 * Expand arithmetic expression. Backup to start of expression,
6248 * evaluate, place result in (backed up) result, adjust string position.
6260 * This routine is slightly over-complicated for
6261 * efficiency. Next we scan backwards looking for the
6262 * start of arithmetic.
6264 start = stackblock();
6271 while ((unsigned char)*p != CTLARI) {
6275 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6280 esc = esclen(start, p);
6290 removerecordregions(begoff);
6294 if (flag & QUOTES_ESC)
6295 rmescapes(p + 1, 0);
6297 len = cvtnum(ash_arith(p + 1));
6299 if (!(flag & EXP_QUOTED))
6300 recordregion(begoff, begoff + len, 0);
6304 /* argstr needs it */
6305 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6308 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6309 * characters to allow for further processing. Otherwise treat
6310 * $@ like $* since no splitting will be performed.
6312 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6313 * over shell variables. Needed for "A=a B=$A; echo $B" case - we use it
6314 * for correct expansion of "B=$A" word.
6317 argstr(char *p, int flags, struct strlist *var_str_list)
6319 static const char spclchars[] ALIGN1 = {
6327 #if ENABLE_FEATURE_SH_MATH
6332 const char *reject = spclchars;
6333 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6338 if (!(flags & EXP_VARTILDE)) {
6340 } else if (flags & EXP_VARTILDE2) {
6345 if (flags & EXP_TILDE) {
6348 flags &= ~EXP_TILDE;
6352 p = exptilde(p, q, flags);
6355 startloc = expdest - (char *)stackblock();
6359 length += strcspn(p + length, reject);
6363 IF_FEATURE_SH_MATH(|| c == CTLENDARI)
6365 /* c == '=' || c == ':' || c == CTLENDARI */
6371 expdest = stack_nputstr(p, length, expdest);
6372 newloc = expdest - (char *)stackblock();
6373 if (breakall && !inquotes && newloc > startloc) {
6374 recordregion(startloc, newloc, 0);
6385 if (flags & EXP_VARTILDE2) {
6389 flags |= EXP_VARTILDE2;
6394 * sort of a hack - expand tildes in variable
6395 * assignments (after the first '=' and after ':'s).
6404 case CTLENDVAR: /* ??? */
6407 inquotes ^= EXP_QUOTED;
6408 /* "$@" syntax adherence hack */
6409 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6410 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6414 if (flags & QUOTES_ESC) {
6425 * Quoted parameter expansion pattern: remove quote
6426 * unless inside inner quotes or we have a literal
6429 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6430 EXP_QPAT && *p != '\\')
6435 TRACE(("argstr: evalvar('%s')\n", p));
6436 p = evalvar(p, flags | inquotes, var_str_list);
6437 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6440 expbackq(argbackq->n, flags | inquotes);
6441 argbackq = argbackq->next;
6443 #if ENABLE_FEATURE_SH_MATH
6446 expari(flags | inquotes);
6455 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6456 char *pattern, int quotes, int zero)
6465 const char *s = loc2;
6472 match = pmatch(pattern, s);
6477 if (quotes && (unsigned char)*loc == CTLESC)
6486 scanright(char *startp, char *rmesc, char *rmescend,
6487 char *pattern, int quotes, int match_at_start)
6489 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6490 int try2optimize = match_at_start;
6496 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6497 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6498 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6500 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6501 * and on each iteration they go back two/one char until they reach the beginning.
6502 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6504 /* TODO: document in what other circumstances we are called. */
6506 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6509 const char *s = loc2;
6510 if (match_at_start) {
6514 match = pmatch(pattern, s);
6515 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6519 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6521 /* Maybe we can optimize this:
6522 * if pattern ends with unescaped *, we can avoid checking
6523 * shorter strings: if "foo*" doesn't match "raw_value_of_v",
6524 * it won't match truncated "raw_value_of_" strings too.
6526 unsigned plen = strlen(pattern);
6527 /* Does it end with "*"? */
6528 if (plen != 0 && pattern[--plen] == '*') {
6529 /* "xxxx*" is not escaped */
6530 /* "xxx\*" is escaped */
6531 /* "xx\\*" is not escaped */
6532 /* "x\\\*" is escaped */
6534 while (plen != 0 && pattern[--plen] == '\\')
6537 break; /* ends with unescaped "*" */
6545 esc = esclen(startp, loc);
6556 static void varunset(const char *, const char *, const char *, int) NORETURN;
6558 varunset(const char *end, const char *var, const char *umsg, int varflags)
6564 msg = "parameter not set";
6566 if ((unsigned char)*end == CTLENDVAR) {
6567 if (varflags & VSNUL)
6573 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6577 subevalvar(char *p, char *varname, int strloc, int subtype,
6578 int startloc, int varflags, int flag, struct strlist *var_str_list)
6580 struct nodelist *saveargbackq = argbackq;
6581 int quotes = flag & QUOTES_ESC;
6584 char *rmesc, *rmescend;
6586 IF_BASH_SUBSTR(int pos, len, orig_len;)
6587 int amount, resetloc;
6588 IF_BASH_PATTERN_SUBST(int workloc;)
6589 IF_BASH_PATTERN_SUBST(char *repl = NULL;)
6591 char *(*scan)(char*, char*, char*, char*, int, int);
6593 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6594 // p, varname, strloc, subtype, startloc, varflags, quotes);
6596 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6597 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6599 STPUTC('\0', expdest);
6600 argbackq = saveargbackq;
6601 startp = (char *)stackblock() + startloc;
6605 setvar0(varname, startp);
6606 amount = startp - expdest;
6607 STADJUST(amount, expdest);
6611 varunset(p, varname, startp, varflags);
6616 //TODO: support more general format ${v:EXPR:EXPR},
6617 // where EXPR follows $(()) rules
6618 loc = str = stackblock() + strloc;
6619 /* Read POS in ${var:POS:LEN} */
6620 pos = atoi(loc); /* number(loc) errors out on "1:4" */
6621 len = str - startp - 1;
6623 /* *loc != '\0', guaranteed by parser */
6627 /* Adjust the length by the number of escapes */
6628 for (ptr = startp; ptr < (str - 1); ptr++) {
6629 if ((unsigned char)*ptr == CTLESC) {
6637 if (*loc++ == ':') {
6641 /* Skip POS in ${var:POS:LEN} */
6643 while (*loc && *loc != ':') {
6645 * bash complains on: var=qwe; echo ${var:1a:123}
6647 ash_msg_and_raise_error(msg_illnum, str);
6651 if (*loc++ == ':') {
6656 /* ${VAR:$((-n)):l} starts n chars from the end */
6657 pos = orig_len + pos;
6659 if ((unsigned)pos >= orig_len) {
6660 /* apart from obvious ${VAR:999999:l},
6661 * covers ${VAR:$((-9999999)):l} - result is ""
6667 if (len > (orig_len - pos))
6668 len = orig_len - pos;
6670 for (str = startp; pos; str++, pos--) {
6671 if (quotes && (unsigned char)*str == CTLESC)
6674 for (loc = startp; len; len--) {
6675 if (quotes && (unsigned char)*str == CTLESC)
6680 amount = loc - expdest;
6681 STADJUST(amount, expdest);
6683 #endif /* BASH_SUBSTR */
6686 resetloc = expdest - (char *)stackblock();
6688 #if BASH_PATTERN_SUBST
6689 /* We'll comeback here if we grow the stack while handling
6690 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6691 * stack will need rebasing, and we'll need to remove our work
6697 amount = expdest - ((char *)stackblock() + resetloc);
6698 STADJUST(-amount, expdest);
6699 startp = (char *)stackblock() + startloc;
6702 rmescend = (char *)stackblock() + strloc;
6704 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6705 if (rmesc != startp) {
6707 startp = (char *)stackblock() + startloc;
6711 str = (char *)stackblock() + strloc;
6713 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6714 * The result is a_\_z_c (not a\_\_z_c)!
6716 * The search pattern and replace string treat backslashes differently!
6717 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6718 * and string. It's only used on the first call.
6720 preglob(str, IF_BASH_PATTERN_SUBST(
6721 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6722 RMESCAPE_SLASH : ) 0);
6724 #if BASH_PATTERN_SUBST
6725 workloc = expdest - (char *)stackblock();
6726 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6730 repl = strchr(str, CTLESC);
6736 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6738 /* If there's no pattern to match, return the expansion unmolested */
6747 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6748 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6750 /* No match, advance */
6751 char *restart_detect = stackblock();
6753 STPUTC(*idx, expdest);
6754 if (quotes && (unsigned char)*idx == CTLESC) {
6757 STPUTC(*idx, expdest);
6759 if (stackblock() != restart_detect)
6764 /* continue; - prone to quadratic behavior, smarter code: */
6767 if (str[0] == '*') {
6768 /* Pattern is "*foo". If "*foo" does not match "long_string",
6769 * it would never match "ong_string" etc, no point in trying.
6776 if (subtype == VSREPLACEALL) {
6778 if (quotes && (unsigned char)*idx == CTLESC)
6787 //bb_error_msg("repl:'%s'", repl);
6788 for (loc = (char*)repl; *loc; loc++) {
6789 char *restart_detect = stackblock();
6790 if (quotes && *loc == '\\') {
6791 STPUTC(CTLESC, expdest);
6794 STPUTC(*loc, expdest);
6795 if (stackblock() != restart_detect)
6800 if (subtype == VSREPLACE) {
6801 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6803 char *restart_detect = stackblock();
6804 STPUTC(*idx, expdest);
6805 if (stackblock() != restart_detect)
6814 /* We've put the replaced text into a buffer at workloc, now
6815 * move it to the right place and adjust the stack.
6817 STPUTC('\0', expdest);
6818 startp = (char *)stackblock() + startloc;
6819 memmove(startp, (char *)stackblock() + workloc, len + 1);
6820 //bb_error_msg("startp:'%s'", startp);
6821 amount = expdest - (startp + len);
6822 STADJUST(-amount, expdest);
6825 #endif /* BASH_PATTERN_SUBST */
6827 subtype -= VSTRIMRIGHT;
6829 if (subtype < 0 || subtype > 7)
6832 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6833 zero = subtype >> 1;
6834 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6835 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6837 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6840 memmove(startp, loc, str - loc);
6841 loc = startp + (str - loc) - 1;
6844 amount = loc - expdest;
6845 STADJUST(amount, expdest);
6851 * Add the value of a specialized variable to the stack string.
6852 * name parameter (examples):
6853 * ash -c 'echo $1' name:'1='
6854 * ash -c 'echo $qwe' name:'qwe='
6855 * ash -c 'echo $$' name:'$='
6856 * ash -c 'echo ${$}' name:'$='
6857 * ash -c 'echo ${$##q}' name:'$=q'
6858 * ash -c 'echo ${#$}' name:'$='
6859 * note: examples with bad shell syntax:
6860 * ash -c 'echo ${#$1}' name:'$=1'
6861 * ash -c 'echo ${#1#}' name:'1=#'
6863 static NOINLINE ssize_t
6864 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list, int *quotedp)
6871 int quoted = *quotedp;
6872 int subtype = varflags & VSTYPE;
6873 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6874 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6877 sep = (flags & EXP_FULL) << CHAR_BIT;
6878 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6888 num = shellparam.nparam;
6896 goto check_1char_name;
6898 expdest = makestrspace(NOPTS, expdest);
6899 for (i = NOPTS - 1; i >= 0; i--) {
6901 USTPUTC(optletters(i), expdest);
6907 /* handles cases similar to ${#$1} */
6908 if (name[2] != '\0')
6909 raise_error_syntax("bad substitution");
6922 sep |= ifsset() ? ifsval()[0] : ' ';
6929 while ((p = *ap++) != NULL) {
6930 len += strtodest(p, syntax, quotes);
6934 memtodest(&sepc, 1, syntax, quotes);
6949 num = atoi(name); /* number(name) fails on ${N#str} etc */
6950 if (num < 0 || num > shellparam.nparam)
6952 p = num ? shellparam.p[num - 1] : arg0;
6955 /* NB: name has form "VAR=..." */
6957 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6958 * which should be considered before we check variables. */
6960 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6964 str = var_str_list->text;
6965 eq = strchr(str, '=');
6966 if (!eq) /* stop at first non-assignment */
6969 if (name_len == (unsigned)(eq - str)
6970 && strncmp(str, name, name_len) == 0
6973 /* goto value; - WRONG! */
6974 /* think "A=1 A=2 B=$A" */
6976 var_str_list = var_str_list->next;
6977 } while (var_str_list);
6981 p = lookupvar(name);
6986 len = strtodest(p, syntax, quotes);
6987 #if ENABLE_UNICODE_SUPPORT
6988 if (subtype == VSLENGTH && len > 0) {
6989 reinit_unicode_for_ash();
6990 if (unicode_status == UNICODE_ON) {
6991 STADJUST(-len, expdest);
6993 len = unicode_strlen(p);
7001 STADJUST(-len, expdest);
7006 * Expand a variable, and return a pointer to the next character in the
7010 evalvar(char *p, int flag, struct strlist *var_str_list)
7021 varflags = (unsigned char) *p++;
7022 subtype = varflags & VSTYPE;
7025 raise_error_syntax("bad substitution");
7027 quoted = flag & EXP_QUOTED;
7029 easy = (!quoted || (*var == '@' && shellparam.nparam));
7030 startloc = expdest - (char *)stackblock();
7031 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
7034 varlen = varvalue(var, varflags, flag, var_str_list, "ed);
7035 if (varflags & VSNUL)
7038 if (subtype == VSPLUS) {
7039 varlen = -1 - varlen;
7043 if (subtype == VSMINUS) {
7048 flag | EXP_TILDE | EXP_WORD,
7056 if (subtype == VSASSIGN || subtype == VSQUESTION) {
7060 subevalvar(p, var, 0, subtype, startloc, varflags,
7061 flag & ~QUOTES_ESC, var_str_list);
7064 * Remove any recorded regions beyond
7067 removerecordregions(startloc);
7071 if (varlen < 0 && uflag)
7072 varunset(p, var, 0, 0);
7074 if (subtype == VSLENGTH) {
7075 cvtnum(varlen > 0 ? varlen : 0);
7079 if (subtype == VSNORMAL) {
7083 recordregion(startloc, expdest - (char *)stackblock(), quoted);
7092 case VSTRIMRIGHTMAX:
7096 #if BASH_PATTERN_SUBST
7108 * Terminate the string and start recording the pattern
7111 STPUTC('\0', expdest);
7112 patloc = expdest - (char *)stackblock();
7113 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
7114 startloc, varflags, flag, var_str_list)) {
7115 int amount = expdest - (
7116 (char *)stackblock() + patloc - 1
7118 STADJUST(-amount, expdest);
7120 /* Remove any recorded regions beyond start of variable */
7121 removerecordregions(startloc);
7126 if (subtype != VSNORMAL) { /* skip to end of alternative */
7129 unsigned char c = *p++;
7132 else if (c == CTLBACKQ) {
7134 argbackq = argbackq->next;
7135 } else if (c == CTLVAR) {
7136 if ((*p++ & VSTYPE) != VSNORMAL)
7138 } else if (c == CTLENDVAR) {
7148 * Add a file name to the list.
7151 addfname(const char *name)
7155 sp = stzalloc(sizeof(*sp));
7156 sp->text = sstrdup(name);
7158 exparg.lastp = &sp->next;
7161 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7163 hasmeta(const char *p)
7165 static const char chars[] ALIGN1 = {
7166 '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
7170 p = strpbrk(p, chars);
7173 switch ((unsigned char) *p) {
7177 if (*p == CTLQUOTEMARK)
7181 if (*p == '\0') /* huh? */
7192 if (!strchr(p + 1, ']')) {
7193 /* It's not a properly closed [] pattern,
7194 * but other metas may follow. Continue checking.
7195 * my[file* _is_ globbed by bash
7196 * and matches filenames like "my[file1".
7212 /* If we want to use glob() from libc... */
7213 #if !ENABLE_ASH_INTERNAL_GLOB
7215 /* Add the result of glob() to the list */
7217 addglob(const glob_t *pglob)
7219 char **p = pglob->gl_pathv;
7226 expandmeta(struct strlist *str /*, int flag*/)
7228 /* TODO - EXP_REDIR */
7238 if (!hasmeta(str->text))
7242 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7243 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7244 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7246 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7247 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7248 // Which means you need to unescape the string, right? Not so fast:
7249 // if there _is_ a file named "file\?" (with backslash), it is returned
7250 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7251 // You DON'T KNOW by looking at the result whether you need to unescape it.
7253 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7254 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7255 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7256 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7257 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7258 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7259 i = glob(p, 0, NULL, &pglob);
7260 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7265 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7266 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7267 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7279 *exparg.lastp = str;
7280 rmescapes(str->text, 0);
7281 exparg.lastp = &str->next;
7283 default: /* GLOB_NOSPACE */
7286 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7293 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7296 * Do metacharacter (i.e. *, ?, [...]) expansion.
7299 expmeta(char *expdir, char *enddir, char *name)
7315 for (p = name; esc = 0, *p; p += esc + 1) {
7316 if (*p == '*' || *p == '?')
7318 else if (*p == '[') {
7325 if (*q == '/' || *q == '\0')
7335 if (p[esc] == '/') {
7338 start = p + esc + 1;
7342 if (metaflag == 0) { /* we've reached the end of the file name */
7343 if (enddir != expdir)
7351 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7362 } while (p < start);
7364 if (enddir == expdir) {
7366 } else if (enddir == expdir + 1 && *expdir == '/') {
7375 if (enddir != expdir)
7377 if (*endname == 0) {
7390 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7391 if (dp->d_name[0] == '.' && !matchdot)
7393 if (pmatch(start, dp->d_name)) {
7395 strcpy(enddir, dp->d_name);
7398 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7401 expmeta(expdir, p, endname);
7407 endname[-esc - 1] = esc ? '\\' : '/';
7410 static struct strlist *
7411 msort(struct strlist *list, int len)
7413 struct strlist *p, *q = NULL;
7414 struct strlist **lpp;
7422 for (n = half; --n >= 0;) {
7426 q->next = NULL; /* terminate first half of list */
7427 q = msort(list, half); /* sort first half of list */
7428 p = msort(p, len - half); /* sort second half */
7431 #if ENABLE_LOCALE_SUPPORT
7432 if (strcoll(p->text, q->text) < 0)
7434 if (strcmp(p->text, q->text) < 0)
7458 * Sort the results of file name expansion. It calculates the number of
7459 * strings to sort and then calls msort (short for merge sort) to do the
7462 static struct strlist *
7463 expsort(struct strlist *str)
7469 for (sp = str; sp; sp = sp->next)
7471 return msort(str, len);
7475 expandmeta(struct strlist *str /*, int flag*/)
7477 /* TODO - EXP_REDIR */
7481 struct strlist **savelastp;
7487 if (!hasmeta(str->text))
7489 savelastp = exparg.lastp;
7492 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7494 int i = strlen(str->text);
7495 //BUGGY estimation of how long expanded name can be
7496 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7498 expmeta(expdir, expdir, p);
7503 if (exparg.lastp == savelastp) {
7508 *exparg.lastp = str;
7509 rmescapes(str->text, 0);
7510 exparg.lastp = &str->next;
7512 *exparg.lastp = NULL;
7513 *savelastp = sp = expsort(*savelastp);
7514 while (sp->next != NULL)
7516 exparg.lastp = &sp->next;
7521 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7524 * Perform variable substitution and command substitution on an argument,
7525 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7526 * perform splitting and file name expansion. When arglist is NULL, perform
7527 * here document expansion.
7530 expandarg(union node *arg, struct arglist *arglist, int flag)
7535 argbackq = arg->narg.backquote;
7536 STARTSTACKSTR(expdest);
7537 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7538 argstr(arg->narg.text, flag,
7539 /* var_str_list: */ arglist ? arglist->list : NULL);
7540 p = _STPUTC('\0', expdest);
7542 if (arglist == NULL) {
7543 /* here document expanded */
7546 p = grabstackstr(p);
7547 TRACE(("expandarg: p:'%s'\n", p));
7548 exparg.lastp = &exparg.list;
7552 if (flag & EXP_FULL) {
7553 ifsbreakup(p, &exparg);
7554 *exparg.lastp = NULL;
7555 exparg.lastp = &exparg.list;
7556 expandmeta(exparg.list /*, flag*/);
7558 if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
7560 TRACE(("expandarg: rmescapes:'%s'\n", p));
7562 sp = stzalloc(sizeof(*sp));
7565 exparg.lastp = &sp->next;
7567 *exparg.lastp = NULL;
7569 *arglist->lastp = exparg.list;
7570 arglist->lastp = exparg.lastp;
7578 * Expand shell variables and backquotes inside a here document.
7581 expandhere(union node *arg, int fd)
7583 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7584 full_write(fd, stackblock(), expdest - (char *)stackblock());
7588 * Returns true if the pattern matches the string.
7591 patmatch(char *pattern, const char *string)
7593 return pmatch(preglob(pattern, 0), string);
7597 * See if a pattern matches in a case statement.
7600 casematch(union node *pattern, char *val)
7602 struct stackmark smark;
7605 setstackmark(&smark);
7606 argbackq = pattern->narg.backquote;
7607 STARTSTACKSTR(expdest);
7608 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7609 /* var_str_list: */ NULL);
7610 STACKSTRNUL(expdest);
7612 result = patmatch(stackblock(), val);
7613 popstackmark(&smark);
7618 /* ============ find_command */
7622 int (*builtin)(int, char **) FAST_FUNC;
7623 /* unsigned flags; */
7625 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7626 /* "regular" builtins always take precedence over commands,
7627 * regardless of PATH=....%builtin... position */
7628 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7629 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7632 smallint cmdtype; /* CMDxxx */
7635 /* index >= 0 for commands without path (slashes) */
7636 /* (TODO: what exactly does the value mean? PATH position?) */
7637 /* index == -1 for commands with slashes */
7638 /* index == (-2 - applet_no) for NOFORK applets */
7639 const struct builtincmd *cmd;
7640 struct funcnode *func;
7643 /* values of cmdtype */
7644 #define CMDUNKNOWN -1 /* no entry in table for command */
7645 #define CMDNORMAL 0 /* command is an executable program */
7646 #define CMDFUNCTION 1 /* command is a shell function */
7647 #define CMDBUILTIN 2 /* command is a shell builtin */
7649 /* action to find_command() */
7650 #define DO_ERR 0x01 /* prints errors */
7651 #define DO_ABS 0x02 /* checks absolute paths */
7652 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7653 #define DO_ALTPATH 0x08 /* using alternate path */
7654 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7656 static void find_command(char *, struct cmdentry *, int, const char *);
7659 /* ============ Hashing commands */
7662 * When commands are first encountered, they are entered in a hash table.
7663 * This ensures that a full path search will not have to be done for them
7664 * on each invocation.
7666 * We should investigate converting to a linear search, even though that
7667 * would make the command name "hash" a misnomer.
7671 struct tblentry *next; /* next entry in hash chain */
7672 union param param; /* definition of builtin function */
7673 smallint cmdtype; /* CMDxxx */
7674 char rehash; /* if set, cd done since entry created */
7675 char cmdname[1]; /* name of command */
7678 static struct tblentry **cmdtable;
7679 #define INIT_G_cmdtable() do { \
7680 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7683 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7687 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7689 #if ENABLE_FEATURE_SH_STANDALONE
7690 if (applet_no >= 0) {
7691 if (APPLET_IS_NOEXEC(applet_no)) {
7695 run_applet_no_and_exit(applet_no, argv);
7697 /* re-exec ourselves with the new arguments */
7698 execve(bb_busybox_exec_path, argv, envp);
7699 /* If they called chroot or otherwise made the binary no longer
7700 * executable, fall through */
7707 execve(cmd, argv, envp);
7708 } while (errno == EINTR);
7710 execve(cmd, argv, envp);
7712 if (cmd != (char*) bb_busybox_exec_path && errno == ENOEXEC) {
7713 /* Run "cmd" as a shell script:
7714 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7715 * "If the execve() function fails with ENOEXEC, the shell
7716 * shall execute a command equivalent to having a shell invoked
7717 * with the command name as its first operand,
7718 * with any remaining arguments passed to the new shell"
7720 * That is, do not use $SHELL, user's shell, or /bin/sh;
7721 * just call ourselves.
7723 * Note that bash reads ~80 chars of the file, and if it sees
7724 * a zero byte before it sees newline, it doesn't try to
7725 * interpret it, but fails with "cannot execute binary file"
7726 * message and exit code 126. For one, this prevents attempts
7727 * to interpret foreign ELF binaries as shell scripts.
7730 cmd = (char*) bb_busybox_exec_path;
7731 /* NB: this is only possible because all callers of shellexec()
7732 * ensure that the argv[-1] slot exists!
7735 argv[0] = (char*) "ash";
7741 * Exec a program. Never returns. If you change this routine, you may
7742 * have to change the find_command routine as well.
7743 * argv[-1] must exist and be writable! See tryexec() for why.
7745 static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
7746 static void shellexec(char *prog, char **argv, const char *path, int idx)
7752 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7754 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7755 if (strchr(prog, '/') != NULL
7756 #if ENABLE_FEATURE_SH_STANDALONE
7757 || (applet_no = find_applet_by_name(prog)) >= 0
7760 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
7761 if (applet_no >= 0) {
7762 /* We tried execing ourself, but it didn't work.
7763 * Maybe /proc/self/exe doesn't exist?
7772 while ((cmdname = path_advance(&path, prog)) != NULL) {
7773 if (--idx < 0 && pathopt == NULL) {
7774 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7775 if (errno != ENOENT && errno != ENOTDIR)
7782 /* Map to POSIX errors */
7794 exitstatus = exerrno;
7795 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7796 prog, e, suppress_int));
7797 ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
7802 printentry(struct tblentry *cmdp)
7808 idx = cmdp->param.index;
7811 name = path_advance(&path, cmdp->cmdname);
7813 } while (--idx >= 0);
7814 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7818 * Clear out command entries. The argument specifies the first entry in
7819 * PATH which has changed.
7822 clearcmdentry(int firstchange)
7824 struct tblentry **tblp;
7825 struct tblentry **pp;
7826 struct tblentry *cmdp;
7829 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7831 while ((cmdp = *pp) != NULL) {
7832 if ((cmdp->cmdtype == CMDNORMAL &&
7833 cmdp->param.index >= firstchange)
7834 || (cmdp->cmdtype == CMDBUILTIN &&
7835 builtinloc >= firstchange)
7848 * Locate a command in the command hash table. If "add" is nonzero,
7849 * add the command to the table if it is not already present. The
7850 * variable "lastcmdentry" is set to point to the address of the link
7851 * pointing to the entry, so that delete_cmd_entry can delete the
7854 * Interrupts must be off if called with add != 0.
7856 static struct tblentry **lastcmdentry;
7858 static struct tblentry *
7859 cmdlookup(const char *name, int add)
7861 unsigned int hashval;
7863 struct tblentry *cmdp;
7864 struct tblentry **pp;
7867 hashval = (unsigned char)*p << 4;
7869 hashval += (unsigned char)*p++;
7871 pp = &cmdtable[hashval % CMDTABLESIZE];
7872 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7873 if (strcmp(cmdp->cmdname, name) == 0)
7877 if (add && cmdp == NULL) {
7878 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7880 /* + 1 - already done because
7881 * tblentry::cmdname is char[1] */);
7882 /*cmdp->next = NULL; - ckzalloc did it */
7883 cmdp->cmdtype = CMDUNKNOWN;
7884 strcpy(cmdp->cmdname, name);
7891 * Delete the command entry returned on the last lookup.
7894 delete_cmd_entry(void)
7896 struct tblentry *cmdp;
7899 cmdp = *lastcmdentry;
7900 *lastcmdentry = cmdp->next;
7901 if (cmdp->cmdtype == CMDFUNCTION)
7902 freefunc(cmdp->param.func);
7908 * Add a new command entry, replacing any existing command entry for
7909 * the same name - except special builtins.
7912 addcmdentry(char *name, struct cmdentry *entry)
7914 struct tblentry *cmdp;
7916 cmdp = cmdlookup(name, 1);
7917 if (cmdp->cmdtype == CMDFUNCTION) {
7918 freefunc(cmdp->param.func);
7920 cmdp->cmdtype = entry->cmdtype;
7921 cmdp->param = entry->u;
7925 static int FAST_FUNC
7926 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7928 struct tblentry **pp;
7929 struct tblentry *cmdp;
7931 struct cmdentry entry;
7934 if (nextopt("r") != '\0') {
7939 if (*argptr == NULL) {
7940 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7941 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7942 if (cmdp->cmdtype == CMDNORMAL)
7950 while ((name = *argptr) != NULL) {
7951 cmdp = cmdlookup(name, 0);
7953 && (cmdp->cmdtype == CMDNORMAL
7954 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7958 find_command(name, &entry, DO_ERR, pathval());
7959 if (entry.cmdtype == CMDUNKNOWN)
7967 * Called when a cd is done. Marks all commands so the next time they
7968 * are executed they will be rehashed.
7973 struct tblentry **pp;
7974 struct tblentry *cmdp;
7976 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7977 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7978 if (cmdp->cmdtype == CMDNORMAL
7979 || (cmdp->cmdtype == CMDBUILTIN
7980 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7990 * Fix command hash table when PATH changed.
7991 * Called before PATH is changed. The argument is the new value of PATH;
7992 * pathval() still returns the old value at this point.
7993 * Called with interrupts off.
7995 static void FAST_FUNC
7996 changepath(const char *new)
8004 firstchange = 9999; /* assume no change */
8010 if ((*old == '\0' && *new == ':')
8011 || (*old == ':' && *new == '\0')
8015 old = new; /* ignore subsequent differences */
8019 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
8026 if (builtinloc < 0 && idx_bltin >= 0)
8027 builtinloc = idx_bltin; /* zap builtins */
8028 if (builtinloc >= 0 && idx_bltin < 0)
8030 clearcmdentry(firstchange);
8031 builtinloc = idx_bltin;
8067 typedef smallint token_id_t;
8069 /* Nth bit indicates if token marks the end of a list */
8072 /* 0 */ | (1u << TEOF)
8073 /* 1 */ | (0u << TNL)
8074 /* 2 */ | (0u << TREDIR)
8075 /* 3 */ | (0u << TWORD)
8076 /* 4 */ | (0u << TSEMI)
8077 /* 5 */ | (0u << TBACKGND)
8078 /* 6 */ | (0u << TAND)
8079 /* 7 */ | (0u << TOR)
8080 /* 8 */ | (0u << TPIPE)
8081 /* 9 */ | (0u << TLP)
8082 /* 10 */ | (1u << TRP)
8083 /* 11 */ | (1u << TENDCASE)
8084 /* 12 */ | (1u << TENDBQUOTE)
8085 /* 13 */ | (0u << TNOT)
8086 /* 14 */ | (0u << TCASE)
8087 /* 15 */ | (1u << TDO)
8088 /* 16 */ | (1u << TDONE)
8089 /* 17 */ | (1u << TELIF)
8090 /* 18 */ | (1u << TELSE)
8091 /* 19 */ | (1u << TESAC)
8092 /* 20 */ | (1u << TFI)
8093 /* 21 */ | (0u << TFOR)
8095 /* 22 */ | (0u << TFUNCTION)
8097 /* 23 */ | (0u << TIF)
8098 /* 24 */ | (0u << TIN)
8099 /* 25 */ | (1u << TTHEN)
8100 /* 26 */ | (0u << TUNTIL)
8101 /* 27 */ | (0u << TWHILE)
8102 /* 28 */ | (0u << TBEGIN)
8103 /* 29 */ | (1u << TEND)
8104 , /* thus far 29 bits used */
8107 static const char *const tokname_array[] = {
8121 #define KWDOFFSET 13
8122 /* the following are keywords */
8144 /* Wrapper around strcmp for qsort/bsearch/... */
8146 pstrcmp(const void *a, const void *b)
8148 return strcmp((char*)a, *(char**)b);
8151 static const char *const *
8152 findkwd(const char *s)
8154 return bsearch(s, tokname_array + KWDOFFSET,
8155 ARRAY_SIZE(tokname_array) - KWDOFFSET,
8156 sizeof(tokname_array[0]), pstrcmp);
8160 * Locate and print what a word is...
8163 describe_command(char *command, const char *path, int describe_command_verbose)
8165 struct cmdentry entry;
8166 struct tblentry *cmdp;
8167 #if ENABLE_ASH_ALIAS
8168 const struct alias *ap;
8171 path = path ? path : pathval();
8173 if (describe_command_verbose) {
8177 /* First look at the keywords */
8178 if (findkwd(command)) {
8179 out1str(describe_command_verbose ? " is a shell keyword" : command);
8183 #if ENABLE_ASH_ALIAS
8184 /* Then look at the aliases */
8185 ap = lookupalias(command, 0);
8187 if (!describe_command_verbose) {
8192 out1fmt(" is an alias for %s", ap->val);
8196 /* Then check if it is a tracked alias */
8197 cmdp = cmdlookup(command, 0);
8199 entry.cmdtype = cmdp->cmdtype;
8200 entry.u = cmdp->param;
8202 /* Finally use brute force */
8203 find_command(command, &entry, DO_ABS, path);
8206 switch (entry.cmdtype) {
8208 int j = entry.u.index;
8214 p = path_advance(&path, command);
8218 if (describe_command_verbose) {
8220 (cmdp ? " a tracked alias for" : nullstr), p
8229 if (describe_command_verbose) {
8230 out1str(" is a shell function");
8237 if (describe_command_verbose) {
8238 out1fmt(" is a %sshell builtin",
8239 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8240 "special " : nullstr
8248 if (describe_command_verbose) {
8249 out1str(": not found\n");
8258 static int FAST_FUNC
8259 typecmd(int argc UNUSED_PARAM, char **argv)
8265 /* type -p ... ? (we don't bother checking for 'p') */
8266 if (argv[1] && argv[1][0] == '-') {
8271 err |= describe_command(argv[i++], NULL, verbose);
8276 #if ENABLE_ASH_CMDCMD
8277 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8279 parse_command_args(char **argv, const char **path)
8292 if (c == '-' && !*cp) {
8300 *path = bb_default_path;
8303 /* run 'typecmd' for other options */
8312 static int FAST_FUNC
8313 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8321 const char *path = NULL;
8323 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8324 * never reaches this function.
8327 while ((c = nextopt("pvV")) != '\0')
8329 verify |= VERIFY_VERBOSE;
8331 /*verify |= VERIFY_BRIEF*/;
8337 path = bb_default_path;
8339 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8341 if (/*verify && */ cmd)
8342 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8349 /*static int funcblocksize; // size of structures in function */
8350 /*static int funcstringsize; // size of strings in node */
8351 static void *funcblock; /* block to allocate function from */
8352 static char *funcstring_end; /* end of block to allocate strings from */
8354 /* flags in argument to evaltree */
8355 #define EV_EXIT 01 /* exit after evaluating tree */
8356 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
8358 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8359 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8360 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8361 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8362 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8363 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8364 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8365 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8366 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8367 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8368 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8369 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8370 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8371 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8372 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8373 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8374 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8375 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8376 #if BASH_REDIR_OUTPUT
8377 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8379 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8380 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8381 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8382 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8383 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8384 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8385 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8386 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8387 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8390 static int calcsize(int funcblocksize, union node *n);
8393 sizenodelist(int funcblocksize, struct nodelist *lp)
8396 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8397 funcblocksize = calcsize(funcblocksize, lp->n);
8400 return funcblocksize;
8404 calcsize(int funcblocksize, union node *n)
8407 return funcblocksize;
8408 funcblocksize += nodesize[n->type];
8411 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8412 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8413 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8416 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8421 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8422 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8429 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8430 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8433 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8434 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8435 funcblocksize = calcsize(funcblocksize, n->nif.test);
8438 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8439 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8440 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8443 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8444 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8447 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8448 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8449 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8453 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8454 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8455 funcblocksize = calcsize(funcblocksize, n->narg.next);
8458 #if BASH_REDIR_OUTPUT
8465 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8466 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8470 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8471 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8475 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8476 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8479 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8482 return funcblocksize;
8486 nodeckstrdup(char *s)
8488 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8489 return strcpy(funcstring_end, s);
8492 static union node *copynode(union node *);
8494 static struct nodelist *
8495 copynodelist(struct nodelist *lp)
8497 struct nodelist *start;
8498 struct nodelist **lpp;
8503 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8504 (*lpp)->n = copynode(lp->n);
8506 lpp = &(*lpp)->next;
8513 copynode(union node *n)
8520 funcblock = (char *) funcblock + nodesize[n->type];
8524 new->ncmd.redirect = copynode(n->ncmd.redirect);
8525 new->ncmd.args = copynode(n->ncmd.args);
8526 new->ncmd.assign = copynode(n->ncmd.assign);
8529 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8530 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8535 new->nredir.redirect = copynode(n->nredir.redirect);
8536 new->nredir.n = copynode(n->nredir.n);
8543 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8544 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8547 new->nif.elsepart = copynode(n->nif.elsepart);
8548 new->nif.ifpart = copynode(n->nif.ifpart);
8549 new->nif.test = copynode(n->nif.test);
8552 new->nfor.var = nodeckstrdup(n->nfor.var);
8553 new->nfor.body = copynode(n->nfor.body);
8554 new->nfor.args = copynode(n->nfor.args);
8557 new->ncase.cases = copynode(n->ncase.cases);
8558 new->ncase.expr = copynode(n->ncase.expr);
8561 new->nclist.body = copynode(n->nclist.body);
8562 new->nclist.pattern = copynode(n->nclist.pattern);
8563 new->nclist.next = copynode(n->nclist.next);
8567 new->narg.backquote = copynodelist(n->narg.backquote);
8568 new->narg.text = nodeckstrdup(n->narg.text);
8569 new->narg.next = copynode(n->narg.next);
8572 #if BASH_REDIR_OUTPUT
8579 new->nfile.fname = copynode(n->nfile.fname);
8580 new->nfile.fd = n->nfile.fd;
8581 new->nfile.next = copynode(n->nfile.next);
8585 new->ndup.vname = copynode(n->ndup.vname);
8586 new->ndup.dupfd = n->ndup.dupfd;
8587 new->ndup.fd = n->ndup.fd;
8588 new->ndup.next = copynode(n->ndup.next);
8592 new->nhere.doc = copynode(n->nhere.doc);
8593 new->nhere.fd = n->nhere.fd;
8594 new->nhere.next = copynode(n->nhere.next);
8597 new->nnot.com = copynode(n->nnot.com);
8600 new->type = n->type;
8605 * Make a copy of a parse tree.
8607 static struct funcnode *
8608 copyfunc(union node *n)
8613 /*funcstringsize = 0;*/
8614 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8615 f = ckzalloc(blocksize /* + funcstringsize */);
8616 funcblock = (char *) f + offsetof(struct funcnode, n);
8617 funcstring_end = (char *) f + blocksize;
8619 /* f->count = 0; - ckzalloc did it */
8624 * Define a shell function.
8627 defun(union node *func)
8629 struct cmdentry entry;
8632 entry.cmdtype = CMDFUNCTION;
8633 entry.u.func = copyfunc(func);
8634 addcmdentry(func->narg.text, &entry);
8638 /* Reasons for skipping commands (see comment on breakcmd routine) */
8639 #define SKIPBREAK (1 << 0)
8640 #define SKIPCONT (1 << 1)
8641 #define SKIPFUNC (1 << 2)
8642 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8643 static int skipcount; /* number of levels to skip */
8644 static int funcnest; /* depth of function calls */
8645 static int loopnest; /* current loop nesting level */
8647 /* Forward decl way out to parsing code - dotrap needs it */
8648 static int evalstring(char *s, int flags);
8650 /* Called to execute a trap.
8651 * Single callsite - at the end of evaltree().
8652 * If we return non-zero, evaltree raises EXEXIT exception.
8654 * Perhaps we should avoid entering new trap handlers
8655 * while we are executing a trap handler. [is it a TODO?]
8662 uint8_t last_status;
8667 last_status = exitstatus;
8671 TRACE(("dotrap entered\n"));
8672 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8684 /* non-trapped SIGINT is handled separately by raise_interrupt,
8685 * don't upset it by resetting gotsig[SIGINT-1] */
8686 if (sig == SIGINT && !p)
8689 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8695 exitstatus = last_status;
8696 TRACE(("dotrap returns\n"));
8699 /* forward declarations - evaluation is fairly recursive business... */
8700 static int evalloop(union node *, int);
8701 static int evalfor(union node *, int);
8702 static int evalcase(union node *, int);
8703 static int evalsubshell(union node *, int);
8704 static void expredir(union node *);
8705 static int evalpipe(union node *, int);
8706 static int evalcommand(union node *, int);
8707 static int evalbltin(const struct builtincmd *, int, char **, int);
8708 static void prehash(union node *);
8711 * Evaluate a parse tree. The value is left in the global variable
8715 evaltree(union node *n, int flags)
8718 int (*evalfn)(union node *, int);
8722 TRACE(("evaltree(NULL) called\n"));
8725 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8732 out1fmt("Node type = %d\n", n->type);
8737 status = !evaltree(n->nnot.com, EV_TESTED);
8740 expredir(n->nredir.redirect);
8741 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8743 status = evaltree(n->nredir.n, flags & EV_TESTED);
8745 if (n->nredir.redirect)
8746 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8749 evalfn = evalcommand;
8751 if (eflag && !(flags & EV_TESTED))
8763 evalfn = evalsubshell;
8776 #error NAND + 1 != NOR
8778 #if NOR + 1 != NSEMI
8779 #error NOR + 1 != NSEMI
8781 unsigned is_or = n->type - NAND;
8784 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8786 if ((!status) == is_or || evalskip)
8792 status = evalfn(n, flags);
8796 status = evaltree(n->nif.test, EV_TESTED);
8803 if (n->nif.elsepart) {
8804 n = n->nif.elsepart;
8811 /* Not necessary. To test it:
8812 * "false; f() { qwerty; }; echo $?" should print 0.
8816 exitstatus = status;
8820 /* Order of checks below is important:
8821 * signal handlers trigger before exit caused by "set -e".
8825 if (checkexit & status)
8826 raise_exception(EXEXIT);
8827 if (flags & EV_EXIT)
8828 raise_exception(EXEXIT);
8830 TRACE(("leaving evaltree (no interrupts)\n"));
8834 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8837 int evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8842 int skip = evalskip;
8849 if (--skipcount <= 0) {
8860 evalloop(union node *n, int flags)
8871 i = evaltree(n->nbinary.ch1, EV_TESTED);
8873 if (skip == SKIPFUNC)
8877 if (n->type != NWHILE)
8881 status = evaltree(n->nbinary.ch2, flags);
8883 } while (!(skip & ~SKIPCONT));
8890 evalfor(union node *n, int flags)
8892 struct arglist arglist;
8895 struct stackmark smark;
8898 setstackmark(&smark);
8899 arglist.list = NULL;
8900 arglist.lastp = &arglist.list;
8901 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8902 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8904 *arglist.lastp = NULL;
8908 for (sp = arglist.list; sp; sp = sp->next) {
8909 setvar0(n->nfor.var, sp->text);
8910 status = evaltree(n->nfor.body, flags);
8911 if (skiploop() & ~SKIPCONT)
8915 popstackmark(&smark);
8921 evalcase(union node *n, int flags)
8925 struct arglist arglist;
8926 struct stackmark smark;
8929 setstackmark(&smark);
8930 arglist.list = NULL;
8931 arglist.lastp = &arglist.list;
8932 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8933 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8934 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8935 if (casematch(patp, arglist.list->text)) {
8936 /* Ensure body is non-empty as otherwise
8937 * EV_EXIT may prevent us from setting the
8940 if (evalskip == 0 && cp->nclist.body) {
8941 status = evaltree(cp->nclist.body, flags);
8948 popstackmark(&smark);
8954 * Kick off a subshell to evaluate a tree.
8957 evalsubshell(union node *n, int flags)
8960 int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
8963 expredir(n->nredir.redirect);
8964 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8967 if (backgnd == FORK_FG)
8969 jp = makejob(/*n,*/ 1);
8970 if (forkshell(jp, n, backgnd) == 0) {
8975 flags &= ~EV_TESTED;
8977 redirect(n->nredir.redirect, 0);
8978 evaltreenr(n->nredir.n, flags);
8983 if (backgnd == FORK_FG)
8984 status = waitforjob(jp);
8990 * Compute the names of the files in a redirection list.
8992 static void fixredir(union node *, const char *, int);
8994 expredir(union node *n)
8998 for (redir = n; redir; redir = redir->nfile.next) {
9002 fn.lastp = &fn.list;
9003 switch (redir->type) {
9007 #if BASH_REDIR_OUTPUT
9012 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
9013 TRACE(("expredir expanded to '%s'\n", fn.list->text));
9014 #if BASH_REDIR_OUTPUT
9018 // By the design of stack allocator, the loop of this kind:
9019 // while true; do while true; do break; done </dev/null; done
9020 // will look like a memory leak: ash plans to free expfname's
9021 // of "/dev/null" as soon as it finishes running the loop
9022 // (in this case, never).
9023 // This "fix" is wrong:
9024 if (redir->nfile.expfname)
9025 stunalloc(redir->nfile.expfname);
9026 // It results in corrupted state of stacked allocations.
9028 redir->nfile.expfname = fn.list->text;
9031 case NTOFD: /* >& */
9032 if (redir->ndup.vname) {
9033 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
9034 if (fn.list == NULL)
9035 ash_msg_and_raise_error("redir error");
9036 #if BASH_REDIR_OUTPUT
9037 //FIXME: we used expandarg with different args!
9038 if (!isdigit_str9(fn.list->text)) {
9039 /* >&file, not >&fd */
9040 if (redir->nfile.fd != 1) /* 123>&file - BAD */
9041 ash_msg_and_raise_error("redir error");
9043 goto store_expfname;
9046 fixredir(redir, fn.list->text, 1);
9054 * Evaluate a pipeline. All the processes in the pipeline are children
9055 * of the process creating the pipeline. (This differs from some versions
9056 * of the shell, which make the last process in a pipeline the parent
9060 evalpipe(union node *n, int flags)
9063 struct nodelist *lp;
9069 TRACE(("evalpipe(0x%lx) called\n", (long)n));
9071 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
9075 if (n->npipe.pipe_backgnd == 0)
9077 jp = makejob(/*n,*/ pipelen);
9079 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
9083 if (pipe(pip) < 0) {
9085 ash_msg_and_raise_error("pipe call failed");
9088 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
9102 evaltreenr(lp->n, flags);
9109 /* Don't want to trigger debugging */
9113 if (n->npipe.pipe_backgnd == 0) {
9114 status = waitforjob(jp);
9115 TRACE(("evalpipe: job done exit status %d\n", status));
9123 * Controls whether the shell is interactive or not.
9126 setinteractive(int on)
9128 static smallint is_interactive;
9130 if (++on == is_interactive)
9132 is_interactive = on;
9136 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9137 if (is_interactive > 1) {
9138 /* Looks like they want an interactive shell */
9139 static smallint did_banner;
9142 /* note: ash and hush share this string */
9143 out1fmt("\n\n%s %s\n"
9144 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
9147 "built-in shell (ash)"
9161 setinteractive(iflag);
9163 #if ENABLE_FEATURE_EDITING_VI
9165 line_input_state->flags |= VI_MODE;
9167 line_input_state->flags &= ~VI_MODE;
9169 viflag = 0; /* forcibly keep the option off */
9173 static struct localvar *localvars;
9176 * Called after a function returns.
9177 * Interrupts must be off.
9182 struct localvar *lvp;
9185 while ((lvp = localvars) != NULL) {
9186 localvars = lvp->next;
9188 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9189 if (vp == NULL) { /* $- saved */
9190 memcpy(optlist, lvp->text, sizeof(optlist));
9191 free((char*)lvp->text);
9193 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
9194 unsetvar(vp->var_text);
9197 vp->var_func(var_end(lvp->text));
9198 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9199 free((char*)vp->var_text);
9200 vp->flags = lvp->flags;
9201 vp->var_text = lvp->text;
9208 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9210 volatile struct shparam saveparam;
9211 struct localvar *volatile savelocalvars;
9212 struct jmploc *volatile savehandler;
9213 struct jmploc jmploc;
9216 saveparam = shellparam;
9217 savelocalvars = localvars;
9218 savehandler = exception_handler;
9219 e = setjmp(jmploc.loc);
9224 exception_handler = &jmploc;
9226 shellparam.malloced = 0;
9230 shellparam.nparam = argc - 1;
9231 shellparam.p = argv + 1;
9232 #if ENABLE_ASH_GETOPTS
9233 shellparam.optind = 1;
9234 shellparam.optoff = -1;
9236 evaltree(func->n.narg.next, flags & EV_TESTED);
9242 localvars = savelocalvars;
9243 freeparam(&shellparam);
9244 shellparam = saveparam;
9245 exception_handler = savehandler;
9247 evalskip &= ~SKIPFUNC;
9252 * Make a variable a local variable. When a variable is made local, it's
9253 * value and flags are saved in a localvar structure. The saved values
9254 * will be restored when the shell function returns. We handle the name
9255 * "-" as a special case: it makes changes to "set +-options" local
9256 * (options will be restored on return from the function).
9261 struct localvar *lvp;
9264 char *eq = strchr(name, '=');
9267 /* Cater for duplicate "local". Examples:
9268 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9269 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9273 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9277 * it's a duplicate "local VAR" declaration, do nothing
9284 lvp = ckzalloc(sizeof(*lvp));
9285 if (LONE_DASH(name)) {
9287 p = ckmalloc(sizeof(optlist));
9288 lvp->text = memcpy(p, optlist, sizeof(optlist));
9291 vpp = hashvar(name);
9292 vp = *findvar(vpp, name);
9294 /* variable did not exist yet */
9296 setvareq(name, VSTRFIXED);
9298 setvar(name, NULL, VSTRFIXED);
9299 vp = *vpp; /* the new variable */
9300 lvp->flags = VUNSET;
9302 lvp->text = vp->var_text;
9303 lvp->flags = vp->flags;
9304 /* make sure neither "struct var" nor string gets freed
9305 * during (un)setting:
9307 vp->flags |= VSTRFIXED|VTEXTFIXED;
9311 /* "local VAR" unsets VAR: */
9312 setvar0(name, NULL);
9316 lvp->next = localvars;
9323 * The "local" command.
9325 static int FAST_FUNC
9326 localcmd(int argc UNUSED_PARAM, char **argv)
9331 ash_msg_and_raise_error("not in a function");
9334 while ((name = *argv++) != NULL) {
9340 static int FAST_FUNC
9341 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9346 static int FAST_FUNC
9347 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9352 static int FAST_FUNC
9353 execcmd(int argc UNUSED_PARAM, char **argv)
9356 while (nextopt("a:") != '\0')
9357 /* nextopt() sets optionarg to "-a ARGV0" */;
9363 iflag = 0; /* exit on error */
9366 /* We should set up signals for "exec CMD"
9367 * the same way as for "CMD" without "exec".
9368 * But optschanged->setinteractive->setsignal
9369 * still thought we are a root shell. Therefore, for example,
9370 * SIGQUIT is still set to IGN. Fix it:
9374 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9375 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9376 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9380 argv[0] = optionarg;
9381 shellexec(prog, argv, pathval(), 0);
9388 * The return command.
9390 static int FAST_FUNC
9391 returncmd(int argc UNUSED_PARAM, char **argv)
9394 * If called outside a function, do what ksh does;
9395 * skip the rest of the file.
9397 evalskip = SKIPFUNC;
9398 return argv[1] ? number(argv[1]) : exitstatus;
9401 /* Forward declarations for builtintab[] */
9402 static int breakcmd(int, char **) FAST_FUNC;
9403 static int dotcmd(int, char **) FAST_FUNC;
9404 static int evalcmd(int, char **, int) FAST_FUNC;
9405 static int exitcmd(int, char **) FAST_FUNC;
9406 static int exportcmd(int, char **) FAST_FUNC;
9407 #if ENABLE_ASH_GETOPTS
9408 static int getoptscmd(int, char **) FAST_FUNC;
9411 static int helpcmd(int, char **) FAST_FUNC;
9414 static int historycmd(int, char **) FAST_FUNC;
9416 #if ENABLE_FEATURE_SH_MATH
9417 static int letcmd(int, char **) FAST_FUNC;
9419 static int readcmd(int, char **) FAST_FUNC;
9420 static int setcmd(int, char **) FAST_FUNC;
9421 static int shiftcmd(int, char **) FAST_FUNC;
9422 static int timescmd(int, char **) FAST_FUNC;
9423 static int trapcmd(int, char **) FAST_FUNC;
9424 static int umaskcmd(int, char **) FAST_FUNC;
9425 static int unsetcmd(int, char **) FAST_FUNC;
9426 static int ulimitcmd(int, char **) FAST_FUNC;
9428 #define BUILTIN_NOSPEC "0"
9429 #define BUILTIN_SPECIAL "1"
9430 #define BUILTIN_REGULAR "2"
9431 #define BUILTIN_SPEC_REG "3"
9432 #define BUILTIN_ASSIGN "4"
9433 #define BUILTIN_SPEC_ASSG "5"
9434 #define BUILTIN_REG_ASSG "6"
9435 #define BUILTIN_SPEC_REG_ASSG "7"
9437 /* Stubs for calling non-FAST_FUNC's */
9439 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9441 #if ENABLE_ASH_PRINTF
9442 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9444 #if ENABLE_ASH_TEST || BASH_TEST2
9445 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9448 /* Keep these in proper order since it is searched via bsearch() */
9449 static const struct builtincmd builtintab[] = {
9450 { BUILTIN_SPEC_REG "." , dotcmd },
9451 { BUILTIN_SPEC_REG ":" , truecmd },
9453 { BUILTIN_REGULAR "[" , testcmd },
9456 { BUILTIN_REGULAR "[[" , testcmd },
9458 #if ENABLE_ASH_ALIAS
9459 { BUILTIN_REG_ASSG "alias" , aliascmd },
9462 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9464 { BUILTIN_SPEC_REG "break" , breakcmd },
9465 { BUILTIN_REGULAR "cd" , cdcmd },
9466 { BUILTIN_NOSPEC "chdir" , cdcmd },
9467 #if ENABLE_ASH_CMDCMD
9468 { BUILTIN_REGULAR "command" , commandcmd },
9470 { BUILTIN_SPEC_REG "continue", breakcmd },
9472 { BUILTIN_REGULAR "echo" , echocmd },
9474 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9475 { BUILTIN_SPEC_REG "exec" , execcmd },
9476 { BUILTIN_SPEC_REG "exit" , exitcmd },
9477 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9478 { BUILTIN_REGULAR "false" , falsecmd },
9480 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9482 #if ENABLE_ASH_GETOPTS
9483 { BUILTIN_REGULAR "getopts" , getoptscmd },
9485 { BUILTIN_NOSPEC "hash" , hashcmd },
9487 { BUILTIN_NOSPEC "help" , helpcmd },
9490 { BUILTIN_NOSPEC "history" , historycmd },
9493 { BUILTIN_REGULAR "jobs" , jobscmd },
9494 { BUILTIN_REGULAR "kill" , killcmd },
9496 #if ENABLE_FEATURE_SH_MATH
9497 { BUILTIN_NOSPEC "let" , letcmd },
9499 { BUILTIN_ASSIGN "local" , localcmd },
9500 #if ENABLE_ASH_PRINTF
9501 { BUILTIN_REGULAR "printf" , printfcmd },
9503 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9504 { BUILTIN_REGULAR "read" , readcmd },
9505 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9506 { BUILTIN_SPEC_REG "return" , returncmd },
9507 { BUILTIN_SPEC_REG "set" , setcmd },
9508 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9510 { BUILTIN_SPEC_REG "source" , dotcmd },
9513 { BUILTIN_REGULAR "test" , testcmd },
9515 { BUILTIN_SPEC_REG "times" , timescmd },
9516 { BUILTIN_SPEC_REG "trap" , trapcmd },
9517 { BUILTIN_REGULAR "true" , truecmd },
9518 { BUILTIN_NOSPEC "type" , typecmd },
9519 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9520 { BUILTIN_REGULAR "umask" , umaskcmd },
9521 #if ENABLE_ASH_ALIAS
9522 { BUILTIN_REGULAR "unalias" , unaliascmd },
9524 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9525 { BUILTIN_REGULAR "wait" , waitcmd },
9528 /* Should match the above table! */
9529 #define COMMANDCMD (builtintab + \
9531 /* [ */ 1 * ENABLE_ASH_TEST + \
9532 /* [[ */ 1 * BASH_TEST2 + \
9533 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9534 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9535 /* break cd cddir */ 3)
9536 #define EVALCMD (COMMANDCMD + \
9537 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9538 /* continue */ 1 + \
9539 /* echo */ 1 * ENABLE_ASH_ECHO + \
9541 #define EXECCMD (EVALCMD + \
9545 * Search the table of builtin commands.
9548 pstrcmp1(const void *a, const void *b)
9550 return strcmp((char*)a, *(char**)b + 1);
9552 static struct builtincmd *
9553 find_builtin(const char *name)
9555 struct builtincmd *bp;
9558 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9565 * Execute a simple command.
9568 isassignment(const char *p)
9570 const char *q = endofname(p);
9575 static int FAST_FUNC
9576 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9578 /* Preserve exitstatus of a previous possible redirection
9579 * as POSIX mandates */
9580 return back_exitstatus;
9583 evalcommand(union node *cmd, int flags)
9585 static const struct builtincmd null_bltin = {
9586 "\0\0", bltincmd /* why three NULs? */
9588 struct stackmark smark;
9590 struct arglist arglist;
9591 struct arglist varlist;
9594 const struct strlist *sp;
9595 struct cmdentry cmdentry;
9602 struct builtincmd *bcmd;
9603 smallint cmd_is_exec;
9604 smallint pseudovarflag = 0;
9606 /* First expand the arguments. */
9607 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9608 setstackmark(&smark);
9609 back_exitstatus = 0;
9611 cmdentry.cmdtype = CMDBUILTIN;
9612 cmdentry.u.cmd = &null_bltin;
9613 varlist.lastp = &varlist.list;
9614 *varlist.lastp = NULL;
9615 arglist.lastp = &arglist.list;
9616 *arglist.lastp = NULL;
9619 if (cmd->ncmd.args) {
9620 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9621 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9624 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9625 struct strlist **spp;
9627 spp = arglist.lastp;
9628 if (pseudovarflag && isassignment(argp->narg.text))
9629 expandarg(argp, &arglist, EXP_VARTILDE);
9631 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9633 for (sp = *spp; sp; sp = sp->next)
9637 /* Reserve one extra spot at the front for shellexec. */
9638 nargv = stalloc(sizeof(char *) * (argc + 2));
9640 for (sp = arglist.list; sp; sp = sp->next) {
9641 TRACE(("evalcommand arg: %s\n", sp->text));
9642 *nargv++ = sp->text;
9647 if (iflag && funcnest == 0 && argc > 0)
9648 lastarg = nargv[-1];
9651 expredir(cmd->ncmd.redirect);
9652 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9654 path = vpath.var_text;
9655 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9656 struct strlist **spp;
9659 spp = varlist.lastp;
9660 expandarg(argp, &varlist, EXP_VARTILDE);
9663 * Modify the command lookup path, if a PATH= assignment
9667 if (varcmp(p, path) == 0)
9671 /* Print the command if xflag is set. */
9674 const char *p = " %s" + 1;
9676 fdprintf(preverrout_fd, p, expandstr(ps4val()));
9678 for (n = 0; n < 2; n++) {
9680 fdprintf(preverrout_fd, p, sp->text);
9686 safe_write(preverrout_fd, "\n", 1);
9692 /* Now locate the command. */
9694 int cmd_flag = DO_ERR;
9695 #if ENABLE_ASH_CMDCMD
9696 const char *oldpath = path + 5;
9700 find_command(argv[0], &cmdentry, cmd_flag, path);
9701 if (cmdentry.cmdtype == CMDUNKNOWN) {
9702 flush_stdout_stderr();
9707 /* implement bltin and command here */
9708 if (cmdentry.cmdtype != CMDBUILTIN)
9711 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9712 if (cmdentry.u.cmd == EXECCMD)
9714 #if ENABLE_ASH_CMDCMD
9715 if (cmdentry.u.cmd == COMMANDCMD) {
9717 nargv = parse_command_args(argv, &path);
9720 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9721 * nargv => "PROG". path is updated if -p.
9723 argc -= nargv - argv;
9725 cmd_flag |= DO_NOFUNC;
9734 exitstatus = status;
9736 /* We have a redirection error. */
9738 raise_exception(EXERROR);
9743 /* Execute the command. */
9744 switch (cmdentry.cmdtype) {
9747 #if ENABLE_FEATURE_SH_NOFORK
9748 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9749 * around run_nofork_applet() call.
9750 * (2) Should this check also be done in forkshell()?
9751 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9753 /* find_command() encodes applet_no as (-2 - applet_no) */
9754 int applet_no = (- cmdentry.u.index - 2);
9755 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9756 listsetvar(varlist.list, VEXPORT|VSTACK);
9757 /* run <applet>_main() */
9758 status = run_nofork_applet(applet_no, argv);
9762 /* Can we avoid forking off? For example, very last command
9763 * in a script or a subshell does not need forking,
9764 * we can just exec it.
9766 if (!(flags & EV_EXIT) || may_have_traps) {
9767 /* No, forking off a child is necessary */
9770 jp = makejob(/*cmd,*/ 1);
9771 if (forkshell(jp, cmd, FORK_FG) != 0) {
9773 status = waitforjob(jp);
9775 TRACE(("forked child exited with %d\n", status));
9780 /* fall through to exec'ing external program */
9782 listsetvar(varlist.list, VEXPORT|VSTACK);
9783 shellexec(argv[0], argv, path, cmdentry.u.index);
9787 cmdenviron = varlist.list;
9789 struct strlist *list = cmdenviron;
9791 if (spclbltin > 0 || argc == 0) {
9793 if (cmd_is_exec && argc > 1)
9796 listsetvar(list, i);
9798 /* Tight loop with builtins only:
9799 * "while kill -0 $child; do true; done"
9800 * will never exit even if $child died, unless we do this
9801 * to reap the zombie and make kill detect that it's gone: */
9802 dowait(DOWAIT_NONBLOCK, NULL);
9804 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
9805 if (exception_type == EXERROR && spclbltin <= 0) {
9810 longjmp(exception_handler->loc, 1);
9815 listsetvar(varlist.list, 0);
9816 /* See above for the rationale */
9817 dowait(DOWAIT_NONBLOCK, NULL);
9818 if (evalfun(cmdentry.u.func, argc, argv, flags))
9821 status = exitstatus;
9826 if (cmd->ncmd.redirect)
9827 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9829 /* dsl: I think this is intended to be used to support
9830 * '_' in 'vi' command mode during line editing...
9831 * However I implemented that within libedit itself.
9833 setvar0("_", lastarg);
9835 popstackmark(&smark);
9841 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
9843 char *volatile savecmdname;
9844 struct jmploc *volatile savehandler;
9845 struct jmploc jmploc;
9849 savecmdname = commandname;
9850 savehandler = exception_handler;
9851 i = setjmp(jmploc.loc);
9854 exception_handler = &jmploc;
9855 commandname = argv[0];
9857 optptr = NULL; /* initialize nextopt */
9859 status = evalcmd(argc, argv, flags);
9861 status = (*cmd->builtin)(argc, argv);
9862 flush_stdout_stderr();
9863 status |= ferror(stdout);
9864 exitstatus = status;
9867 commandname = savecmdname;
9868 exception_handler = savehandler;
9874 goodname(const char *p)
9876 return endofname(p)[0] == '\0';
9881 * Search for a command. This is called before we fork so that the
9882 * location of the command will be available in the parent as well as
9883 * the child. The check for "goodname" is an overly conservative
9884 * check that the name will not be subject to expansion.
9887 prehash(union node *n)
9889 struct cmdentry entry;
9891 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9892 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9896 /* ============ Builtin commands
9898 * Builtin commands whose functions are closely tied to evaluation
9899 * are implemented here.
9903 * Handle break and continue commands. Break, continue, and return are
9904 * all handled by setting the evalskip flag. The evaluation routines
9905 * above all check this flag, and if it is set they start skipping
9906 * commands rather than executing them. The variable skipcount is
9907 * the number of loops to break/continue, or the number of function
9908 * levels to return. (The latter is always 1.) It should probably
9909 * be an error to break out of more loops than exist, but it isn't
9910 * in the standard shell so we don't make it one here.
9912 static int FAST_FUNC
9913 breakcmd(int argc UNUSED_PARAM, char **argv)
9915 int n = argv[1] ? number(argv[1]) : 1;
9918 ash_msg_and_raise_error(msg_illnum, argv[1]);
9922 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9930 * This implements the input routines used by the parser.
9934 INPUT_PUSH_FILE = 1,
9935 INPUT_NOFILE_OK = 2,
9938 static smallint checkkwd;
9939 /* values of checkkwd variable */
9940 #define CHKALIAS 0x1
9945 * Push a string back onto the input at this current parsefile level.
9946 * We handle aliases this way.
9948 #if !ENABLE_ASH_ALIAS
9949 #define pushstring(s, ap) pushstring(s)
9952 pushstring(char *s, struct alias *ap)
9959 if (g_parsefile->strpush) {
9960 sp = ckzalloc(sizeof(*sp));
9961 sp->prev = g_parsefile->strpush;
9963 sp = &(g_parsefile->basestrpush);
9965 g_parsefile->strpush = sp;
9966 sp->prev_string = g_parsefile->next_to_pgetc;
9967 sp->prev_left_in_line = g_parsefile->left_in_line;
9968 sp->unget = g_parsefile->unget;
9969 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
9970 #if ENABLE_ASH_ALIAS
9973 ap->flag |= ALIASINUSE;
9977 g_parsefile->next_to_pgetc = s;
9978 g_parsefile->left_in_line = len;
9979 g_parsefile->unget = 0;
9986 struct strpush *sp = g_parsefile->strpush;
9989 #if ENABLE_ASH_ALIAS
9991 if (g_parsefile->next_to_pgetc[-1] == ' '
9992 || g_parsefile->next_to_pgetc[-1] == '\t'
9994 checkkwd |= CHKALIAS;
9996 if (sp->string != sp->ap->val) {
9999 sp->ap->flag &= ~ALIASINUSE;
10000 if (sp->ap->flag & ALIASDEAD) {
10001 unalias(sp->ap->name);
10005 g_parsefile->next_to_pgetc = sp->prev_string;
10006 g_parsefile->left_in_line = sp->prev_left_in_line;
10007 g_parsefile->unget = sp->unget;
10008 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
10009 g_parsefile->strpush = sp->prev;
10010 if (sp != &(g_parsefile->basestrpush))
10019 char *buf = g_parsefile->buf;
10021 g_parsefile->next_to_pgetc = buf;
10022 #if ENABLE_FEATURE_EDITING
10024 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
10025 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10028 # if ENABLE_ASH_IDLE_TIMEOUT
10030 const char *tmout_var = lookupvar("TMOUT");
10032 timeout = atoi(tmout_var) * 1000;
10038 # if ENABLE_FEATURE_TAB_COMPLETION
10039 line_input_state->path_lookup = pathval();
10041 reinit_unicode_for_ash();
10042 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
10044 /* ^C pressed, "convert" to SIGINT */
10045 write(STDOUT_FILENO, "^C", 2);
10046 if (trap[SIGINT]) {
10052 exitstatus = 128 + SIGINT;
10058 /* Ctrl+D pressed */
10061 # if ENABLE_ASH_IDLE_TIMEOUT
10062 else if (errno == EAGAIN && timeout > 0) {
10063 puts("\007timed out waiting for input: auto-logout");
10070 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10073 #if 0 /* disabled: nonblock_immune_read() handles this problem */
10075 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
10076 int flags = fcntl(0, F_GETFL);
10077 if (flags >= 0 && (flags & O_NONBLOCK)) {
10078 flags &= ~O_NONBLOCK;
10079 if (fcntl(0, F_SETFL, flags) >= 0) {
10080 out2str("sh: turning off NDELAY mode\n");
10091 * Refill the input buffer and return the next input character:
10093 * 1) If a string was pushed back on the input, pop it;
10094 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
10095 * or we are reading from a string so we can't refill the buffer,
10097 * 3) If there is more stuff in this buffer, use it else call read to fill it.
10098 * 4) Process input up to the next newline, deleting nul characters.
10100 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
10101 #define pgetc_debug(...) ((void)0)
10102 static int pgetc(void);
10109 if (g_parsefile->strpush) {
10110 #if ENABLE_ASH_ALIAS
10111 if (g_parsefile->left_in_line == -1
10112 && g_parsefile->strpush->ap
10113 && g_parsefile->next_to_pgetc[-1] != ' '
10114 && g_parsefile->next_to_pgetc[-1] != '\t'
10116 pgetc_debug("preadbuffer PEOA");
10123 /* on both branches above g_parsefile->left_in_line < 0.
10124 * "pgetc" needs refilling.
10127 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
10128 * pungetc() may increment it a few times.
10129 * Assuming it won't increment it to less than -90.
10131 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
10132 pgetc_debug("preadbuffer PEOF1");
10133 /* even in failure keep left_in_line and next_to_pgetc
10134 * in lock step, for correct multi-layer pungetc.
10135 * left_in_line was decremented before preadbuffer(),
10136 * must inc next_to_pgetc: */
10137 g_parsefile->next_to_pgetc++;
10141 more = g_parsefile->left_in_buffer;
10143 flush_stdout_stderr();
10147 /* don't try reading again */
10148 g_parsefile->left_in_line = -99;
10149 pgetc_debug("preadbuffer PEOF2");
10150 g_parsefile->next_to_pgetc++;
10155 /* Find out where's the end of line.
10156 * Set g_parsefile->left_in_line
10157 * and g_parsefile->left_in_buffer acordingly.
10158 * NUL chars are deleted.
10160 q = g_parsefile->next_to_pgetc;
10168 memmove(q, q + 1, more);
10172 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10178 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10179 if (g_parsefile->left_in_line < 0)
10184 g_parsefile->left_in_buffer = more;
10189 out2str(g_parsefile->next_to_pgetc);
10193 pgetc_debug("preadbuffer at %d:%p'%s'",
10194 g_parsefile->left_in_line,
10195 g_parsefile->next_to_pgetc,
10196 g_parsefile->next_to_pgetc);
10197 return (unsigned char)*g_parsefile->next_to_pgetc++;
10203 g_parsefile->linno++;
10204 setprompt_if(doprompt, 2);
10209 g_parsefile->linno++;
10210 needprompt = doprompt;
10218 pgetc_debug("pgetc at %d:%p'%s'",
10219 g_parsefile->left_in_line,
10220 g_parsefile->next_to_pgetc,
10221 g_parsefile->next_to_pgetc);
10222 if (g_parsefile->unget)
10223 return g_parsefile->lastc[--g_parsefile->unget];
10225 if (--g_parsefile->left_in_line >= 0)
10226 c = (unsigned char)*g_parsefile->next_to_pgetc++;
10230 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10231 g_parsefile->lastc[0] = c;
10236 #if ENABLE_ASH_ALIAS
10238 pgetc_without_PEOA(void)
10242 pgetc_debug("pgetc at %d:%p'%s'",
10243 g_parsefile->left_in_line,
10244 g_parsefile->next_to_pgetc,
10245 g_parsefile->next_to_pgetc);
10247 } while (c == PEOA);
10251 # define pgetc_without_PEOA() pgetc()
10255 * Read a line from the script.
10258 pfgets(char *line, int len)
10264 while (--nleft > 0) {
10265 c = pgetc_without_PEOA();
10280 * Undo a call to pgetc. Only two characters may be pushed back.
10281 * PEOF may be pushed back.
10286 g_parsefile->unget++;
10289 /* This one eats backslash+newline */
10295 while ((c = pgetc()) == '\\') {
10296 if (pgetc() != '\n') {
10308 * To handle the "." command, a stack of input files is used. Pushfile
10309 * adds a new entry to the stack and popfile restores the previous level.
10314 struct parsefile *pf;
10316 pf = ckzalloc(sizeof(*pf));
10317 pf->prev = g_parsefile;
10319 /*pf->strpush = NULL; - ckzalloc did it */
10320 /*pf->basestrpush.prev = NULL;*/
10328 struct parsefile *pf = g_parsefile;
10334 if (pf->pf_fd >= 0)
10337 while (pf->strpush)
10339 g_parsefile = pf->prev;
10345 * Return to top level.
10350 while (g_parsefile != &basepf)
10355 * Close the file(s) that the shell is reading commands from. Called
10356 * after a fork is done.
10362 if (g_parsefile->pf_fd > 0) {
10363 close(g_parsefile->pf_fd);
10364 g_parsefile->pf_fd = 0;
10369 * Like setinputfile, but takes an open file descriptor. Call this with
10373 setinputfd(int fd, int push)
10377 g_parsefile->buf = NULL;
10379 g_parsefile->pf_fd = fd;
10380 if (g_parsefile->buf == NULL)
10381 g_parsefile->buf = ckmalloc(IBUFSIZ);
10382 g_parsefile->left_in_buffer = 0;
10383 g_parsefile->left_in_line = 0;
10384 g_parsefile->linno = 1;
10388 * Set the input to take input from a file. If push is set, push the
10389 * old input onto the stack first.
10392 setinputfile(const char *fname, int flags)
10397 fd = open(fname, O_RDONLY);
10399 if (flags & INPUT_NOFILE_OK)
10402 ash_msg_and_raise_error("can't open '%s'", fname);
10407 close_on_exec_on(fd);
10408 setinputfd(fd, flags & INPUT_PUSH_FILE);
10415 * Like setinputfile, but takes input from a string.
10418 setinputstring(char *string)
10422 g_parsefile->next_to_pgetc = string;
10423 g_parsefile->left_in_line = strlen(string);
10424 g_parsefile->buf = NULL;
10425 g_parsefile->linno = 1;
10431 * Routines to check for mail.
10434 #if ENABLE_ASH_MAIL
10436 /* Hash of mtimes of mailboxes */
10437 static unsigned mailtime_hash;
10438 /* Set if MAIL or MAILPATH is changed. */
10439 static smallint mail_var_path_changed;
10442 * Print appropriate message(s) if mail has arrived.
10443 * If mail_var_path_changed is set,
10444 * then the value of MAIL has mail_var_path_changed,
10445 * so we just update the values.
10454 struct stackmark smark;
10457 setstackmark(&smark);
10458 mpath = mpathset() ? mpathval() : mailval();
10461 p = path_advance(&mpath, nullstr);
10466 for (q = p; *q; q++)
10472 q[-1] = '\0'; /* delete trailing '/' */
10473 if (stat(p, &statb) < 0) {
10476 /* Very simplistic "hash": just a sum of all mtimes */
10477 new_hash += (unsigned)statb.st_mtime;
10479 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10480 if (mailtime_hash != 0)
10481 out2str("you have mail\n");
10482 mailtime_hash = new_hash;
10484 mail_var_path_changed = 0;
10485 popstackmark(&smark);
10488 static void FAST_FUNC
10489 changemail(const char *val UNUSED_PARAM)
10491 mail_var_path_changed = 1;
10494 #endif /* ASH_MAIL */
10497 /* ============ ??? */
10500 * Set the shell parameters.
10503 setparam(char **argv)
10509 for (nparam = 0; argv[nparam]; nparam++)
10511 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10513 *ap++ = ckstrdup(*argv++);
10516 freeparam(&shellparam);
10517 shellparam.malloced = 1;
10518 shellparam.nparam = nparam;
10519 shellparam.p = newparam;
10520 #if ENABLE_ASH_GETOPTS
10521 shellparam.optind = 1;
10522 shellparam.optoff = -1;
10527 * Process shell options. The global variable argptr contains a pointer
10528 * to the argument list; we advance it past the options.
10530 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10531 * For a non-interactive shell, an error condition encountered
10532 * by a special built-in ... shall cause the shell to write a diagnostic message
10533 * to standard error and exit as shown in the following table:
10534 * Error Special Built-In
10536 * Utility syntax error (option or operand error) Shall exit
10538 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10539 * we see that bash does not do that (set "finishes" with error code 1 instead,
10540 * and shell continues), and people rely on this behavior!
10542 * set -o barfoo 2>/dev/null
10545 * Oh well. Let's mimic that.
10548 plus_minus_o(char *name, int val)
10553 for (i = 0; i < NOPTS; i++) {
10554 if (strcmp(name, optnames(i)) == 0) {
10559 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10562 for (i = 0; i < NOPTS; i++) {
10564 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10566 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10572 setoption(int flag, int val)
10576 for (i = 0; i < NOPTS; i++) {
10577 if (optletters(i) == flag) {
10582 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10586 options(int cmdline)
10594 while ((p = *argptr) != NULL) {
10596 if (c != '-' && c != '+')
10599 val = 0; /* val = 0 if c == '+' */
10602 if (p[0] == '\0' || LONE_DASH(p)) {
10604 /* "-" means turn off -x and -v */
10607 /* "--" means reset params */
10608 else if (*argptr == NULL)
10611 break; /* "-" or "--" terminates options */
10614 /* first char was + or - */
10615 while ((c = *p++) != '\0') {
10616 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10617 if (c == 'c' && cmdline) {
10618 minusc = p; /* command is after shell args */
10619 } else if (c == 'o') {
10620 if (plus_minus_o(*argptr, val)) {
10621 /* it already printed err message */
10622 return 1; /* error */
10626 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10628 /* bash does not accept +-login, we also won't */
10629 } else if (cmdline && val && (c == '-')) { /* long options */
10630 if (strcmp(p, "login") == 0)
10642 * The shift builtin command.
10644 static int FAST_FUNC
10645 shiftcmd(int argc UNUSED_PARAM, char **argv)
10652 n = number(argv[1]);
10653 if (n > shellparam.nparam)
10654 n = 0; /* bash compat, was = shellparam.nparam; */
10656 shellparam.nparam -= n;
10657 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10658 if (shellparam.malloced)
10661 ap2 = shellparam.p;
10662 while ((*ap2++ = *ap1++) != NULL)
10664 #if ENABLE_ASH_GETOPTS
10665 shellparam.optind = 1;
10666 shellparam.optoff = -1;
10673 * POSIX requires that 'set' (but not export or readonly) output the
10674 * variables in lexicographic order - by the locale's collating order (sigh).
10675 * Maybe we could keep them in an ordered balanced binary tree
10676 * instead of hashed lists.
10677 * For now just roll 'em through qsort for printing...
10680 showvars(const char *sep_prefix, int on, int off)
10683 char **ep, **epend;
10685 ep = listvars(on, off, &epend);
10686 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10688 sep = *sep_prefix ? " " : sep_prefix;
10690 for (; ep < epend; ep++) {
10694 p = strchrnul(*ep, '=');
10697 q = single_quote(++p);
10698 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10704 * The set command builtin.
10706 static int FAST_FUNC
10707 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10712 return showvars(nullstr, 0, VUNSET);
10715 retval = options(/*cmdline:*/ 0);
10716 if (retval == 0) { /* if no parse error... */
10718 if (*argptr != NULL) {
10726 #if ENABLE_ASH_RANDOM_SUPPORT
10727 static void FAST_FUNC
10728 change_random(const char *value)
10732 if (value == NULL) {
10733 /* "get", generate */
10734 t = next_random(&random_gen);
10735 /* set without recursion */
10736 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10737 vrandom.flags &= ~VNOFUNC;
10740 t = strtoul(value, NULL, 10);
10741 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10746 #if ENABLE_ASH_GETOPTS
10748 getopts(char *optstr, char *optvar, char **optfirst)
10755 int ind = shellparam.optind;
10756 int off = shellparam.optoff;
10760 shellparam.optind = -1;
10761 optnext = optfirst + ind - 1;
10763 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
10766 p = optnext[-1] + off;
10767 if (p == NULL || *p == '\0') {
10768 /* Current word is done, advance */
10770 if (p == NULL || *p != '-' || *++p == '\0') {
10777 if (LONE_DASH(p)) /* check for "--" */
10782 for (q = optstr; *q != c;) {
10784 if (optstr[0] == ':') {
10786 /*sbuf[1] = '\0'; - already is */
10787 setvar0("OPTARG", sbuf);
10789 fprintf(stderr, "Illegal option -%c\n", c);
10790 unsetvar("OPTARG");
10800 if (*p == '\0' && (p = *optnext) == NULL) {
10801 if (optstr[0] == ':') {
10803 /*sbuf[1] = '\0'; - already is */
10804 setvar0("OPTARG", sbuf);
10807 fprintf(stderr, "No arg for -%c option\n", c);
10808 unsetvar("OPTARG");
10816 setvar0("OPTARG", p);
10819 setvar0("OPTARG", nullstr);
10821 ind = optnext - optfirst + 1;
10822 setvar("OPTIND", itoa(ind), VNOFUNC);
10824 /*sbuf[1] = '\0'; - already is */
10825 setvar0(optvar, sbuf);
10827 shellparam.optoff = p ? p - *(optnext - 1) : -1;
10828 shellparam.optind = ind;
10834 * The getopts builtin. Shellparam.optnext points to the next argument
10835 * to be processed. Shellparam.optptr points to the next character to
10836 * be processed in the current argument. If shellparam.optnext is NULL,
10837 * then it's the first time getopts has been called.
10839 static int FAST_FUNC
10840 getoptscmd(int argc, char **argv)
10845 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10847 optbase = shellparam.p;
10848 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
10849 shellparam.optind = 1;
10850 shellparam.optoff = -1;
10853 optbase = &argv[3];
10854 if ((unsigned)shellparam.optind > argc - 2) {
10855 shellparam.optind = 1;
10856 shellparam.optoff = -1;
10860 return getopts(argv[1], argv[2], optbase);
10862 #endif /* ASH_GETOPTS */
10865 /* ============ Shell parser */
10868 struct heredoc *next; /* next here document in list */
10869 union node *here; /* redirection node */
10870 char *eofmark; /* string indicating end of input */
10871 smallint striptabs; /* if set, strip leading tabs */
10874 static smallint tokpushback; /* last token pushed back */
10875 static smallint quoteflag; /* set if (part of) last token was quoted */
10876 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10877 static struct heredoc *heredoclist; /* list of here documents to read */
10878 static char *wordtext; /* text of last word returned by readtoken */
10879 static struct nodelist *backquotelist;
10880 static union node *redirnode;
10881 static struct heredoc *heredoc;
10883 static const char *
10884 tokname(char *buf, int tok)
10887 return tokname_array[tok];
10888 sprintf(buf, "\"%s\"", tokname_array[tok]);
10892 /* raise_error_unexpected_syntax:
10893 * Called when an unexpected token is read during the parse. The argument
10894 * is the token that is expected, or -1 if more than one type of token can
10895 * occur at this point.
10897 static void raise_error_unexpected_syntax(int) NORETURN;
10899 raise_error_unexpected_syntax(int token)
10905 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10907 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10908 raise_error_syntax(msg);
10912 #define EOFMARKLEN 79
10914 /* parsing is heavily cross-recursive, need these forward decls */
10915 static union node *andor(void);
10916 static union node *pipeline(void);
10917 static union node *parse_command(void);
10918 static void parseheredoc(void);
10919 static int peektoken(void);
10920 static int readtoken(void);
10922 static union node *
10925 union node *n1, *n2, *n3;
10930 switch (peektoken()) {
10938 if (!n1 && (nlflag & 1))
10944 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10945 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
10951 if (tok == TBACKGND) {
10952 if (n2->type == NPIPE) {
10953 n2->npipe.pipe_backgnd = 1;
10955 if (n2->type != NREDIR) {
10956 n3 = stzalloc(sizeof(struct nredir));
10958 /*n3->nredir.redirect = NULL; - stzalloc did it */
10961 n2->type = NBACKGND;
10967 n3 = stzalloc(sizeof(struct nbinary));
10969 n3->nbinary.ch1 = n1;
10970 n3->nbinary.ch2 = n2;
10983 raise_error_unexpected_syntax(-1);
10990 static union node *
10993 union node *n1, *n2, *n3;
11001 } else if (t == TOR) {
11007 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11009 n3 = stzalloc(sizeof(struct nbinary));
11011 n3->nbinary.ch1 = n1;
11012 n3->nbinary.ch2 = n2;
11017 static union node *
11020 union node *n1, *n2, *pipenode;
11021 struct nodelist *lp, *prev;
11025 TRACE(("pipeline: entered\n"));
11026 if (readtoken() == TNOT) {
11028 checkkwd = CHKKWD | CHKALIAS;
11031 n1 = parse_command();
11032 if (readtoken() == TPIPE) {
11033 pipenode = stzalloc(sizeof(struct npipe));
11034 pipenode->type = NPIPE;
11035 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
11036 lp = stzalloc(sizeof(struct nodelist));
11037 pipenode->npipe.cmdlist = lp;
11041 lp = stzalloc(sizeof(struct nodelist));
11042 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11043 lp->n = parse_command();
11045 } while (readtoken() == TPIPE);
11051 n2 = stzalloc(sizeof(struct nnot));
11059 static union node *
11064 n = stzalloc(sizeof(struct narg));
11066 /*n->narg.next = NULL; - stzalloc did it */
11067 n->narg.text = wordtext;
11068 n->narg.backquote = backquotelist;
11073 fixredir(union node *n, const char *text, int err)
11077 TRACE(("Fix redir %s %d\n", text, err));
11079 n->ndup.vname = NULL;
11081 fd = bb_strtou(text, NULL, 10);
11082 if (!errno && fd >= 0)
11083 n->ndup.dupfd = fd;
11084 else if (LONE_DASH(text))
11085 n->ndup.dupfd = -1;
11088 raise_error_syntax("bad fd number");
11089 n->ndup.vname = makename();
11094 * Returns true if the text contains nothing to expand (no dollar signs
11098 noexpand(const char *text)
11102 while ((c = *text++) != '\0') {
11103 if (c == CTLQUOTEMARK)
11107 else if (SIT(c, BASESYNTAX) == CCTL)
11116 union node *n = redirnode;
11118 if (readtoken() != TWORD)
11119 raise_error_unexpected_syntax(-1);
11120 if (n->type == NHERE) {
11121 struct heredoc *here = heredoc;
11125 if (quoteflag == 0)
11127 TRACE(("Here document %d\n", n->type));
11128 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
11129 raise_error_syntax("illegal eof marker for << redirection");
11130 rmescapes(wordtext, 0);
11131 here->eofmark = wordtext;
11133 if (heredoclist == NULL)
11134 heredoclist = here;
11136 for (p = heredoclist; p->next; p = p->next)
11140 } else if (n->type == NTOFD || n->type == NFROMFD) {
11141 fixredir(n, wordtext, 0);
11143 n->nfile.fname = makename();
11147 static union node *
11150 union node *args, **app;
11151 union node *n = NULL;
11152 union node *vars, **vpp;
11153 union node **rpp, *redir;
11156 smallint double_brackets_flag = 0;
11158 IF_BASH_FUNCTION(smallint function_flag = 0;)
11167 savecheckkwd = CHKALIAS;
11170 checkkwd = savecheckkwd;
11175 if (peektoken() != TWORD)
11176 raise_error_unexpected_syntax(TWORD);
11181 case TAND: /* "&&" */
11182 case TOR: /* "||" */
11183 if (!double_brackets_flag) {
11187 wordtext = (char *) (t == TAND ? "-a" : "-o");
11190 n = stzalloc(sizeof(struct narg));
11192 /*n->narg.next = NULL; - stzalloc did it */
11193 n->narg.text = wordtext;
11195 if (strcmp("[[", wordtext) == 0)
11196 double_brackets_flag = 1;
11197 else if (strcmp("]]", wordtext) == 0)
11198 double_brackets_flag = 0;
11200 n->narg.backquote = backquotelist;
11201 if (savecheckkwd && isassignment(wordtext)) {
11203 vpp = &n->narg.next;
11206 app = &n->narg.next;
11210 if (function_flag) {
11211 checkkwd = CHKNL | CHKKWD;
11212 switch (peektoken()) {
11224 if (strcmp("[[", wordtext) == 0)
11228 raise_error_unexpected_syntax(-1);
11234 *rpp = n = redirnode;
11235 rpp = &n->nfile.next;
11236 parsefname(); /* read name of redirection file */
11239 IF_BASH_FUNCTION(do_func:)
11240 if (args && app == &args->narg.next
11243 struct builtincmd *bcmd;
11246 /* We have a function */
11247 if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
11248 raise_error_unexpected_syntax(TRP);
11249 name = n->narg.text;
11250 if (!goodname(name)
11251 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11253 raise_error_syntax("bad function name");
11256 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11257 n->narg.next = parse_command();
11260 IF_BASH_FUNCTION(function_flag = 0;)
11271 n = stzalloc(sizeof(struct ncmd));
11273 n->ncmd.args = args;
11274 n->ncmd.assign = vars;
11275 n->ncmd.redirect = redir;
11279 static union node *
11280 parse_command(void)
11282 union node *n1, *n2;
11283 union node *ap, **app;
11284 union node *cp, **cpp;
11285 union node *redir, **rpp;
11292 switch (readtoken()) {
11294 raise_error_unexpected_syntax(-1);
11297 n1 = stzalloc(sizeof(struct nif));
11299 n1->nif.test = list(0);
11300 if (readtoken() != TTHEN)
11301 raise_error_unexpected_syntax(TTHEN);
11302 n1->nif.ifpart = list(0);
11304 while (readtoken() == TELIF) {
11305 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11306 n2 = n2->nif.elsepart;
11308 n2->nif.test = list(0);
11309 if (readtoken() != TTHEN)
11310 raise_error_unexpected_syntax(TTHEN);
11311 n2->nif.ifpart = list(0);
11313 if (lasttoken == TELSE)
11314 n2->nif.elsepart = list(0);
11316 n2->nif.elsepart = NULL;
11324 n1 = stzalloc(sizeof(struct nbinary));
11325 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11326 n1->nbinary.ch1 = list(0);
11329 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11330 got == TWORD ? wordtext : ""));
11331 raise_error_unexpected_syntax(TDO);
11333 n1->nbinary.ch2 = list(0);
11338 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11339 raise_error_syntax("bad for loop variable");
11340 n1 = stzalloc(sizeof(struct nfor));
11342 n1->nfor.var = wordtext;
11343 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11344 if (readtoken() == TIN) {
11346 while (readtoken() == TWORD) {
11347 n2 = stzalloc(sizeof(struct narg));
11349 /*n2->narg.next = NULL; - stzalloc did it */
11350 n2->narg.text = wordtext;
11351 n2->narg.backquote = backquotelist;
11353 app = &n2->narg.next;
11356 n1->nfor.args = ap;
11357 if (lasttoken != TNL && lasttoken != TSEMI)
11358 raise_error_unexpected_syntax(-1);
11360 n2 = stzalloc(sizeof(struct narg));
11362 /*n2->narg.next = NULL; - stzalloc did it */
11363 n2->narg.text = (char *)dolatstr;
11364 /*n2->narg.backquote = NULL;*/
11365 n1->nfor.args = n2;
11367 * Newline or semicolon here is optional (but note
11368 * that the original Bourne shell only allowed NL).
11370 if (lasttoken != TSEMI)
11373 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11374 if (readtoken() != TDO)
11375 raise_error_unexpected_syntax(TDO);
11376 n1->nfor.body = list(0);
11380 n1 = stzalloc(sizeof(struct ncase));
11382 if (readtoken() != TWORD)
11383 raise_error_unexpected_syntax(TWORD);
11384 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11386 /*n2->narg.next = NULL; - stzalloc did it */
11387 n2->narg.text = wordtext;
11388 n2->narg.backquote = backquotelist;
11389 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11390 if (readtoken() != TIN)
11391 raise_error_unexpected_syntax(TIN);
11392 cpp = &n1->ncase.cases;
11394 checkkwd = CHKNL | CHKKWD;
11396 while (t != TESAC) {
11397 if (lasttoken == TLP)
11399 *cpp = cp = stzalloc(sizeof(struct nclist));
11401 app = &cp->nclist.pattern;
11403 *app = ap = stzalloc(sizeof(struct narg));
11405 /*ap->narg.next = NULL; - stzalloc did it */
11406 ap->narg.text = wordtext;
11407 ap->narg.backquote = backquotelist;
11408 if (readtoken() != TPIPE)
11410 app = &ap->narg.next;
11413 //ap->narg.next = NULL;
11414 if (lasttoken != TRP)
11415 raise_error_unexpected_syntax(TRP);
11416 cp->nclist.body = list(2);
11418 cpp = &cp->nclist.next;
11420 checkkwd = CHKNL | CHKKWD;
11424 raise_error_unexpected_syntax(TENDCASE);
11431 n1 = stzalloc(sizeof(struct nredir));
11432 n1->type = NSUBSHELL;
11433 n1->nredir.n = list(0);
11434 /*n1->nredir.redirect = NULL; - stzalloc did it */
11441 IF_BASH_FUNCTION(case TFUNCTION:)
11445 return simplecmd();
11448 if (readtoken() != t)
11449 raise_error_unexpected_syntax(t);
11452 /* Now check for redirection which may follow command */
11453 checkkwd = CHKKWD | CHKALIAS;
11455 while (readtoken() == TREDIR) {
11456 *rpp = n2 = redirnode;
11457 rpp = &n2->nfile.next;
11463 if (n1->type != NSUBSHELL) {
11464 n2 = stzalloc(sizeof(struct nredir));
11469 n1->nredir.redirect = redir;
11474 #if BASH_DOLLAR_SQUOTE
11476 decode_dollar_squote(void)
11478 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11484 p = strchr(C_escapes, c);
11489 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11493 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11495 } else if (c == 'x') { /* \xHH */
11499 } while (isxdigit(c) && --cnt);
11501 if (cnt == 3) { /* \x but next char is "bad" */
11505 } else { /* simple seq like \\ or \t */
11510 c = bb_process_escape_sequence((void*)&p);
11511 } else { /* unrecognized "\z": print both chars unless ' or " */
11512 if (c != '\'' && c != '"') {
11514 c |= 0x100; /* "please encode \, then me" */
11522 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11523 * is not NULL, read a here document. In the latter case, eofmark is the
11524 * word which marks the end of the document and striptabs is true if
11525 * leading tabs should be stripped from the document. The argument c
11526 * is the first character of the input token or document.
11528 * Because C does not have internal subroutines, I have simulated them
11529 * using goto's to implement the subroutine linkage. The following macros
11530 * will run code that appears at the end of readtoken1.
11532 #define CHECKEND() {goto checkend; checkend_return:;}
11533 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11534 #define PARSESUB() {goto parsesub; parsesub_return:;}
11535 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11536 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11537 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11539 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11541 /* NB: syntax parameter fits into smallint */
11542 /* c parameter is an unsigned char or PEOF or PEOA */
11545 char line[EOFMARKLEN + 1];
11546 struct nodelist *bqlist;
11550 IF_FEATURE_SH_MATH(smallint prevsyntax;) /* syntax before arithmetic */
11551 #if ENABLE_ASH_EXPAND_PRMT
11552 smallint pssyntax; /* we are expanding a prompt string */
11554 int varnest; /* levels of variables expansion */
11555 IF_FEATURE_SH_MATH(int arinest;) /* levels of arithmetic expansion */
11556 IF_FEATURE_SH_MATH(int parenlevel;) /* levels of parens in arithmetic */
11557 int dqvarnest; /* levels of variables expansion within double quotes */
11559 IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
11561 startlinno = g_parsefile->linno;
11564 IF_FEATURE_SH_MATH(prevsyntax = 0;)
11565 #if ENABLE_ASH_EXPAND_PRMT
11566 pssyntax = (syntax == PSSYNTAX);
11570 dblquote = (syntax == DQSYNTAX);
11572 IF_FEATURE_SH_MATH(arinest = 0;)
11573 IF_FEATURE_SH_MATH(parenlevel = 0;)
11576 STARTSTACKSTR(out);
11578 /* For each line, until end of word */
11579 CHECKEND(); /* set c to PEOF if at end of here document */
11580 for (;;) { /* until end of line or end of word */
11581 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11582 switch (SIT(c, syntax)) {
11583 case CNL: /* '\n' */
11584 if (syntax == BASESYNTAX)
11585 goto endword; /* exit outer loop */
11589 goto loop; /* continue outer loop */
11594 #if BASH_DOLLAR_SQUOTE
11595 if (c == '\\' && bash_dollar_squote) {
11596 c = decode_dollar_squote();
11598 /* skip $'\000', $'\x00' (like bash) */
11602 /* Unknown escape. Encode as '\z' */
11603 c = (unsigned char)c;
11604 if (eofmark == NULL || dblquote)
11605 USTPUTC(CTLESC, out);
11606 USTPUTC('\\', out);
11610 if (eofmark == NULL || dblquote)
11611 USTPUTC(CTLESC, out);
11614 case CBACK: /* backslash */
11615 c = pgetc_without_PEOA();
11617 USTPUTC(CTLESC, out);
11618 USTPUTC('\\', out);
11620 } else if (c == '\n') {
11623 #if ENABLE_ASH_EXPAND_PRMT
11624 if (c == '$' && pssyntax) {
11625 USTPUTC(CTLESC, out);
11626 USTPUTC('\\', out);
11629 /* Backslash is retained if we are in "str" and next char isn't special */
11634 && (c != '"' || eofmark != NULL)
11636 USTPUTC('\\', out);
11638 USTPUTC(CTLESC, out);
11646 if (eofmark == NULL) {
11647 USTPUTC(CTLQUOTEMARK, out);
11655 IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
11656 if (eofmark != NULL && varnest == 0) {
11659 if (dqvarnest == 0) {
11660 syntax = BASESYNTAX;
11667 case CVAR: /* '$' */
11668 PARSESUB(); /* parse substitution */
11670 case CENDVAR: /* '}' */
11673 if (dqvarnest > 0) {
11680 #if ENABLE_FEATURE_SH_MATH
11681 case CLP: /* '(' in arithmetic */
11685 case CRP: /* ')' in arithmetic */
11686 if (parenlevel > 0) {
11689 if (pgetc_eatbnl() == ')') {
11691 if (--arinest == 0) {
11692 syntax = prevsyntax;
11696 * unbalanced parens
11697 * (don't 2nd guess - no error)
11705 case CBQUOTE: /* '`' */
11709 goto endword; /* exit outer loop */
11713 if (varnest == 0) {
11714 #if BASH_REDIR_OUTPUT
11716 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11717 if (pgetc() == '>')
11718 c = 0x100 + '>'; /* flag &> */
11722 goto endword; /* exit outer loop */
11724 IF_ASH_ALIAS(if (c != PEOA))
11731 #if ENABLE_FEATURE_SH_MATH
11732 if (syntax == ARISYNTAX)
11733 raise_error_syntax("missing '))'");
11735 if (syntax != BASESYNTAX && eofmark == NULL)
11736 raise_error_syntax("unterminated quoted string");
11737 if (varnest != 0) {
11738 startlinno = g_parsefile->linno;
11740 raise_error_syntax("missing '}'");
11742 USTPUTC('\0', out);
11743 len = out - (char *)stackblock();
11744 out = stackblock();
11745 if (eofmark == NULL) {
11746 if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
11749 if (isdigit_str9(out)) {
11750 PARSEREDIR(); /* passed as params: out, c */
11751 lasttoken = TREDIR;
11754 /* else: non-number X seen, interpret it
11755 * as "NNNX>file" = "NNNX >file" */
11759 quoteflag = quotef;
11760 backquotelist = bqlist;
11761 grabstackblock(len);
11765 /* end of readtoken routine */
11768 * Check to see whether we are at the end of the here document. When this
11769 * is called, c is set to the first character of the next input line. If
11770 * we are at the end of the here document, this routine sets the c to PEOF.
11774 #if ENABLE_ASH_ALIAS
11776 c = pgetc_without_PEOA();
11779 while (c == '\t') {
11780 c = pgetc_without_PEOA();
11783 if (c == *eofmark) {
11784 if (pfgets(line, sizeof(line)) != NULL) {
11789 for (q = eofmark + 1;; p++, q++) {
11793 if (!*q || cc != *q)
11800 pushstring(line, NULL);
11805 goto checkend_return;
11809 * Parse a redirection operator. The variable "out" points to a string
11810 * specifying the fd to be redirected. The variable "c" contains the
11811 * first character of the redirection operator.
11814 /* out is already checked to be a valid number or "" */
11815 int fd = (*out == '\0' ? -1 : atoi(out));
11818 np = stzalloc(sizeof(struct nfile));
11823 np->type = NAPPEND;
11825 np->type = NCLOBBER;
11828 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11834 #if BASH_REDIR_OUTPUT
11835 else if (c == 0x100 + '>') { /* this flags &> redirection */
11837 pgetc(); /* this is '>', no need to check */
11841 else { /* c == '<' */
11842 /*np->nfile.fd = 0; - stzalloc did it */
11846 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11847 np = stzalloc(sizeof(struct nhere));
11848 /*np->nfile.fd = 0; - stzalloc did it */
11851 heredoc = stzalloc(sizeof(struct heredoc));
11852 heredoc->here = np;
11855 heredoc->striptabs = 1;
11857 /*heredoc->striptabs = 0; - stzalloc did it */
11863 np->type = NFROMFD;
11867 np->type = NFROMTO;
11879 goto parseredir_return;
11883 * Parse a substitution. At this point, we have read the dollar sign
11884 * and nothing else.
11887 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11888 * (assuming ascii char codes, as the original implementation did) */
11889 #define is_special(c) \
11890 (((unsigned)(c) - 33 < 32) \
11891 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11893 unsigned char subtype;
11896 c = pgetc_eatbnl();
11897 if (c > 255 /* PEOA or PEOF */
11898 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11900 #if BASH_DOLLAR_SQUOTE
11901 if (syntax != DQSYNTAX && c == '\'')
11902 bash_dollar_squote = 1;
11907 } else if (c == '(') {
11908 /* $(command) or $((arith)) */
11909 if (pgetc_eatbnl() == '(') {
11910 #if ENABLE_FEATURE_SH_MATH
11913 raise_error_syntax("you disabled math support for $((arith)) syntax");
11920 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11921 USTPUTC(CTLVAR, out);
11922 typeloc = out - (char *)stackblock();
11924 subtype = VSNORMAL;
11926 c = pgetc_eatbnl();
11931 /* $[{[#]]NAME[}] */
11934 c = pgetc_eatbnl();
11935 } while (is_in_name(c));
11936 } else if (isdigit(c)) {
11937 /* $[{[#]]NUM[}] */
11940 c = pgetc_eatbnl();
11941 } while (isdigit(c));
11942 } else if (is_special(c)) {
11943 /* $[{[#]]<specialchar>[}] */
11946 c = pgetc_eatbnl();
11947 if (!subtype && cc == '#') {
11948 subtype = VSLENGTH;
11949 if (c == '_' || isalnum(c))
11952 c = pgetc_eatbnl();
11953 if (cc == '}' || c != '}') {
11964 if (c != '}' && subtype == VSLENGTH) {
11965 /* ${#VAR didn't end with } */
11969 if (subtype == 0) {
11970 static const char types[] ALIGN1 = "}-+?=";
11971 /* ${VAR...} but not $VAR or ${#VAR} */
11972 /* c == first char after VAR */
11975 c = pgetc_eatbnl();
11977 /* This check is only needed to not misinterpret
11978 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
11981 if (!strchr(types, c)) {
11982 subtype = VSSUBSTR;
11984 break; /* "goto badsub" is bigger (!) */
11990 const char *p = strchr(types, c);
11993 subtype |= p - types + VSNORMAL;
11999 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
12000 c = pgetc_eatbnl();
12006 #if BASH_PATTERN_SUBST
12008 /* ${v/[/]pattern/repl} */
12009 //TODO: encode pattern and repl separately.
12010 // Currently ${v/$var_with_slash/repl} is horribly broken
12011 subtype = VSREPLACE;
12012 c = pgetc_eatbnl();
12015 subtype++; /* VSREPLACEALL */
12023 ((unsigned char *)stackblock())[typeloc] = subtype;
12024 if (subtype != VSNORMAL) {
12031 goto parsesub_return;
12035 * Called to parse command substitutions. Newstyle is set if the command
12036 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
12037 * list of commands (passed by reference), and savelen is the number of
12038 * characters on the top of the stack which must be preserved.
12041 struct nodelist **nlpp;
12045 smallint saveprompt = 0;
12048 savelen = out - (char *)stackblock();
12051 * FIXME: this can allocate very large block on stack and SEGV.
12053 * echo "..<100kbytes>..`true` $(true) `true` ..."
12054 * allocates 100kb for every command subst. With about
12055 * a hundred command substitutions stack overflows.
12056 * With larger prepended string, SEGV happens sooner.
12058 str = alloca(savelen);
12059 memcpy(str, stackblock(), savelen);
12063 /* We must read until the closing backquote, giving special
12064 * treatment to some slashes, and then push the string and
12065 * reread it as input, interpreting it normally.
12071 STARTSTACKSTR(pout);
12075 setprompt_if(needprompt, 2);
12086 * If eating a newline, avoid putting
12087 * the newline into the new character
12088 * stream (via the STPUTC after the
12093 if (pc != '\\' && pc != '`' && pc != '$'
12094 && (!dblquote || pc != '"')
12096 STPUTC('\\', pout);
12098 if (pc <= 255 /* not PEOA or PEOF */) {
12104 IF_ASH_ALIAS(case PEOA:)
12105 startlinno = g_parsefile->linno;
12106 raise_error_syntax("EOF in backquote substitution");
12118 STPUTC('\0', pout);
12119 psavelen = pout - (char *)stackblock();
12120 if (psavelen > 0) {
12121 pstr = grabstackstr(pout);
12122 setinputstring(pstr);
12127 nlpp = &(*nlpp)->next;
12128 *nlpp = stzalloc(sizeof(**nlpp));
12129 /* (*nlpp)->next = NULL; - stzalloc did it */
12132 saveprompt = doprompt;
12139 doprompt = saveprompt;
12140 else if (readtoken() != TRP)
12141 raise_error_unexpected_syntax(TRP);
12146 * Start reading from old file again, ignoring any pushed back
12147 * tokens left from the backquote parsing
12152 while (stackblocksize() <= savelen)
12154 STARTSTACKSTR(out);
12156 memcpy(out, str, savelen);
12157 STADJUST(savelen, out);
12159 USTPUTC(CTLBACKQ, out);
12161 goto parsebackq_oldreturn;
12162 goto parsebackq_newreturn;
12165 #if ENABLE_FEATURE_SH_MATH
12167 * Parse an arithmetic expansion (indicate start of one and set state)
12170 if (++arinest == 1) {
12171 prevsyntax = syntax;
12172 syntax = ARISYNTAX;
12174 USTPUTC(CTLARI, out);
12175 goto parsearith_return;
12178 } /* end of readtoken */
12181 * Read the next input token.
12182 * If the token is a word, we set backquotelist to the list of cmds in
12183 * backquotes. We set quoteflag to true if any part of the word was
12185 * If the token is TREDIR, then we set redirnode to a structure containing
12187 * In all cases, the variable startlinno is set to the number of the line
12188 * on which the token starts.
12190 * [Change comment: here documents and internal procedures]
12191 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12192 * word parsing code into a separate routine. In this case, readtoken
12193 * doesn't need to have any internal procedures, but parseword does.
12194 * We could also make parseoperator in essence the main routine, and
12195 * have parseword (readtoken1?) handle both words and redirection.]
12197 #define NEW_xxreadtoken
12198 #ifdef NEW_xxreadtoken
12199 /* singles must be first! */
12200 static const char xxreadtoken_chars[7] ALIGN1 = {
12201 '\n', '(', ')', /* singles */
12202 '&', '|', ';', /* doubles */
12206 #define xxreadtoken_singles 3
12207 #define xxreadtoken_doubles 3
12209 static const char xxreadtoken_tokens[] ALIGN1 = {
12210 TNL, TLP, TRP, /* only single occurrence allowed */
12211 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12212 TEOF, /* corresponds to trailing nul */
12213 TAND, TOR, TENDCASE /* if double occurrence */
12225 setprompt_if(needprompt, 2);
12226 startlinno = g_parsefile->linno;
12227 for (;;) { /* until token or start of word found */
12229 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12233 while ((c = pgetc()) != '\n' && c != PEOF)
12236 } else if (c == '\\') {
12237 if (pgetc() != '\n') {
12239 break; /* return readtoken1(...) */
12245 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12251 p = strchr(xxreadtoken_chars, c);
12253 break; /* return readtoken1(...) */
12255 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12257 if (cc == c) { /* double occurrence? */
12258 p += xxreadtoken_doubles + 1;
12261 #if BASH_REDIR_OUTPUT
12262 if (c == '&' && cc == '>') /* &> */
12263 break; /* return readtoken1(...) */
12268 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12273 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12275 #else /* old xxreadtoken */
12276 #define RETURN(token) return lasttoken = token
12286 setprompt_if(needprompt, 2);
12287 startlinno = g_parsefile->linno;
12288 for (;;) { /* until token or start of word found */
12291 case ' ': case '\t':
12292 IF_ASH_ALIAS(case PEOA:)
12295 while ((c = pgetc()) != '\n' && c != PEOF)
12300 if (pgetc() == '\n') {
12312 if (pgetc() == '&')
12317 if (pgetc() == '|')
12322 if (pgetc() == ';')
12335 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12338 #endif /* old xxreadtoken */
12344 int kwd = checkkwd;
12346 smallint alreadyseen = tokpushback;
12349 #if ENABLE_ASH_ALIAS
12365 if (t != TWORD || quoteflag) {
12370 * check for keywords
12372 if (kwd & CHKKWD) {
12373 const char *const *pp;
12375 pp = findkwd(wordtext);
12377 lasttoken = t = pp - tokname_array;
12378 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12383 if (checkkwd & CHKALIAS) {
12384 #if ENABLE_ASH_ALIAS
12386 ap = lookupalias(wordtext, 1);
12389 pushstring(ap->val, ap);
12399 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12401 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12417 * Read and parse a command. Returns NODE_EOF on end of file.
12418 * (NULL is a valid parse tree indicating a blank line.)
12420 static union node *
12421 parsecmd(int interact)
12426 doprompt = interact;
12427 setprompt_if(doprompt, doprompt);
12433 * Input any here documents.
12438 struct heredoc *here;
12441 here = heredoclist;
12442 heredoclist = NULL;
12445 setprompt_if(needprompt, 2);
12446 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12447 here->eofmark, here->striptabs);
12448 n = stzalloc(sizeof(struct narg));
12449 n->narg.type = NARG;
12450 /*n->narg.next = NULL; - stzalloc did it */
12451 n->narg.text = wordtext;
12452 n->narg.backquote = backquotelist;
12453 here->here->nhere.doc = n;
12460 * called by editline -- any expansions to the prompt should be added here.
12462 #if ENABLE_ASH_EXPAND_PRMT
12463 static const char *
12464 expandstr(const char *ps)
12469 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12470 * and token processing _can_ alter it (delete NULs etc). */
12471 setinputstring((char *)ps);
12473 saveprompt = doprompt;
12475 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12476 doprompt = saveprompt;
12480 n.narg.type = NARG;
12481 n.narg.next = NULL;
12482 n.narg.text = wordtext;
12483 n.narg.backquote = backquotelist;
12485 expandarg(&n, NULL, EXP_QUOTED);
12486 return stackblock();
12491 * Execute a command or commands contained in a string.
12494 evalstring(char *s, int flags)
12496 struct jmploc *volatile savehandler;
12497 struct jmploc jmploc;
12501 struct stackmark smark;
12506 setstackmark(&smark);
12509 /* On exception inside execution loop, we must popfile().
12510 * Try interactively:
12512 * command eval "a=b" # throws "is read only" error
12513 * "command BLTIN" is not supposed to abort (even in non-interactive use).
12514 * But if we skip popfile(), we hit EOF in eval's string, and exit.
12516 savehandler = exception_handler;
12517 ex = setjmp(jmploc.loc);
12520 exception_handler = &jmploc;
12522 while ((n = parsecmd(0)) != NODE_EOF) {
12525 i = evaltree(n, flags);
12528 popstackmark(&smark);
12533 popstackmark(&smark);
12537 exception_handler = savehandler;
12539 longjmp(exception_handler->loc, ex);
12545 * The eval command.
12547 static int FAST_FUNC
12548 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12557 STARTSTACKSTR(concat);
12559 concat = stack_putstr(p, concat);
12563 STPUTC(' ', concat);
12565 STPUTC('\0', concat);
12566 p = grabstackstr(concat);
12568 return evalstring(p, flags & EV_TESTED);
12574 * Read and execute commands.
12575 * "Top" is nonzero for the top level command loop;
12576 * it turns on prompting if the shell is interactive.
12582 struct stackmark smark;
12587 TRACE(("cmdloop(%d) called\n", top));
12591 setstackmark(&smark);
12594 showjobs(SHOW_CHANGED|SHOW_STDERR);
12597 if (iflag && top) {
12601 n = parsecmd(inter);
12603 if (DEBUG > 2 && debug && (n != NODE_EOF))
12606 if (n == NODE_EOF) {
12607 if (!top || numeof >= 50)
12609 if (!stoppedjobs()) {
12612 out2str("\nUse \"exit\" to leave shell.\n");
12615 } else if (nflag == 0) {
12618 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12621 i = evaltree(n, 0);
12625 popstackmark(&smark);
12629 evalskip &= ~SKIPFUNC;
12637 * Take commands from a file. To be compatible we should do a path
12638 * search for the file, which is necessary to find sub-commands.
12641 find_dot_file(char *name)
12644 const char *path = pathval();
12647 /* don't try this for absolute or relative paths */
12648 if (strchr(name, '/'))
12651 while ((fullname = path_advance(&path, name)) != NULL) {
12652 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12654 * Don't bother freeing here, since it will
12655 * be freed by the caller.
12659 if (fullname != name)
12660 stunalloc(fullname);
12663 /* not found in the PATH */
12664 ash_msg_and_raise_error("%s: not found", name);
12668 static int FAST_FUNC
12669 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12671 /* "false; . empty_file; echo $?" should print 0, not 1: */
12675 char *args_need_save;
12676 struct strlist *sp;
12677 volatile struct shparam saveparam;
12679 for (sp = cmdenviron; sp; sp = sp->next)
12680 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12682 nextopt(nullstr); /* handle possible "--" */
12686 /* bash says: "bash: .: filename argument required" */
12687 return 2; /* bash compat */
12690 /* This aborts if file isn't found, which is POSIXly correct.
12691 * bash returns exitcode 1 instead.
12693 fullname = find_dot_file(argv[0]);
12695 args_need_save = argv[0];
12696 if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
12698 saveparam = shellparam;
12699 shellparam.malloced = 0;
12703 shellparam.nparam = argc;
12704 shellparam.p = argv;
12707 /* This aborts if file can't be opened, which is POSIXly correct.
12708 * bash returns exitcode 1 instead.
12710 setinputfile(fullname, INPUT_PUSH_FILE);
12711 commandname = fullname;
12712 status = cmdloop(0);
12715 if (args_need_save) {
12716 freeparam(&shellparam);
12717 shellparam = saveparam;
12723 static int FAST_FUNC
12724 exitcmd(int argc UNUSED_PARAM, char **argv)
12729 exitstatus = number(argv[1]);
12730 raise_exception(EXEXIT);
12735 * Read a file containing shell functions.
12738 readcmdfile(char *name)
12740 setinputfile(name, INPUT_PUSH_FILE);
12746 /* ============ find_command inplementation */
12749 * Resolve a command name. If you change this routine, you may have to
12750 * change the shellexec routine as well.
12753 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12755 struct tblentry *cmdp;
12762 struct builtincmd *bcmd;
12764 /* If name contains a slash, don't use PATH or hash table */
12765 if (strchr(name, '/') != NULL) {
12766 entry->u.index = -1;
12767 if (act & DO_ABS) {
12768 while (stat(name, &statb) < 0) {
12770 if (errno == EINTR)
12773 entry->cmdtype = CMDUNKNOWN;
12777 entry->cmdtype = CMDNORMAL;
12781 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12783 updatetbl = (path == pathval());
12786 if (strstr(path, "%builtin") != NULL)
12787 act |= DO_ALTBLTIN;
12790 /* If name is in the table, check answer will be ok */
12791 cmdp = cmdlookup(name, 0);
12792 if (cmdp != NULL) {
12795 switch (cmdp->cmdtype) {
12813 } else if (cmdp->rehash == 0)
12814 /* if not invalidated by cd, we're done */
12818 /* If %builtin not in path, check for builtin next */
12819 bcmd = find_builtin(name);
12821 if (IS_BUILTIN_REGULAR(bcmd))
12822 goto builtin_success;
12823 if (act & DO_ALTPATH) {
12824 if (!(act & DO_ALTBLTIN))
12825 goto builtin_success;
12826 } else if (builtinloc <= 0) {
12827 goto builtin_success;
12831 #if ENABLE_FEATURE_SH_STANDALONE
12833 int applet_no = find_applet_by_name(name);
12834 if (applet_no >= 0) {
12835 entry->cmdtype = CMDNORMAL;
12836 entry->u.index = -2 - applet_no;
12842 /* We have to search path. */
12843 prev = -1; /* where to start */
12844 if (cmdp && cmdp->rehash) { /* doing a rehash */
12845 if (cmdp->cmdtype == CMDBUILTIN)
12848 prev = cmdp->param.index;
12854 while ((fullname = path_advance(&path, name)) != NULL) {
12855 stunalloc(fullname);
12856 /* NB: code below will still use fullname
12857 * despite it being "unallocated" */
12860 if (prefix(pathopt, "builtin")) {
12862 goto builtin_success;
12865 if ((act & DO_NOFUNC)
12866 || !prefix(pathopt, "func")
12867 ) { /* ignore unimplemented options */
12871 /* if rehash, don't redo absolute path names */
12872 if (fullname[0] == '/' && idx <= prev) {
12875 TRACE(("searchexec \"%s\": no change\n", name));
12878 while (stat(fullname, &statb) < 0) {
12880 if (errno == EINTR)
12883 if (errno != ENOENT && errno != ENOTDIR)
12887 e = EACCES; /* if we fail, this will be the error */
12888 if (!S_ISREG(statb.st_mode))
12890 if (pathopt) { /* this is a %func directory */
12891 stalloc(strlen(fullname) + 1);
12892 /* NB: stalloc will return space pointed by fullname
12893 * (because we don't have any intervening allocations
12894 * between stunalloc above and this stalloc) */
12895 readcmdfile(fullname);
12896 cmdp = cmdlookup(name, 0);
12897 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12898 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12899 stunalloc(fullname);
12902 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12904 entry->cmdtype = CMDNORMAL;
12905 entry->u.index = idx;
12909 cmdp = cmdlookup(name, 1);
12910 cmdp->cmdtype = CMDNORMAL;
12911 cmdp->param.index = idx;
12916 /* We failed. If there was an entry for this command, delete it */
12917 if (cmdp && updatetbl)
12918 delete_cmd_entry();
12920 ash_msg("%s: %s", name, errmsg(e, "not found"));
12921 entry->cmdtype = CMDUNKNOWN;
12926 entry->cmdtype = CMDBUILTIN;
12927 entry->u.cmd = bcmd;
12931 cmdp = cmdlookup(name, 1);
12932 cmdp->cmdtype = CMDBUILTIN;
12933 cmdp->param.cmd = bcmd;
12937 entry->cmdtype = cmdp->cmdtype;
12938 entry->u = cmdp->param;
12943 * The trap builtin.
12945 static int FAST_FUNC
12946 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12950 int signo, exitcode;
12955 for (signo = 0; signo < NSIG; signo++) {
12956 char *tr = trap_ptr[signo];
12958 /* note: bash adds "SIG", but only if invoked
12959 * as "bash". If called as "sh", or if set -o posix,
12960 * then it prints short signal names.
12961 * We are printing short names: */
12962 out1fmt("trap -- %s %s\n",
12964 get_signame(signo));
12965 /* trap_ptr != trap only if we are in special-cased `trap` code.
12966 * In this case, we will exit very soon, no need to free(). */
12967 /* if (trap_ptr != trap && tp[0]) */
12972 if (trap_ptr != trap) {
12985 signo = get_signum(*ap);
12987 /* Mimic bash message exactly */
12988 ash_msg("%s: invalid signal specification", *ap);
12994 if (LONE_DASH(action))
12997 if (action[0]) /* not NULL and not "" and not "-" */
12998 may_have_traps = 1;
12999 action = ckstrdup(action);
13003 trap[signo] = action;
13014 /* ============ Builtins */
13016 #if ENABLE_ASH_HELP
13017 static int FAST_FUNC
13018 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13024 "Built-in commands:\n"
13025 "------------------\n");
13026 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
13027 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
13028 builtintab[i].name + 1);
13034 # if ENABLE_FEATURE_SH_STANDALONE
13036 const char *a = applet_names;
13038 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
13043 while (*a++ != '\0')
13048 newline_and_flush(stdout);
13049 return EXIT_SUCCESS;
13054 static int FAST_FUNC
13055 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13057 show_history(line_input_state);
13058 return EXIT_SUCCESS;
13063 * The export and readonly commands.
13065 static int FAST_FUNC
13066 exportcmd(int argc UNUSED_PARAM, char **argv)
13076 /* "readonly" in bash accepts, but ignores -n.
13077 * We do the same: it saves a conditional in nextopt's param.
13080 while ((opt = nextopt("np")) != '\0') {
13082 flag_off = VEXPORT;
13085 if (argv[0][0] == 'r') {
13087 flag_off = 0; /* readonly ignores -n */
13089 flag_off = ~flag_off;
13091 /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
13097 p = strchr(name, '=');
13101 vp = *findvar(hashvar(name), name);
13103 vp->flags = ((vp->flags | flag) & flag_off);
13107 setvar(name, p, (flag & flag_off));
13108 } while ((name = *++aptr) != NULL);
13113 /* No arguments. Show the list of exported or readonly vars.
13116 showvars(argv[0], flag, 0);
13121 * Delete a function if it exists.
13124 unsetfunc(const char *name)
13126 struct tblentry *cmdp;
13128 cmdp = cmdlookup(name, 0);
13129 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
13130 delete_cmd_entry();
13134 * The unset builtin command. We unset the function before we unset the
13135 * variable to allow a function to be unset when there is a readonly variable
13136 * with the same name.
13138 static int FAST_FUNC
13139 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13146 while ((i = nextopt("vf")) != 0) {
13150 for (ap = argptr; *ap; ap++) {
13163 static const unsigned char timescmd_str[] ALIGN1 = {
13164 ' ', offsetof(struct tms, tms_utime),
13165 '\n', offsetof(struct tms, tms_stime),
13166 ' ', offsetof(struct tms, tms_cutime),
13167 '\n', offsetof(struct tms, tms_cstime),
13170 static int FAST_FUNC
13171 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13173 unsigned long clk_tck, s, t;
13174 const unsigned char *p;
13177 clk_tck = bb_clk_tck();
13182 t = *(clock_t *)(((char *) &buf) + p[1]);
13185 out1fmt("%lum%lu.%03lus%c",
13187 (t * 1000) / clk_tck,
13195 #if ENABLE_FEATURE_SH_MATH
13197 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13198 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13200 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13202 static int FAST_FUNC
13203 letcmd(int argc UNUSED_PARAM, char **argv)
13209 ash_msg_and_raise_error("expression expected");
13211 i = ash_arith(*argv);
13219 * The read builtin. Options:
13220 * -r Do not interpret '\' specially
13221 * -s Turn off echo (tty only)
13222 * -n NCHARS Read NCHARS max
13223 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13224 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13225 * -u FD Read from given FD instead of fd 0
13226 * This uses unbuffered input, which may be avoidable in some cases.
13227 * TODO: bash also has:
13228 * -a ARRAY Read into array[0],[1],etc
13229 * -d DELIM End on DELIM char, not newline
13230 * -e Use line editing (tty only)
13232 static int FAST_FUNC
13233 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13235 char *opt_n = NULL;
13236 char *opt_p = NULL;
13237 char *opt_t = NULL;
13238 char *opt_u = NULL;
13239 int read_flags = 0;
13243 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
13252 read_flags |= BUILTIN_READ_SILENT;
13258 read_flags |= BUILTIN_READ_RAW;
13268 /* "read -s" needs to save/restore termios, can't allow ^C
13269 * to jump out of it.
13273 r = shell_builtin_read(setvar0,
13275 bltinlookup("IFS"), /* can be NULL */
13284 if ((uintptr_t)r == 1 && errno == EINTR) {
13285 /* to get SIGCHLD: sleep 1 & read x; echo $x */
13286 if (pending_sig == 0)
13290 if ((uintptr_t)r > 1)
13291 ash_msg_and_raise_error(r);
13293 return (uintptr_t)r;
13296 static int FAST_FUNC
13297 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13299 static const char permuser[3] ALIGN1 = "ogu";
13302 int symbolic_mode = 0;
13304 while (nextopt("S") != '\0') {
13313 if (*argptr == NULL) {
13314 if (symbolic_mode) {
13315 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13322 *p++ = permuser[i];
13324 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13325 if (!(mask & 0400)) *p++ = 'r';
13326 if (!(mask & 0200)) *p++ = 'w';
13327 if (!(mask & 0100)) *p++ = 'x';
13335 out1fmt("%04o\n", mask);
13338 char *modestr = *argptr;
13339 /* numeric umasks are taken as-is */
13340 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13341 if (!isdigit(modestr[0]))
13343 mask = bb_parse_mode(modestr, mask);
13344 if ((unsigned)mask > 0777) {
13345 ash_msg_and_raise_error("illegal mode: %s", modestr);
13347 if (!isdigit(modestr[0]))
13354 static int FAST_FUNC
13355 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13357 return shell_builtin_ulimit(argv);
13360 /* ============ main() and helpers */
13363 * Called to exit the shell.
13372 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13373 save_history(line_input_state);
13375 status = exitstatus;
13376 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13377 if (setjmp(loc.loc)) {
13378 if (exception_type == EXEXIT)
13379 status = exitstatus;
13382 exception_handler = &loc;
13388 /*free(p); - we'll exit soon */
13391 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13392 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13395 flush_stdout_stderr();
13403 /* we will never free this */
13404 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13406 sigmode[SIGCHLD - 1] = S_DFL;
13407 setsignal(SIGCHLD);
13409 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13410 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13412 signal(SIGHUP, SIG_DFL);
13417 struct stat st1, st2;
13420 for (envp = environ; envp && *envp; envp++) {
13421 p = endofname(*envp);
13422 if (p != *envp && *p == '=') {
13423 setvareq(*envp, VEXPORT|VTEXTFIXED);
13427 setvareq((char*)defoptindvar, VTEXTFIXED);
13429 setvar0("PPID", utoa(getppid()));
13431 p = lookupvar("SHLVL");
13432 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13434 #if BASH_HOSTNAME_VAR
13435 if (!lookupvar("HOSTNAME")) {
13436 struct utsname uts;
13438 setvar0("HOSTNAME", uts.nodename);
13441 p = lookupvar("PWD");
13443 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13444 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13454 //usage:#define ash_trivial_usage
13455 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13456 //usage:#define ash_full_usage "\n\n"
13457 //usage: "Unix shell interpreter"
13460 * Process the shell command line arguments.
13463 procargs(char **argv)
13466 const char *xminusc;
13471 /* if (xargv[0]) - mmm, this is always true! */
13473 for (i = 0; i < NOPTS; i++)
13476 if (options(/*cmdline:*/ 1)) {
13477 /* it already printed err message */
13478 raise_exception(EXERROR);
13482 if (*xargv == NULL) {
13484 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13487 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13491 for (i = 0; i < NOPTS; i++)
13492 if (optlist[i] == 2)
13497 /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
13502 } else if (!sflag) {
13503 setinputfile(*xargv, 0);
13506 commandname = arg0;
13509 shellparam.p = xargv;
13510 #if ENABLE_ASH_GETOPTS
13511 shellparam.optind = 1;
13512 shellparam.optoff = -1;
13514 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13516 shellparam.nparam++;
13523 * Read /etc/profile, ~/.profile, $ENV.
13526 read_profile(const char *name)
13528 name = expandstr(name);
13529 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13536 * This routine is called when an error or an interrupt occurs in an
13537 * interactive shell and control is returned to the main command loop.
13538 * (In dash, this function is auto-generated by build machinery).
13547 /* from expand.c: */
13550 /* from input.c: */
13551 g_parsefile->left_in_buffer = 0;
13552 g_parsefile->left_in_line = 0; /* clear input buffer */
13555 /* from redir.c: */
13557 popredir(/*drop:*/ 0, /*restore:*/ 0);
13561 static short profile_buf[16384];
13562 extern int etext();
13566 * Main routine. We initialize things, parse the arguments, execute
13567 * profiles if we're a login shell, and then call cmdloop to execute
13568 * commands. The setjmp call sets up the location to jump to when an
13569 * exception occurs. When an exception occurs the variable "state"
13570 * is used to figure out how far we had gotten.
13572 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13573 int ash_main(int argc UNUSED_PARAM, char **argv)
13575 volatile smallint state;
13576 struct jmploc jmploc;
13577 struct stackmark smark;
13579 /* Initialize global data */
13583 #if ENABLE_ASH_ALIAS
13589 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13592 #if ENABLE_FEATURE_EDITING
13593 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13596 if (setjmp(jmploc.loc)) {
13602 e = exception_type;
13604 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13608 newline_and_flush(stderr);
13611 popstackmark(&smark);
13612 FORCE_INT_ON; /* enable interrupts */
13621 exception_handler = &jmploc;
13622 rootpid = getpid();
13625 setstackmark(&smark);
13628 TRACE(("Shell args: "));
13629 trace_puts_args(argv);
13632 if (argv[0] && argv[0][0] == '-')
13638 read_profile("/etc/profile");
13641 hp = lookupvar("HOME");
13643 read_profile("$HOME/.profile");
13649 getuid() == geteuid() && getgid() == getegid() &&
13653 const char *shinit = lookupvar("ENV");
13654 if (shinit != NULL && *shinit != '\0')
13655 read_profile(shinit);
13657 popstackmark(&smark);
13661 /* evalstring pushes parsefile stack.
13662 * Ensure we don't falsely claim that 0 (stdin)
13663 * is one of stacked source fds.
13664 * Testcase: ash -c 'exec 1>&0' must not complain. */
13665 // if (!sflag) g_parsefile->pf_fd = -1;
13666 // ^^ not necessary since now we special-case fd 0
13667 // in is_hidden_fd() to not be considered "hidden fd"
13668 evalstring(minusc, 0);
13671 if (sflag || minusc == NULL) {
13672 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13674 const char *hp = lookupvar("HISTFILE");
13676 hp = lookupvar("HOME");
13679 hp = concat_path_file(hp, ".ash_history");
13680 setvar0("HISTFILE", hp);
13683 hp = lookupvar("HISTFILE");
13687 line_input_state->hist_file = hp;
13688 # if ENABLE_FEATURE_SH_HISTFILESIZE
13689 hp = lookupvar("HISTFILESIZE");
13690 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13694 state4: /* XXX ??? - why isn't this before the "if" statement */
13702 extern void _mcleanup(void);
13706 TRACE(("End of main reached\n"));
13713 * Copyright (c) 1989, 1991, 1993, 1994
13714 * The Regents of the University of California. All rights reserved.
13716 * This code is derived from software contributed to Berkeley by
13717 * Kenneth Almquist.
13719 * Redistribution and use in source and binary forms, with or without
13720 * modification, are permitted provided that the following conditions
13722 * 1. Redistributions of source code must retain the above copyright
13723 * notice, this list of conditions and the following disclaimer.
13724 * 2. Redistributions in binary form must reproduce the above copyright
13725 * notice, this list of conditions and the following disclaimer in the
13726 * documentation and/or other materials provided with the distribution.
13727 * 3. Neither the name of the University nor the names of its contributors
13728 * may be used to endorse or promote products derived from this software
13729 * without specific prior written permission.
13731 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13732 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13733 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13734 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13735 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13736 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13737 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13738 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13739 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13740 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF