1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * This code is derived from software contributed to Berkeley by
8 * Original BSD copyright notice is retained at the end of this file.
10 * Copyright (c) 1989, 1991, 1993, 1994
11 * The Regents of the University of California. All rights reserved.
13 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
14 * was re-ported from NetBSD and debianized.
16 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
19 //config: bool "ash (77 kb)"
21 //config: depends on !NOMMU
23 //config: The most complete and most pedantically correct shell included with
24 //config: busybox. This shell is actually a derivative of the Debian 'dash'
25 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
26 //config: (written by Kenneth Almquist) from NetBSD.
28 //config:# ash options
29 //config:# note: Don't remove !NOMMU part in the next line; it would break
30 //config:# menuconfig's indenting.
31 //config:if !NOMMU && (ASH || SH_IS_ASH || BASH_IS_ASH)
33 //config:config ASH_OPTIMIZE_FOR_SIZE
34 //config: bool "Optimize for size instead of speed"
36 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
38 //config:config ASH_INTERNAL_GLOB
39 //config: bool "Use internal glob() implementation"
40 //config: default y # Y is bigger, but because of uclibc glob() bug, let Y be default for now
41 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
43 //config: Do not use glob() function from libc, use internal implementation.
44 //config: Use this if you are getting "glob.h: No such file or directory"
45 //config: or similar build errors.
46 //config: Note that as of now (2017-01), uclibc and musl glob() both have bugs
47 //config: which would break ash if you select N here.
49 //config:config ASH_BASH_COMPAT
50 //config: bool "bash-compatible extensions"
52 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
54 //config:config ASH_JOB_CONTROL
55 //config: bool "Job control"
57 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
59 //config:config ASH_ALIAS
60 //config: bool "Alias support"
62 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
64 //config:config ASH_RANDOM_SUPPORT
65 //config: bool "Pseudorandom generator and $RANDOM variable"
67 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
69 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
70 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
71 //config: You can reset the generator by using a specified start value.
72 //config: After "unset RANDOM" the generator will switch off and this
73 //config: variable will no longer have special treatment.
75 //config:config ASH_EXPAND_PRMT
76 //config: bool "Expand prompt string"
78 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
80 //config: $PS# may contain volatile content, such as backquote commands.
81 //config: This option recreates the prompt string from the environment
82 //config: variable each time it is displayed.
84 //config:config ASH_IDLE_TIMEOUT
85 //config: bool "Idle timeout variable $TMOUT"
87 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
89 //config: Enable bash-like auto-logout after $TMOUT seconds of idle time.
91 //config:config ASH_MAIL
92 //config: bool "Check for new mail in interactive shell"
94 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
96 //config: Enable "check for new mail" function:
97 //config: if set, $MAIL file and $MAILPATH list of files
98 //config: are checked for mtime changes, and "you have mail"
99 //config: message is printed if change is detected.
101 //config:config ASH_ECHO
102 //config: bool "echo builtin"
104 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
106 //config:config ASH_PRINTF
107 //config: bool "printf builtin"
109 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
111 //config:config ASH_TEST
112 //config: bool "test builtin"
114 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
116 //config:config ASH_HELP
117 //config: bool "help builtin"
119 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
121 //config:config ASH_GETOPTS
122 //config: bool "getopts builtin"
124 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
126 //config:config ASH_CMDCMD
127 //config: bool "command builtin"
129 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
131 //config: Enable support for the 'command' builtin, which allows
132 //config: you to run the specified command or builtin,
133 //config: even when there is a function with the same name.
135 //config:endif # ash options
137 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
138 // APPLET_ODDNAME:name main location suid_type help
139 //applet:IF_SH_IS_ASH( APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
140 //applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
142 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
143 //kbuild:lib-$(CONFIG_SH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
144 //kbuild:lib-$(CONFIG_BASH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
145 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
148 * DEBUG=1 to compile in debugging ('set -o debug' turns on)
149 * DEBUG=2 to compile in and turn on debugging.
150 * When debugging is on ("set -o debug" was executed, or DEBUG=2),
151 * debugging info is written to ./trace, quit signal generates core dump.
154 /* Tweak debug output verbosity here */
158 #define DEBUG_INTONOFF 0
162 #define JOBS ENABLE_ASH_JOB_CONTROL
166 #include <sys/times.h>
167 #include <sys/utsname.h> /* for setting $HOSTNAME */
168 #include "busybox.h" /* for applet_names */
170 /* So far, all bash compat is controlled by one config option */
171 /* Separate defines document which part of code implements what */
172 /* function keyword */
173 #define BASH_FUNCTION ENABLE_ASH_BASH_COMPAT
174 #define IF_BASH_FUNCTION IF_ASH_BASH_COMPAT
176 #define BASH_REDIR_OUTPUT ENABLE_ASH_BASH_COMPAT
177 #define IF_BASH_REDIR_OUTPUT IF_ASH_BASH_COMPAT
179 #define BASH_DOLLAR_SQUOTE ENABLE_ASH_BASH_COMPAT
180 #define IF_BASH_DOLLAR_SQUOTE IF_ASH_BASH_COMPAT
181 #define BASH_PATTERN_SUBST ENABLE_ASH_BASH_COMPAT
182 #define IF_BASH_PATTERN_SUBST IF_ASH_BASH_COMPAT
183 #define BASH_SUBSTR ENABLE_ASH_BASH_COMPAT
184 #define IF_BASH_SUBSTR IF_ASH_BASH_COMPAT
186 #define BASH_TEST2 (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)
187 #define BASH_SOURCE ENABLE_ASH_BASH_COMPAT
188 #define BASH_PIPEFAIL ENABLE_ASH_BASH_COMPAT
189 #define BASH_HOSTNAME_VAR ENABLE_ASH_BASH_COMPAT
190 #define BASH_SHLVL_VAR ENABLE_ASH_BASH_COMPAT
191 #define BASH_XTRACEFD ENABLE_ASH_BASH_COMPAT
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 typedef long arith_t;
220 # define ARITH_FMT "%ld"
222 #if ENABLE_ASH_RANDOM_SUPPORT
225 # define CLEAR_RANDOM_T(rnd) ((void)0)
228 #include "NUM_APPLETS.h"
230 /* STANDALONE does not make sense, and won't compile */
231 # undef CONFIG_FEATURE_SH_STANDALONE
232 # undef ENABLE_FEATURE_SH_STANDALONE
233 # undef IF_FEATURE_SH_STANDALONE
234 # undef IF_NOT_FEATURE_SH_STANDALONE
235 # define ENABLE_FEATURE_SH_STANDALONE 0
236 # define IF_FEATURE_SH_STANDALONE(...)
237 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
241 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
245 # error "Do not even bother, ash will not run on NOMMU machine"
249 /* ============ Hash table sizes. Configurable. */
253 #define CMDTABLESIZE 31 /* should be prime */
256 /* ============ Shell options */
258 static const char *const optletters_optnames[] = {
282 #define optletters(n) optletters_optnames[n][0]
283 #define optnames(n) (optletters_optnames[n] + 1)
285 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
288 /* ============ Misc data */
290 #define msg_illnum "Illegal number: %s"
293 * We enclose jmp_buf in a structure so that we can declare pointers to
294 * jump locations. The global variable handler contains the location to
295 * jump to when an exception occurs, and the global variable exception_type
296 * contains a code identifying the exception. To implement nested
297 * exception handlers, the user should save the value of handler on entry
298 * to an inner scope, set handler to point to a jmploc structure for the
299 * inner scope, and restore handler on exit from the scope.
305 struct globals_misc {
306 uint8_t exitstatus; /* exit status of last command */
307 uint8_t back_exitstatus;/* exit status of backquoted command */
308 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
309 int rootpid; /* pid of main shell */
310 /* shell level: 0 for the main shell, 1 for its children, and so on */
312 #define rootshell (!shlvl)
313 char *minusc; /* argument to -c option */
315 char *curdir; // = nullstr; /* current working directory */
316 char *physdir; // = nullstr; /* physical working directory */
318 char *arg0; /* value of $0 */
320 struct jmploc *exception_handler;
322 volatile int suppress_int; /* counter */
323 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
324 volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
325 volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
326 smallint exception_type; /* kind of exception (0..5) */
328 #define EXINT 0 /* SIGINT received */
329 #define EXERROR 1 /* a generic error */
330 #define EXEXIT 4 /* exit the shell */
332 char nullstr[1]; /* zero length string */
335 #define eflag optlist[0]
336 #define fflag optlist[1]
337 #define Iflag optlist[2]
338 #define iflag optlist[3]
339 #define mflag optlist[4]
340 #define nflag optlist[5]
341 #define sflag optlist[6]
342 #define xflag optlist[7]
343 #define vflag optlist[8]
344 #define Cflag optlist[9]
345 #define aflag optlist[10]
346 #define bflag optlist[11]
347 #define uflag optlist[12]
348 #define viflag optlist[13]
350 # define pipefail optlist[14]
355 # define nolog optlist[14 + BASH_PIPEFAIL]
356 # define debug optlist[15 + BASH_PIPEFAIL]
359 /* trap handler commands */
361 * Sigmode records the current value of the signal handlers for the various
362 * modes. A value of zero means that the current handler is not known.
363 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
365 char sigmode[NSIG - 1];
366 #define S_DFL 1 /* default signal handling (SIG_DFL) */
367 #define S_CATCH 2 /* signal is caught */
368 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
369 #define S_HARD_IGN 4 /* signal is ignored permanently (it was SIG_IGN on entry to shell) */
371 /* indicates specified signal received */
372 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
373 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
375 char **trap_ptr; /* used only by "trap hack" */
377 /* Rarely referenced stuff */
378 #if ENABLE_ASH_RANDOM_SUPPORT
381 pid_t backgndpid; /* pid of last background process */
383 extern struct globals_misc *const ash_ptr_to_globals_misc;
384 #define G_misc (*ash_ptr_to_globals_misc)
385 #define exitstatus (G_misc.exitstatus )
386 #define back_exitstatus (G_misc.back_exitstatus )
387 #define job_warning (G_misc.job_warning)
388 #define rootpid (G_misc.rootpid )
389 #define shlvl (G_misc.shlvl )
390 #define minusc (G_misc.minusc )
391 #define curdir (G_misc.curdir )
392 #define physdir (G_misc.physdir )
393 #define arg0 (G_misc.arg0 )
394 #define exception_handler (G_misc.exception_handler)
395 #define exception_type (G_misc.exception_type )
396 #define suppress_int (G_misc.suppress_int )
397 #define pending_int (G_misc.pending_int )
398 #define got_sigchld (G_misc.got_sigchld )
399 #define pending_sig (G_misc.pending_sig )
400 #define nullstr (G_misc.nullstr )
401 #define optlist (G_misc.optlist )
402 #define sigmode (G_misc.sigmode )
403 #define gotsig (G_misc.gotsig )
404 #define may_have_traps (G_misc.may_have_traps )
405 #define trap (G_misc.trap )
406 #define trap_ptr (G_misc.trap_ptr )
407 #define random_gen (G_misc.random_gen )
408 #define backgndpid (G_misc.backgndpid )
409 #define INIT_G_misc() do { \
410 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
418 /* ============ DEBUG */
420 static void trace_printf(const char *fmt, ...);
421 static void trace_vprintf(const char *fmt, va_list va);
422 # define TRACE(param) trace_printf param
423 # define TRACEV(param) trace_vprintf param
424 # define close(fd) do { \
426 if (close(dfd) < 0) \
427 bb_error_msg("bug on %d: closing %d(0x%x)", \
428 __LINE__, dfd, dfd); \
431 # define TRACE(param)
432 # define TRACEV(param)
436 /* ============ Utility functions */
437 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
438 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
441 isdigit_str9(const char *str)
443 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
444 while (--maxlen && isdigit(*str))
446 return (*str == '\0');
450 var_end(const char *var)
459 /* ============ Interrupts / exceptions */
461 static void exitshell(void) NORETURN;
464 * These macros allow the user to suspend the handling of interrupt signals
465 * over a period of time. This is similar to SIGHOLD or to sigblock, but
466 * much more efficient and portable. (But hacking the kernel is so much
467 * more fun than worrying about efficiency and portability. :-))
470 # define INT_OFF do { \
471 TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
476 # define INT_OFF do { \
483 * Called to raise an exception. Since C doesn't include exceptions, we
484 * just do a longjmp to the exception handler. The type of exception is
485 * stored in the global variable "exception_type".
487 static void raise_exception(int) NORETURN;
489 raise_exception(int e)
492 if (exception_handler == NULL)
497 longjmp(exception_handler->loc, 1);
500 #define raise_exception(e) do { \
501 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
502 raise_exception(e); \
507 * Called when a SIGINT is received. (If the user specifies
508 * that SIGINT is to be trapped or ignored using the trap builtin, then
509 * this routine is not called.) Suppressint is nonzero when interrupts
510 * are held using the INT_OFF macro. (The test for iflag is just
511 * defensive programming.)
513 static void raise_interrupt(void) NORETURN;
515 raise_interrupt(void)
518 /* Signal is not automatically unmasked after it is raised,
519 * do it ourself - unmask all signals */
520 sigprocmask_allsigs(SIG_UNBLOCK);
521 /* pending_sig = 0; - now done in signal_handler() */
523 if (!(rootshell && iflag)) {
524 /* Kill ourself with SIGINT */
525 signal(SIGINT, SIG_DFL);
528 /* bash: ^C even on empty command line sets $? */
529 exitstatus = SIGINT + 128;
530 raise_exception(EXINT);
534 #define raise_interrupt() do { \
535 TRACE(("raising interrupt on line %d\n", __LINE__)); \
540 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
544 if (--suppress_int == 0 && pending_int) {
549 # define INT_ON do { \
550 TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
554 # define INT_ON int_on()
556 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
564 #define FORCE_INT_ON force_int_on()
566 #define SAVE_INT(v) ((v) = suppress_int)
568 #define RESTORE_INT(v) do { \
570 suppress_int = (v); \
571 if (suppress_int == 0 && pending_int) \
576 /* ============ Stdout/stderr output */
579 outstr(const char *p, FILE *file)
587 flush_stdout_stderr(void)
594 /* Was called outcslow(c,FILE*), but c was always '\n' */
596 newline_and_flush(FILE *dest)
604 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
606 out1fmt(const char *fmt, ...)
613 r = vprintf(fmt, ap);
619 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
621 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
628 ret = vsnprintf(outbuf, length, fmt, ap);
635 out1str(const char *p)
641 out2str(const char *p)
644 flush_stdout_stderr();
648 /* ============ Parser structures */
650 /* control characters in argument strings */
651 #define CTL_FIRST CTLESC
652 #define CTLESC ((unsigned char)'\201') /* escape next character */
653 #define CTLVAR ((unsigned char)'\202') /* variable defn */
654 #define CTLENDVAR ((unsigned char)'\203')
655 #define CTLBACKQ ((unsigned char)'\204')
656 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
657 #define CTLENDARI ((unsigned char)'\207')
658 #define CTLQUOTEMARK ((unsigned char)'\210')
659 #define CTL_LAST CTLQUOTEMARK
661 /* variable substitution byte (follows CTLVAR) */
662 #define VSTYPE 0x0f /* type of variable substitution */
663 #define VSNUL 0x10 /* colon--treat the empty string as unset */
665 /* values of VSTYPE field */
666 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
667 #define VSMINUS 0x2 /* ${var-text} */
668 #define VSPLUS 0x3 /* ${var+text} */
669 #define VSQUESTION 0x4 /* ${var?message} */
670 #define VSASSIGN 0x5 /* ${var=text} */
671 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
672 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
673 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
674 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
675 #define VSLENGTH 0xa /* ${#var} */
677 #define VSSUBSTR 0xc /* ${var:position:length} */
679 #if BASH_PATTERN_SUBST
680 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
681 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
684 static const char dolatstr[] ALIGN1 = {
685 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
687 #define DOLATSTRLEN 6
706 #if BASH_REDIR_OUTPUT
723 smallint type; /* Nxxxx */
726 union node *redirect;
731 smallint pipe_backgnd;
732 struct nodelist *cmdlist;
738 union node *redirect;
751 union node *elsepart;
778 struct nodelist *backquote;
781 /* nfile and ndup layout must match!
782 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
783 * that it is actually NTO2 (>&file), and change its type.
800 char *_unused_expfname;
819 struct nredir nredir;
820 struct nbinary nbinary;
824 struct nclist nclist;
833 * NODE_EOF is returned by parsecmd when it encounters an end of file.
834 * It must be distinct from NULL.
836 #define NODE_EOF ((union node *) -1L)
839 struct nodelist *next;
852 freefunc(struct funcnode *f)
854 if (f && --f->count < 0)
859 /* ============ Debugging output */
863 static FILE *tracefile;
866 trace_printf(const char *fmt, ...)
873 fprintf(tracefile, "%u ", (int) time(NULL));
875 fprintf(tracefile, "[%u] ", (int) getpid());
877 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
879 vfprintf(tracefile, fmt, va);
884 trace_vprintf(const char *fmt, va_list va)
888 vfprintf(tracefile, fmt, va);
889 fprintf(tracefile, "\n");
893 trace_puts(const char *s)
901 trace_puts_quoted(char *s)
908 putc('"', tracefile);
909 for (p = s; *p; p++) {
910 switch ((unsigned char)*p) {
911 case '\n': c = 'n'; goto backslash;
912 case '\t': c = 't'; goto backslash;
913 case '\r': c = 'r'; goto backslash;
914 case '\"': c = '\"'; goto backslash;
915 case '\\': c = '\\'; goto backslash;
916 case CTLESC: c = 'e'; goto backslash;
917 case CTLVAR: c = 'v'; goto backslash;
918 case CTLBACKQ: c = 'q'; goto backslash;
920 putc('\\', tracefile);
924 if (*p >= ' ' && *p <= '~')
927 putc('\\', tracefile);
928 putc((*p >> 6) & 03, tracefile);
929 putc((*p >> 3) & 07, tracefile);
930 putc(*p & 07, tracefile);
935 putc('"', tracefile);
939 trace_puts_args(char **ap)
946 trace_puts_quoted(*ap);
948 putc('\n', tracefile);
951 putc(' ', tracefile);
966 /* leave open because libedit might be using it */
969 strcpy(s, "./trace");
971 if (!freopen(s, "a", tracefile)) {
972 fprintf(stderr, "Can't re-open %s\n", s);
977 tracefile = fopen(s, "a");
978 if (tracefile == NULL) {
979 fprintf(stderr, "Can't open %s\n", s);
985 flags = fcntl(fileno(tracefile), F_GETFL);
987 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
989 setlinebuf(tracefile);
990 fputs("\nTracing started.\n", tracefile);
994 indent(int amount, char *pfx, FILE *fp)
998 for (i = 0; i < amount; i++) {
999 if (pfx && i == amount - 1)
1005 /* little circular references here... */
1006 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
1009 sharg(union node *arg, FILE *fp)
1012 struct nodelist *bqlist;
1013 unsigned char subtype;
1015 if (arg->type != NARG) {
1016 out1fmt("<node type %d>\n", arg->type);
1019 bqlist = arg->narg.backquote;
1020 for (p = arg->narg.text; *p; p++) {
1021 switch ((unsigned char)*p) {
1030 if (subtype == VSLENGTH)
1038 if (subtype & VSNUL)
1041 switch (subtype & VSTYPE) {
1067 case VSTRIMRIGHTMAX:
1074 out1fmt("<subtype %d>", subtype);
1083 shtree(bqlist->n, -1, NULL, fp);
1094 shcmd(union node *cmd, FILE *fp)
1102 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1108 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1112 switch (np->nfile.type) {
1113 case NTO: s = ">>"+1; dftfd = 1; break;
1114 case NCLOBBER: s = ">|"; dftfd = 1; break;
1115 case NAPPEND: s = ">>"; dftfd = 1; break;
1116 #if BASH_REDIR_OUTPUT
1119 case NTOFD: s = ">&"; dftfd = 1; break;
1120 case NFROM: s = "<"; break;
1121 case NFROMFD: s = "<&"; break;
1122 case NFROMTO: s = "<>"; break;
1123 default: s = "*error*"; break;
1125 if (np->nfile.fd != dftfd)
1126 fprintf(fp, "%d", np->nfile.fd);
1128 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1129 fprintf(fp, "%d", np->ndup.dupfd);
1131 sharg(np->nfile.fname, fp);
1138 shtree(union node *n, int ind, char *pfx, FILE *fp)
1140 struct nodelist *lp;
1146 indent(ind, pfx, fp);
1148 if (n == NODE_EOF) {
1163 shtree(n->nbinary.ch1, ind, NULL, fp);
1166 shtree(n->nbinary.ch2, ind, NULL, fp);
1174 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1175 shtree(lp->n, 0, NULL, fp);
1179 if (n->npipe.pipe_backgnd)
1185 fprintf(fp, "<node type %d>", n->type);
1193 showtree(union node *n)
1195 trace_puts("showtree called\n");
1196 shtree(n, 1, NULL, stderr);
1202 /* ============ Parser data */
1205 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1208 struct strlist *next;
1215 struct strpush *prev; /* preceding string on stack */
1217 int prev_left_in_line;
1218 #if ENABLE_ASH_ALIAS
1219 struct alias *ap; /* if push was associated with an alias */
1221 char *string; /* remember the string since it may change */
1223 /* Remember last two characters for pungetc. */
1226 /* Number of outstanding calls to pungetc. */
1231 struct parsefile *prev; /* preceding file on stack */
1232 int linno; /* current line */
1233 int pf_fd; /* file descriptor (or -1 if string) */
1234 int left_in_line; /* number of chars left in this line */
1235 int left_in_buffer; /* number of chars left in this buffer past the line */
1236 char *next_to_pgetc; /* next char in buffer */
1237 char *buf; /* input buffer */
1238 struct strpush *strpush; /* for pushing strings at this level */
1239 struct strpush basestrpush; /* so pushing one is fast */
1241 /* Remember last two characters for pungetc. */
1244 /* Number of outstanding calls to pungetc. */
1248 static struct parsefile basepf; /* top level input file */
1249 static struct parsefile *g_parsefile = &basepf; /* current input file */
1250 static int startlinno; /* line # where last token started */
1251 static char *commandname; /* currently executing 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);
1309 * Use '%m' to append error string on platforms that support it, '%s' and
1310 * strerror() on those that don't.
1312 * 'fmt' must be a string literal.
1314 #ifdef HAVE_PRINTF_PERCENTM
1315 #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": %m", ##__VA_ARGS__)
1317 #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": %s", ##__VA_ARGS__, strerror(errno))
1320 static void raise_error_syntax(const char *) NORETURN;
1322 raise_error_syntax(const char *msg)
1324 ash_msg_and_raise_error("syntax error: %s", msg);
1328 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1330 ash_msg_and_raise(int cond, const char *msg, ...)
1335 ash_vmsg_and_raise(cond, msg, ap);
1341 * error/warning routines for external builtins
1344 ash_msg(const char *fmt, ...)
1354 * Return a string describing an error. The returned string may be a
1355 * pointer to a static buffer that will be overwritten on the next call.
1356 * Action describes the operation that got the error.
1359 errmsg(int e, const char *em)
1361 if (e == ENOENT || e == ENOTDIR) {
1368 /* ============ Memory allocation */
1371 /* I consider these wrappers nearly useless:
1372 * ok, they return you to nearest exception handler, but
1373 * how much memory do you leak in the process, making
1374 * memory starvation worse?
1377 ckrealloc(void * p, size_t nbytes)
1379 p = realloc(p, nbytes);
1381 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1386 ckmalloc(size_t nbytes)
1388 return ckrealloc(NULL, nbytes);
1392 ckzalloc(size_t nbytes)
1394 return memset(ckmalloc(nbytes), 0, nbytes);
1398 ckstrdup(const char *s)
1400 char *p = strdup(s);
1402 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1406 /* Using bbox equivalents. They exit if out of memory */
1407 # define ckrealloc xrealloc
1408 # define ckmalloc xmalloc
1409 # define ckzalloc xzalloc
1410 # define ckstrdup xstrdup
1414 * It appears that grabstackstr() will barf with such alignments
1415 * because stalloc() will return a string allocated in a new stackblock.
1417 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1419 /* Most machines require the value returned from malloc to be aligned
1420 * in some way. The following macro will get this right
1421 * on many machines. */
1422 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1423 /* Minimum size of a block */
1424 MINSIZE = SHELL_ALIGN(504),
1427 struct stack_block {
1428 struct stack_block *prev;
1429 char space[MINSIZE];
1433 struct stack_block *stackp;
1439 struct globals_memstack {
1440 struct stack_block *g_stackp; // = &stackbase;
1441 char *g_stacknxt; // = stackbase.space;
1442 char *sstrend; // = stackbase.space + MINSIZE;
1443 size_t g_stacknleft; // = MINSIZE;
1444 struct stack_block stackbase;
1446 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1447 #define G_memstack (*ash_ptr_to_globals_memstack)
1448 #define g_stackp (G_memstack.g_stackp )
1449 #define g_stacknxt (G_memstack.g_stacknxt )
1450 #define sstrend (G_memstack.sstrend )
1451 #define g_stacknleft (G_memstack.g_stacknleft)
1452 #define stackbase (G_memstack.stackbase )
1453 #define INIT_G_memstack() do { \
1454 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1456 g_stackp = &stackbase; \
1457 g_stacknxt = stackbase.space; \
1458 g_stacknleft = MINSIZE; \
1459 sstrend = stackbase.space + MINSIZE; \
1463 #define stackblock() ((void *)g_stacknxt)
1464 #define stackblocksize() g_stacknleft
1467 * Parse trees for commands are allocated in lifo order, so we use a stack
1468 * to make this more efficient, and also to avoid all sorts of exception
1469 * handling code to handle interrupts in the middle of a parse.
1471 * The size 504 was chosen because the Ultrix malloc handles that size
1475 stalloc(size_t nbytes)
1480 aligned = SHELL_ALIGN(nbytes);
1481 if (aligned > g_stacknleft) {
1484 struct stack_block *sp;
1486 blocksize = aligned;
1487 if (blocksize < MINSIZE)
1488 blocksize = MINSIZE;
1489 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1490 if (len < blocksize)
1491 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1494 sp->prev = g_stackp;
1495 g_stacknxt = sp->space;
1496 g_stacknleft = blocksize;
1497 sstrend = g_stacknxt + blocksize;
1502 g_stacknxt += aligned;
1503 g_stacknleft -= aligned;
1508 stzalloc(size_t nbytes)
1510 return memset(stalloc(nbytes), 0, nbytes);
1517 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1518 write(STDERR_FILENO, "stunalloc\n", 10);
1522 g_stacknleft += g_stacknxt - (char *)p;
1527 * Like strdup but works with the ash stack.
1530 sstrdup(const char *p)
1532 size_t len = strlen(p) + 1;
1533 return memcpy(stalloc(len), p, len);
1537 grabstackblock(size_t len)
1543 pushstackmark(struct stackmark *mark, size_t len)
1545 mark->stackp = g_stackp;
1546 mark->stacknxt = g_stacknxt;
1547 mark->stacknleft = g_stacknleft;
1548 grabstackblock(len);
1552 setstackmark(struct stackmark *mark)
1554 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1558 popstackmark(struct stackmark *mark)
1560 struct stack_block *sp;
1566 while (g_stackp != mark->stackp) {
1568 g_stackp = sp->prev;
1571 g_stacknxt = mark->stacknxt;
1572 g_stacknleft = mark->stacknleft;
1573 sstrend = mark->stacknxt + mark->stacknleft;
1578 * When the parser reads in a string, it wants to stick the string on the
1579 * stack and only adjust the stack pointer when it knows how big the
1580 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1581 * of space on top of the stack and stackblocklen returns the length of
1582 * this block. Growstackblock will grow this space by at least one byte,
1583 * possibly moving it (like realloc). Grabstackblock actually allocates the
1584 * part of the block that has been used.
1587 growstackblock(void)
1591 newlen = g_stacknleft * 2;
1592 if (newlen < g_stacknleft)
1593 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1597 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1598 struct stack_block *sp;
1599 struct stack_block *prevstackp;
1604 prevstackp = sp->prev;
1605 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1606 sp = ckrealloc(sp, grosslen);
1607 sp->prev = prevstackp;
1609 g_stacknxt = sp->space;
1610 g_stacknleft = newlen;
1611 sstrend = sp->space + newlen;
1614 char *oldspace = g_stacknxt;
1615 size_t oldlen = g_stacknleft;
1616 char *p = stalloc(newlen);
1618 /* free the space we just allocated */
1619 g_stacknxt = memcpy(p, oldspace, oldlen);
1620 g_stacknleft += newlen;
1625 * The following routines are somewhat easier to use than the above.
1626 * The user declares a variable of type STACKSTR, which may be declared
1627 * to be a register. The macro STARTSTACKSTR initializes things. Then
1628 * the user uses the macro STPUTC to add characters to the string. In
1629 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1630 * grown as necessary. When the user is done, she can just leave the
1631 * string there and refer to it using stackblock(). Or she can allocate
1632 * the space for it using grabstackstr(). If it is necessary to allow
1633 * someone else to use the stack temporarily and then continue to grow
1634 * the string, the user should use grabstack to allocate the space, and
1635 * then call ungrabstr(p) to return to the previous mode of operation.
1637 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1638 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1639 * is space for at least one character.
1644 size_t len = stackblocksize();
1646 return (char *)stackblock() + len;
1650 * Called from CHECKSTRSPACE.
1653 makestrspace(size_t newlen, char *p)
1655 size_t len = p - g_stacknxt;
1661 size = stackblocksize();
1663 if (nleft >= newlen)
1667 return (char *)stackblock() + len;
1671 stack_nputstr(const char *s, size_t n, char *p)
1673 p = makestrspace(n, p);
1674 p = (char *)mempcpy(p, s, n);
1679 stack_putstr(const char *s, char *p)
1681 return stack_nputstr(s, strlen(s), p);
1685 _STPUTC(int c, char *p)
1693 #define STARTSTACKSTR(p) ((p) = stackblock())
1694 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1695 #define CHECKSTRSPACE(n, p) do { \
1698 size_t m = sstrend - q; \
1700 (p) = makestrspace(l, q); \
1702 #define USTPUTC(c, p) (*(p)++ = (c))
1703 #define STACKSTRNUL(p) do { \
1704 if ((p) == sstrend) \
1705 (p) = growstackstr(); \
1708 #define STUNPUTC(p) (--(p))
1709 #define STTOPC(p) ((p)[-1])
1710 #define STADJUST(amount, p) ((p) += (amount))
1712 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1713 #define ungrabstackstr(s, p) stunalloc(s)
1714 #define stackstrend() ((void *)sstrend)
1717 /* ============ String helpers */
1720 * prefix -- see if pfx is a prefix of string.
1723 prefix(const char *string, const char *pfx)
1726 if (*pfx++ != *string++)
1729 return (char *) string;
1733 * Check for a valid number. This should be elsewhere.
1736 is_number(const char *p)
1741 } while (*++p != '\0');
1746 * Convert a string of digits to an integer, printing an error message on
1750 number(const char *s)
1753 ash_msg_and_raise_error(msg_illnum, s);
1758 * Produce a single quoted string suitable as input to the shell.
1759 * The return string is allocated on the stack.
1762 single_quote(const char *s)
1772 len = strchrnul(s, '\'') - s;
1774 q = p = makestrspace(len + 3, p);
1777 q = (char *)mempcpy(q, s, len);
1786 do len++; while (*++s == '\'');
1788 q = p = makestrspace(len + 3, p);
1791 q = (char *)mempcpy(q, s - len, len);
1799 return stackblock();
1803 * Produce a possibly single quoted string suitable as input to the shell.
1804 * If quoting was done, the return string is allocated on the stack,
1805 * otherwise a pointer to the original string is returned.
1808 maybe_single_quote(const char *s)
1813 /* Assuming ACSII */
1814 /* quote ctrl_chars space !"#$%&'()* */
1818 if (*p >= ';' && *p <= '?')
1827 /* quote {|}~ DEL and high bytes */
1830 /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
1831 /* TODO: maybe avoid quoting % */
1837 return single_quote(s);
1841 /* ============ nextopt */
1843 static char **argptr; /* argument list for builtin commands */
1844 static char *optionarg; /* set by nextopt (like getopt) */
1845 static char *optptr; /* used by nextopt */
1848 * XXX - should get rid of. Have all builtins use getopt(3).
1849 * The library getopt must have the BSD extension static variable
1850 * "optreset", otherwise it can't be used within the shell safely.
1852 * Standard option processing (a la getopt) for builtin routines.
1853 * The only argument that is passed to nextopt is the option string;
1854 * the other arguments are unnecessary. It returns the character,
1855 * or '\0' on end of input.
1858 nextopt(const char *optstring)
1865 if (p == NULL || *p == '\0') {
1866 /* We ate entire "-param", take next one */
1872 if (*++p == '\0') /* just "-" ? */
1875 if (LONE_DASH(p)) /* "--" ? */
1877 /* p => next "-param" */
1879 /* p => some option char in the middle of a "-param" */
1881 for (q = optstring; *q != c;) {
1883 ash_msg_and_raise_error("illegal option -%c", c);
1891 ash_msg_and_raise_error("no arg for -%c option", c);
1901 /* ============ Shell variables */
1904 * The parsefile structure pointed to by the global variable parsefile
1905 * contains information about the current file being read.
1908 int nparam; /* # of positional parameters (without $0) */
1909 #if ENABLE_ASH_GETOPTS
1910 int optind; /* next parameter to be processed by getopts */
1911 int optoff; /* used by getopts */
1913 unsigned char malloced; /* if parameter list dynamically allocated */
1914 char **p; /* parameter list */
1918 * Free the list of positional parameters.
1921 freeparam(volatile struct shparam *param)
1923 if (param->malloced) {
1925 ap = ap1 = param->p;
1932 #if ENABLE_ASH_GETOPTS
1933 static void FAST_FUNC getoptsreset(const char *value);
1937 struct var *next; /* next entry in hash list */
1938 int flags; /* flags are defined above */
1939 const char *var_text; /* name=value */
1940 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1941 /* the variable gets set/unset */
1945 struct localvar *next; /* next local variable in list */
1946 struct var *vp; /* the variable that was made local */
1947 int flags; /* saved flags */
1948 const char *text; /* saved text */
1952 #define VEXPORT 0x01 /* variable is exported */
1953 #define VREADONLY 0x02 /* variable cannot be modified */
1954 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1955 #define VTEXTFIXED 0x08 /* text is statically allocated */
1956 #define VSTACK 0x10 /* text is allocated on the stack */
1957 #define VUNSET 0x20 /* the variable is not set */
1958 #define VNOFUNC 0x40 /* don't call the callback function */
1959 #define VNOSET 0x80 /* do not set variable - just readonly test */
1960 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1961 #if ENABLE_ASH_RANDOM_SUPPORT
1962 # define VDYNAMIC 0x200 /* dynamic variable */
1968 /* Need to be before varinit_data[] */
1969 #if ENABLE_LOCALE_SUPPORT
1970 static void FAST_FUNC
1971 change_lc_all(const char *value)
1973 if (value && *value != '\0')
1974 setlocale(LC_ALL, value);
1976 static void FAST_FUNC
1977 change_lc_ctype(const char *value)
1979 if (value && *value != '\0')
1980 setlocale(LC_CTYPE, value);
1984 static void chkmail(void);
1985 static void changemail(const char *var_value) FAST_FUNC;
1987 # define chkmail() ((void)0)
1989 static void changepath(const char *) FAST_FUNC;
1990 #if ENABLE_ASH_RANDOM_SUPPORT
1991 static void change_random(const char *) FAST_FUNC;
1994 static const struct {
1996 const char *var_text;
1997 void (*var_func)(const char *) FAST_FUNC;
1998 } varinit_data[] = {
2000 * Note: VEXPORT would not work correctly here for NOFORK applets:
2001 * some environment strings may be constant.
2003 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
2005 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
2006 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
2008 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
2009 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
2010 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
2011 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
2012 #if ENABLE_ASH_GETOPTS
2013 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
2015 #if ENABLE_ASH_RANDOM_SUPPORT
2016 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
2018 #if ENABLE_LOCALE_SUPPORT
2019 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
2020 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
2022 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
2023 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
2029 struct globals_var {
2030 struct shparam shellparam; /* $@ current positional parameters */
2031 struct redirtab *redirlist;
2032 int preverrout_fd; /* stderr fd: usually 2, unless redirect moved it */
2033 struct var *vartab[VTABSIZE];
2034 struct var varinit[ARRAY_SIZE(varinit_data)];
2036 extern struct globals_var *const ash_ptr_to_globals_var;
2037 #define G_var (*ash_ptr_to_globals_var)
2038 #define shellparam (G_var.shellparam )
2039 //#define redirlist (G_var.redirlist )
2040 #define preverrout_fd (G_var.preverrout_fd)
2041 #define vartab (G_var.vartab )
2042 #define varinit (G_var.varinit )
2043 #define INIT_G_var() do { \
2045 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
2047 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
2048 varinit[i].flags = varinit_data[i].flags; \
2049 varinit[i].var_text = varinit_data[i].var_text; \
2050 varinit[i].var_func = varinit_data[i].var_func; \
2054 #define vifs varinit[0]
2056 # define vmail (&vifs)[1]
2057 # define vmpath (&vmail)[1]
2058 # define vpath (&vmpath)[1]
2060 # define vpath (&vifs)[1]
2062 #define vps1 (&vpath)[1]
2063 #define vps2 (&vps1)[1]
2064 #define vps4 (&vps2)[1]
2065 #if ENABLE_ASH_GETOPTS
2066 # define voptind (&vps4)[1]
2067 # if ENABLE_ASH_RANDOM_SUPPORT
2068 # define vrandom (&voptind)[1]
2071 # if ENABLE_ASH_RANDOM_SUPPORT
2072 # define vrandom (&vps4)[1]
2077 * The following macros access the values of the above variables.
2078 * They have to skip over the name. They return the null string
2079 * for unset variables.
2081 #define ifsval() (vifs.var_text + 4)
2082 #define ifsset() ((vifs.flags & VUNSET) == 0)
2084 # define mailval() (vmail.var_text + 5)
2085 # define mpathval() (vmpath.var_text + 9)
2086 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2088 #define pathval() (vpath.var_text + 5)
2089 #define ps1val() (vps1.var_text + 4)
2090 #define ps2val() (vps2.var_text + 4)
2091 #define ps4val() (vps4.var_text + 4)
2092 #if ENABLE_ASH_GETOPTS
2093 # define optindval() (voptind.var_text + 7)
2096 #if ENABLE_ASH_GETOPTS
2097 static void FAST_FUNC
2098 getoptsreset(const char *value)
2100 shellparam.optind = number(value) ?: 1;
2101 shellparam.optoff = -1;
2106 * Compares two strings up to the first = or '\0'. The first
2107 * string must be terminated by '='; the second may be terminated by
2108 * either '=' or '\0'.
2111 varcmp(const char *p, const char *q)
2115 while ((c = *p) == (d = *q)) {
2116 if (c == '\0' || c == '=')
2130 * Find the appropriate entry in the hash table from the name.
2132 static struct var **
2133 hashvar(const char *p)
2137 hashval = ((unsigned char) *p) << 4;
2138 while (*p && *p != '=')
2139 hashval += (unsigned char) *p++;
2140 return &vartab[hashval % VTABSIZE];
2144 vpcmp(const void *a, const void *b)
2146 return varcmp(*(const char **)a, *(const char **)b);
2150 * This routine initializes the builtin variables.
2160 * PS1 depends on uid
2162 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2163 vps1.var_text = "PS1=\\w \\$ ";
2166 vps1.var_text = "PS1=# ";
2169 end = vp + ARRAY_SIZE(varinit);
2171 vpp = hashvar(vp->var_text);
2174 } while (++vp < end);
2177 static struct var **
2178 findvar(struct var **vpp, const char *name)
2180 for (; *vpp; vpp = &(*vpp)->next) {
2181 if (varcmp((*vpp)->var_text, name) == 0) {
2189 * Find the value of a variable. Returns NULL if not set.
2191 static const char* FAST_FUNC
2192 lookupvar(const char *name)
2196 v = *findvar(hashvar(name), name);
2198 #if ENABLE_ASH_RANDOM_SUPPORT
2200 * Dynamic variables are implemented roughly the same way they are
2201 * in bash. Namely, they're "special" so long as they aren't unset.
2202 * As soon as they're unset, they're no longer dynamic, and dynamic
2203 * lookup will no longer happen at that point. -- PFM.
2205 if (v->flags & VDYNAMIC)
2208 if (!(v->flags & VUNSET))
2209 return var_end(v->var_text);
2214 #if ENABLE_UNICODE_SUPPORT
2216 reinit_unicode_for_ash(void)
2218 /* Unicode support should be activated even if LANG is set
2219 * _during_ shell execution, not only if it was set when
2220 * shell was started. Therefore, re-check LANG every time:
2222 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2223 || ENABLE_UNICODE_USING_LOCALE
2225 const char *s = lookupvar("LC_ALL");
2226 if (!s) s = lookupvar("LC_CTYPE");
2227 if (!s) s = lookupvar("LANG");
2232 # define reinit_unicode_for_ash() ((void)0)
2236 * Search the environment of a builtin command.
2238 static ALWAYS_INLINE const char *
2239 bltinlookup(const char *name)
2241 return lookupvar(name);
2245 * Same as setvar except that the variable and value are passed in
2246 * the first argument as name=value. Since the first argument will
2247 * be actually stored in the table, it should not be a string that
2249 * Called with interrupts off.
2252 setvareq(char *s, int flags)
2254 struct var *vp, **vpp;
2257 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2258 vpp = findvar(vpp, s);
2261 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2264 if (flags & VNOSAVE)
2268 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2274 if (vp->var_func && !(flags & VNOFUNC))
2275 vp->var_func(var_end(s));
2277 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2278 free((char*)vp->var_text);
2280 if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
2284 if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
2289 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2291 /* variable s is not found */
2294 if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
2296 vp = ckzalloc(sizeof(*vp));
2298 /*vp->func = NULL; - ckzalloc did it */
2301 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2311 * Set the value of a variable. The flags argument is ored with the
2312 * flags of the variable. If val is NULL, the variable is unset.
2315 setvar(const char *name, const char *val, int flags)
2324 q = endofname(name);
2325 p = strchrnul(q, '=');
2327 if (!namelen || p != q)
2328 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2333 vallen = strlen(val);
2337 nameeq = ckmalloc(namelen + vallen + 2);
2338 p = mempcpy(nameeq, name, namelen);
2341 p = mempcpy(p, val, vallen);
2344 vp = setvareq(nameeq, flags | VNOSAVE);
2350 static void FAST_FUNC
2351 setvar0(const char *name, const char *val)
2353 setvar(name, val, 0);
2357 * Unset the specified variable.
2360 unsetvar(const char *s)
2366 * Process a linked list of variable assignments.
2369 listsetvar(struct strlist *list_set_var, int flags)
2371 struct strlist *lp = list_set_var;
2377 setvareq(lp->text, flags);
2384 * Generate a list of variables satisfying the given conditions.
2387 listvars(int on, int off, char ***end)
2398 for (vp = *vpp; vp; vp = vp->next) {
2399 if ((vp->flags & mask) == on) {
2400 if (ep == stackstrend())
2401 ep = growstackstr();
2402 *ep++ = (char*)vp->var_text;
2405 } while (++vpp < vartab + VTABSIZE);
2406 if (ep == stackstrend())
2407 ep = growstackstr();
2411 return grabstackstr(ep);
2415 /* ============ Path search helper
2417 * The variable path (passed by reference) should be set to the start
2418 * of the path before the first call; path_advance will update
2419 * this value as it proceeds. Successive calls to path_advance will return
2420 * the possible path expansions in sequence. If an option (indicated by
2421 * a percent sign) appears in the path entry then the global variable
2422 * pathopt will be set to point to it; otherwise pathopt will be set to
2425 static const char *pathopt; /* set by path_advance */
2428 path_advance(const char **path, const char *name)
2438 for (p = start; *p && *p != ':' && *p != '%'; p++)
2440 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2441 while (stackblocksize() < len)
2445 q = mempcpy(q, start, p - start);
2452 while (*p && *p != ':')
2459 return stalloc(len);
2463 /* ============ Prompt */
2465 static smallint doprompt; /* if set, prompt the user */
2466 static smallint needprompt; /* true if interactive and at start of line */
2468 #if ENABLE_FEATURE_EDITING
2469 static line_input_t *line_input_state;
2470 static const char *cmdedit_prompt;
2472 putprompt(const char *s)
2474 if (ENABLE_ASH_EXPAND_PRMT) {
2475 free((char*)cmdedit_prompt);
2476 cmdedit_prompt = ckstrdup(s);
2483 putprompt(const char *s)
2489 /* expandstr() needs parsing machinery, so it is far away ahead... */
2490 static const char *expandstr(const char *ps, int syntax_type);
2491 /* Values for syntax param */
2492 #define BASESYNTAX 0 /* not in quotes */
2493 #define DQSYNTAX 1 /* in double quotes */
2494 #define SQSYNTAX 2 /* in single quotes */
2495 #define ARISYNTAX 3 /* in arithmetic */
2496 #if ENABLE_ASH_EXPAND_PRMT
2497 # define PSSYNTAX 4 /* prompt. never passed to SIT() */
2499 /* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
2502 * called by editline -- any expansions to the prompt should be added here.
2505 setprompt_if(smallint do_set, int whichprompt)
2508 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2515 switch (whichprompt) {
2525 #if ENABLE_ASH_EXPAND_PRMT
2526 pushstackmark(&smark, stackblocksize());
2527 putprompt(expandstr(prompt, PSSYNTAX));
2528 popstackmark(&smark);
2535 /* ============ The cd and pwd commands */
2537 #define CD_PHYSICAL 1
2547 while ((i = nextopt("LP")) != '\0') {
2549 flags ^= CD_PHYSICAL;
2558 * Update curdir (the name of the current directory) in response to a
2562 updatepwd(const char *dir)
2569 cdcomppath = sstrdup(dir);
2572 if (curdir == nullstr)
2574 new = stack_putstr(curdir, new);
2576 new = makestrspace(strlen(dir) + 2, new);
2577 lim = (char *)stackblock() + 1;
2581 if (new > lim && *lim == '/')
2586 if (dir[1] == '/' && dir[2] != '/') {
2592 p = strtok(cdcomppath, "/");
2596 if (p[1] == '.' && p[2] == '\0') {
2608 new = stack_putstr(p, new);
2611 p = strtok(NULL, "/");
2616 return stackblock();
2620 * Find out what the current directory is. If we already know the current
2621 * directory, this routine returns immediately.
2626 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2627 return dir ? dir : nullstr;
2631 setpwd(const char *val, int setold)
2635 oldcur = dir = curdir;
2638 setvar("OLDPWD", oldcur, VEXPORT);
2641 if (physdir != nullstr) {
2642 if (physdir != oldcur)
2646 if (oldcur == val || !val) {
2652 dir = ckstrdup(val);
2653 if (oldcur != dir && oldcur != nullstr) {
2658 setvar("PWD", dir, VEXPORT);
2661 static void hashcd(void);
2664 * Actually do the chdir. We also call hashcd to let other routines
2665 * know that the current directory has changed.
2668 docd(const char *dest, int flags)
2670 const char *dir = NULL;
2673 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2676 if (!(flags & CD_PHYSICAL)) {
2677 dir = updatepwd(dest);
2691 static int FAST_FUNC
2692 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2704 dest = bltinlookup("HOME");
2705 else if (LONE_DASH(dest)) {
2706 dest = bltinlookup("OLDPWD");
2728 path = bltinlookup("CDPATH");
2731 p = path_advance(&path, dest);
2732 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2736 if (!docd(p, flags))
2747 ash_msg_and_raise_error("can't cd to %s", dest);
2750 if (flags & CD_PRINT)
2751 out1fmt("%s\n", curdir);
2755 static int FAST_FUNC
2756 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2759 const char *dir = curdir;
2763 if (physdir == nullstr)
2767 out1fmt("%s\n", dir);
2772 /* ============ ... */
2775 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2777 /* Syntax classes */
2778 #define CWORD 0 /* character is nothing special */
2779 #define CNL 1 /* newline character */
2780 #define CBACK 2 /* a backslash character */
2781 #define CSQUOTE 3 /* single quote */
2782 #define CDQUOTE 4 /* double quote */
2783 #define CENDQUOTE 5 /* a terminating quote */
2784 #define CBQUOTE 6 /* backwards single quote */
2785 #define CVAR 7 /* a dollar sign */
2786 #define CENDVAR 8 /* a '}' character */
2787 #define CLP 9 /* a left paren in arithmetic */
2788 #define CRP 10 /* a right paren in arithmetic */
2789 #define CENDFILE 11 /* end of file */
2790 #define CCTL 12 /* like CWORD, except it must be escaped */
2791 #define CSPCL 13 /* these terminate a word */
2792 #define CIGN 14 /* character should be ignored */
2795 #if ENABLE_ASH_ALIAS
2799 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2801 #if ENABLE_FEATURE_SH_MATH
2802 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2804 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2806 static const uint16_t S_I_T[] ALIGN2 = {
2807 #if ENABLE_ASH_ALIAS
2808 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2810 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2811 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2812 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2813 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2814 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2815 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2816 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2817 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2818 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2819 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2820 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2821 #if !USE_SIT_FUNCTION
2822 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2823 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2824 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2828 /* Constants below must match table above */
2830 #if ENABLE_ASH_ALIAS
2831 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2833 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2834 CNL_CNL_CNL_CNL , /* 2 */
2835 CWORD_CCTL_CCTL_CWORD , /* 3 */
2836 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2837 CVAR_CVAR_CWORD_CVAR , /* 5 */
2838 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2839 CSPCL_CWORD_CWORD_CLP , /* 7 */
2840 CSPCL_CWORD_CWORD_CRP , /* 8 */
2841 CBACK_CBACK_CCTL_CBACK , /* 9 */
2842 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2843 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2844 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2845 CWORD_CWORD_CWORD_CWORD , /* 13 */
2846 CCTL_CCTL_CCTL_CCTL , /* 14 */
2849 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2850 * caller must ensure proper cast on it if c is *char_ptr!
2852 #if USE_SIT_FUNCTION
2855 SIT(int c, int syntax)
2857 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2858 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2860 * This causes '/' to be prepended with CTLESC in dquoted string,
2861 * making "./file"* treated incorrectly because we feed
2862 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2863 * The "homegrown" glob implementation is okay with that,
2864 * but glibc one isn't. With '/' always treated as CWORD,
2867 # if ENABLE_ASH_ALIAS
2868 static const uint8_t syntax_index_table[] ALIGN1 = {
2869 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2870 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2871 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2875 static const uint8_t syntax_index_table[] ALIGN1 = {
2876 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2877 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2878 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2887 # if ENABLE_ASH_ALIAS
2893 /* Cast is purely for paranoia here,
2894 * just in case someone passed signed char to us */
2895 if ((unsigned char)c >= CTL_FIRST
2896 && (unsigned char)c <= CTL_LAST
2900 s = strchrnul(spec_symbls, c);
2903 indx = syntax_index_table[s - spec_symbls];
2905 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2908 #else /* !USE_SIT_FUNCTION */
2910 static const uint8_t syntax_index_table[] ALIGN1 = {
2911 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2912 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2922 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2923 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2945 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2946 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2947 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2949 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2951 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2952 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2953 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2954 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2955 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2957 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2958 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2959 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2960 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2972 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2973 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2974 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2975 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2976 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2977 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2993 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
3004 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
3005 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
3006 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
3007 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
3008 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
3009 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
3010 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
3011 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
3012 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
3013 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
3014 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
3015 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
3016 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
3017 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
3018 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
3019 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
3020 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
3021 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
3022 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
3023 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
3024 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3025 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3026 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3027 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3028 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3029 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3030 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3031 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3032 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3033 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3034 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3035 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3036 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3037 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3038 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3039 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3040 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
3041 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
3043 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
3044 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
3045 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
3046 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
3047 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3048 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3049 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3050 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3113 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3114 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3115 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3116 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3117 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3118 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3119 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3120 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3121 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3122 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3123 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3124 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3125 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3126 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3127 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3128 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3129 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3130 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3131 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3132 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3133 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3134 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3135 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3136 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3137 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3138 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3139 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3140 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3141 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3142 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3143 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3144 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3145 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3146 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3147 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3148 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3149 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3150 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3151 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3152 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3153 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3154 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3155 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3156 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3157 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3158 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3159 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3160 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3161 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3162 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3163 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3164 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3165 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3166 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3167 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3168 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3169 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3170 # if ENABLE_ASH_ALIAS
3171 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3176 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3177 #else /* debug version, caught one signed char bug */
3178 # define SIT(c, syntax) \
3180 if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
3181 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3182 if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
3183 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3184 ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
3188 #endif /* !USE_SIT_FUNCTION */
3191 /* ============ Alias handling */
3193 #if ENABLE_ASH_ALIAS
3195 #define ALIASINUSE 1
3206 static struct alias **atab; // [ATABSIZE];
3207 #define INIT_G_alias() do { \
3208 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3212 static struct alias **
3213 __lookupalias(const char *name)
3215 unsigned int hashval;
3222 ch = (unsigned char)*p;
3226 ch = (unsigned char)*++p;
3228 app = &atab[hashval % ATABSIZE];
3230 for (; *app; app = &(*app)->next) {
3231 if (strcmp(name, (*app)->name) == 0) {
3239 static struct alias *
3240 lookupalias(const char *name, int check)
3242 struct alias *ap = *__lookupalias(name);
3244 if (check && ap && (ap->flag & ALIASINUSE))
3249 static struct alias *
3250 freealias(struct alias *ap)
3254 if (ap->flag & ALIASINUSE) {
3255 ap->flag |= ALIASDEAD;
3267 setalias(const char *name, const char *val)
3269 struct alias *ap, **app;
3271 app = __lookupalias(name);
3275 if (!(ap->flag & ALIASINUSE)) {
3278 ap->val = ckstrdup(val);
3279 ap->flag &= ~ALIASDEAD;
3282 ap = ckzalloc(sizeof(struct alias));
3283 ap->name = ckstrdup(name);
3284 ap->val = ckstrdup(val);
3285 /*ap->flag = 0; - ckzalloc did it */
3286 /*ap->next = NULL;*/
3293 unalias(const char *name)
3297 app = __lookupalias(name);
3301 *app = freealias(*app);
3312 struct alias *ap, **app;
3316 for (i = 0; i < ATABSIZE; i++) {
3318 for (ap = *app; ap; ap = *app) {
3319 *app = freealias(*app);
3329 printalias(const struct alias *ap)
3331 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3335 * TODO - sort output
3337 static int FAST_FUNC
3338 aliascmd(int argc UNUSED_PARAM, char **argv)
3347 for (i = 0; i < ATABSIZE; i++) {
3348 for (ap = atab[i]; ap; ap = ap->next) {
3354 while ((n = *++argv) != NULL) {
3355 v = strchr(n+1, '=');
3356 if (v == NULL) { /* n+1: funny ksh stuff */
3357 ap = *__lookupalias(n);
3359 fprintf(stderr, "%s: %s not found\n", "alias", n);
3372 static int FAST_FUNC
3373 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3377 while (nextopt("a") != '\0') {
3381 for (i = 0; *argptr; argptr++) {
3382 if (unalias(*argptr)) {
3383 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3391 #endif /* ASH_ALIAS */
3394 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3397 #define FORK_NOJOB 2
3399 /* mode flags for showjob(s) */
3400 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3401 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3402 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3403 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3406 * A job structure contains information about a job. A job is either a
3407 * single process or a set of processes contained in a pipeline. In the
3408 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3412 pid_t ps_pid; /* process id */
3413 int ps_status; /* last process status from wait() */
3414 char *ps_cmd; /* text of command being run */
3418 struct procstat ps0; /* status of process */
3419 struct procstat *ps; /* status or processes when more than one */
3421 int stopstatus; /* status of a stopped job */
3423 unsigned nprocs; /* number of processes */
3425 #define JOBRUNNING 0 /* at least one proc running */
3426 #define JOBSTOPPED 1 /* all procs are stopped */
3427 #define JOBDONE 2 /* all procs are completed */
3431 sigint: 1, /* job was killed by SIGINT */
3432 jobctl: 1, /* job running under job control */
3434 waited: 1, /* true if this entry has been waited for */
3435 used: 1, /* true if this entry is in used */
3436 changed: 1; /* true if status has changed */
3437 struct job *prev_job; /* previous job */
3440 static struct job *makejob(/*union node *,*/ int);
3441 static int forkshell(struct job *, union node *, int);
3442 static int waitforjob(struct job *);
3445 enum { doing_jobctl = 0 };
3446 #define setjobctl(on) do {} while (0)
3448 static smallint doing_jobctl; //references:8
3449 static void setjobctl(int);
3456 ignoresig(int signo)
3458 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3459 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3460 /* No, need to do it */
3461 signal(signo, SIG_IGN);
3463 sigmode[signo - 1] = S_HARD_IGN;
3467 * Only one usage site - in setsignal()
3470 signal_handler(int signo)
3472 if (signo == SIGCHLD) {
3478 gotsig[signo - 1] = 1;
3479 pending_sig = signo;
3481 if (signo == SIGINT && !trap[SIGINT]) {
3482 if (!suppress_int) {
3484 raise_interrupt(); /* does not return */
3491 * Set the signal handler for the specified signal. The routine figures
3492 * out what it should be set to.
3495 setsignal(int signo)
3498 char cur_act, new_act;
3499 struct sigaction act;
3503 if (t != NULL) { /* trap for this sig is set */
3505 if (t[0] == '\0') /* trap is "": ignore this sig */
3509 if (rootshell && new_act == S_DFL) {
3512 if (iflag || minusc || sflag == 0)
3521 * "In all cases, bash ignores SIGQUIT. Non-builtin
3522 * commands run by bash have signal handlers
3523 * set to the values inherited by the shell
3524 * from its parent". */
3540 /* if !rootshell, we reset SIGQUIT to DFL,
3541 * whereas we have to restore it to what shell got on entry.
3542 * This is handled by the fact that if signal was IGNored on entry,
3543 * then cur_act is S_HARD_IGN and we never change its sigaction
3547 if (signo == SIGCHLD)
3550 t = &sigmode[signo - 1];
3553 /* current setting is not yet known */
3554 if (sigaction(signo, NULL, &act)) {
3555 /* pretend it worked; maybe we should give a warning,
3556 * but other shells don't. We don't alter sigmode,
3557 * so we retry every time.
3558 * btw, in Linux it never fails. --vda */
3561 if (act.sa_handler == SIG_IGN) {
3562 cur_act = S_HARD_IGN;
3564 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3566 cur_act = S_IGN; /* don't hard ignore these */
3569 if (act.sa_handler == SIG_DFL && new_act == S_DFL) {
3570 /* installing SIG_DFL over SIG_DFL is a no-op */
3571 /* saves one sigaction call in each "sh -c SCRIPT" invocation */
3576 if (cur_act == S_HARD_IGN || cur_act == new_act)
3581 act.sa_handler = SIG_DFL;
3584 act.sa_handler = signal_handler;
3587 act.sa_handler = SIG_IGN;
3590 /* flags and mask matter only if !DFL and !IGN, but we do it
3591 * for all cases for more deterministic behavior:
3593 act.sa_flags = 0; //TODO: why not SA_RESTART?
3594 sigfillset(&act.sa_mask);
3596 sigaction_set(signo, &act);
3599 /* mode flags for set_curjob */
3600 #define CUR_DELETE 2
3601 #define CUR_RUNNING 1
3602 #define CUR_STOPPED 0
3605 /* pgrp of shell on invocation */
3606 static int initialpgrp; //references:2
3607 static int ttyfd = -1; //5
3610 static struct job *jobtab; //5
3612 static unsigned njobs; //4
3614 static struct job *curjob; //lots
3615 /* number of presumed living untracked jobs */
3616 static int jobless; //4
3619 /* Bash has a feature: it restores termios after a successful wait for
3620 * a foreground job which had at least one stopped or sigkilled member.
3621 * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
3622 * properly restoring tty state. Should we do this too?
3623 * A reproducer: ^Z an interactive python:
3626 * Python 2.7.12 (...)
3628 * { python leaves tty in -icanon -echo state. We do survive that... }
3629 * [1]+ Stopped python
3630 * { ...however, next program (python #2) does not survive it well: }
3632 * Python 2.7.12 (...)
3633 * >>> Traceback (most recent call last):
3634 * { above, I typed "qwerty<CR>", but -echo state is still in effect }
3635 * File "<stdin>", line 1, in <module>
3636 * NameError: name 'qwerty' is not defined
3638 * The implementation below is modeled on bash code and seems to work.
3639 * However, I'm not sure we should do this. For one: what if I'd fg
3640 * the stopped python instead? It'll be confused by "restored" tty state.
3642 static struct termios shell_tty_info;
3646 if (rootshell && ttyfd >= 0)
3647 tcgetattr(ttyfd, &shell_tty_info);
3652 /* if (rootshell) - caller ensures this */
3654 tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
3657 job_signal_status(struct job *jp)
3661 struct procstat *ps = jp->ps;
3662 for (i = 0; i < jp->nprocs; i++) {
3663 status = ps[i].ps_status;
3664 if (WIFSIGNALED(status) || WIFSTOPPED(status))
3670 restore_tty_if_stopped_or_signaled(struct job *jp)
3672 //TODO: check what happens if we come from waitforjob() in expbackq()
3674 int s = job_signal_status(jp);
3675 if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
3680 # define get_tty_state() ((void)0)
3681 # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
3685 set_curjob(struct job *jp, unsigned mode)
3688 struct job **jpp, **curp;
3690 /* first remove from list */
3691 jpp = curp = &curjob;
3696 jpp = &jp1->prev_job;
3698 *jpp = jp1->prev_job;
3700 /* Then re-insert in correct position */
3708 /* job being deleted */
3711 /* newly created job or backgrounded job,
3712 * put after all stopped jobs.
3717 if (!jp1 || jp1->state != JOBSTOPPED)
3720 jpp = &jp1->prev_job;
3726 /* newly stopped job - becomes curjob */
3727 jp->prev_job = *jpp;
3735 jobno(const struct job *jp)
3737 return jp - jobtab + 1;
3742 * Convert a job name to a job structure.
3745 #define getjob(name, getctl) getjob(name)
3748 getjob(const char *name, int getctl)
3752 const char *err_msg = "%s: no such job";
3756 char *(*match)(const char *, const char *);
3771 if (c == '+' || c == '%') {
3773 err_msg = "No current job";
3779 err_msg = "No previous job";
3789 if (num > 0 && num <= njobs) {
3790 jp = jobtab + num - 1;
3805 if (match(jp->ps[0].ps_cmd, p)) {
3809 err_msg = "%s: ambiguous";
3819 err_msg = "job %s not created under job control";
3820 if (getctl && jp->jobctl == 0)
3825 ash_msg_and_raise_error(err_msg, name);
3829 * Mark a job structure as unused.
3832 freejob(struct job *jp)
3834 struct procstat *ps;
3838 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3839 if (ps->ps_cmd != nullstr)
3842 if (jp->ps != &jp->ps0)
3845 set_curjob(jp, CUR_DELETE);
3851 xtcsetpgrp(int fd, pid_t pgrp)
3853 if (tcsetpgrp(fd, pgrp))
3854 ash_msg_and_raise_perror("can't set tty process group");
3858 * Turn job control on and off.
3860 * Note: This code assumes that the third arg to ioctl is a character
3861 * pointer, which is true on Berkeley systems but not System V. Since
3862 * System V doesn't have job control yet, this isn't a problem now.
3864 * Called with interrupts off.
3872 if (on == doing_jobctl || rootshell == 0)
3876 ofd = fd = open(_PATH_TTY, O_RDWR);
3878 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3879 * That sometimes helps to acquire controlling tty.
3880 * Obviously, a workaround for bugs when someone
3881 * failed to provide a controlling tty to bash! :) */
3887 /* fd is a tty at this point */
3888 fd = fcntl(fd, F_DUPFD, 10);
3889 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
3892 goto out; /* F_DUPFD failed */
3893 close_on_exec_on(fd);
3894 while (1) { /* while we are in the background */
3895 pgrp = tcgetpgrp(fd);
3898 ash_msg("can't access tty; job control turned off");
3902 if (pgrp == getpgrp())
3913 xtcsetpgrp(fd, pgrp);
3915 /* turning job control off */
3918 /* was xtcsetpgrp, but this can make exiting ash
3919 * loop forever if pty is already deleted */
3920 tcsetpgrp(fd, pgrp);
3934 static int FAST_FUNC
3935 killcmd(int argc, char **argv)
3937 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3940 if (argv[i][0] == '%') {
3942 * "kill %N" - job kill
3943 * Converting to pgrp / pid kill
3949 jp = getjob(argv[i], 0);
3951 * In jobs started under job control, we signal
3952 * entire process group by kill -PGRP_ID.
3953 * This happens, f.e., in interactive shell.
3955 * Otherwise, we signal each child via
3956 * kill PID1 PID2 PID3.
3958 * sh -c 'sleep 1|sleep 1 & kill %1'
3959 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3960 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3962 n = jp->nprocs; /* can't be 0 (I hope) */
3965 dst = alloca(n * sizeof(int)*4);
3967 for (j = 0; j < n; j++) {
3968 struct procstat *ps = &jp->ps[j];
3969 /* Skip non-running and not-stopped members
3970 * (i.e. dead members) of the job
3972 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3975 * kill_main has matching code to expect
3976 * leading space. Needed to not confuse
3977 * negative pids with "kill -SIGNAL_NO" syntax
3979 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3983 } while (argv[++i]);
3985 return kill_main(argc, argv);
3989 showpipe(struct job *jp /*, FILE *out*/)
3991 struct procstat *ps;
3992 struct procstat *psend;
3994 psend = jp->ps + jp->nprocs;
3995 for (ps = jp->ps + 1; ps < psend; ps++)
3996 printf(" | %s", ps->ps_cmd);
3997 newline_and_flush(stdout);
3998 flush_stdout_stderr();
4003 restartjob(struct job *jp, int mode)
4005 struct procstat *ps;
4011 if (jp->state == JOBDONE)
4013 jp->state = JOBRUNNING;
4014 pgid = jp->ps[0].ps_pid;
4015 if (mode == FORK_FG) {
4017 xtcsetpgrp(ttyfd, pgid);
4019 killpg(pgid, SIGCONT);
4023 if (WIFSTOPPED(ps->ps_status)) {
4029 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
4034 static int FAST_FUNC
4035 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
4041 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
4045 jp = getjob(*argv, 1);
4046 if (mode == FORK_BG) {
4047 set_curjob(jp, CUR_RUNNING);
4048 printf("[%d] ", jobno(jp));
4050 out1str(jp->ps[0].ps_cmd);
4051 showpipe(jp /*, stdout*/);
4052 retval = restartjob(jp, mode);
4053 } while (*argv && *++argv);
4059 sprint_status48(char *s, int status, int sigonly)
4065 if (!WIFEXITED(status)) {
4067 if (WIFSTOPPED(status))
4068 st = WSTOPSIG(status);
4071 st = WTERMSIG(status);
4073 if (st == SIGINT || st == SIGPIPE)
4076 if (WIFSTOPPED(status))
4081 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
4082 col = fmtstr(s, 32, strsignal(st));
4083 if (WCOREDUMP(status)) {
4084 strcpy(s + col, " (core dumped)");
4085 col += sizeof(" (core dumped)")-1;
4087 } else if (!sigonly) {
4088 st = WEXITSTATUS(status);
4089 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
4096 wait_block_or_sig(int *status)
4103 /* Poll all children for changes in their state */
4105 /* if job control is active, accept stopped processes too */
4106 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
4108 break; /* Error (e.g. EINTR, ECHILD) or pid */
4110 /* Children exist, but none are ready. Sleep until interesting signal */
4113 sigprocmask(SIG_SETMASK, &mask, &mask);
4114 while (!got_sigchld && !pending_sig)
4116 sigprocmask(SIG_SETMASK, &mask, NULL);
4117 #else /* unsafe: a signal can set pending_sig after check, but before pause() */
4118 while (!got_sigchld && !pending_sig)
4122 /* If it was SIGCHLD, poll children again */
4123 } while (got_sigchld);
4128 #define DOWAIT_NONBLOCK 0
4129 #define DOWAIT_BLOCK 1
4130 #define DOWAIT_BLOCK_OR_SIG 2
4133 dowait(int block, struct job *job)
4138 struct job *thisjob = NULL;
4140 TRACE(("dowait(0x%x) called\n", block));
4142 /* It's wrong to call waitpid() outside of INT_OFF region:
4143 * signal can arrive just after syscall return and handler can
4144 * longjmp away, losing stop/exit notification processing.
4145 * Thus, for "jobs" builtin, and for waiting for a fg job,
4146 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
4148 * However, for "wait" builtin it is wrong to simply call waitpid()
4149 * in INT_OFF region: "wait" needs to wait for any running job
4150 * to change state, but should exit on any trap too.
4151 * In INT_OFF region, a signal just before syscall entry can set
4152 * pending_sig variables, but we can't check them, and we would
4153 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
4155 * Because of this, we run inside INT_OFF, but use a special routine
4156 * which combines waitpid() and sigsuspend().
4157 * This is the reason why we need to have a handler for SIGCHLD:
4158 * SIG_DFL handler does not wake sigsuspend().
4161 if (block == DOWAIT_BLOCK_OR_SIG) {
4162 pid = wait_block_or_sig(&status);
4165 if (block == DOWAIT_NONBLOCK)
4166 wait_flags = WNOHANG;
4167 /* if job control is active, accept stopped processes too */
4169 wait_flags |= WUNTRACED;
4170 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4171 pid = waitpid(-1, &status, wait_flags);
4173 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4174 pid, status, errno, strerror(errno)));
4179 for (jp = curjob; jp; jp = jp->prev_job) {
4181 struct procstat *ps;
4182 struct procstat *psend;
4183 if (jp->state == JOBDONE)
4187 psend = ps + jp->nprocs;
4189 if (ps->ps_pid == pid) {
4190 TRACE(("Job %d: changing status of proc %d "
4191 "from 0x%x to 0x%x\n",
4192 jobno(jp), pid, ps->ps_status, status));
4193 ps->ps_status = status;
4196 if (ps->ps_status == -1)
4197 jobstate = JOBRUNNING;
4199 if (jobstate == JOBRUNNING)
4201 if (WIFSTOPPED(ps->ps_status)) {
4202 jp->stopstatus = ps->ps_status;
4203 jobstate = JOBSTOPPED;
4206 } while (++ps < psend);
4210 /* Found the job where one of its processes changed its state.
4211 * Is there at least one live and running process in this job? */
4212 if (jobstate != JOBRUNNING) {
4213 /* No. All live processes in the job are stopped
4214 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4216 thisjob->changed = 1;
4217 if (thisjob->state != jobstate) {
4218 TRACE(("Job %d: changing state from %d to %d\n",
4219 jobno(thisjob), thisjob->state, jobstate));
4220 thisjob->state = jobstate;
4222 if (jobstate == JOBSTOPPED)
4223 set_curjob(thisjob, CUR_STOPPED);
4229 /* The process wasn't found in job list */
4231 if (!WIFSTOPPED(status))
4237 if (thisjob && thisjob == job) {
4241 len = sprint_status48(s, status, 1);
4253 showjob(struct job *jp, int mode)
4255 struct procstat *ps;
4256 struct procstat *psend;
4259 char s[16 + 16 + 48];
4260 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4264 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4265 /* just output process (group) id of pipeline */
4266 fprintf(out, "%d\n", ps->ps_pid);
4270 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4275 else if (curjob && jp == curjob->prev_job)
4278 if (mode & SHOW_PIDS)
4279 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4281 psend = ps + jp->nprocs;
4283 if (jp->state == JOBRUNNING) {
4284 strcpy(s + col, "Running");
4285 col += sizeof("Running") - 1;
4287 int status = psend[-1].ps_status;
4288 if (jp->state == JOBSTOPPED)
4289 status = jp->stopstatus;
4290 col += sprint_status48(s + col, status, 0);
4292 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4294 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4295 * or prints several "PID | <cmdN>" lines,
4296 * depending on SHOW_PIDS bit.
4297 * We do not print status of individual processes
4298 * between PID and <cmdN>. bash does it, but not very well:
4299 * first line shows overall job status, not process status,
4300 * making it impossible to know 1st process status.
4304 /* for each process */
4307 if (mode & SHOW_PIDS)
4308 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4310 fprintf(out, "%s%*c%s%s",
4312 33 - col >= 0 ? 33 - col : 0, ' ',
4313 ps == jp->ps ? "" : "| ",
4316 } while (++ps != psend);
4317 newline_and_flush(out);
4321 if (jp->state == JOBDONE) {
4322 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4328 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4329 * statuses have changed since the last call to showjobs.
4336 TRACE(("showjobs(0x%x) called\n", mode));
4338 /* Handle all finished jobs */
4339 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4342 for (jp = curjob; jp; jp = jp->prev_job) {
4343 if (!(mode & SHOW_CHANGED) || jp->changed) {
4349 static int FAST_FUNC
4350 jobscmd(int argc UNUSED_PARAM, char **argv)
4355 while ((m = nextopt("lp")) != '\0') {
4359 mode |= SHOW_ONLY_PGID;
4365 showjob(getjob(*argv, 0), mode);
4375 /* Called only on finished or stopped jobs (no members are running) */
4377 getstatus(struct job *job)
4381 struct procstat *ps;
4383 /* Fetch last member's status */
4384 ps = job->ps + job->nprocs - 1;
4385 status = ps->ps_status;
4387 /* "set -o pipefail" mode: use last _nonzero_ status */
4388 while (status == 0 && --ps >= job->ps)
4389 status = ps->ps_status;
4392 retval = WEXITSTATUS(status);
4393 if (!WIFEXITED(status)) {
4395 retval = WSTOPSIG(status);
4396 if (!WIFSTOPPED(status))
4399 /* XXX: limits number of signals */
4400 retval = WTERMSIG(status);
4402 if (retval == SIGINT)
4408 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4409 jobno(job), job->nprocs, status, retval));
4413 static int FAST_FUNC
4414 waitcmd(int argc UNUSED_PARAM, char **argv)
4425 /* wait for all jobs */
4429 if (!jp) /* no running procs */
4431 if (jp->state == JOBRUNNING)
4437 * "When bash is waiting for an asynchronous command via
4438 * the wait builtin, the reception of a signal for which a trap
4439 * has been set will cause the wait builtin to return immediately
4440 * with an exit status greater than 128, immediately after which
4441 * the trap is executed."
4443 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4444 /* if child sends us a signal *and immediately exits*,
4445 * dowait() returns pid > 0. Check this case,
4446 * not "if (dowait() < 0)"!
4455 if (**argv != '%') {
4456 pid_t pid = number(*argv);
4461 if (job->ps[job->nprocs - 1].ps_pid == pid)
4463 job = job->prev_job;
4466 job = getjob(*argv, 0);
4468 /* loop until process terminated or stopped */
4469 while (job->state == JOBRUNNING) {
4470 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4475 retval = getstatus(job);
4482 retval = 128 + pending_sig;
4491 struct job *jp, *jq;
4493 len = njobs * sizeof(*jp);
4495 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4497 offset = (char *)jp - (char *)jq;
4499 /* Relocate pointers */
4502 jq = (struct job *)((char *)jq + l);
4506 #define joff(p) ((struct job *)((char *)(p) + l))
4507 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4508 if (joff(jp)->ps == &jq->ps0)
4509 jmove(joff(jp)->ps);
4510 if (joff(jp)->prev_job)
4511 jmove(joff(jp)->prev_job);
4521 jp = (struct job *)((char *)jp + len);
4525 } while (--jq >= jp);
4530 * Return a new job structure.
4531 * Called with interrupts off.
4534 makejob(/*union node *node,*/ int nprocs)
4539 for (i = njobs, jp = jobtab; ; jp++) {
4546 if (jp->state != JOBDONE || !jp->waited)
4555 memset(jp, 0, sizeof(*jp));
4557 /* jp->jobctl is a bitfield.
4558 * "jp->jobctl |= doing_jobctl" likely to give awful code */
4562 jp->prev_job = curjob;
4567 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4569 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4576 * Return a string identifying a command (to be printed by the
4579 static char *cmdnextc;
4582 cmdputs(const char *s)
4584 static const char vstype[VSTYPE + 1][3] = {
4585 "", "}", "-", "+", "?", "=",
4586 "%", "%%", "#", "##"
4587 IF_BASH_SUBSTR(, ":")
4588 IF_BASH_PATTERN_SUBST(, "/", "//")
4591 const char *p, *str;
4595 unsigned char subtype = 0;
4599 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4601 while ((c = *p++) != '\0') {
4609 if ((subtype & VSTYPE) == VSLENGTH)
4615 str = "\"}" + !(quoted & 1);
4622 #if ENABLE_FEATURE_SH_MATH
4637 if ((subtype & VSTYPE) != VSNORMAL)
4639 str = vstype[subtype & VSTYPE];
4640 if (subtype & VSNUL)
4649 /* These can only happen inside quotes */
4655 // [1]+ Done true ${\$} <<=== BUG: ${\$} is not a valid way to write $$ (${$} would be ok)
4666 while ((c = *str++) != '\0') {
4669 } /* while *p++ not NUL */
4672 USTPUTC('"', nextc);
4678 /* cmdtxt() and cmdlist() call each other */
4679 static void cmdtxt(union node *n);
4682 cmdlist(union node *np, int sep)
4684 for (; np; np = np->narg.next) {
4688 if (sep && np->narg.next)
4694 cmdtxt(union node *n)
4697 struct nodelist *lp;
4708 lp = n->npipe.cmdlist;
4726 cmdtxt(n->nbinary.ch1);
4742 cmdtxt(n->nif.test);
4744 if (n->nif.elsepart) {
4745 cmdtxt(n->nif.ifpart);
4747 n = n->nif.elsepart;
4765 cmdtxt(n->nbinary.ch1);
4775 cmdputs(n->nfor.var);
4777 cmdlist(n->nfor.args, 1);
4782 cmdputs(n->narg.text);
4786 cmdlist(n->ncmd.args, 1);
4787 cmdlist(n->ncmd.redirect, 0);
4800 cmdputs(n->ncase.expr->narg.text);
4802 for (np = n->ncase.cases; np; np = np->nclist.next) {
4803 cmdtxt(np->nclist.pattern);
4805 cmdtxt(np->nclist.body);
4819 #if BASH_REDIR_OUTPUT
4834 cmdputs(utoa(n->nfile.fd));
4836 if (n->type == NTOFD || n->type == NFROMFD) {
4837 if (n->ndup.dupfd >= 0)
4838 cmdputs(utoa(n->ndup.dupfd));
4849 commandtext(union node *n)
4853 STARTSTACKSTR(cmdnextc);
4855 name = stackblock();
4856 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4857 return ckstrdup(name);
4862 * Fork off a subshell. If we are doing job control, give the subshell its
4863 * own process group. Jp is a job structure that the job is to be added to.
4864 * N is the command that will be evaluated by the child. Both jp and n may
4865 * be NULL. The mode parameter can be one of the following:
4866 * FORK_FG - Fork off a foreground process.
4867 * FORK_BG - Fork off a background process.
4868 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4869 * process group even if job control is on.
4871 * When job control is turned off, background processes have their standard
4872 * input redirected to /dev/null (except for the second and later processes
4875 * Called with interrupts off.
4878 * Clear traps on a fork.
4886 for (tp = trap; tp < &trap[NSIG]; tp++) {
4887 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4888 if (trap_ptr == trap)
4890 /* else: it "belongs" to trap_ptr vector, don't free */
4892 if ((tp - trap) != 0)
4893 setsignal(tp - trap);
4900 /* Lives far away from here, needed for forkchild */
4901 static void closescript(void);
4903 /* Called after fork(), in child */
4904 /* jp and n are NULL when called by openhere() for heredoc support */
4905 static NOINLINE void
4906 forkchild(struct job *jp, union node *n, int mode)
4910 TRACE(("Child shell %d\n", getpid()));
4914 /* man bash: "Non-builtin commands run by bash have signal handlers
4915 * set to the values inherited by the shell from its parent".
4916 * Do we do it correctly? */
4920 if (mode == FORK_NOJOB /* is it `xxx` ? */
4921 && n && n->type == NCMD /* is it single cmd? */
4922 /* && n->ncmd.args->type == NARG - always true? */
4923 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4924 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4925 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4927 TRACE(("Trap hack\n"));
4928 /* Awful hack for `trap` or $(trap).
4930 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4931 * contains an example where "trap" is executed in a subshell:
4933 * save_traps=$(trap)
4935 * eval "$save_traps"
4937 * Standard does not say that "trap" in subshell shall print
4938 * parent shell's traps. It only says that its output
4939 * must have suitable form, but then, in the above example
4940 * (which is not supposed to be normative), it implies that.
4942 * bash (and probably other shell) does implement it
4943 * (traps are reset to defaults, but "trap" still shows them),
4944 * but as a result, "trap" logic is hopelessly messed up:
4947 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4948 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4949 * # true | trap <--- trap is in subshell - no output (ditto)
4950 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4951 * trap -- 'echo Ho' SIGWINCH
4952 * # echo `(trap)` <--- in subshell in subshell - output
4953 * trap -- 'echo Ho' SIGWINCH
4954 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4955 * trap -- 'echo Ho' SIGWINCH
4957 * The rules when to forget and when to not forget traps
4958 * get really complex and nonsensical.
4960 * Our solution: ONLY bare $(trap) or `trap` is special.
4962 /* Save trap handler strings for trap builtin to print */
4963 trap_ptr = xmemdup(trap, sizeof(trap));
4964 /* Fall through into clearing traps */
4968 /* do job control only in root shell */
4970 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4973 if (jp->nprocs == 0)
4976 pgrp = jp->ps[0].ps_pid;
4977 /* this can fail because we are doing it in the parent also */
4979 if (mode == FORK_FG)
4980 xtcsetpgrp(ttyfd, pgrp);
4985 if (mode == FORK_BG) {
4986 /* man bash: "When job control is not in effect,
4987 * asynchronous commands ignore SIGINT and SIGQUIT" */
4990 if (jp->nprocs == 0) {
4992 if (open(bb_dev_null, O_RDONLY) != 0)
4993 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4997 if (iflag) { /* why if iflag only? */
5002 * "In all cases, bash ignores SIGQUIT. Non-builtin
5003 * commands run by bash have signal handlers
5004 * set to the values inherited by the shell
5006 * Take care of the second rule: */
5010 if (n && n->type == NCMD
5011 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
5013 TRACE(("Job hack\n"));
5014 /* "jobs": we do not want to clear job list for it,
5015 * instead we remove only _its_ own_ job from job list.
5016 * This makes "jobs .... | cat" more useful.
5022 for (jp = curjob; jp; jp = jp->prev_job)
5027 /* Called after fork(), in parent */
5029 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
5032 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
5034 TRACE(("In parent shell: child = %d\n", pid));
5036 /* jp is NULL when called by openhere() for heredoc support */
5037 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
5043 if (mode != FORK_NOJOB && jp->jobctl) {
5046 if (jp->nprocs == 0)
5049 pgrp = jp->ps[0].ps_pid;
5050 /* This can fail because we are doing it in the child also */
5054 if (mode == FORK_BG) {
5055 backgndpid = pid; /* set $! */
5056 set_curjob(jp, CUR_RUNNING);
5059 struct procstat *ps = &jp->ps[jp->nprocs++];
5062 ps->ps_cmd = nullstr;
5064 if (doing_jobctl && n)
5065 ps->ps_cmd = commandtext(n);
5070 /* jp and n are NULL when called by openhere() for heredoc support */
5072 forkshell(struct job *jp, union node *n, int mode)
5076 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
5079 TRACE(("Fork failed, errno=%d", errno));
5082 ash_msg_and_raise_error("can't fork");
5085 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
5086 forkchild(jp, n, mode);
5088 forkparent(jp, n, mode, pid);
5094 * Wait for job to finish.
5096 * Under job control we have the problem that while a child process
5097 * is running interrupts generated by the user are sent to the child
5098 * but not to the shell. This means that an infinite loop started by
5099 * an interactive user may be hard to kill. With job control turned off,
5100 * an interactive user may place an interactive program inside a loop.
5101 * If the interactive program catches interrupts, the user doesn't want
5102 * these interrupts to also abort the loop. The approach we take here
5103 * is to have the shell ignore interrupt signals while waiting for a
5104 * foreground process to terminate, and then send itself an interrupt
5105 * signal if the child process was terminated by an interrupt signal.
5106 * Unfortunately, some programs want to do a bit of cleanup and then
5107 * exit on interrupt; unless these processes terminate themselves by
5108 * sending a signal to themselves (instead of calling exit) they will
5109 * confuse this approach.
5111 * Called with interrupts off.
5114 waitforjob(struct job *jp)
5118 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
5121 while (jp->state == JOBRUNNING) {
5122 /* In non-interactive shells, we _can_ get
5123 * a keyboard signal here and be EINTRed,
5124 * but we just loop back, waiting for command to complete.
5127 * "If bash is waiting for a command to complete and receives
5128 * a signal for which a trap has been set, the trap
5129 * will not be executed until the command completes."
5131 * Reality is that even if trap is not set, bash
5132 * will not act on the signal until command completes.
5133 * Try this. sleep5intoff.c:
5134 * #include <signal.h>
5135 * #include <unistd.h>
5138 * sigemptyset(&set);
5139 * sigaddset(&set, SIGINT);
5140 * sigaddset(&set, SIGQUIT);
5141 * sigprocmask(SIG_BLOCK, &set, NULL);
5145 * $ bash -c './sleep5intoff; echo hi'
5146 * ^C^C^C^C <--- pressing ^C once a second
5148 * $ bash -c './sleep5intoff; echo hi'
5149 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
5152 dowait(DOWAIT_BLOCK, jp);
5159 xtcsetpgrp(ttyfd, rootpid);
5160 restore_tty_if_stopped_or_signaled(jp);
5163 * This is truly gross.
5164 * If we're doing job control, then we did a TIOCSPGRP which
5165 * caused us (the shell) to no longer be in the controlling
5166 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
5167 * intuit from the subprocess exit status whether a SIGINT
5168 * occurred, and if so interrupt ourselves. Yuck. - mycroft
5170 if (jp->sigint) /* TODO: do the same with all signals */
5171 raise(SIGINT); /* ... by raise(jp->sig) instead? */
5173 if (jp->state == JOBDONE)
5180 * return 1 if there are stopped jobs, otherwise 0
5192 if (jp && jp->state == JOBSTOPPED) {
5193 out2str("You have stopped jobs.\n");
5203 * Code for dealing with input/output redirection.
5208 #define EMPTY -2 /* marks an unused slot in redirtab */
5209 #define CLOSED -1 /* marks a slot of previously-closed fd */
5212 * Handle here documents. Normally we fork off a process to write the
5213 * data to a pipe. If the document is short, we can stuff the data in
5214 * the pipe without forking.
5216 /* openhere needs this forward reference */
5217 static void expandhere(union node *arg, int fd);
5219 openhere(union node *redir)
5225 ash_msg_and_raise_error("pipe call failed");
5226 if (redir->type == NHERE) {
5227 len = strlen(redir->nhere.doc->narg.text);
5228 if (len <= PIPE_BUF) {
5229 full_write(pip[1], redir->nhere.doc->narg.text, len);
5233 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5236 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5237 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5238 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5239 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5240 signal(SIGPIPE, SIG_DFL);
5241 if (redir->type == NHERE)
5242 full_write(pip[1], redir->nhere.doc->narg.text, len);
5244 expandhere(redir->nhere.doc, pip[1]);
5245 _exit(EXIT_SUCCESS);
5253 openredirect(union node *redir)
5259 switch (redir->nfile.type) {
5260 /* Can't happen, our single caller does this itself */
5266 return openhere(redir);
5269 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5270 * allocated space. Do it only when we know it is safe.
5272 fname = redir->nfile.expfname;
5274 switch (redir->nfile.type) {
5280 f = open(fname, O_RDONLY);
5285 f = open(fname, O_RDWR|O_CREAT, 0666);
5290 #if BASH_REDIR_OUTPUT
5293 /* Take care of noclobber mode. */
5295 if (stat(fname, &sb) < 0) {
5296 f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5299 } else if (!S_ISREG(sb.st_mode)) {
5300 f = open(fname, O_WRONLY, 0666);
5303 if (fstat(f, &sb) < 0 && S_ISREG(sb.st_mode)) {
5316 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5321 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5329 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5331 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5335 * Copy a file descriptor to be >= 10. Throws exception on error.
5343 newfd = fcntl(from, F_DUPFD, 10);
5344 err = newfd < 0 ? errno : 0;
5347 ash_msg_and_raise_perror("%d", from);
5349 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5355 dup2_or_raise(int from, int to)
5359 newfd = (from != to) ? dup2(from, to) : to;
5361 /* Happens when source fd is not open: try "echo >&99" */
5362 ash_msg_and_raise_perror("%d", from);
5367 fcntl_F_DUPFD(int fd, int avoid_fd)
5371 newfd = fcntl(fd, F_DUPFD, avoid_fd + 1);
5381 xdup_CLOEXEC_and_close(int fd, int avoid_fd)
5385 newfd = fcntl(fd, F_DUPFD, avoid_fd + 1);
5391 /* fd was not open? */
5394 ash_msg_and_raise_perror("%d", newfd);
5396 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5401 /* Struct def and variable are moved down to the first usage site */
5407 struct redirtab *next;
5409 struct squirrel two_fd[];
5411 #define redirlist (G_var.redirlist)
5414 add_squirrel_closed(struct redirtab *sq, int fd)
5421 for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
5422 /* If we collide with an already moved fd... */
5423 if (fd == sq->two_fd[i].orig_fd) {
5425 * "echo 3>FILE 3>&- 3>FILE"
5426 * "echo 3>&- 3>FILE"
5427 * No need for last redirect to insert
5428 * another "need to close 3" indicator.
5430 TRACE(("redirect_fd %d: already moved or closed\n", fd));
5434 TRACE(("redirect_fd %d: previous fd was closed\n", fd));
5435 sq->two_fd[i].orig_fd = fd;
5436 sq->two_fd[i].moved_to = CLOSED;
5440 save_fd_on_redirect(int fd, int avoid_fd, struct redirtab *sq)
5444 if (avoid_fd < 9) /* the important case here is that it can be -1 */
5449 /* Testcase: "ls -l /proc/$$/fd 10>&-" should work */
5450 ttyfd = xdup_CLOEXEC_and_close(ttyfd, avoid_fd);
5451 TRACE(("redirect_fd %d: matches ttyfd, moving it to %d\n", fd, ttyfd));
5452 return 1; /* "we closed fd" */
5455 /* Are we called from redirect(0)? E.g. redirect
5456 * in a forked child. No need to save fds,
5457 * we aren't going to use them anymore, ok to trash.
5462 /* If this one of script's fds? */
5464 struct parsefile *pf = g_parsefile;
5466 /* We skip fd == 0 case because of the following:
5467 * $ ash # running ash interactively
5469 * and in script.sh: "exec 9>&0".
5470 * Even though top-level pf_fd _is_ 0,
5471 * it's still ok to use it: "read" builtin uses it,
5472 * why should we cripple "exec" builtin?
5474 if (fd == pf->pf_fd) {
5475 pf->pf_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
5476 return 1; /* "we closed fd" */
5482 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
5484 /* First: do we collide with some already moved fds? */
5485 for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
5486 /* If we collide with an already moved fd... */
5487 if (fd == sq->two_fd[i].moved_to) {
5488 new_fd = fcntl_F_DUPFD(fd, avoid_fd);
5489 sq->two_fd[i].moved_to = new_fd;
5490 TRACE(("redirect_fd %d: already busy, moving to %d\n", fd, new_fd));
5491 if (new_fd < 0) /* what? */
5493 return 0; /* "we did not close fd" */
5495 if (fd == sq->two_fd[i].orig_fd) {
5496 /* Example: echo Hello >/dev/null 1>&2 */
5497 TRACE(("redirect_fd %d: already moved\n", fd));
5498 return 0; /* "we did not close fd" */
5502 /* If this fd is open, we move and remember it; if it's closed, new_fd = CLOSED (-1) */
5503 new_fd = fcntl_F_DUPFD(fd, avoid_fd);
5504 TRACE(("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, new_fd));
5508 /* new_fd = CLOSED; - already is -1 */
5510 sq->two_fd[i].moved_to = new_fd;
5511 sq->two_fd[i].orig_fd = fd;
5513 /* if we move stderr, let "set -x" code know */
5514 if (fd == preverrout_fd)
5515 preverrout_fd = new_fd;
5517 return 0; /* "we did not close fd" */
5521 internally_opened_fd(int fd, struct redirtab *sq)
5528 /* If this one of script's fds? */
5530 struct parsefile *pf = g_parsefile;
5532 if (fd == pf->pf_fd)
5538 if (sq) for (i = 0; i < sq->pair_count && sq->two_fd[i].orig_fd != EMPTY; i++) {
5539 if (fd == sq->two_fd[i].moved_to)
5546 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5547 * old file descriptors are stashed away so that the redirection can be
5548 * undone by calling popredir.
5550 /* flags passed to redirect */
5551 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5553 redirect(union node *redir, int flags)
5555 struct redirtab *sv;
5562 if (flags & REDIR_PUSH)
5570 fd = redir->nfile.fd;
5571 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5572 //bb_error_msg("doing %d > %d", fd, newfd);
5573 newfd = redir->ndup.dupfd;
5576 newfd = openredirect(redir); /* always >= 0 */
5578 /* open() gave us precisely the fd we wanted.
5579 * This means that this fd was not busy
5580 * (not opened to anywhere).
5581 * Remember to close it on restore:
5583 add_squirrel_closed(sv, fd);
5592 /* if "N>FILE": move newfd to fd */
5593 /* if "N>&M": dup newfd to fd */
5594 /* if "N>&-": close fd (newfd is -1) */
5596 IF_BASH_REDIR_OUTPUT(redirect_more:)
5598 closed = save_fd_on_redirect(fd, /*avoid:*/ newfd, sv);
5600 /* "N>&-" means "close me" */
5602 /* ^^^ optimization: saving may already
5603 * have closed it. If not... */
5607 /* if newfd is a script fd or saved fd, simulate EBADF */
5608 if (internally_opened_fd(newfd, sv)) {
5610 ash_msg_and_raise_perror("%d", newfd);
5612 dup2_or_raise(newfd, fd);
5613 if (close_fd >= 0) /* "N>FILE" or ">&FILE" or heredoc? */
5615 #if BASH_REDIR_OUTPUT
5616 if (redir->nfile.type == NTO2 && fd == 1) {
5617 /* ">&FILE". we already redirected to 1, now copy 1 to 2 */
5625 } while ((redir = redir->nfile.next) != NULL);
5628 //dash:#define REDIR_SAVEFD2 03 /* set preverrout */
5629 #define REDIR_SAVEFD2 0
5630 // dash has a bug: since REDIR_SAVEFD2=3 and REDIR_PUSH=1, this test
5631 // triggers for pure REDIR_PUSH too. Thus, this is done almost always,
5632 // not only for calls with flags containing REDIR_SAVEFD2.
5633 // We do this unconditionally (see save_fd_on_redirect()).
5634 //if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5635 // preverrout_fd = copied_fd2;
5639 redirectsafe(union node *redir, int flags)
5642 volatile int saveint;
5643 struct jmploc *volatile savehandler = exception_handler;
5644 struct jmploc jmploc;
5647 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5648 err = setjmp(jmploc.loc); /* was = setjmp(jmploc.loc) * 2; */
5650 exception_handler = &jmploc;
5651 redirect(redir, flags);
5653 exception_handler = savehandler;
5654 if (err && exception_type != EXERROR)
5655 longjmp(exception_handler->loc, 1);
5656 RESTORE_INT(saveint);
5660 static struct redirtab*
5661 pushredir(union node *redir)
5663 struct redirtab *sv;
5672 #if BASH_REDIR_OUTPUT
5673 if (redir->nfile.type == NTO2)
5676 redir = redir->nfile.next;
5679 sv = ckzalloc(sizeof(*sv) + i * sizeof(sv->two_fd[0]));
5682 sv->two_fd[i].orig_fd = sv->two_fd[i].moved_to = EMPTY;
5683 sv->next = redirlist;
5689 * Undo the effects of the last redirection.
5694 struct redirtab *rp;
5697 if (redirlist == NULL)
5701 for (i = 0; i < rp->pair_count; i++) {
5702 int fd = rp->two_fd[i].orig_fd;
5703 int copy = rp->two_fd[i].moved_to;
5704 if (copy == CLOSED) {
5709 if (copy != EMPTY) {
5712 dup2_or_raise(copy, fd);
5717 redirlist = rp->next;
5723 unwindredir(struct redirtab *stop)
5725 while (redirlist != stop)
5726 popredir(/*drop:*/ 0);
5730 /* ============ Routines to expand arguments to commands
5732 * We have to deal with backquotes, shell variables, and file metacharacters.
5735 #if ENABLE_FEATURE_SH_MATH
5737 ash_arith(const char *s)
5739 arith_state_t math_state;
5742 math_state.lookupvar = lookupvar;
5743 math_state.setvar = setvar0;
5744 //math_state.endofname = endofname;
5747 result = arith(&math_state, s);
5748 if (math_state.errmsg)
5749 ash_msg_and_raise_error(math_state.errmsg);
5759 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5760 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5761 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5762 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5763 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5764 * POSIX says for this case:
5765 * Pathname expansion shall not be performed on the word by a
5766 * non-interactive shell; an interactive shell may perform it, but shall
5767 * do so only when the expansion would result in one word.
5768 * Currently, our code complies to the above rule by never globbing
5769 * redirection filenames.
5770 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5771 * (this means that on a typical Linux distro, bash almost always
5772 * performs globbing, and thus diverges from what we do).
5774 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5775 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5776 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5777 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5778 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5782 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5783 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5784 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5785 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5786 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5788 /* Add CTLESC when necessary. */
5789 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT)
5790 /* Do not skip NUL characters. */
5791 #define QUOTES_KEEPNUL EXP_TILDE
5794 * Structure specifying which parts of the string should be searched
5795 * for IFS characters.
5798 struct ifsregion *next; /* next region in list */
5799 int begoff; /* offset of start of region */
5800 int endoff; /* offset of end of region */
5801 int nulonly; /* search for nul bytes only */
5805 struct strlist *list;
5806 struct strlist **lastp;
5809 /* output of current string */
5810 static char *expdest;
5811 /* list of back quote expressions */
5812 static struct nodelist *argbackq;
5813 /* first struct in list of ifs regions */
5814 static struct ifsregion ifsfirst;
5815 /* last struct in list */
5816 static struct ifsregion *ifslastp;
5817 /* holds expanded arg list */
5818 static struct arglist exparg;
5822 * cvtnum() is used even if math support is off (to prepare $? values and such).
5829 /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
5830 len = sizeof(arith_t) * 3;
5831 /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
5832 if (sizeof(arith_t) < 4) len += 2;
5834 expdest = makestrspace(len, expdest);
5835 len = fmtstr(expdest, len, ARITH_FMT, num);
5836 STADJUST(len, expdest);
5841 * Break the argument string into pieces based upon IFS and add the
5842 * strings to the argument list. The regions of the string to be
5843 * searched for IFS characters have been stored by recordregion.
5846 ifsbreakup(char *string, struct arglist *arglist)
5848 struct ifsregion *ifsp;
5853 const char *ifs, *realifs;
5858 if (ifslastp != NULL) {
5861 realifs = ifsset() ? ifsval() : defifs;
5864 p = string + ifsp->begoff;
5865 nulonly = ifsp->nulonly;
5866 ifs = nulonly ? nullstr : realifs;
5868 while (p < string + ifsp->endoff) {
5870 if ((unsigned char)*p == CTLESC)
5872 if (!strchr(ifs, *p)) {
5877 ifsspc = (strchr(defifs, *p) != NULL);
5878 /* Ignore IFS whitespace at start */
5879 if (q == start && ifsspc) {
5885 sp = stzalloc(sizeof(*sp));
5887 *arglist->lastp = sp;
5888 arglist->lastp = &sp->next;
5892 if (p >= string + ifsp->endoff) {
5896 if ((unsigned char)*p == CTLESC)
5898 if (strchr(ifs, *p) == NULL) {
5902 if (strchr(defifs, *p) == NULL) {
5917 } while (ifsp != NULL);
5926 sp = stzalloc(sizeof(*sp));
5928 *arglist->lastp = sp;
5929 arglist->lastp = &sp->next;
5935 struct ifsregion *p = ifsfirst.next;
5942 struct ifsregion *ifsp;
5947 ifsfirst.next = NULL;
5954 esclen(const char *start, const char *p)
5958 while (p > start && (unsigned char)*--p == CTLESC) {
5965 * Remove any CTLESC characters from a string.
5968 rmescapes(char *str, int flag)
5970 static const char qchars[] ALIGN1 = {
5971 IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
5975 unsigned protect_against_glob;
5977 IF_BASH_PATTERN_SUBST(unsigned slash = flag & RMESCAPE_SLASH;)
5979 p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash));
5985 if (flag & RMESCAPE_ALLOC) {
5986 size_t len = p - str;
5987 size_t fulllen = len + strlen(p) + 1;
5989 if (flag & RMESCAPE_GROW) {
5990 int strloc = str - (char *)stackblock();
5991 r = makestrspace(fulllen, expdest);
5992 /* p and str may be invalidated by makestrspace */
5993 str = (char *)stackblock() + strloc;
5995 } else if (flag & RMESCAPE_HEAP) {
5996 r = ckmalloc(fulllen);
5998 r = stalloc(fulllen);
6002 q = (char *)mempcpy(q, str, len);
6007 globbing = flag & RMESCAPE_GLOB;
6008 protect_against_glob = globbing;
6010 if ((unsigned char)*p == CTLQUOTEMARK) {
6011 // Note: both inquotes and protect_against_glob only affect whether
6012 // CTLESC,<ch> gets converted to <ch> or to \<ch>
6013 inquotes = ~inquotes;
6015 protect_against_glob = globbing;
6018 if ((unsigned char)*p == CTLESC) {
6022 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
6024 if (protect_against_glob) {
6026 * We used to trust glob() and fnmatch() to eat
6027 * superfluous escapes (\z where z has no
6028 * special meaning anyway). But this causes
6029 * bugs such as string of one greek letter rho
6030 * (unicode-encoded as two bytes "cf,81")
6031 * getting encoded as "cf,CTLESC,81"
6032 * and here, converted to "cf,\,81" -
6033 * which does not go well with some flavors
6034 * of fnmatch() in unicode locales
6035 * (for example, glibc <= 2.22).
6037 * Lets add "\" only on the chars which need it.
6038 * Testcases for less obvious chars are shown.
6043 || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
6044 || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
6045 || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
6046 || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
6047 /* Some libc support [^negate], that's why "^" also needs love */
6048 || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
6053 } else if (*p == '\\' && !inquotes) {
6054 /* naked back slash */
6055 protect_against_glob = 0;
6058 #if BASH_PATTERN_SUBST
6059 else if (*p == '/' && slash) {
6060 /* stop handling globbing and mark location of slash */
6061 globbing = slash = 0;
6065 protect_against_glob = globbing;
6070 if (flag & RMESCAPE_GROW) {
6072 STADJUST(q - r + 1, expdest);
6076 #define pmatch(a, b) !fnmatch((a), (b), 0)
6079 * Prepare a pattern for a expmeta (internal glob(3)) call.
6081 * Returns an stalloced string.
6084 preglob(const char *pattern, int flag)
6086 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
6090 * Put a string on the stack.
6093 memtodest(const char *p, size_t len, int syntax, int quotes)
6100 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
6103 unsigned char c = *p++;
6105 if (quotes & QUOTES_ESC) {
6106 int n = SIT(c, syntax);
6108 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
6115 } else if (!(quotes & QUOTES_KEEPNUL))
6124 strtodest(const char *p, int syntax, int quotes)
6126 size_t len = strlen(p);
6127 memtodest(p, len, syntax, quotes);
6132 * Record the fact that we have to scan this region of the
6133 * string for IFS characters.
6136 recordregion(int start, int end, int nulonly)
6138 struct ifsregion *ifsp;
6140 if (ifslastp == NULL) {
6144 ifsp = ckzalloc(sizeof(*ifsp));
6145 /*ifsp->next = NULL; - ckzalloc did it */
6146 ifslastp->next = ifsp;
6150 ifslastp->begoff = start;
6151 ifslastp->endoff = end;
6152 ifslastp->nulonly = nulonly;
6156 removerecordregions(int endoff)
6158 if (ifslastp == NULL)
6161 if (ifsfirst.endoff > endoff) {
6162 while (ifsfirst.next) {
6163 struct ifsregion *ifsp;
6165 ifsp = ifsfirst.next->next;
6166 free(ifsfirst.next);
6167 ifsfirst.next = ifsp;
6170 if (ifsfirst.begoff > endoff) {
6173 ifslastp = &ifsfirst;
6174 ifsfirst.endoff = endoff;
6179 ifslastp = &ifsfirst;
6180 while (ifslastp->next && ifslastp->next->begoff < endoff)
6181 ifslastp = ifslastp->next;
6182 while (ifslastp->next) {
6183 struct ifsregion *ifsp;
6185 ifsp = ifslastp->next->next;
6186 free(ifslastp->next);
6187 ifslastp->next = ifsp;
6190 if (ifslastp->endoff > endoff)
6191 ifslastp->endoff = endoff;
6195 exptilde(char *startp, char *p, int flags)
6201 int quotes = flags & QUOTES_ESC;
6205 while ((c = *++p) != '\0') {
6212 if (flags & EXP_VARTILDE)
6222 if (*name == '\0') {
6223 home = lookupvar("HOME");
6225 pw = getpwnam(name);
6230 if (!home || !*home)
6233 strtodest(home, SQSYNTAX, quotes);
6241 * Execute a command inside back quotes. If it's a builtin command, we
6242 * want to save its output in a block obtained from malloc. Otherwise
6243 * we fork off a subprocess and get the output of the command via a pipe.
6244 * Should be called with interrupts off.
6246 struct backcmd { /* result of evalbackcmd */
6247 int fd; /* file descriptor to read from */
6248 int nleft; /* number of chars in buffer */
6249 char *buf; /* buffer */
6250 struct job *jp; /* job structure for command */
6253 /* These forward decls are needed to use "eval" code for backticks handling: */
6254 /* flags in argument to evaltree */
6255 #define EV_EXIT 01 /* exit after evaluating tree */
6256 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
6257 static int evaltree(union node *, int);
6259 /* An evaltree() which is known to never return.
6260 * Used to use an alias:
6261 * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
6262 * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
6264 static ALWAYS_INLINE NORETURN void
6265 evaltreenr(union node *n, int flags)
6268 bb_unreachable(abort());
6272 static void FAST_FUNC
6273 evalbackcmd(union node *n, struct backcmd *result)
6287 ash_msg_and_raise_error("pipe call failed");
6288 jp = makejob(/*n,*/ 1);
6289 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6295 dup2_or_raise(pip[1], 1);
6298 /* TODO: eflag clearing makes the following not abort:
6299 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6300 * which is what bash does (unless it is in POSIX mode).
6301 * dash deleted "eflag = 0" line in the commit
6302 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6303 * [EVAL] Don't clear eflag in evalbackcmd
6304 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6308 evaltreenr(n, EV_EXIT);
6313 result->fd = pip[0];
6317 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6318 result->fd, result->buf, result->nleft, result->jp));
6322 * Expand stuff in backwards quotes.
6325 expbackq(union node *cmd, int flag)
6333 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6334 struct stackmark smark;
6337 startloc = expdest - (char *)stackblock();
6338 pushstackmark(&smark, startloc);
6339 evalbackcmd(cmd, &in);
6340 popstackmark(&smark);
6347 memtodest(p, i, syntax, flag & QUOTES_ESC);
6351 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6352 TRACE(("expbackq: read returns %d\n", i));
6361 back_exitstatus = waitforjob(in.jp);
6365 /* Eat all trailing newlines */
6367 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6371 if (!(flag & EXP_QUOTED))
6372 recordregion(startloc, dest - (char *)stackblock(), 0);
6373 TRACE(("evalbackq: size:%d:'%.*s'\n",
6374 (int)((dest - (char *)stackblock()) - startloc),
6375 (int)((dest - (char *)stackblock()) - startloc),
6376 stackblock() + startloc));
6379 #if ENABLE_FEATURE_SH_MATH
6381 * Expand arithmetic expression. Backup to start of expression,
6382 * evaluate, place result in (backed up) result, adjust string position.
6394 * This routine is slightly over-complicated for
6395 * efficiency. Next we scan backwards looking for the
6396 * start of arithmetic.
6398 start = stackblock();
6405 while ((unsigned char)*p != CTLARI) {
6409 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6414 esc = esclen(start, p);
6424 removerecordregions(begoff);
6428 if (flag & QUOTES_ESC)
6429 rmescapes(p + 1, 0);
6431 len = cvtnum(ash_arith(p + 1));
6433 if (!(flag & EXP_QUOTED))
6434 recordregion(begoff, begoff + len, 0);
6438 /* argstr needs it */
6439 static char *evalvar(char *p, int flags);
6442 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6443 * characters to allow for further processing. Otherwise treat
6444 * $@ like $* since no splitting will be performed.
6447 argstr(char *p, int flags)
6449 static const char spclchars[] ALIGN1 = {
6457 #if ENABLE_FEATURE_SH_MATH
6462 const char *reject = spclchars;
6463 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6468 if (!(flags & EXP_VARTILDE)) {
6470 } else if (flags & EXP_VARTILDE2) {
6475 if (flags & EXP_TILDE) {
6478 flags &= ~EXP_TILDE;
6482 p = exptilde(p, q, flags);
6485 startloc = expdest - (char *)stackblock();
6489 length += strcspn(p + length, reject);
6493 IF_FEATURE_SH_MATH(|| c == CTLENDARI)
6495 /* c == '=' || c == ':' || c == CTLENDARI */
6501 expdest = stack_nputstr(p, length, expdest);
6502 newloc = expdest - (char *)stackblock();
6503 if (breakall && !inquotes && newloc > startloc) {
6504 recordregion(startloc, newloc, 0);
6515 if (flags & EXP_VARTILDE2) {
6519 flags |= EXP_VARTILDE2;
6524 * sort of a hack - expand tildes in variable
6525 * assignments (after the first '=' and after ':'s).
6534 case CTLENDVAR: /* ??? */
6537 inquotes ^= EXP_QUOTED;
6538 /* "$@" syntax adherence hack */
6539 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6540 p = evalvar(p + 1, flags | inquotes) + 1;
6544 if (flags & QUOTES_ESC) {
6555 * Quoted parameter expansion pattern: remove quote
6556 * unless inside inner quotes or we have a literal
6559 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6560 EXP_QPAT && *p != '\\')
6565 TRACE(("argstr: evalvar('%s')\n", p));
6566 p = evalvar(p, flags | inquotes);
6567 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6570 expbackq(argbackq->n, flags | inquotes);
6571 argbackq = argbackq->next;
6573 #if ENABLE_FEATURE_SH_MATH
6576 expari(flags | inquotes);
6585 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6586 char *pattern, int quotes, int zero)
6595 const char *s = loc2;
6602 match = pmatch(pattern, s);
6607 if (quotes && (unsigned char)*loc == CTLESC)
6616 scanright(char *startp, char *rmesc, char *rmescend,
6617 char *pattern, int quotes, int match_at_start)
6619 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6620 int try2optimize = match_at_start;
6626 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6627 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6628 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6630 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6631 * and on each iteration they go back two/one char until they reach the beginning.
6632 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6634 /* TODO: document in what other circumstances we are called. */
6636 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6639 const char *s = loc2;
6640 if (match_at_start) {
6644 match = pmatch(pattern, s);
6645 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6649 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6651 /* Maybe we can optimize this:
6652 * if pattern ends with unescaped *, we can avoid checking
6653 * shorter strings: if "foo*" doesn't match "raw_value_of_v",
6654 * it won't match truncated "raw_value_of_" strings too.
6656 unsigned plen = strlen(pattern);
6657 /* Does it end with "*"? */
6658 if (plen != 0 && pattern[--plen] == '*') {
6659 /* "xxxx*" is not escaped */
6660 /* "xxx\*" is escaped */
6661 /* "xx\\*" is not escaped */
6662 /* "x\\\*" is escaped */
6664 while (plen != 0 && pattern[--plen] == '\\')
6667 break; /* ends with unescaped "*" */
6675 esc = esclen(startp, loc);
6686 static void varunset(const char *, const char *, const char *, int) NORETURN;
6688 varunset(const char *end, const char *var, const char *umsg, int varflags)
6694 msg = "parameter not set";
6696 if ((unsigned char)*end == CTLENDVAR) {
6697 if (varflags & VSNUL)
6703 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6707 subevalvar(char *p, char *varname, int strloc, int subtype,
6708 int startloc, int varflags, int flag)
6710 struct nodelist *saveargbackq = argbackq;
6711 int quotes = flag & QUOTES_ESC;
6714 char *rmesc, *rmescend;
6716 int amount, resetloc;
6717 IF_BASH_PATTERN_SUBST(int workloc;)
6718 IF_BASH_PATTERN_SUBST(char *repl = NULL;)
6720 char *(*scan)(char*, char*, char*, char*, int, int);
6722 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6723 // p, varname, strloc, subtype, startloc, varflags, quotes);
6725 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6726 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0)
6728 STPUTC('\0', expdest);
6729 argbackq = saveargbackq;
6730 startp = (char *)stackblock() + startloc;
6734 setvar0(varname, startp);
6735 amount = startp - expdest;
6736 STADJUST(amount, expdest);
6740 varunset(p, varname, startp, varflags);
6745 int pos, len, orig_len;
6748 loc = str = stackblock() + strloc;
6750 # if !ENABLE_FEATURE_SH_MATH
6751 # define ash_arith number
6753 /* Read POS in ${var:POS:LEN} */
6754 colon = strchr(loc, ':');
6755 if (colon) *colon = '\0';
6756 pos = ash_arith(loc);
6757 if (colon) *colon = ':';
6759 /* Read LEN in ${var:POS:LEN} */
6760 len = str - startp - 1;
6761 /* *loc != '\0', guaranteed by parser */
6765 /* Adjust the length by the number of escapes */
6766 for (ptr = startp; ptr < (str - 1); ptr++) {
6767 if ((unsigned char)*ptr == CTLESC) {
6774 if (*loc++ == ':') {
6776 len = ash_arith(loc);
6778 /* Skip POS in ${var:POS:LEN} */
6780 while (*loc && *loc != ':') {
6783 if (*loc++ == ':') {
6784 len = ash_arith(loc);
6790 /* ${VAR:$((-n)):l} starts n chars from the end */
6791 pos = orig_len + pos;
6793 if ((unsigned)pos >= orig_len) {
6794 /* apart from obvious ${VAR:999999:l},
6795 * covers ${VAR:$((-9999999)):l} - result is ""
6802 /* ${VAR:N:-M} sets LEN to strlen()-M */
6803 len = (orig_len - pos) + len;
6805 if ((unsigned)len > (orig_len - pos))
6806 len = orig_len - pos;
6808 for (str = startp; pos; str++, pos--) {
6809 if (quotes && (unsigned char)*str == CTLESC)
6812 for (loc = startp; len; len--) {
6813 if (quotes && (unsigned char)*str == CTLESC)
6818 amount = loc - expdest;
6819 STADJUST(amount, expdest);
6822 #endif /* BASH_SUBSTR */
6825 resetloc = expdest - (char *)stackblock();
6827 #if BASH_PATTERN_SUBST
6828 /* We'll comeback here if we grow the stack while handling
6829 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6830 * stack will need rebasing, and we'll need to remove our work
6836 amount = expdest - ((char *)stackblock() + resetloc);
6837 STADJUST(-amount, expdest);
6838 startp = (char *)stackblock() + startloc;
6841 rmescend = (char *)stackblock() + strloc;
6843 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6844 if (rmesc != startp) {
6846 startp = (char *)stackblock() + startloc;
6850 str = (char *)stackblock() + strloc;
6852 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6853 * The result is a_\_z_c (not a\_\_z_c)!
6855 * The search pattern and replace string treat backslashes differently!
6856 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6857 * and string. It's only used on the first call.
6859 preglob(str, IF_BASH_PATTERN_SUBST(
6860 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6861 RMESCAPE_SLASH : ) 0);
6863 #if BASH_PATTERN_SUBST
6864 workloc = expdest - (char *)stackblock();
6865 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6870 repl = strchr(str, CTLESC);
6876 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6878 /* If there's no pattern to match, return the expansion unmolested */
6887 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6888 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6890 /* No match, advance */
6891 char *restart_detect = stackblock();
6893 STPUTC(*idx, expdest);
6894 if (quotes && (unsigned char)*idx == CTLESC) {
6897 STPUTC(*idx, expdest);
6899 if (stackblock() != restart_detect)
6904 /* continue; - prone to quadratic behavior, smarter code: */
6907 if (str[0] == '*') {
6908 /* Pattern is "*foo". If "*foo" does not match "long_string",
6909 * it would never match "ong_string" etc, no point in trying.
6916 if (subtype == VSREPLACEALL) {
6918 if (quotes && (unsigned char)*idx == CTLESC)
6927 //bb_error_msg("repl:'%s'", repl);
6928 for (loc = (char*)repl; *loc; loc++) {
6929 char *restart_detect = stackblock();
6930 if (quotes && *loc == '\\') {
6931 STPUTC(CTLESC, expdest);
6934 STPUTC(*loc, expdest);
6935 if (stackblock() != restart_detect)
6940 if (subtype == VSREPLACE) {
6941 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6943 char *restart_detect = stackblock();
6944 STPUTC(*idx, expdest);
6945 if (stackblock() != restart_detect)
6954 /* We've put the replaced text into a buffer at workloc, now
6955 * move it to the right place and adjust the stack.
6957 STPUTC('\0', expdest);
6958 startp = (char *)stackblock() + startloc;
6959 memmove(startp, (char *)stackblock() + workloc, len + 1);
6960 //bb_error_msg("startp:'%s'", startp);
6961 amount = expdest - (startp + len);
6962 STADJUST(-amount, expdest);
6965 #endif /* BASH_PATTERN_SUBST */
6967 subtype -= VSTRIMRIGHT;
6969 if (subtype < 0 || subtype > 7)
6972 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6973 zero = subtype >> 1;
6974 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6975 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6977 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6980 memmove(startp, loc, str - loc);
6981 loc = startp + (str - loc) - 1;
6984 amount = loc - expdest;
6985 STADJUST(amount, expdest);
6991 * Add the value of a specialized variable to the stack string.
6992 * name parameter (examples):
6993 * ash -c 'echo $1' name:'1='
6994 * ash -c 'echo $qwe' name:'qwe='
6995 * ash -c 'echo $$' name:'$='
6996 * ash -c 'echo ${$}' name:'$='
6997 * ash -c 'echo ${$##q}' name:'$=q'
6998 * ash -c 'echo ${#$}' name:'$='
6999 * note: examples with bad shell syntax:
7000 * ash -c 'echo ${#$1}' name:'$=1'
7001 * ash -c 'echo ${#1#}' name:'1=#'
7003 static NOINLINE ssize_t
7004 varvalue(char *name, int varflags, int flags, int *quotedp)
7011 int quoted = *quotedp;
7012 int subtype = varflags & VSTYPE;
7013 int discard = subtype == VSPLUS || subtype == VSLENGTH;
7014 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
7017 sep = (flags & EXP_FULL) << CHAR_BIT;
7018 syntax = quoted ? DQSYNTAX : BASESYNTAX;
7028 num = shellparam.nparam;
7036 goto check_1char_name;
7038 expdest = makestrspace(NOPTS, expdest);
7039 for (i = NOPTS - 1; i >= 0; i--) {
7041 USTPUTC(optletters(i), expdest);
7047 /* handles cases similar to ${#$1} */
7048 if (name[2] != '\0')
7049 raise_error_syntax("bad substitution");
7062 sep |= ifsset() ? ifsval()[0] : ' ';
7069 while ((p = *ap++) != NULL) {
7070 len += strtodest(p, syntax, quotes);
7074 memtodest(&sepc, 1, syntax, quotes);
7089 num = atoi(name); /* number(name) fails on ${N#str} etc */
7090 if (num < 0 || num > shellparam.nparam)
7092 p = num ? shellparam.p[num - 1] : arg0;
7095 /* NB: name has form "VAR=..." */
7096 p = lookupvar(name);
7101 len = strtodest(p, syntax, quotes);
7102 #if ENABLE_UNICODE_SUPPORT
7103 if (subtype == VSLENGTH && len > 0) {
7104 reinit_unicode_for_ash();
7105 if (unicode_status == UNICODE_ON) {
7106 STADJUST(-len, expdest);
7108 len = unicode_strlen(p);
7116 STADJUST(-len, expdest);
7121 * Expand a variable, and return a pointer to the next character in the
7125 evalvar(char *p, int flag)
7136 varflags = (unsigned char) *p++;
7137 subtype = varflags & VSTYPE;
7140 raise_error_syntax("bad substitution");
7142 quoted = flag & EXP_QUOTED;
7144 easy = (!quoted || (*var == '@' && shellparam.nparam));
7145 startloc = expdest - (char *)stackblock();
7146 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
7149 varlen = varvalue(var, varflags, flag, "ed);
7150 if (varflags & VSNUL)
7153 if (subtype == VSPLUS) {
7154 varlen = -1 - varlen;
7158 if (subtype == VSMINUS) {
7163 flag | EXP_TILDE | EXP_WORD
7170 if (subtype == VSASSIGN || subtype == VSQUESTION) {
7174 subevalvar(p, var, 0, subtype, startloc, varflags,
7175 flag & ~QUOTES_ESC);
7178 * Remove any recorded regions beyond
7181 removerecordregions(startloc);
7185 if (varlen < 0 && uflag)
7186 varunset(p, var, 0, 0);
7188 if (subtype == VSLENGTH) {
7189 cvtnum(varlen > 0 ? varlen : 0);
7193 if (subtype == VSNORMAL) {
7197 recordregion(startloc, expdest - (char *)stackblock(), quoted);
7206 case VSTRIMRIGHTMAX:
7210 #if BASH_PATTERN_SUBST
7222 * Terminate the string and start recording the pattern
7225 STPUTC('\0', expdest);
7226 patloc = expdest - (char *)stackblock();
7227 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
7228 startloc, varflags, flag)) {
7229 int amount = expdest - (
7230 (char *)stackblock() + patloc - 1
7232 STADJUST(-amount, expdest);
7234 /* Remove any recorded regions beyond start of variable */
7235 removerecordregions(startloc);
7240 if (subtype != VSNORMAL) { /* skip to end of alternative */
7243 unsigned char c = *p++;
7246 else if (c == CTLBACKQ) {
7248 argbackq = argbackq->next;
7249 } else if (c == CTLVAR) {
7250 if ((*p++ & VSTYPE) != VSNORMAL)
7252 } else if (c == CTLENDVAR) {
7262 * Add a file name to the list.
7265 addfname(const char *name)
7269 sp = stzalloc(sizeof(*sp));
7270 sp->text = sstrdup(name);
7272 exparg.lastp = &sp->next;
7275 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7277 hasmeta(const char *p)
7279 static const char chars[] ALIGN1 = {
7280 '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
7284 p = strpbrk(p, chars);
7287 switch ((unsigned char) *p) {
7291 if (*p == CTLQUOTEMARK)
7295 if (*p == '\0') /* huh? */
7306 if (!strchr(p + 1, ']')) {
7307 /* It's not a properly closed [] pattern,
7308 * but other metas may follow. Continue checking.
7309 * my[file* _is_ globbed by bash
7310 * and matches filenames like "my[file1".
7326 /* If we want to use glob() from libc... */
7327 #if !ENABLE_ASH_INTERNAL_GLOB
7329 /* Add the result of glob() to the list */
7331 addglob(const glob_t *pglob)
7333 char **p = pglob->gl_pathv;
7340 expandmeta(struct strlist *str /*, int flag*/)
7342 /* TODO - EXP_REDIR */
7352 if (!hasmeta(str->text))
7356 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7357 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7358 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7360 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7361 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7362 // Which means you need to unescape the string, right? Not so fast:
7363 // if there _is_ a file named "file\?" (with backslash), it is returned
7364 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7365 // You DON'T KNOW by looking at the result whether you need to unescape it.
7367 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7368 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7369 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7370 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7371 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7372 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7373 i = glob(p, 0, NULL, &pglob);
7374 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7379 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7380 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7381 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7393 *exparg.lastp = str;
7394 rmescapes(str->text, 0);
7395 exparg.lastp = &str->next;
7397 default: /* GLOB_NOSPACE */
7400 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7407 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7410 * Do metacharacter (i.e. *, ?, [...]) expansion.
7413 expmeta(char *expdir, char *enddir, char *name)
7429 for (p = name; esc = 0, *p; p += esc + 1) {
7430 if (*p == '*' || *p == '?')
7432 else if (*p == '[') {
7439 if (*q == '/' || *q == '\0')
7449 if (p[esc] == '/') {
7452 start = p + esc + 1;
7456 if (metaflag == 0) { /* we've reached the end of the file name */
7457 if (enddir != expdir)
7465 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7476 } while (p < start);
7478 if (enddir == expdir) {
7480 } else if (enddir == expdir + 1 && *expdir == '/') {
7489 if (enddir != expdir)
7491 if (*endname == 0) {
7504 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7505 if (dp->d_name[0] == '.' && !matchdot)
7507 if (pmatch(start, dp->d_name)) {
7509 strcpy(enddir, dp->d_name);
7512 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7515 expmeta(expdir, p, endname);
7521 endname[-esc - 1] = esc ? '\\' : '/';
7524 static struct strlist *
7525 msort(struct strlist *list, int len)
7527 struct strlist *p, *q = NULL;
7528 struct strlist **lpp;
7536 for (n = half; --n >= 0;) {
7540 q->next = NULL; /* terminate first half of list */
7541 q = msort(list, half); /* sort first half of list */
7542 p = msort(p, len - half); /* sort second half */
7545 #if ENABLE_LOCALE_SUPPORT
7546 if (strcoll(p->text, q->text) < 0)
7548 if (strcmp(p->text, q->text) < 0)
7572 * Sort the results of file name expansion. It calculates the number of
7573 * strings to sort and then calls msort (short for merge sort) to do the
7576 static struct strlist *
7577 expsort(struct strlist *str)
7583 for (sp = str; sp; sp = sp->next)
7585 return msort(str, len);
7589 expandmeta(struct strlist *str /*, int flag*/)
7591 /* TODO - EXP_REDIR */
7595 struct strlist **savelastp;
7601 if (!hasmeta(str->text))
7603 savelastp = exparg.lastp;
7606 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7608 int i = strlen(str->text);
7609 //BUGGY estimation of how long expanded name can be
7610 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7612 expmeta(expdir, expdir, p);
7617 if (exparg.lastp == savelastp) {
7622 *exparg.lastp = str;
7623 rmescapes(str->text, 0);
7624 exparg.lastp = &str->next;
7626 *exparg.lastp = NULL;
7627 *savelastp = sp = expsort(*savelastp);
7628 while (sp->next != NULL)
7630 exparg.lastp = &sp->next;
7635 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7638 * Perform variable substitution and command substitution on an argument,
7639 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7640 * perform splitting and file name expansion. When arglist is NULL, perform
7641 * here document expansion.
7644 expandarg(union node *arg, struct arglist *arglist, int flag)
7649 argbackq = arg->narg.backquote;
7650 STARTSTACKSTR(expdest);
7651 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7652 argstr(arg->narg.text, flag);
7653 p = _STPUTC('\0', expdest);
7655 if (arglist == NULL) {
7656 /* here document expanded */
7659 p = grabstackstr(p);
7660 TRACE(("expandarg: p:'%s'\n", p));
7661 exparg.lastp = &exparg.list;
7665 if (flag & EXP_FULL) {
7666 ifsbreakup(p, &exparg);
7667 *exparg.lastp = NULL;
7668 exparg.lastp = &exparg.list;
7669 expandmeta(exparg.list /*, flag*/);
7671 sp = stzalloc(sizeof(*sp));
7674 exparg.lastp = &sp->next;
7676 *exparg.lastp = NULL;
7678 *arglist->lastp = exparg.list;
7679 arglist->lastp = exparg.lastp;
7687 * Expand shell variables and backquotes inside a here document.
7690 expandhere(union node *arg, int fd)
7692 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7693 full_write(fd, stackblock(), expdest - (char *)stackblock());
7697 * Returns true if the pattern matches the string.
7700 patmatch(char *pattern, const char *string)
7702 char *p = preglob(pattern, 0);
7703 //bb_error_msg("fnmatch(pattern:'%s',str:'%s')", p, string);
7704 return pmatch(p, string);
7708 * See if a pattern matches in a case statement.
7711 casematch(union node *pattern, char *val)
7713 struct stackmark smark;
7716 setstackmark(&smark);
7717 argbackq = pattern->narg.backquote;
7718 STARTSTACKSTR(expdest);
7719 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
7720 STACKSTRNUL(expdest);
7722 result = patmatch(stackblock(), val);
7723 popstackmark(&smark);
7728 /* ============ find_command */
7732 int (*builtin)(int, char **) FAST_FUNC;
7733 /* unsigned flags; */
7735 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7736 /* "regular" builtins always take precedence over commands,
7737 * regardless of PATH=....%builtin... position */
7738 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7739 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7742 smallint cmdtype; /* CMDxxx */
7745 /* index >= 0 for commands without path (slashes) */
7746 /* (TODO: what exactly does the value mean? PATH position?) */
7747 /* index == -1 for commands with slashes */
7748 /* index == (-2 - applet_no) for NOFORK applets */
7749 const struct builtincmd *cmd;
7750 struct funcnode *func;
7753 /* values of cmdtype */
7754 #define CMDUNKNOWN -1 /* no entry in table for command */
7755 #define CMDNORMAL 0 /* command is an executable program */
7756 #define CMDFUNCTION 1 /* command is a shell function */
7757 #define CMDBUILTIN 2 /* command is a shell builtin */
7759 /* action to find_command() */
7760 #define DO_ERR 0x01 /* prints errors */
7761 #define DO_ABS 0x02 /* checks absolute paths */
7762 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7763 #define DO_ALTPATH 0x08 /* using alternate path */
7764 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7766 static void find_command(char *, struct cmdentry *, int, const char *);
7769 /* ============ Hashing commands */
7772 * When commands are first encountered, they are entered in a hash table.
7773 * This ensures that a full path search will not have to be done for them
7774 * on each invocation.
7776 * We should investigate converting to a linear search, even though that
7777 * would make the command name "hash" a misnomer.
7781 struct tblentry *next; /* next entry in hash chain */
7782 union param param; /* definition of builtin function */
7783 smallint cmdtype; /* CMDxxx */
7784 char rehash; /* if set, cd done since entry created */
7785 char cmdname[1]; /* name of command */
7788 static struct tblentry **cmdtable;
7789 #define INIT_G_cmdtable() do { \
7790 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7793 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7797 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
7799 #if ENABLE_FEATURE_SH_STANDALONE
7800 if (applet_no >= 0) {
7801 if (APPLET_IS_NOEXEC(applet_no)) {
7805 popredir(/*drop:*/ 1);
7806 run_applet_no_and_exit(applet_no, cmd, argv);
7808 /* re-exec ourselves with the new arguments */
7809 execve(bb_busybox_exec_path, argv, envp);
7810 /* If they called chroot or otherwise made the binary no longer
7811 * executable, fall through */
7818 execve(cmd, argv, envp);
7819 } while (errno == EINTR);
7821 execve(cmd, argv, envp);
7823 if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
7824 /* Run "cmd" as a shell script:
7825 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7826 * "If the execve() function fails with ENOEXEC, the shell
7827 * shall execute a command equivalent to having a shell invoked
7828 * with the command name as its first operand,
7829 * with any remaining arguments passed to the new shell"
7831 * That is, do not use $SHELL, user's shell, or /bin/sh;
7832 * just call ourselves.
7834 * Note that bash reads ~80 chars of the file, and if it sees
7835 * a zero byte before it sees newline, it doesn't try to
7836 * interpret it, but fails with "cannot execute binary file"
7837 * message and exit code 126. For one, this prevents attempts
7838 * to interpret foreign ELF binaries as shell scripts.
7840 argv[0] = (char*) cmd;
7841 cmd = bb_busybox_exec_path;
7842 /* NB: this is only possible because all callers of shellexec()
7843 * ensure that the argv[-1] slot exists!
7846 argv[0] = (char*) "ash";
7852 * Exec a program. Never returns. If you change this routine, you may
7853 * have to change the find_command routine as well.
7854 * argv[-1] must exist and be writable! See tryexec() for why.
7856 static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
7857 static void shellexec(char *prog, char **argv, const char *path, int idx)
7863 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7865 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7866 if (strchr(prog, '/') != NULL
7867 #if ENABLE_FEATURE_SH_STANDALONE
7868 || (applet_no = find_applet_by_name(prog)) >= 0
7871 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
7872 if (applet_no >= 0) {
7873 /* We tried execing ourself, but it didn't work.
7874 * Maybe /proc/self/exe doesn't exist?
7883 while ((cmdname = path_advance(&path, prog)) != NULL) {
7884 if (--idx < 0 && pathopt == NULL) {
7885 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7886 if (errno != ENOENT && errno != ENOTDIR)
7893 /* Map to POSIX errors */
7905 exitstatus = exerrno;
7906 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7907 prog, e, suppress_int));
7908 ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
7913 printentry(struct tblentry *cmdp)
7919 idx = cmdp->param.index;
7922 name = path_advance(&path, cmdp->cmdname);
7924 } while (--idx >= 0);
7925 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7929 * Clear out command entries. The argument specifies the first entry in
7930 * PATH which has changed.
7933 clearcmdentry(int firstchange)
7935 struct tblentry **tblp;
7936 struct tblentry **pp;
7937 struct tblentry *cmdp;
7940 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7942 while ((cmdp = *pp) != NULL) {
7943 if ((cmdp->cmdtype == CMDNORMAL &&
7944 cmdp->param.index >= firstchange)
7945 || (cmdp->cmdtype == CMDBUILTIN &&
7946 builtinloc >= firstchange)
7959 * Locate a command in the command hash table. If "add" is nonzero,
7960 * add the command to the table if it is not already present. The
7961 * variable "lastcmdentry" is set to point to the address of the link
7962 * pointing to the entry, so that delete_cmd_entry can delete the
7965 * Interrupts must be off if called with add != 0.
7967 static struct tblentry **lastcmdentry;
7969 static struct tblentry *
7970 cmdlookup(const char *name, int add)
7972 unsigned int hashval;
7974 struct tblentry *cmdp;
7975 struct tblentry **pp;
7978 hashval = (unsigned char)*p << 4;
7980 hashval += (unsigned char)*p++;
7982 pp = &cmdtable[hashval % CMDTABLESIZE];
7983 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7984 if (strcmp(cmdp->cmdname, name) == 0)
7988 if (add && cmdp == NULL) {
7989 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7991 /* + 1 - already done because
7992 * tblentry::cmdname is char[1] */);
7993 /*cmdp->next = NULL; - ckzalloc did it */
7994 cmdp->cmdtype = CMDUNKNOWN;
7995 strcpy(cmdp->cmdname, name);
8002 * Delete the command entry returned on the last lookup.
8005 delete_cmd_entry(void)
8007 struct tblentry *cmdp;
8010 cmdp = *lastcmdentry;
8011 *lastcmdentry = cmdp->next;
8012 if (cmdp->cmdtype == CMDFUNCTION)
8013 freefunc(cmdp->param.func);
8019 * Add a new command entry, replacing any existing command entry for
8020 * the same name - except special builtins.
8023 addcmdentry(char *name, struct cmdentry *entry)
8025 struct tblentry *cmdp;
8027 cmdp = cmdlookup(name, 1);
8028 if (cmdp->cmdtype == CMDFUNCTION) {
8029 freefunc(cmdp->param.func);
8031 cmdp->cmdtype = entry->cmdtype;
8032 cmdp->param = entry->u;
8036 static int FAST_FUNC
8037 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8039 struct tblentry **pp;
8040 struct tblentry *cmdp;
8042 struct cmdentry entry;
8045 if (nextopt("r") != '\0') {
8050 if (*argptr == NULL) {
8051 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8052 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8053 if (cmdp->cmdtype == CMDNORMAL)
8061 while ((name = *argptr) != NULL) {
8062 cmdp = cmdlookup(name, 0);
8064 && (cmdp->cmdtype == CMDNORMAL
8065 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
8069 find_command(name, &entry, DO_ERR, pathval());
8070 if (entry.cmdtype == CMDUNKNOWN)
8078 * Called when a cd is done. Marks all commands so the next time they
8079 * are executed they will be rehashed.
8084 struct tblentry **pp;
8085 struct tblentry *cmdp;
8087 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8088 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8089 if (cmdp->cmdtype == CMDNORMAL
8090 || (cmdp->cmdtype == CMDBUILTIN
8091 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
8101 * Fix command hash table when PATH changed.
8102 * Called before PATH is changed. The argument is the new value of PATH;
8103 * pathval() still returns the old value at this point.
8104 * Called with interrupts off.
8106 static void FAST_FUNC
8107 changepath(const char *new)
8115 firstchange = 9999; /* assume no change */
8121 if ((*old == '\0' && *new == ':')
8122 || (*old == ':' && *new == '\0')
8126 old = new; /* ignore subsequent differences */
8130 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
8137 if (builtinloc < 0 && idx_bltin >= 0)
8138 builtinloc = idx_bltin; /* zap builtins */
8139 if (builtinloc >= 0 && idx_bltin < 0)
8141 clearcmdentry(firstchange);
8142 builtinloc = idx_bltin;
8178 typedef smallint token_id_t;
8180 /* Nth bit indicates if token marks the end of a list */
8183 /* 0 */ | (1u << TEOF)
8184 /* 1 */ | (0u << TNL)
8185 /* 2 */ | (0u << TREDIR)
8186 /* 3 */ | (0u << TWORD)
8187 /* 4 */ | (0u << TSEMI)
8188 /* 5 */ | (0u << TBACKGND)
8189 /* 6 */ | (0u << TAND)
8190 /* 7 */ | (0u << TOR)
8191 /* 8 */ | (0u << TPIPE)
8192 /* 9 */ | (0u << TLP)
8193 /* 10 */ | (1u << TRP)
8194 /* 11 */ | (1u << TENDCASE)
8195 /* 12 */ | (1u << TENDBQUOTE)
8196 /* 13 */ | (0u << TNOT)
8197 /* 14 */ | (0u << TCASE)
8198 /* 15 */ | (1u << TDO)
8199 /* 16 */ | (1u << TDONE)
8200 /* 17 */ | (1u << TELIF)
8201 /* 18 */ | (1u << TELSE)
8202 /* 19 */ | (1u << TESAC)
8203 /* 20 */ | (1u << TFI)
8204 /* 21 */ | (0u << TFOR)
8206 /* 22 */ | (0u << TFUNCTION)
8208 /* 23 */ | (0u << TIF)
8209 /* 24 */ | (0u << TIN)
8210 /* 25 */ | (1u << TTHEN)
8211 /* 26 */ | (0u << TUNTIL)
8212 /* 27 */ | (0u << TWHILE)
8213 /* 28 */ | (0u << TBEGIN)
8214 /* 29 */ | (1u << TEND)
8215 , /* thus far 29 bits used */
8218 static const char *const tokname_array[] = {
8232 #define KWDOFFSET 13
8233 /* the following are keywords */
8255 /* Wrapper around strcmp for qsort/bsearch/... */
8257 pstrcmp(const void *a, const void *b)
8259 return strcmp((char*)a, *(char**)b);
8262 static const char *const *
8263 findkwd(const char *s)
8265 return bsearch(s, tokname_array + KWDOFFSET,
8266 ARRAY_SIZE(tokname_array) - KWDOFFSET,
8267 sizeof(tokname_array[0]), pstrcmp);
8271 * Locate and print what a word is...
8274 describe_command(char *command, const char *path, int describe_command_verbose)
8276 struct cmdentry entry;
8277 #if ENABLE_ASH_ALIAS
8278 const struct alias *ap;
8281 path = path ? path : pathval();
8283 if (describe_command_verbose) {
8287 /* First look at the keywords */
8288 if (findkwd(command)) {
8289 out1str(describe_command_verbose ? " is a shell keyword" : command);
8293 #if ENABLE_ASH_ALIAS
8294 /* Then look at the aliases */
8295 ap = lookupalias(command, 0);
8297 if (!describe_command_verbose) {
8302 out1fmt(" is an alias for %s", ap->val);
8307 find_command(command, &entry, DO_ABS, path);
8309 switch (entry.cmdtype) {
8311 int j = entry.u.index;
8317 p = path_advance(&path, command);
8321 if (describe_command_verbose) {
8322 out1fmt(" is %s", p);
8330 if (describe_command_verbose) {
8331 out1str(" is a shell function");
8338 if (describe_command_verbose) {
8339 out1fmt(" is a %sshell builtin",
8340 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8341 "special " : nullstr
8349 if (describe_command_verbose) {
8350 out1str(": not found\n");
8359 static int FAST_FUNC
8360 typecmd(int argc UNUSED_PARAM, char **argv)
8366 /* type -p ... ? (we don't bother checking for 'p') */
8367 if (argv[1] && argv[1][0] == '-') {
8372 err |= describe_command(argv[i++], NULL, verbose);
8377 #if ENABLE_ASH_CMDCMD
8378 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8380 parse_command_args(char **argv, const char **path)
8393 if (c == '-' && !*cp) {
8401 *path = bb_default_path;
8404 /* run 'typecmd' for other options */
8413 static int FAST_FUNC
8414 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8422 const char *path = NULL;
8424 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8425 * never reaches this function.
8428 while ((c = nextopt("pvV")) != '\0')
8430 verify |= VERIFY_VERBOSE;
8432 /*verify |= VERIFY_BRIEF*/;
8438 path = bb_default_path;
8440 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8442 if (/*verify && */ cmd)
8443 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8450 /*static int funcblocksize; // size of structures in function */
8451 /*static int funcstringsize; // size of strings in node */
8452 static void *funcblock; /* block to allocate function from */
8453 static char *funcstring_end; /* end of block to allocate strings from */
8455 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8456 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8457 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8458 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8459 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8460 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8461 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8462 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8463 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8464 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8465 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8466 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8467 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8468 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8469 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8470 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8471 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8472 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8473 #if BASH_REDIR_OUTPUT
8474 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8476 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8477 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8478 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8479 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8480 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8481 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8482 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8483 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8484 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8487 static int calcsize(int funcblocksize, union node *n);
8490 sizenodelist(int funcblocksize, struct nodelist *lp)
8493 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8494 funcblocksize = calcsize(funcblocksize, lp->n);
8497 return funcblocksize;
8501 calcsize(int funcblocksize, union node *n)
8504 return funcblocksize;
8505 funcblocksize += nodesize[n->type];
8508 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8509 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8510 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8513 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8518 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8519 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8526 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8527 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8530 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8531 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8532 funcblocksize = calcsize(funcblocksize, n->nif.test);
8535 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8536 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8537 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8540 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8541 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8544 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8545 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8546 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8550 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8551 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8552 funcblocksize = calcsize(funcblocksize, n->narg.next);
8555 #if BASH_REDIR_OUTPUT
8562 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8563 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8567 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8568 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8572 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8573 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8576 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8579 return funcblocksize;
8583 nodeckstrdup(char *s)
8585 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8586 return strcpy(funcstring_end, s);
8589 static union node *copynode(union node *);
8591 static struct nodelist *
8592 copynodelist(struct nodelist *lp)
8594 struct nodelist *start;
8595 struct nodelist **lpp;
8600 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8601 (*lpp)->n = copynode(lp->n);
8603 lpp = &(*lpp)->next;
8610 copynode(union node *n)
8617 funcblock = (char *) funcblock + nodesize[n->type];
8621 new->ncmd.redirect = copynode(n->ncmd.redirect);
8622 new->ncmd.args = copynode(n->ncmd.args);
8623 new->ncmd.assign = copynode(n->ncmd.assign);
8626 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8627 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8632 new->nredir.redirect = copynode(n->nredir.redirect);
8633 new->nredir.n = copynode(n->nredir.n);
8640 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8641 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8644 new->nif.elsepart = copynode(n->nif.elsepart);
8645 new->nif.ifpart = copynode(n->nif.ifpart);
8646 new->nif.test = copynode(n->nif.test);
8649 new->nfor.var = nodeckstrdup(n->nfor.var);
8650 new->nfor.body = copynode(n->nfor.body);
8651 new->nfor.args = copynode(n->nfor.args);
8654 new->ncase.cases = copynode(n->ncase.cases);
8655 new->ncase.expr = copynode(n->ncase.expr);
8658 new->nclist.body = copynode(n->nclist.body);
8659 new->nclist.pattern = copynode(n->nclist.pattern);
8660 new->nclist.next = copynode(n->nclist.next);
8664 new->narg.backquote = copynodelist(n->narg.backquote);
8665 new->narg.text = nodeckstrdup(n->narg.text);
8666 new->narg.next = copynode(n->narg.next);
8669 #if BASH_REDIR_OUTPUT
8676 new->nfile.fname = copynode(n->nfile.fname);
8677 new->nfile.fd = n->nfile.fd;
8678 new->nfile.next = copynode(n->nfile.next);
8682 new->ndup.vname = copynode(n->ndup.vname);
8683 new->ndup.dupfd = n->ndup.dupfd;
8684 new->ndup.fd = n->ndup.fd;
8685 new->ndup.next = copynode(n->ndup.next);
8689 new->nhere.doc = copynode(n->nhere.doc);
8690 new->nhere.fd = n->nhere.fd;
8691 new->nhere.next = copynode(n->nhere.next);
8694 new->nnot.com = copynode(n->nnot.com);
8697 new->type = n->type;
8702 * Make a copy of a parse tree.
8704 static struct funcnode *
8705 copyfunc(union node *n)
8710 /*funcstringsize = 0;*/
8711 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8712 f = ckzalloc(blocksize /* + funcstringsize */);
8713 funcblock = (char *) f + offsetof(struct funcnode, n);
8714 funcstring_end = (char *) f + blocksize;
8716 /* f->count = 0; - ckzalloc did it */
8721 * Define a shell function.
8724 defun(union node *func)
8726 struct cmdentry entry;
8729 entry.cmdtype = CMDFUNCTION;
8730 entry.u.func = copyfunc(func);
8731 addcmdentry(func->narg.text, &entry);
8735 /* Reasons for skipping commands (see comment on breakcmd routine) */
8736 #define SKIPBREAK (1 << 0)
8737 #define SKIPCONT (1 << 1)
8738 #define SKIPFUNC (1 << 2)
8739 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8740 static int skipcount; /* number of levels to skip */
8741 static int funcnest; /* depth of function calls */
8742 static int loopnest; /* current loop nesting level */
8744 /* Forward decl way out to parsing code - dotrap needs it */
8745 static int evalstring(char *s, int flags);
8747 /* Called to execute a trap.
8748 * Single callsite - at the end of evaltree().
8749 * If we return non-zero, evaltree raises EXEXIT exception.
8751 * Perhaps we should avoid entering new trap handlers
8752 * while we are executing a trap handler. [is it a TODO?]
8759 uint8_t last_status;
8764 last_status = exitstatus;
8768 TRACE(("dotrap entered\n"));
8769 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8781 /* non-trapped SIGINT is handled separately by raise_interrupt,
8782 * don't upset it by resetting gotsig[SIGINT-1] */
8783 if (sig == SIGINT && !p)
8786 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8792 exitstatus = last_status;
8793 TRACE(("dotrap returns\n"));
8796 /* forward declarations - evaluation is fairly recursive business... */
8797 static int evalloop(union node *, int);
8798 static int evalfor(union node *, int);
8799 static int evalcase(union node *, int);
8800 static int evalsubshell(union node *, int);
8801 static void expredir(union node *);
8802 static int evalpipe(union node *, int);
8803 static int evalcommand(union node *, int);
8804 static int evalbltin(const struct builtincmd *, int, char **, int);
8805 static void prehash(union node *);
8808 * Evaluate a parse tree. The value is left in the global variable
8812 evaltree(union node *n, int flags)
8815 int (*evalfn)(union node *, int);
8819 TRACE(("evaltree(NULL) called\n"));
8822 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8829 out1fmt("Node type = %d\n", n->type);
8834 status = !evaltree(n->nnot.com, EV_TESTED);
8837 expredir(n->nredir.redirect);
8838 pushredir(n->nredir.redirect);
8839 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8841 status = evaltree(n->nredir.n, flags & EV_TESTED);
8843 if (n->nredir.redirect)
8844 popredir(/*drop:*/ 0);
8847 evalfn = evalcommand;
8849 if (eflag && !(flags & EV_TESTED))
8861 evalfn = evalsubshell;
8874 #error NAND + 1 != NOR
8876 #if NOR + 1 != NSEMI
8877 #error NOR + 1 != NSEMI
8879 unsigned is_or = n->type - NAND;
8882 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8884 if ((!status) == is_or || evalskip)
8890 status = evalfn(n, flags);
8894 status = evaltree(n->nif.test, EV_TESTED);
8901 if (n->nif.elsepart) {
8902 n = n->nif.elsepart;
8909 /* Not necessary. To test it:
8910 * "false; f() { qwerty; }; echo $?" should print 0.
8914 exitstatus = status;
8918 /* Order of checks below is important:
8919 * signal handlers trigger before exit caused by "set -e".
8923 if (checkexit & status)
8924 raise_exception(EXEXIT);
8925 if (flags & EV_EXIT)
8926 raise_exception(EXEXIT);
8928 TRACE(("leaving evaltree (no interrupts)\n"));
8935 int skip = evalskip;
8942 if (--skipcount <= 0) {
8953 evalloop(union node *n, int flags)
8964 i = evaltree(n->nbinary.ch1, EV_TESTED);
8966 if (skip == SKIPFUNC)
8970 if (n->type != NWHILE)
8974 status = evaltree(n->nbinary.ch2, flags);
8976 } while (!(skip & ~SKIPCONT));
8983 evalfor(union node *n, int flags)
8985 struct arglist arglist;
8988 struct stackmark smark;
8991 setstackmark(&smark);
8992 arglist.list = NULL;
8993 arglist.lastp = &arglist.list;
8994 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8995 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8997 *arglist.lastp = NULL;
9001 for (sp = arglist.list; sp; sp = sp->next) {
9002 setvar0(n->nfor.var, sp->text);
9003 status = evaltree(n->nfor.body, flags);
9004 if (skiploop() & ~SKIPCONT)
9008 popstackmark(&smark);
9014 evalcase(union node *n, int flags)
9018 struct arglist arglist;
9019 struct stackmark smark;
9022 setstackmark(&smark);
9023 arglist.list = NULL;
9024 arglist.lastp = &arglist.list;
9025 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
9026 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
9027 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
9028 if (casematch(patp, arglist.list->text)) {
9029 /* Ensure body is non-empty as otherwise
9030 * EV_EXIT may prevent us from setting the
9033 if (evalskip == 0 && cp->nclist.body) {
9034 status = evaltree(cp->nclist.body, flags);
9041 popstackmark(&smark);
9047 * Kick off a subshell to evaluate a tree.
9050 evalsubshell(union node *n, int flags)
9053 int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
9056 expredir(n->nredir.redirect);
9057 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
9060 if (backgnd == FORK_FG)
9062 jp = makejob(/*n,*/ 1);
9063 if (forkshell(jp, n, backgnd) == 0) {
9068 flags &= ~EV_TESTED;
9070 redirect(n->nredir.redirect, 0);
9071 evaltreenr(n->nredir.n, flags);
9076 if (backgnd == FORK_FG)
9077 status = waitforjob(jp);
9083 * Compute the names of the files in a redirection list.
9085 static void fixredir(union node *, const char *, int);
9087 expredir(union node *n)
9091 for (redir = n; redir; redir = redir->nfile.next) {
9095 fn.lastp = &fn.list;
9096 switch (redir->type) {
9100 #if BASH_REDIR_OUTPUT
9105 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
9106 TRACE(("expredir expanded to '%s'\n", fn.list->text));
9107 #if BASH_REDIR_OUTPUT
9111 // By the design of stack allocator, the loop of this kind:
9112 // while true; do while true; do break; done </dev/null; done
9113 // will look like a memory leak: ash plans to free expfname's
9114 // of "/dev/null" as soon as it finishes running the loop
9115 // (in this case, never).
9116 // This "fix" is wrong:
9117 if (redir->nfile.expfname)
9118 stunalloc(redir->nfile.expfname);
9119 // It results in corrupted state of stacked allocations.
9121 redir->nfile.expfname = fn.list->text;
9124 case NTOFD: /* >& */
9125 if (redir->ndup.vname) {
9126 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
9127 if (fn.list == NULL)
9128 ash_msg_and_raise_error("redir error");
9129 #if BASH_REDIR_OUTPUT
9130 //FIXME: we used expandarg with different args!
9131 if (!isdigit_str9(fn.list->text)) {
9132 /* >&file, not >&fd */
9133 if (redir->nfile.fd != 1) /* 123>&file - BAD */
9134 ash_msg_and_raise_error("redir error");
9136 goto store_expfname;
9139 fixredir(redir, fn.list->text, 1);
9147 * Evaluate a pipeline. All the processes in the pipeline are children
9148 * of the process creating the pipeline. (This differs from some versions
9149 * of the shell, which make the last process in a pipeline the parent
9153 evalpipe(union node *n, int flags)
9156 struct nodelist *lp;
9162 TRACE(("evalpipe(0x%lx) called\n", (long)n));
9164 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
9168 if (n->npipe.pipe_backgnd == 0)
9170 jp = makejob(/*n,*/ pipelen);
9172 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
9176 if (pipe(pip) < 0) {
9178 ash_msg_and_raise_error("pipe call failed");
9181 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
9195 evaltreenr(lp->n, flags);
9202 /* Don't want to trigger debugging */
9206 if (n->npipe.pipe_backgnd == 0) {
9207 status = waitforjob(jp);
9208 TRACE(("evalpipe: job done exit status %d\n", status));
9216 * Controls whether the shell is interactive or not.
9219 setinteractive(int on)
9221 static smallint is_interactive;
9223 if (++on == is_interactive)
9225 is_interactive = on;
9229 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9230 if (is_interactive > 1) {
9231 /* Looks like they want an interactive shell */
9232 static smallint did_banner;
9235 /* note: ash and hush share this string */
9236 out1fmt("\n\n%s %s\n"
9237 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
9240 "built-in shell (ash)"
9254 setinteractive(iflag);
9256 #if ENABLE_FEATURE_EDITING_VI
9258 line_input_state->flags |= VI_MODE;
9260 line_input_state->flags &= ~VI_MODE;
9262 viflag = 0; /* forcibly keep the option off */
9266 struct localvar_list {
9267 struct localvar_list *next;
9268 struct localvar *lv;
9271 static struct localvar_list *localvar_stack;
9274 * Called after a function returns.
9275 * Interrupts must be off.
9278 poplocalvars(int keep)
9280 struct localvar_list *ll;
9281 struct localvar *lvp, *next;
9285 ll = localvar_stack;
9286 localvar_stack = ll->next;
9291 while ((lvp = next) != NULL) {
9294 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9296 int bits = VSTRFIXED;
9298 if (lvp->flags != VUNSET) {
9299 if (vp->var_text == lvp->text)
9301 else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
9302 free((char*)lvp->text);
9306 vp->flags |= (lvp->flags & bits);
9309 (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
9310 unsetvar(vp->var_text);
9311 } else if (vp == NULL) { /* $- saved */
9312 memcpy(optlist, lvp->text, sizeof(optlist));
9313 free((char*)lvp->text);
9315 } else if (lvp->flags == VUNSET) {
9316 vp->flags &= ~(VSTRFIXED|VREADONLY);
9317 unsetvar(vp->var_text);
9320 vp->var_func(var_end(lvp->text));
9321 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9322 free((char*)vp->var_text);
9323 vp->flags = lvp->flags;
9324 vp->var_text = lvp->text;
9332 * Create a new localvar environment.
9334 static struct localvar_list *
9337 struct localvar_list *ll;
9340 ll = ckzalloc(sizeof(*ll));
9341 /*ll->lv = NULL; - zalloc did it */
9342 ll->next = localvar_stack;
9343 localvar_stack = ll;
9350 unwindlocalvars(struct localvar_list *stop)
9352 while (localvar_stack != stop)
9357 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9359 volatile struct shparam saveparam;
9360 struct jmploc *volatile savehandler;
9361 struct jmploc jmploc;
9364 saveparam = shellparam;
9365 savehandler = exception_handler;
9366 e = setjmp(jmploc.loc);
9371 exception_handler = &jmploc;
9372 shellparam.malloced = 0;
9376 shellparam.nparam = argc - 1;
9377 shellparam.p = argv + 1;
9378 #if ENABLE_ASH_GETOPTS
9379 shellparam.optind = 1;
9380 shellparam.optoff = -1;
9383 evaltree(func->n.narg.next, flags & EV_TESTED);
9389 freeparam(&shellparam);
9390 shellparam = saveparam;
9391 exception_handler = savehandler;
9393 evalskip &= ~SKIPFUNC;
9398 * Make a variable a local variable. When a variable is made local, it's
9399 * value and flags are saved in a localvar structure. The saved values
9400 * will be restored when the shell function returns. We handle the name
9401 * "-" as a special case: it makes changes to "set +-options" local
9402 * (options will be restored on return from the function).
9407 struct localvar *lvp;
9410 char *eq = strchr(name, '=');
9413 /* Cater for duplicate "local". Examples:
9414 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9415 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9417 lvp = localvar_stack->lv;
9419 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9423 * it's a duplicate "local VAR" declaration, do nothing
9430 lvp = ckzalloc(sizeof(*lvp));
9431 if (LONE_DASH(name)) {
9433 p = ckmalloc(sizeof(optlist));
9434 lvp->text = memcpy(p, optlist, sizeof(optlist));
9437 vpp = hashvar(name);
9438 vp = *findvar(vpp, name);
9440 /* variable did not exist yet */
9442 vp = setvareq(name, VSTRFIXED);
9444 vp = setvar(name, NULL, VSTRFIXED);
9445 lvp->flags = VUNSET;
9447 lvp->text = vp->var_text;
9448 lvp->flags = vp->flags;
9449 /* make sure neither "struct var" nor string gets freed
9450 * during (un)setting:
9452 vp->flags |= VSTRFIXED|VTEXTFIXED;
9456 /* "local VAR" unsets VAR: */
9457 setvar0(name, NULL);
9461 lvp->next = localvar_stack->lv;
9462 localvar_stack->lv = lvp;
9468 * The "local" command.
9470 static int FAST_FUNC
9471 localcmd(int argc UNUSED_PARAM, char **argv)
9475 if (!localvar_stack)
9476 ash_msg_and_raise_error("not in a function");
9479 while ((name = *argv++) != NULL) {
9485 static int FAST_FUNC
9486 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9491 static int FAST_FUNC
9492 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9497 static int FAST_FUNC
9498 execcmd(int argc UNUSED_PARAM, char **argv)
9501 while (nextopt("a:") != '\0')
9502 /* nextopt() sets optionarg to "-a ARGV0" */;
9508 iflag = 0; /* exit on error */
9511 /* We should set up signals for "exec CMD"
9512 * the same way as for "CMD" without "exec".
9513 * But optschanged->setinteractive->setsignal
9514 * still thought we are a root shell. Therefore, for example,
9515 * SIGQUIT is still set to IGN. Fix it:
9519 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9520 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9521 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9525 argv[0] = optionarg;
9526 shellexec(prog, argv, pathval(), 0);
9533 * The return command.
9535 static int FAST_FUNC
9536 returncmd(int argc UNUSED_PARAM, char **argv)
9539 * If called outside a function, do what ksh does;
9540 * skip the rest of the file.
9542 evalskip = SKIPFUNC;
9543 return argv[1] ? number(argv[1]) : exitstatus;
9546 /* Forward declarations for builtintab[] */
9547 static int breakcmd(int, char **) FAST_FUNC;
9548 static int dotcmd(int, char **) FAST_FUNC;
9549 static int evalcmd(int, char **, int) FAST_FUNC;
9550 static int exitcmd(int, char **) FAST_FUNC;
9551 static int exportcmd(int, char **) FAST_FUNC;
9552 #if ENABLE_ASH_GETOPTS
9553 static int getoptscmd(int, char **) FAST_FUNC;
9556 static int helpcmd(int, char **) FAST_FUNC;
9559 static int historycmd(int, char **) FAST_FUNC;
9561 #if ENABLE_FEATURE_SH_MATH
9562 static int letcmd(int, char **) FAST_FUNC;
9564 static int readcmd(int, char **) FAST_FUNC;
9565 static int setcmd(int, char **) FAST_FUNC;
9566 static int shiftcmd(int, char **) FAST_FUNC;
9567 static int timescmd(int, char **) FAST_FUNC;
9568 static int trapcmd(int, char **) FAST_FUNC;
9569 static int umaskcmd(int, char **) FAST_FUNC;
9570 static int unsetcmd(int, char **) FAST_FUNC;
9571 static int ulimitcmd(int, char **) FAST_FUNC;
9573 #define BUILTIN_NOSPEC "0"
9574 #define BUILTIN_SPECIAL "1"
9575 #define BUILTIN_REGULAR "2"
9576 #define BUILTIN_SPEC_REG "3"
9577 #define BUILTIN_ASSIGN "4"
9578 #define BUILTIN_SPEC_ASSG "5"
9579 #define BUILTIN_REG_ASSG "6"
9580 #define BUILTIN_SPEC_REG_ASSG "7"
9582 /* Stubs for calling non-FAST_FUNC's */
9584 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9586 #if ENABLE_ASH_PRINTF
9587 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9589 #if ENABLE_ASH_TEST || BASH_TEST2
9590 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9593 /* Keep these in proper order since it is searched via bsearch() */
9594 static const struct builtincmd builtintab[] = {
9595 { BUILTIN_SPEC_REG "." , dotcmd },
9596 { BUILTIN_SPEC_REG ":" , truecmd },
9598 { BUILTIN_REGULAR "[" , testcmd },
9601 { BUILTIN_REGULAR "[[" , testcmd },
9603 #if ENABLE_ASH_ALIAS
9604 { BUILTIN_REG_ASSG "alias" , aliascmd },
9607 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9609 { BUILTIN_SPEC_REG "break" , breakcmd },
9610 { BUILTIN_REGULAR "cd" , cdcmd },
9611 { BUILTIN_NOSPEC "chdir" , cdcmd },
9612 #if ENABLE_ASH_CMDCMD
9613 { BUILTIN_REGULAR "command" , commandcmd },
9615 { BUILTIN_SPEC_REG "continue", breakcmd },
9617 { BUILTIN_REGULAR "echo" , echocmd },
9619 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9620 { BUILTIN_SPEC_REG "exec" , execcmd },
9621 { BUILTIN_SPEC_REG "exit" , exitcmd },
9622 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9623 { BUILTIN_REGULAR "false" , falsecmd },
9625 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9627 #if ENABLE_ASH_GETOPTS
9628 { BUILTIN_REGULAR "getopts" , getoptscmd },
9630 { BUILTIN_NOSPEC "hash" , hashcmd },
9632 { BUILTIN_NOSPEC "help" , helpcmd },
9635 { BUILTIN_NOSPEC "history" , historycmd },
9638 { BUILTIN_REGULAR "jobs" , jobscmd },
9639 { BUILTIN_REGULAR "kill" , killcmd },
9641 #if ENABLE_FEATURE_SH_MATH
9642 { BUILTIN_NOSPEC "let" , letcmd },
9644 { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
9645 #if ENABLE_ASH_PRINTF
9646 { BUILTIN_REGULAR "printf" , printfcmd },
9648 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9649 { BUILTIN_REGULAR "read" , readcmd },
9650 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9651 { BUILTIN_SPEC_REG "return" , returncmd },
9652 { BUILTIN_SPEC_REG "set" , setcmd },
9653 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9655 { BUILTIN_SPEC_REG "source" , dotcmd },
9658 { BUILTIN_REGULAR "test" , testcmd },
9660 { BUILTIN_SPEC_REG "times" , timescmd },
9661 { BUILTIN_SPEC_REG "trap" , trapcmd },
9662 { BUILTIN_REGULAR "true" , truecmd },
9663 { BUILTIN_NOSPEC "type" , typecmd },
9664 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9665 { BUILTIN_REGULAR "umask" , umaskcmd },
9666 #if ENABLE_ASH_ALIAS
9667 { BUILTIN_REGULAR "unalias" , unaliascmd },
9669 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9670 { BUILTIN_REGULAR "wait" , waitcmd },
9673 /* Should match the above table! */
9674 #define COMMANDCMD (builtintab + \
9676 /* [ */ 1 * ENABLE_ASH_TEST + \
9677 /* [[ */ 1 * BASH_TEST2 + \
9678 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9679 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9680 /* break cd cddir */ 3)
9681 #define EVALCMD (COMMANDCMD + \
9682 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9683 /* continue */ 1 + \
9684 /* echo */ 1 * ENABLE_ASH_ECHO + \
9686 #define EXECCMD (EVALCMD + \
9690 * Search the table of builtin commands.
9693 pstrcmp1(const void *a, const void *b)
9695 return strcmp((char*)a, *(char**)b + 1);
9697 static struct builtincmd *
9698 find_builtin(const char *name)
9700 struct builtincmd *bp;
9703 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9710 * Execute a simple command.
9713 isassignment(const char *p)
9715 const char *q = endofname(p);
9720 static int FAST_FUNC
9721 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9723 /* Preserve exitstatus of a previous possible redirection
9724 * as POSIX mandates */
9725 return back_exitstatus;
9728 evalcommand(union node *cmd, int flags)
9730 static const struct builtincmd null_bltin = {
9731 "\0\0", bltincmd /* why three NULs? */
9733 struct localvar_list *localvar_stop;
9734 struct redirtab *redir_stop;
9735 struct stackmark smark;
9737 struct arglist arglist;
9738 struct arglist varlist;
9741 const struct strlist *sp;
9742 struct cmdentry cmdentry;
9749 smallint cmd_is_exec;
9751 /* First expand the arguments. */
9752 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9753 setstackmark(&smark);
9754 localvar_stop = pushlocalvars();
9755 back_exitstatus = 0;
9757 cmdentry.cmdtype = CMDBUILTIN;
9758 cmdentry.u.cmd = &null_bltin;
9759 varlist.lastp = &varlist.list;
9760 *varlist.lastp = NULL;
9761 arglist.lastp = &arglist.list;
9762 *arglist.lastp = NULL;
9765 if (cmd->ncmd.args) {
9766 struct builtincmd *bcmd;
9767 smallint pseudovarflag;
9769 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9770 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9772 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9773 struct strlist **spp;
9775 spp = arglist.lastp;
9776 if (pseudovarflag && isassignment(argp->narg.text))
9777 expandarg(argp, &arglist, EXP_VARTILDE);
9779 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9781 for (sp = *spp; sp; sp = sp->next)
9786 /* Reserve one extra spot at the front for shellexec. */
9787 nargv = stalloc(sizeof(char *) * (argc + 2));
9789 for (sp = arglist.list; sp; sp = sp->next) {
9790 TRACE(("evalcommand arg: %s\n", sp->text));
9791 *nargv++ = sp->text;
9796 if (iflag && funcnest == 0 && argc > 0)
9797 lastarg = nargv[-1];
9799 expredir(cmd->ncmd.redirect);
9800 redir_stop = pushredir(cmd->ncmd.redirect);
9802 if (BASH_XTRACEFD && xflag) {
9803 /* NB: bash closes fd == $BASH_XTRACEFD when it is changed.
9804 * we do not emulate this. We only use its value.
9806 const char *xtracefd = lookupvar("BASH_XTRACEFD");
9807 if (xtracefd && is_number(xtracefd))
9808 preverrout_fd = atoi(xtracefd);
9811 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9813 path = vpath.var_text;
9814 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9815 struct strlist **spp;
9818 spp = varlist.lastp;
9819 expandarg(argp, &varlist, EXP_VARTILDE);
9821 mklocal((*spp)->text);
9824 * Modify the command lookup path, if a PATH= assignment
9828 if (varcmp(p, path) == 0)
9832 /* Print the command if xflag is set. */
9834 const char *pfx = "";
9836 fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
9840 char *varval = sp->text;
9841 char *eq = strchrnul(varval, '=');
9844 fdprintf(preverrout_fd, "%s%.*s%s",
9846 (int)(eq - varval), varval,
9847 maybe_single_quote(eq)
9855 fdprintf(preverrout_fd, "%s%s",
9857 /* always quote if matches reserved word: */
9859 ? single_quote(sp->text)
9860 : maybe_single_quote(sp->text)
9865 safe_write(preverrout_fd, "\n", 1);
9871 /* Now locate the command. */
9873 int cmd_flag = DO_ERR;
9874 #if ENABLE_ASH_CMDCMD
9875 const char *oldpath = path + 5;
9879 find_command(argv[0], &cmdentry, cmd_flag, path);
9880 if (cmdentry.cmdtype == CMDUNKNOWN) {
9881 flush_stdout_stderr();
9886 /* implement bltin and command here */
9887 if (cmdentry.cmdtype != CMDBUILTIN)
9890 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9891 if (cmdentry.u.cmd == EXECCMD)
9893 #if ENABLE_ASH_CMDCMD
9894 if (cmdentry.u.cmd == COMMANDCMD) {
9896 nargv = parse_command_args(argv, &path);
9899 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9900 * nargv => "PROG". path is updated if -p.
9902 argc -= nargv - argv;
9904 cmd_flag |= DO_NOFUNC;
9913 exitstatus = status;
9915 /* We have a redirection error. */
9917 raise_exception(EXERROR);
9922 /* Execute the command. */
9923 switch (cmdentry.cmdtype) {
9926 #if ENABLE_FEATURE_SH_NOFORK
9927 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9928 * around run_nofork_applet() call.
9929 * (2) Should this check also be done in forkshell()?
9930 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9932 /* find_command() encodes applet_no as (-2 - applet_no) */
9933 int applet_no = (- cmdentry.u.index - 2);
9934 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9935 listsetvar(varlist.list, VEXPORT|VSTACK);
9937 * Run <applet>_main().
9938 * Signals (^C) can't interrupt here.
9939 * Otherwise we can mangle stdio or malloc internal state.
9940 * This makes applets which can run for a long time
9941 * and/or wait for user input ineligible for NOFORK:
9942 * for example, "yes" or "rm" (rm -i waits for input).
9945 status = run_nofork_applet(applet_no, argv);
9947 * Try enabling NOFORK for "yes" applet.
9948 * ^C _will_ stop it (write returns EINTR),
9949 * but this causes stdout FILE to be stuck
9950 * and needing clearerr(). What if other applets
9951 * also can get EINTRs? Do we need to switch
9952 * our signals to SA_RESTART?
9954 /*clearerr(stdout);*/
9959 /* Can we avoid forking? For example, very last command
9960 * in a script or a subshell does not need forking,
9961 * we can just exec it.
9963 if (!(flags & EV_EXIT) || may_have_traps) {
9964 /* No, forking off a child is necessary */
9967 jp = makejob(/*cmd,*/ 1);
9968 if (forkshell(jp, cmd, FORK_FG) != 0) {
9970 status = waitforjob(jp);
9972 TRACE(("forked child exited with %d\n", status));
9977 /* fall through to exec'ing external program */
9979 listsetvar(varlist.list, VEXPORT|VSTACK);
9980 shellexec(argv[0], argv, path, cmdentry.u.index);
9984 if (spclbltin > 0 || argc == 0) {
9986 if (cmd_is_exec && argc > 1)
9987 listsetvar(varlist.list, VEXPORT);
9990 /* Tight loop with builtins only:
9991 * "while kill -0 $child; do true; done"
9992 * will never exit even if $child died, unless we do this
9993 * to reap the zombie and make kill detect that it's gone: */
9994 dowait(DOWAIT_NONBLOCK, NULL);
9996 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
9997 if (exception_type == EXERROR && spclbltin <= 0) {
10002 longjmp(exception_handler->loc, 1);
10008 /* See above for the rationale */
10009 dowait(DOWAIT_NONBLOCK, NULL);
10010 if (evalfun(cmdentry.u.func, argc, argv, flags))
10013 status = exitstatus;
10018 if (cmd->ncmd.redirect)
10019 popredir(/*drop:*/ cmd_is_exec);
10020 unwindredir(redir_stop);
10021 unwindlocalvars(localvar_stop);
10023 /* dsl: I think this is intended to be used to support
10024 * '_' in 'vi' command mode during line editing...
10025 * However I implemented that within libedit itself.
10027 setvar0("_", lastarg);
10029 popstackmark(&smark);
10035 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
10037 char *volatile savecmdname;
10038 struct jmploc *volatile savehandler;
10039 struct jmploc jmploc;
10043 savecmdname = commandname;
10044 savehandler = exception_handler;
10045 i = setjmp(jmploc.loc);
10048 exception_handler = &jmploc;
10049 commandname = argv[0];
10051 optptr = NULL; /* initialize nextopt */
10052 if (cmd == EVALCMD)
10053 status = evalcmd(argc, argv, flags);
10055 status = (*cmd->builtin)(argc, argv);
10056 flush_stdout_stderr();
10057 status |= ferror(stdout);
10058 exitstatus = status;
10061 commandname = savecmdname;
10062 exception_handler = savehandler;
10068 goodname(const char *p)
10070 return endofname(p)[0] == '\0';
10075 * Search for a command. This is called before we fork so that the
10076 * location of the command will be available in the parent as well as
10077 * the child. The check for "goodname" is an overly conservative
10078 * check that the name will not be subject to expansion.
10081 prehash(union node *n)
10083 struct cmdentry entry;
10085 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
10086 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
10090 /* ============ Builtin commands
10092 * Builtin commands whose functions are closely tied to evaluation
10093 * are implemented here.
10097 * Handle break and continue commands. Break, continue, and return are
10098 * all handled by setting the evalskip flag. The evaluation routines
10099 * above all check this flag, and if it is set they start skipping
10100 * commands rather than executing them. The variable skipcount is
10101 * the number of loops to break/continue, or the number of function
10102 * levels to return. (The latter is always 1.) It should probably
10103 * be an error to break out of more loops than exist, but it isn't
10104 * in the standard shell so we don't make it one here.
10106 static int FAST_FUNC
10107 breakcmd(int argc UNUSED_PARAM, char **argv)
10109 int n = argv[1] ? number(argv[1]) : 1;
10112 ash_msg_and_raise_error(msg_illnum, argv[1]);
10116 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
10124 * This implements the input routines used by the parser.
10128 INPUT_PUSH_FILE = 1,
10129 INPUT_NOFILE_OK = 2,
10132 static smallint checkkwd;
10133 /* values of checkkwd variable */
10134 #define CHKALIAS 0x1
10137 #define CHKEOFMARK 0x8
10140 * Push a string back onto the input at this current parsefile level.
10141 * We handle aliases this way.
10143 #if !ENABLE_ASH_ALIAS
10144 #define pushstring(s, ap) pushstring(s)
10147 pushstring(char *s, struct alias *ap)
10149 struct strpush *sp;
10154 if (g_parsefile->strpush) {
10155 sp = ckzalloc(sizeof(*sp));
10156 sp->prev = g_parsefile->strpush;
10158 sp = &(g_parsefile->basestrpush);
10160 g_parsefile->strpush = sp;
10161 sp->prev_string = g_parsefile->next_to_pgetc;
10162 sp->prev_left_in_line = g_parsefile->left_in_line;
10163 sp->unget = g_parsefile->unget;
10164 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
10165 #if ENABLE_ASH_ALIAS
10168 ap->flag |= ALIASINUSE;
10172 g_parsefile->next_to_pgetc = s;
10173 g_parsefile->left_in_line = len;
10174 g_parsefile->unget = 0;
10181 struct strpush *sp = g_parsefile->strpush;
10184 #if ENABLE_ASH_ALIAS
10186 if (g_parsefile->next_to_pgetc[-1] == ' '
10187 || g_parsefile->next_to_pgetc[-1] == '\t'
10189 checkkwd |= CHKALIAS;
10191 if (sp->string != sp->ap->val) {
10194 sp->ap->flag &= ~ALIASINUSE;
10195 if (sp->ap->flag & ALIASDEAD) {
10196 unalias(sp->ap->name);
10200 g_parsefile->next_to_pgetc = sp->prev_string;
10201 g_parsefile->left_in_line = sp->prev_left_in_line;
10202 g_parsefile->unget = sp->unget;
10203 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
10204 g_parsefile->strpush = sp->prev;
10205 if (sp != &(g_parsefile->basestrpush))
10214 char *buf = g_parsefile->buf;
10216 g_parsefile->next_to_pgetc = buf;
10217 #if ENABLE_FEATURE_EDITING
10219 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
10220 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10222 # if ENABLE_ASH_IDLE_TIMEOUT
10225 const char *tmout_var = lookupvar("TMOUT");
10227 timeout = atoi(tmout_var) * 1000;
10232 line_input_state->timeout = timeout;
10234 # if ENABLE_FEATURE_TAB_COMPLETION
10235 line_input_state->path_lookup = pathval();
10237 reinit_unicode_for_ash();
10238 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ);
10240 /* ^C pressed, "convert" to SIGINT */
10241 write(STDOUT_FILENO, "^C", 2);
10242 if (trap[SIGINT]) {
10248 exitstatus = 128 + SIGINT;
10254 /* Ctrl+D pressed */
10257 # if ENABLE_ASH_IDLE_TIMEOUT
10258 else if (errno == EAGAIN && timeout > 0) {
10259 puts("\007timed out waiting for input: auto-logout");
10266 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10269 #if 0 /* disabled: nonblock_immune_read() handles this problem */
10271 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
10272 int flags = fcntl(0, F_GETFL);
10273 if (flags >= 0 && (flags & O_NONBLOCK)) {
10274 flags &= ~O_NONBLOCK;
10275 if (fcntl(0, F_SETFL, flags) >= 0) {
10276 out2str("sh: turning off NDELAY mode\n");
10287 * Refill the input buffer and return the next input character:
10289 * 1) If a string was pushed back on the input, pop it;
10290 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
10291 * or we are reading from a string so we can't refill the buffer,
10293 * 3) If there is more stuff in this buffer, use it else call read to fill it.
10294 * 4) Process input up to the next newline, deleting nul characters.
10296 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
10297 #define pgetc_debug(...) ((void)0)
10298 static int pgetc(void);
10305 if (g_parsefile->strpush) {
10306 #if ENABLE_ASH_ALIAS
10307 if (g_parsefile->left_in_line == -1
10308 && g_parsefile->strpush->ap
10309 && g_parsefile->next_to_pgetc[-1] != ' '
10310 && g_parsefile->next_to_pgetc[-1] != '\t'
10312 pgetc_debug("preadbuffer PEOA");
10319 /* on both branches above g_parsefile->left_in_line < 0.
10320 * "pgetc" needs refilling.
10323 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
10324 * pungetc() may increment it a few times.
10325 * Assuming it won't increment it to less than -90.
10327 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
10328 pgetc_debug("preadbuffer PEOF1");
10329 /* even in failure keep left_in_line and next_to_pgetc
10330 * in lock step, for correct multi-layer pungetc.
10331 * left_in_line was decremented before preadbuffer(),
10332 * must inc next_to_pgetc: */
10333 g_parsefile->next_to_pgetc++;
10337 more = g_parsefile->left_in_buffer;
10339 flush_stdout_stderr();
10343 /* don't try reading again */
10344 g_parsefile->left_in_line = -99;
10345 pgetc_debug("preadbuffer PEOF2");
10346 g_parsefile->next_to_pgetc++;
10351 /* Find out where's the end of line.
10352 * Set g_parsefile->left_in_line
10353 * and g_parsefile->left_in_buffer acordingly.
10354 * NUL chars are deleted.
10356 q = g_parsefile->next_to_pgetc;
10364 memmove(q, q + 1, more);
10368 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10374 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10375 if (g_parsefile->left_in_line < 0)
10380 g_parsefile->left_in_buffer = more;
10385 out2str(g_parsefile->next_to_pgetc);
10389 pgetc_debug("preadbuffer at %d:%p'%s'",
10390 g_parsefile->left_in_line,
10391 g_parsefile->next_to_pgetc,
10392 g_parsefile->next_to_pgetc);
10393 return (unsigned char)*g_parsefile->next_to_pgetc++;
10399 g_parsefile->linno++;
10400 setprompt_if(doprompt, 2);
10405 g_parsefile->linno++;
10406 needprompt = doprompt;
10414 pgetc_debug("pgetc at %d:%p'%s'",
10415 g_parsefile->left_in_line,
10416 g_parsefile->next_to_pgetc,
10417 g_parsefile->next_to_pgetc);
10418 if (g_parsefile->unget)
10419 return g_parsefile->lastc[--g_parsefile->unget];
10421 if (--g_parsefile->left_in_line >= 0)
10422 c = (unsigned char)*g_parsefile->next_to_pgetc++;
10426 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10427 g_parsefile->lastc[0] = c;
10432 #if ENABLE_ASH_ALIAS
10434 pgetc_without_PEOA(void)
10438 pgetc_debug("pgetc at %d:%p'%s'",
10439 g_parsefile->left_in_line,
10440 g_parsefile->next_to_pgetc,
10441 g_parsefile->next_to_pgetc);
10443 } while (c == PEOA);
10447 # define pgetc_without_PEOA() pgetc()
10451 * Undo a call to pgetc. Only two characters may be pushed back.
10452 * PEOF may be pushed back.
10457 g_parsefile->unget++;
10460 /* This one eats backslash+newline */
10466 while ((c = pgetc()) == '\\') {
10467 if (pgetc() != '\n') {
10479 * To handle the "." command, a stack of input files is used. Pushfile
10480 * adds a new entry to the stack and popfile restores the previous level.
10485 struct parsefile *pf;
10487 pf = ckzalloc(sizeof(*pf));
10488 pf->prev = g_parsefile;
10490 /*pf->strpush = NULL; - ckzalloc did it */
10491 /*pf->basestrpush.prev = NULL;*/
10499 struct parsefile *pf = g_parsefile;
10505 if (pf->pf_fd >= 0)
10508 while (pf->strpush)
10510 g_parsefile = pf->prev;
10516 * Return to top level.
10521 while (g_parsefile != &basepf)
10526 * Close the file(s) that the shell is reading commands from. Called
10527 * after a fork is done.
10533 if (g_parsefile->pf_fd > 0) {
10534 close(g_parsefile->pf_fd);
10535 g_parsefile->pf_fd = 0;
10540 * Like setinputfile, but takes an open file descriptor. Call this with
10544 setinputfd(int fd, int push)
10548 g_parsefile->buf = NULL;
10550 g_parsefile->pf_fd = fd;
10551 if (g_parsefile->buf == NULL)
10552 g_parsefile->buf = ckmalloc(IBUFSIZ);
10553 g_parsefile->left_in_buffer = 0;
10554 g_parsefile->left_in_line = 0;
10555 g_parsefile->linno = 1;
10559 * Set the input to take input from a file. If push is set, push the
10560 * old input onto the stack first.
10563 setinputfile(const char *fname, int flags)
10568 fd = open(fname, O_RDONLY);
10570 if (flags & INPUT_NOFILE_OK)
10573 ash_msg_and_raise_error("can't open '%s'", fname);
10578 close_on_exec_on(fd);
10579 setinputfd(fd, flags & INPUT_PUSH_FILE);
10586 * Like setinputfile, but takes input from a string.
10589 setinputstring(char *string)
10593 g_parsefile->next_to_pgetc = string;
10594 g_parsefile->left_in_line = strlen(string);
10595 g_parsefile->buf = NULL;
10596 g_parsefile->linno = 1;
10602 * Routines to check for mail.
10605 #if ENABLE_ASH_MAIL
10607 /* Hash of mtimes of mailboxes */
10608 static unsigned mailtime_hash;
10609 /* Set if MAIL or MAILPATH is changed. */
10610 static smallint mail_var_path_changed;
10613 * Print appropriate message(s) if mail has arrived.
10614 * If mail_var_path_changed is set,
10615 * then the value of MAIL has mail_var_path_changed,
10616 * so we just update the values.
10625 struct stackmark smark;
10628 setstackmark(&smark);
10629 mpath = mpathset() ? mpathval() : mailval();
10632 p = path_advance(&mpath, nullstr);
10637 for (q = p; *q; q++)
10643 q[-1] = '\0'; /* delete trailing '/' */
10644 if (stat(p, &statb) < 0) {
10647 /* Very simplistic "hash": just a sum of all mtimes */
10648 new_hash += (unsigned)statb.st_mtime;
10650 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10651 if (mailtime_hash != 0)
10652 out2str("you have mail\n");
10653 mailtime_hash = new_hash;
10655 mail_var_path_changed = 0;
10656 popstackmark(&smark);
10659 static void FAST_FUNC
10660 changemail(const char *val UNUSED_PARAM)
10662 mail_var_path_changed = 1;
10665 #endif /* ASH_MAIL */
10668 /* ============ ??? */
10671 * Set the shell parameters.
10674 setparam(char **argv)
10680 for (nparam = 0; argv[nparam]; nparam++)
10682 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10684 *ap++ = ckstrdup(*argv++);
10687 freeparam(&shellparam);
10688 shellparam.malloced = 1;
10689 shellparam.nparam = nparam;
10690 shellparam.p = newparam;
10691 #if ENABLE_ASH_GETOPTS
10692 shellparam.optind = 1;
10693 shellparam.optoff = -1;
10698 * Process shell options. The global variable argptr contains a pointer
10699 * to the argument list; we advance it past the options.
10701 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10702 * For a non-interactive shell, an error condition encountered
10703 * by a special built-in ... shall cause the shell to write a diagnostic message
10704 * to standard error and exit as shown in the following table:
10705 * Error Special Built-In
10707 * Utility syntax error (option or operand error) Shall exit
10709 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10710 * we see that bash does not do that (set "finishes" with error code 1 instead,
10711 * and shell continues), and people rely on this behavior!
10713 * set -o barfoo 2>/dev/null
10716 * Oh well. Let's mimic that.
10719 plus_minus_o(char *name, int val)
10724 for (i = 0; i < NOPTS; i++) {
10725 if (strcmp(name, optnames(i)) == 0) {
10730 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10733 for (i = 0; i < NOPTS; i++) {
10735 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10737 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10743 setoption(int flag, int val)
10747 for (i = 0; i < NOPTS; i++) {
10748 if (optletters(i) == flag) {
10753 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10757 options(int cmdline, int *login_sh)
10765 while ((p = *argptr) != NULL) {
10767 if (c != '-' && c != '+')
10770 val = 0; /* val = 0 if c == '+' */
10773 if (p[0] == '\0' || LONE_DASH(p)) {
10775 /* "-" means turn off -x and -v */
10778 /* "--" means reset params */
10779 else if (*argptr == NULL)
10782 break; /* "-" or "--" terminates options */
10785 /* first char was + or - */
10786 while ((c = *p++) != '\0') {
10787 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10788 if (c == 'c' && cmdline) {
10789 minusc = p; /* command is after shell args */
10790 } else if (c == 'o') {
10791 if (plus_minus_o(*argptr, val)) {
10792 /* it already printed err message */
10793 return 1; /* error */
10797 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10800 /* bash does not accept +-login, we also won't */
10801 } else if (cmdline && val && (c == '-')) { /* long options */
10802 if (strcmp(p, "login") == 0) {
10816 * The shift builtin command.
10818 static int FAST_FUNC
10819 shiftcmd(int argc UNUSED_PARAM, char **argv)
10826 n = number(argv[1]);
10827 if (n > shellparam.nparam)
10828 n = 0; /* bash compat, was = shellparam.nparam; */
10830 shellparam.nparam -= n;
10831 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10832 if (shellparam.malloced)
10835 ap2 = shellparam.p;
10836 while ((*ap2++ = *ap1++) != NULL)
10838 #if ENABLE_ASH_GETOPTS
10839 shellparam.optind = 1;
10840 shellparam.optoff = -1;
10847 * POSIX requires that 'set' (but not export or readonly) output the
10848 * variables in lexicographic order - by the locale's collating order (sigh).
10849 * Maybe we could keep them in an ordered balanced binary tree
10850 * instead of hashed lists.
10851 * For now just roll 'em through qsort for printing...
10854 showvars(const char *sep_prefix, int on, int off)
10857 char **ep, **epend;
10859 ep = listvars(on, off, &epend);
10860 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10862 sep = *sep_prefix ? " " : sep_prefix;
10864 for (; ep < epend; ep++) {
10868 p = strchrnul(*ep, '=');
10871 q = single_quote(++p);
10872 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10878 * The set command builtin.
10880 static int FAST_FUNC
10881 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10886 return showvars(nullstr, 0, VUNSET);
10889 retval = options(/*cmdline:*/ 0, NULL);
10890 if (retval == 0) { /* if no parse error... */
10892 if (*argptr != NULL) {
10900 #if ENABLE_ASH_RANDOM_SUPPORT
10901 static void FAST_FUNC
10902 change_random(const char *value)
10906 if (value == NULL) {
10907 /* "get", generate */
10908 t = next_random(&random_gen);
10909 /* set without recursion */
10910 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10911 vrandom.flags &= ~VNOFUNC;
10914 t = strtoul(value, NULL, 10);
10915 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10920 #if ENABLE_ASH_GETOPTS
10922 getopts(char *optstr, char *optvar, char **optfirst)
10929 int ind = shellparam.optind;
10930 int off = shellparam.optoff;
10934 shellparam.optind = -1;
10935 optnext = optfirst + ind - 1;
10937 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
10940 p = optnext[-1] + off;
10941 if (p == NULL || *p == '\0') {
10942 /* Current word is done, advance */
10944 if (p == NULL || *p != '-' || *++p == '\0') {
10951 if (LONE_DASH(p)) /* check for "--" */
10956 for (q = optstr; *q != c;) {
10958 if (optstr[0] == ':') {
10960 /*sbuf[1] = '\0'; - already is */
10961 setvar0("OPTARG", sbuf);
10963 fprintf(stderr, "Illegal option -%c\n", c);
10964 unsetvar("OPTARG");
10974 if (*p == '\0' && (p = *optnext) == NULL) {
10975 if (optstr[0] == ':') {
10977 /*sbuf[1] = '\0'; - already is */
10978 setvar0("OPTARG", sbuf);
10981 fprintf(stderr, "No arg for -%c option\n", c);
10982 unsetvar("OPTARG");
10990 setvar0("OPTARG", p);
10993 setvar0("OPTARG", nullstr);
10995 ind = optnext - optfirst + 1;
10996 setvar("OPTIND", itoa(ind), VNOFUNC);
10998 /*sbuf[1] = '\0'; - already is */
10999 setvar0(optvar, sbuf);
11001 shellparam.optoff = p ? p - *(optnext - 1) : -1;
11002 shellparam.optind = ind;
11008 * The getopts builtin. Shellparam.optnext points to the next argument
11009 * to be processed. Shellparam.optptr points to the next character to
11010 * be processed in the current argument. If shellparam.optnext is NULL,
11011 * then it's the first time getopts has been called.
11013 static int FAST_FUNC
11014 getoptscmd(int argc, char **argv)
11019 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
11021 optbase = shellparam.p;
11022 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
11023 shellparam.optind = 1;
11024 shellparam.optoff = -1;
11027 optbase = &argv[3];
11028 if ((unsigned)shellparam.optind > argc - 2) {
11029 shellparam.optind = 1;
11030 shellparam.optoff = -1;
11034 return getopts(argv[1], argv[2], optbase);
11036 #endif /* ASH_GETOPTS */
11039 /* ============ Shell parser */
11042 struct heredoc *next; /* next here document in list */
11043 union node *here; /* redirection node */
11044 char *eofmark; /* string indicating end of input */
11045 smallint striptabs; /* if set, strip leading tabs */
11048 static smallint tokpushback; /* last token pushed back */
11049 static smallint quoteflag; /* set if (part of) last token was quoted */
11050 static token_id_t lasttoken; /* last token read (integer id Txxx) */
11051 static struct heredoc *heredoclist; /* list of here documents to read */
11052 static char *wordtext; /* text of last word returned by readtoken */
11053 static struct nodelist *backquotelist;
11054 static union node *redirnode;
11055 static struct heredoc *heredoc;
11057 static const char *
11058 tokname(char *buf, int tok)
11061 return tokname_array[tok];
11062 sprintf(buf, "\"%s\"", tokname_array[tok]);
11066 /* raise_error_unexpected_syntax:
11067 * Called when an unexpected token is read during the parse. The argument
11068 * is the token that is expected, or -1 if more than one type of token can
11069 * occur at this point.
11071 static void raise_error_unexpected_syntax(int) NORETURN;
11073 raise_error_unexpected_syntax(int token)
11079 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
11081 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
11082 raise_error_syntax(msg);
11086 /* parsing is heavily cross-recursive, need these forward decls */
11087 static union node *andor(void);
11088 static union node *pipeline(void);
11089 static union node *parse_command(void);
11090 static void parseheredoc(void);
11091 static int peektoken(void);
11092 static int readtoken(void);
11094 static union node *
11097 union node *n1, *n2, *n3;
11102 switch (peektoken()) {
11110 if (!n1 && (nlflag & 1))
11116 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11117 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
11123 if (tok == TBACKGND) {
11124 if (n2->type == NPIPE) {
11125 n2->npipe.pipe_backgnd = 1;
11127 if (n2->type != NREDIR) {
11128 n3 = stzalloc(sizeof(struct nredir));
11130 /*n3->nredir.redirect = NULL; - stzalloc did it */
11133 n2->type = NBACKGND;
11139 n3 = stzalloc(sizeof(struct nbinary));
11141 n3->nbinary.ch1 = n1;
11142 n3->nbinary.ch2 = n2;
11155 raise_error_unexpected_syntax(-1);
11162 static union node *
11165 union node *n1, *n2, *n3;
11173 } else if (t == TOR) {
11179 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11181 n3 = stzalloc(sizeof(struct nbinary));
11183 n3->nbinary.ch1 = n1;
11184 n3->nbinary.ch2 = n2;
11189 static union node *
11192 union node *n1, *n2, *pipenode;
11193 struct nodelist *lp, *prev;
11197 TRACE(("pipeline: entered\n"));
11198 if (readtoken() == TNOT) {
11200 checkkwd = CHKKWD | CHKALIAS;
11203 n1 = parse_command();
11204 if (readtoken() == TPIPE) {
11205 pipenode = stzalloc(sizeof(struct npipe));
11206 pipenode->type = NPIPE;
11207 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
11208 lp = stzalloc(sizeof(struct nodelist));
11209 pipenode->npipe.cmdlist = lp;
11213 lp = stzalloc(sizeof(struct nodelist));
11214 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11215 lp->n = parse_command();
11217 } while (readtoken() == TPIPE);
11223 n2 = stzalloc(sizeof(struct nnot));
11231 static union node *
11236 n = stzalloc(sizeof(struct narg));
11238 /*n->narg.next = NULL; - stzalloc did it */
11239 n->narg.text = wordtext;
11240 n->narg.backquote = backquotelist;
11245 fixredir(union node *n, const char *text, int err)
11249 TRACE(("Fix redir %s %d\n", text, err));
11251 n->ndup.vname = NULL;
11253 fd = bb_strtou(text, NULL, 10);
11254 if (!errno && fd >= 0)
11255 n->ndup.dupfd = fd;
11256 else if (LONE_DASH(text))
11257 n->ndup.dupfd = -1;
11260 raise_error_syntax("bad fd number");
11261 n->ndup.vname = makename();
11268 union node *n = redirnode;
11270 if (n->type == NHERE)
11271 checkkwd = CHKEOFMARK;
11272 if (readtoken() != TWORD)
11273 raise_error_unexpected_syntax(-1);
11274 if (n->type == NHERE) {
11275 struct heredoc *here = heredoc;
11278 if (quoteflag == 0)
11280 TRACE(("Here document %d\n", n->type));
11281 rmescapes(wordtext, 0);
11282 here->eofmark = wordtext;
11284 if (heredoclist == NULL)
11285 heredoclist = here;
11287 for (p = heredoclist; p->next; p = p->next)
11291 } else if (n->type == NTOFD || n->type == NFROMFD) {
11292 fixredir(n, wordtext, 0);
11294 n->nfile.fname = makename();
11298 static union node *
11301 union node *args, **app;
11302 union node *n = NULL;
11303 union node *vars, **vpp;
11304 union node **rpp, *redir;
11307 smallint double_brackets_flag = 0;
11309 IF_BASH_FUNCTION(smallint function_flag = 0;)
11318 savecheckkwd = CHKALIAS;
11321 checkkwd = savecheckkwd;
11326 if (peektoken() != TWORD)
11327 raise_error_unexpected_syntax(TWORD);
11332 case TAND: /* "&&" */
11333 case TOR: /* "||" */
11334 if (!double_brackets_flag) {
11338 wordtext = (char *) (t == TAND ? "-a" : "-o");
11341 n = stzalloc(sizeof(struct narg));
11343 /*n->narg.next = NULL; - stzalloc did it */
11344 n->narg.text = wordtext;
11346 if (strcmp("[[", wordtext) == 0)
11347 double_brackets_flag = 1;
11348 else if (strcmp("]]", wordtext) == 0)
11349 double_brackets_flag = 0;
11351 n->narg.backquote = backquotelist;
11352 if (savecheckkwd && isassignment(wordtext)) {
11354 vpp = &n->narg.next;
11357 app = &n->narg.next;
11361 if (function_flag) {
11362 checkkwd = CHKNL | CHKKWD;
11363 switch (peektoken()) {
11375 if (strcmp("[[", wordtext) == 0)
11379 raise_error_unexpected_syntax(-1);
11385 *rpp = n = redirnode;
11386 rpp = &n->nfile.next;
11387 parsefname(); /* read name of redirection file */
11390 IF_BASH_FUNCTION(do_func:)
11391 if (args && app == &args->narg.next
11394 struct builtincmd *bcmd;
11397 /* We have a function */
11398 if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
11399 raise_error_unexpected_syntax(TRP);
11400 name = n->narg.text;
11401 if (!goodname(name)
11402 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11404 raise_error_syntax("bad function name");
11407 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11408 n->narg.next = parse_command();
11411 IF_BASH_FUNCTION(function_flag = 0;)
11422 n = stzalloc(sizeof(struct ncmd));
11424 n->ncmd.args = args;
11425 n->ncmd.assign = vars;
11426 n->ncmd.redirect = redir;
11430 static union node *
11431 parse_command(void)
11433 union node *n1, *n2;
11434 union node *ap, **app;
11435 union node *cp, **cpp;
11436 union node *redir, **rpp;
11443 switch (readtoken()) {
11445 raise_error_unexpected_syntax(-1);
11448 n1 = stzalloc(sizeof(struct nif));
11450 n1->nif.test = list(0);
11451 if (readtoken() != TTHEN)
11452 raise_error_unexpected_syntax(TTHEN);
11453 n1->nif.ifpart = list(0);
11455 while (readtoken() == TELIF) {
11456 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11457 n2 = n2->nif.elsepart;
11459 n2->nif.test = list(0);
11460 if (readtoken() != TTHEN)
11461 raise_error_unexpected_syntax(TTHEN);
11462 n2->nif.ifpart = list(0);
11464 if (lasttoken == TELSE)
11465 n2->nif.elsepart = list(0);
11467 n2->nif.elsepart = NULL;
11475 n1 = stzalloc(sizeof(struct nbinary));
11476 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11477 n1->nbinary.ch1 = list(0);
11480 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11481 got == TWORD ? wordtext : ""));
11482 raise_error_unexpected_syntax(TDO);
11484 n1->nbinary.ch2 = list(0);
11489 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11490 raise_error_syntax("bad for loop variable");
11491 n1 = stzalloc(sizeof(struct nfor));
11493 n1->nfor.var = wordtext;
11494 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11495 if (readtoken() == TIN) {
11497 while (readtoken() == TWORD) {
11498 n2 = stzalloc(sizeof(struct narg));
11500 /*n2->narg.next = NULL; - stzalloc did it */
11501 n2->narg.text = wordtext;
11502 n2->narg.backquote = backquotelist;
11504 app = &n2->narg.next;
11507 n1->nfor.args = ap;
11508 if (lasttoken != TNL && lasttoken != TSEMI)
11509 raise_error_unexpected_syntax(-1);
11511 n2 = stzalloc(sizeof(struct narg));
11513 /*n2->narg.next = NULL; - stzalloc did it */
11514 n2->narg.text = (char *)dolatstr;
11515 /*n2->narg.backquote = NULL;*/
11516 n1->nfor.args = n2;
11518 * Newline or semicolon here is optional (but note
11519 * that the original Bourne shell only allowed NL).
11521 if (lasttoken != TSEMI)
11524 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11525 if (readtoken() != TDO)
11526 raise_error_unexpected_syntax(TDO);
11527 n1->nfor.body = list(0);
11531 n1 = stzalloc(sizeof(struct ncase));
11533 if (readtoken() != TWORD)
11534 raise_error_unexpected_syntax(TWORD);
11535 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11537 /*n2->narg.next = NULL; - stzalloc did it */
11538 n2->narg.text = wordtext;
11539 n2->narg.backquote = backquotelist;
11540 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11541 if (readtoken() != TIN)
11542 raise_error_unexpected_syntax(TIN);
11543 cpp = &n1->ncase.cases;
11545 checkkwd = CHKNL | CHKKWD;
11547 while (t != TESAC) {
11548 if (lasttoken == TLP)
11550 *cpp = cp = stzalloc(sizeof(struct nclist));
11552 app = &cp->nclist.pattern;
11554 *app = ap = stzalloc(sizeof(struct narg));
11556 /*ap->narg.next = NULL; - stzalloc did it */
11557 ap->narg.text = wordtext;
11558 ap->narg.backquote = backquotelist;
11559 if (readtoken() != TPIPE)
11561 app = &ap->narg.next;
11564 //ap->narg.next = NULL;
11565 if (lasttoken != TRP)
11566 raise_error_unexpected_syntax(TRP);
11567 cp->nclist.body = list(2);
11569 cpp = &cp->nclist.next;
11571 checkkwd = CHKNL | CHKKWD;
11575 raise_error_unexpected_syntax(TENDCASE);
11582 n1 = stzalloc(sizeof(struct nredir));
11583 n1->type = NSUBSHELL;
11584 n1->nredir.n = list(0);
11585 /*n1->nredir.redirect = NULL; - stzalloc did it */
11592 IF_BASH_FUNCTION(case TFUNCTION:)
11596 return simplecmd();
11599 if (readtoken() != t)
11600 raise_error_unexpected_syntax(t);
11603 /* Now check for redirection which may follow command */
11604 checkkwd = CHKKWD | CHKALIAS;
11606 while (readtoken() == TREDIR) {
11607 *rpp = n2 = redirnode;
11608 rpp = &n2->nfile.next;
11614 if (n1->type != NSUBSHELL) {
11615 n2 = stzalloc(sizeof(struct nredir));
11620 n1->nredir.redirect = redir;
11625 #if BASH_DOLLAR_SQUOTE
11627 decode_dollar_squote(void)
11629 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11635 p = strchr(C_escapes, c);
11640 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11644 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11646 } else if (c == 'x') { /* \xHH */
11650 } while (isxdigit(c) && --cnt);
11652 if (cnt == 3) { /* \x but next char is "bad" */
11656 } else { /* simple seq like \\ or \t */
11661 c = bb_process_escape_sequence((void*)&p);
11662 } else { /* unrecognized "\z": print both chars unless ' or " */
11663 if (c != '\'' && c != '"') {
11665 c |= 0x100; /* "please encode \, then me" */
11672 /* Used by expandstr to get here-doc like behaviour. */
11673 #define FAKEEOFMARK ((char*)(uintptr_t)1)
11675 static ALWAYS_INLINE int
11676 realeofmark(const char *eofmark)
11678 return eofmark && eofmark != FAKEEOFMARK;
11682 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11683 * is not NULL, read a here document. In the latter case, eofmark is the
11684 * word which marks the end of the document and striptabs is true if
11685 * leading tabs should be stripped from the document. The argument c
11686 * is the first character of the input token or document.
11688 * Because C does not have internal subroutines, I have simulated them
11689 * using goto's to implement the subroutine linkage. The following macros
11690 * will run code that appears at the end of readtoken1.
11692 #define CHECKEND() {goto checkend; checkend_return:;}
11693 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11694 #define PARSESUB() {goto parsesub; parsesub_return:;}
11695 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11696 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11697 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11699 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11701 /* NB: syntax parameter fits into smallint */
11702 /* c parameter is an unsigned char or PEOF or PEOA */
11705 struct nodelist *bqlist;
11709 IF_FEATURE_SH_MATH(smallint prevsyntax;) /* syntax before arithmetic */
11710 smallint pssyntax; /* we are expanding a prompt string */
11711 int varnest; /* levels of variables expansion */
11712 IF_FEATURE_SH_MATH(int arinest;) /* levels of arithmetic expansion */
11713 IF_FEATURE_SH_MATH(int parenlevel;) /* levels of parens in arithmetic */
11714 int dqvarnest; /* levels of variables expansion within double quotes */
11716 IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
11718 startlinno = g_parsefile->linno;
11721 IF_FEATURE_SH_MATH(prevsyntax = 0;)
11722 #if ENABLE_ASH_EXPAND_PRMT
11723 pssyntax = (syntax == PSSYNTAX);
11727 pssyntax = 0; /* constant */
11729 dblquote = (syntax == DQSYNTAX);
11731 IF_FEATURE_SH_MATH(arinest = 0;)
11732 IF_FEATURE_SH_MATH(parenlevel = 0;)
11735 STARTSTACKSTR(out);
11737 /* For each line, until end of word */
11738 CHECKEND(); /* set c to PEOF if at end of here document */
11739 for (;;) { /* until end of line or end of word */
11740 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11741 switch (SIT(c, syntax)) {
11742 case CNL: /* '\n' */
11743 if (syntax == BASESYNTAX)
11744 goto endword; /* exit outer loop */
11748 goto loop; /* continue outer loop */
11753 #if BASH_DOLLAR_SQUOTE
11754 if (c == '\\' && bash_dollar_squote) {
11755 c = decode_dollar_squote();
11757 /* skip $'\000', $'\x00' (like bash) */
11761 /* Unknown escape. Encode as '\z' */
11762 c = (unsigned char)c;
11763 if (eofmark == NULL || dblquote)
11764 USTPUTC(CTLESC, out);
11765 USTPUTC('\\', out);
11769 if (eofmark == NULL || dblquote)
11770 USTPUTC(CTLESC, out);
11773 case CBACK: /* backslash */
11774 c = pgetc_without_PEOA();
11776 USTPUTC(CTLESC, out);
11777 USTPUTC('\\', out);
11779 } else if (c == '\n') {
11782 if (pssyntax && c == '$') {
11783 USTPUTC(CTLESC, out);
11784 USTPUTC('\\', out);
11786 /* Backslash is retained if we are in "str" and next char isn't special */
11791 && (c != '"' || eofmark != NULL)
11793 USTPUTC('\\', out);
11795 USTPUTC(CTLESC, out);
11803 if (eofmark == NULL) {
11804 USTPUTC(CTLQUOTEMARK, out);
11812 IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
11813 if (eofmark != NULL && varnest == 0) {
11816 if (dqvarnest == 0) {
11817 syntax = BASESYNTAX;
11824 case CVAR: /* '$' */
11825 PARSESUB(); /* parse substitution */
11827 case CENDVAR: /* '}' */
11830 if (dqvarnest > 0) {
11837 #if ENABLE_FEATURE_SH_MATH
11838 case CLP: /* '(' in arithmetic */
11842 case CRP: /* ')' in arithmetic */
11843 if (parenlevel > 0) {
11846 if (pgetc_eatbnl() == ')') {
11848 if (--arinest == 0) {
11849 syntax = prevsyntax;
11853 * unbalanced parens
11854 * (don't 2nd guess - no error)
11862 case CBQUOTE: /* '`' */
11866 goto endword; /* exit outer loop */
11870 if (varnest == 0) {
11871 #if BASH_REDIR_OUTPUT
11873 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11874 if (pgetc() == '>')
11875 c = 0x100 + '>'; /* flag &> */
11879 goto endword; /* exit outer loop */
11881 IF_ASH_ALIAS(if (c != PEOA))
11888 #if ENABLE_FEATURE_SH_MATH
11889 if (syntax == ARISYNTAX)
11890 raise_error_syntax("missing '))'");
11892 if (syntax != BASESYNTAX && eofmark == NULL)
11893 raise_error_syntax("unterminated quoted string");
11894 if (varnest != 0) {
11895 startlinno = g_parsefile->linno;
11897 raise_error_syntax("missing '}'");
11899 USTPUTC('\0', out);
11900 len = out - (char *)stackblock();
11901 out = stackblock();
11902 if (eofmark == NULL) {
11903 if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
11906 if (isdigit_str9(out)) {
11907 PARSEREDIR(); /* passed as params: out, c */
11908 lasttoken = TREDIR;
11911 /* else: non-number X seen, interpret it
11912 * as "NNNX>file" = "NNNX >file" */
11916 quoteflag = quotef;
11917 backquotelist = bqlist;
11918 grabstackblock(len);
11922 /* end of readtoken routine */
11925 * Check to see whether we are at the end of the here document. When this
11926 * is called, c is set to the first character of the next input line. If
11927 * we are at the end of the here document, this routine sets the c to PEOF.
11930 if (realeofmark(eofmark)) {
11934 #if ENABLE_ASH_ALIAS
11936 c = pgetc_without_PEOA();
11939 while (c == '\t') {
11940 c = pgetc_without_PEOA();
11944 markloc = out - (char *)stackblock();
11945 for (p = eofmark; STPUTC(c, out), *p; p++) {
11949 c = pgetc_without_PEOA();
11952 if (c == '\n' || c == PEOF) {
11954 g_parsefile->linno++;
11955 needprompt = doprompt;
11960 p = (char *)stackblock() + markloc + 1;
11961 len_here = out - p;
11964 len_here -= (c >= PEOF);
11970 str = alloca(len_here + 1);
11971 *(char *)mempcpy(str, p, len_here) = '\0';
11973 pushstring(str, NULL);
11978 STADJUST((char *)stackblock() + markloc - out, out);
11980 goto checkend_return;
11984 * Parse a redirection operator. The variable "out" points to a string
11985 * specifying the fd to be redirected. The variable "c" contains the
11986 * first character of the redirection operator.
11989 /* out is already checked to be a valid number or "" */
11990 int fd = (*out == '\0' ? -1 : atoi(out));
11993 np = stzalloc(sizeof(struct nfile));
11998 np->type = NAPPEND;
12000 np->type = NCLOBBER;
12003 /* it also can be NTO2 (>&file), but we can't figure it out yet */
12009 #if BASH_REDIR_OUTPUT
12010 else if (c == 0x100 + '>') { /* this flags &> redirection */
12012 pgetc(); /* this is '>', no need to check */
12016 else { /* c == '<' */
12017 /*np->nfile.fd = 0; - stzalloc did it */
12021 if (sizeof(struct nfile) != sizeof(struct nhere)) {
12022 np = stzalloc(sizeof(struct nhere));
12023 /*np->nfile.fd = 0; - stzalloc did it */
12026 heredoc = stzalloc(sizeof(struct heredoc));
12027 heredoc->here = np;
12030 heredoc->striptabs = 1;
12032 /*heredoc->striptabs = 0; - stzalloc did it */
12038 np->type = NFROMFD;
12042 np->type = NFROMTO;
12054 goto parseredir_return;
12058 * Parse a substitution. At this point, we have read the dollar sign
12059 * and nothing else.
12062 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
12063 * (assuming ascii char codes, as the original implementation did) */
12064 #define is_special(c) \
12065 (((unsigned)(c) - 33 < 32) \
12066 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
12068 unsigned char subtype;
12071 c = pgetc_eatbnl();
12072 if ((checkkwd & CHKEOFMARK)
12073 || c > 255 /* PEOA or PEOF */
12074 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
12076 #if BASH_DOLLAR_SQUOTE
12077 if (syntax != DQSYNTAX && c == '\'')
12078 bash_dollar_squote = 1;
12083 } else if (c == '(') {
12084 /* $(command) or $((arith)) */
12085 if (pgetc_eatbnl() == '(') {
12086 #if ENABLE_FEATURE_SH_MATH
12089 raise_error_syntax("support for $((arith)) is disabled");
12096 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
12097 USTPUTC(CTLVAR, out);
12098 typeloc = out - (char *)stackblock();
12100 subtype = VSNORMAL;
12102 c = pgetc_eatbnl();
12107 /* $[{[#]]NAME[}] */
12110 c = pgetc_eatbnl();
12111 } while (is_in_name(c));
12112 } else if (isdigit(c)) {
12113 /* $[{[#]]NUM[}] */
12116 c = pgetc_eatbnl();
12117 } while (isdigit(c));
12118 } else if (is_special(c)) {
12119 /* $[{[#]]<specialchar>[}] */
12122 c = pgetc_eatbnl();
12123 if (!subtype && cc == '#') {
12124 subtype = VSLENGTH;
12125 if (c == '_' || isalnum(c))
12128 c = pgetc_eatbnl();
12129 if (cc == '}' || c != '}') {
12140 if (c != '}' && subtype == VSLENGTH) {
12141 /* ${#VAR didn't end with } */
12145 if (subtype == 0) {
12146 static const char types[] ALIGN1 = "}-+?=";
12147 /* ${VAR...} but not $VAR or ${#VAR} */
12148 /* c == first char after VAR */
12151 c = pgetc_eatbnl();
12153 /* This check is only needed to not misinterpret
12154 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
12157 if (!strchr(types, c)) {
12158 subtype = VSSUBSTR;
12160 break; /* "goto badsub" is bigger (!) */
12166 const char *p = strchr(types, c);
12169 subtype |= p - types + VSNORMAL;
12175 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
12176 c = pgetc_eatbnl();
12182 #if BASH_PATTERN_SUBST
12184 /* ${v/[/]pattern/repl} */
12185 //TODO: encode pattern and repl separately.
12186 // Currently ${v/$var_with_slash/repl} is horribly broken
12187 subtype = VSREPLACE;
12188 c = pgetc_eatbnl();
12191 subtype++; /* VSREPLACEALL */
12199 ((unsigned char *)stackblock())[typeloc] = subtype;
12200 if (subtype != VSNORMAL) {
12207 goto parsesub_return;
12211 * Called to parse command substitutions. Newstyle is set if the command
12212 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
12213 * list of commands (passed by reference), and savelen is the number of
12214 * characters on the top of the stack which must be preserved.
12217 struct nodelist **nlpp;
12221 smallint saveprompt = 0;
12224 savelen = out - (char *)stackblock();
12227 * FIXME: this can allocate very large block on stack and SEGV.
12229 * echo "..<100kbytes>..`true` $(true) `true` ..."
12230 * allocates 100kb for every command subst. With about
12231 * a hundred command substitutions stack overflows.
12232 * With larger prepended string, SEGV happens sooner.
12234 str = alloca(savelen);
12235 memcpy(str, stackblock(), savelen);
12239 /* We must read until the closing backquote, giving special
12240 * treatment to some slashes, and then push the string and
12241 * reread it as input, interpreting it normally.
12247 STARTSTACKSTR(pout);
12251 setprompt_if(needprompt, 2);
12262 * If eating a newline, avoid putting
12263 * the newline into the new character
12264 * stream (via the STPUTC after the
12269 if (pc != '\\' && pc != '`' && pc != '$'
12270 && (!dblquote || pc != '"')
12272 STPUTC('\\', pout);
12274 if (pc <= 255 /* not PEOA or PEOF */) {
12280 IF_ASH_ALIAS(case PEOA:)
12281 startlinno = g_parsefile->linno;
12282 raise_error_syntax("EOF in backquote substitution");
12294 STPUTC('\0', pout);
12295 psavelen = pout - (char *)stackblock();
12296 if (psavelen > 0) {
12297 pstr = grabstackstr(pout);
12298 setinputstring(pstr);
12303 nlpp = &(*nlpp)->next;
12304 *nlpp = stzalloc(sizeof(**nlpp));
12305 /* (*nlpp)->next = NULL; - stzalloc did it */
12308 saveprompt = doprompt;
12315 doprompt = saveprompt;
12316 else if (readtoken() != TRP)
12317 raise_error_unexpected_syntax(TRP);
12322 * Start reading from old file again, ignoring any pushed back
12323 * tokens left from the backquote parsing
12328 while (stackblocksize() <= savelen)
12330 STARTSTACKSTR(out);
12332 memcpy(out, str, savelen);
12333 STADJUST(savelen, out);
12335 USTPUTC(CTLBACKQ, out);
12337 goto parsebackq_oldreturn;
12338 goto parsebackq_newreturn;
12341 #if ENABLE_FEATURE_SH_MATH
12343 * Parse an arithmetic expansion (indicate start of one and set state)
12346 if (++arinest == 1) {
12347 prevsyntax = syntax;
12348 syntax = ARISYNTAX;
12350 USTPUTC(CTLARI, out);
12351 goto parsearith_return;
12354 } /* end of readtoken */
12357 * Read the next input token.
12358 * If the token is a word, we set backquotelist to the list of cmds in
12359 * backquotes. We set quoteflag to true if any part of the word was
12361 * If the token is TREDIR, then we set redirnode to a structure containing
12363 * In all cases, the variable startlinno is set to the number of the line
12364 * on which the token starts.
12366 * [Change comment: here documents and internal procedures]
12367 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12368 * word parsing code into a separate routine. In this case, readtoken
12369 * doesn't need to have any internal procedures, but parseword does.
12370 * We could also make parseoperator in essence the main routine, and
12371 * have parseword (readtoken1?) handle both words and redirection.]
12373 #define NEW_xxreadtoken
12374 #ifdef NEW_xxreadtoken
12375 /* singles must be first! */
12376 static const char xxreadtoken_chars[7] ALIGN1 = {
12377 '\n', '(', ')', /* singles */
12378 '&', '|', ';', /* doubles */
12382 #define xxreadtoken_singles 3
12383 #define xxreadtoken_doubles 3
12385 static const char xxreadtoken_tokens[] ALIGN1 = {
12386 TNL, TLP, TRP, /* only single occurrence allowed */
12387 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12388 TEOF, /* corresponds to trailing nul */
12389 TAND, TOR, TENDCASE /* if double occurrence */
12401 setprompt_if(needprompt, 2);
12402 startlinno = g_parsefile->linno;
12403 for (;;) { /* until token or start of word found */
12405 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12409 while ((c = pgetc()) != '\n' && c != PEOF)
12412 } else if (c == '\\') {
12413 if (pgetc() != '\n') {
12415 break; /* return readtoken1(...) */
12421 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12427 p = strchr(xxreadtoken_chars, c);
12429 break; /* return readtoken1(...) */
12431 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12433 if (cc == c) { /* double occurrence? */
12434 p += xxreadtoken_doubles + 1;
12437 #if BASH_REDIR_OUTPUT
12438 if (c == '&' && cc == '>') /* &> */
12439 break; /* return readtoken1(...) */
12444 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12449 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12451 #else /* old xxreadtoken */
12452 #define RETURN(token) return lasttoken = token
12462 setprompt_if(needprompt, 2);
12463 startlinno = g_parsefile->linno;
12464 for (;;) { /* until token or start of word found */
12467 case ' ': case '\t':
12468 IF_ASH_ALIAS(case PEOA:)
12471 while ((c = pgetc()) != '\n' && c != PEOF)
12476 if (pgetc() == '\n') {
12488 if (pgetc() == '&')
12493 if (pgetc() == '|')
12498 if (pgetc() == ';')
12511 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12514 #endif /* old xxreadtoken */
12520 int kwd = checkkwd;
12522 smallint alreadyseen = tokpushback;
12525 #if ENABLE_ASH_ALIAS
12541 if (t != TWORD || quoteflag) {
12546 * check for keywords
12548 if (kwd & CHKKWD) {
12549 const char *const *pp;
12551 pp = findkwd(wordtext);
12553 lasttoken = t = pp - tokname_array;
12554 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12559 if (checkkwd & CHKALIAS) {
12560 #if ENABLE_ASH_ALIAS
12562 ap = lookupalias(wordtext, 1);
12565 pushstring(ap->val, ap);
12575 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12577 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12593 * Read and parse a command. Returns NODE_EOF on end of file.
12594 * (NULL is a valid parse tree indicating a blank line.)
12596 static union node *
12597 parsecmd(int interact)
12602 doprompt = interact;
12603 setprompt_if(doprompt, doprompt);
12609 * Input any here documents.
12614 struct heredoc *here;
12617 here = heredoclist;
12618 heredoclist = NULL;
12621 setprompt_if(needprompt, 2);
12622 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12623 here->eofmark, here->striptabs);
12624 n = stzalloc(sizeof(struct narg));
12625 n->narg.type = NARG;
12626 /*n->narg.next = NULL; - stzalloc did it */
12627 n->narg.text = wordtext;
12628 n->narg.backquote = backquotelist;
12629 here->here->nhere.doc = n;
12635 static const char *
12636 expandstr(const char *ps, int syntax_type)
12641 /* XXX Fix (char *) cast. */
12642 setinputstring((char *)ps);
12644 saveprompt = doprompt;
12646 readtoken1(pgetc(), syntax_type, FAKEEOFMARK, 0);
12647 doprompt = saveprompt;
12651 n.narg.type = NARG;
12652 n.narg.next = NULL;
12653 n.narg.text = wordtext;
12654 n.narg.backquote = backquotelist;
12656 expandarg(&n, NULL, EXP_QUOTED);
12657 return stackblock();
12663 return tokpushback && lasttoken == TEOF;
12667 * Execute a command or commands contained in a string.
12670 evalstring(char *s, int flags)
12672 struct jmploc *volatile savehandler;
12673 struct jmploc jmploc;
12677 struct stackmark smark;
12682 setstackmark(&smark);
12685 /* On exception inside execution loop, we must popfile().
12686 * Try interactively:
12688 * command eval "a=b" # throws "is read only" error
12689 * "command BLTIN" is not supposed to abort (even in non-interactive use).
12690 * But if we skip popfile(), we hit EOF in eval's string, and exit.
12692 savehandler = exception_handler;
12693 ex = setjmp(jmploc.loc);
12696 exception_handler = &jmploc;
12698 while ((n = parsecmd(0)) != NODE_EOF) {
12701 i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
12704 popstackmark(&smark);
12709 popstackmark(&smark);
12713 exception_handler = savehandler;
12715 longjmp(exception_handler->loc, ex);
12721 * The eval command.
12723 static int FAST_FUNC
12724 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12733 STARTSTACKSTR(concat);
12735 concat = stack_putstr(p, concat);
12739 STPUTC(' ', concat);
12741 STPUTC('\0', concat);
12742 p = grabstackstr(concat);
12744 return evalstring(p, flags & EV_TESTED);
12750 * Read and execute commands.
12751 * "Top" is nonzero for the top level command loop;
12752 * it turns on prompting if the shell is interactive.
12758 struct stackmark smark;
12763 TRACE(("cmdloop(%d) called\n", top));
12767 setstackmark(&smark);
12770 showjobs(SHOW_CHANGED|SHOW_STDERR);
12773 if (iflag && top) {
12777 n = parsecmd(inter);
12779 if (DEBUG > 2 && debug && (n != NODE_EOF))
12782 if (n == NODE_EOF) {
12783 if (!top || numeof >= 50)
12785 if (!stoppedjobs()) {
12788 out2str("\nUse \"exit\" to leave shell.\n");
12791 } else if (nflag == 0) {
12794 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12797 i = evaltree(n, 0);
12801 popstackmark(&smark);
12805 evalskip &= ~SKIPFUNC;
12813 * Take commands from a file. To be compatible we should do a path
12814 * search for the file, which is necessary to find sub-commands.
12817 find_dot_file(char *name)
12820 const char *path = pathval();
12823 /* don't try this for absolute or relative paths */
12824 if (strchr(name, '/'))
12827 while ((fullname = path_advance(&path, name)) != NULL) {
12828 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12830 * Don't bother freeing here, since it will
12831 * be freed by the caller.
12835 if (fullname != name)
12836 stunalloc(fullname);
12839 /* not found in the PATH */
12840 ash_msg_and_raise_error("%s: not found", name);
12844 static int FAST_FUNC
12845 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12847 /* "false; . empty_file; echo $?" should print 0, not 1: */
12851 char *args_need_save;
12852 volatile struct shparam saveparam;
12855 // struct strlist *sp;
12856 // for (sp = cmdenviron; sp; sp = sp->next)
12857 // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12859 nextopt(nullstr); /* handle possible "--" */
12863 /* bash says: "bash: .: filename argument required" */
12864 return 2; /* bash compat */
12867 /* This aborts if file isn't found, which is POSIXly correct.
12868 * bash returns exitcode 1 instead.
12870 fullname = find_dot_file(argv[0]);
12872 args_need_save = argv[0];
12873 if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
12875 saveparam = shellparam;
12876 shellparam.malloced = 0;
12880 shellparam.nparam = argc;
12881 shellparam.p = argv;
12884 /* This aborts if file can't be opened, which is POSIXly correct.
12885 * bash returns exitcode 1 instead.
12887 setinputfile(fullname, INPUT_PUSH_FILE);
12888 commandname = fullname;
12889 status = cmdloop(0);
12892 if (args_need_save) {
12893 freeparam(&shellparam);
12894 shellparam = saveparam;
12900 static int FAST_FUNC
12901 exitcmd(int argc UNUSED_PARAM, char **argv)
12906 exitstatus = number(argv[1]);
12907 raise_exception(EXEXIT);
12912 * Read a file containing shell functions.
12915 readcmdfile(char *name)
12917 setinputfile(name, INPUT_PUSH_FILE);
12923 /* ============ find_command inplementation */
12926 * Resolve a command name. If you change this routine, you may have to
12927 * change the shellexec routine as well.
12930 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12932 struct tblentry *cmdp;
12939 struct builtincmd *bcmd;
12941 /* If name contains a slash, don't use PATH or hash table */
12942 if (strchr(name, '/') != NULL) {
12943 entry->u.index = -1;
12944 if (act & DO_ABS) {
12945 while (stat(name, &statb) < 0) {
12947 if (errno == EINTR)
12950 entry->cmdtype = CMDUNKNOWN;
12954 entry->cmdtype = CMDNORMAL;
12958 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12960 updatetbl = (path == pathval());
12963 if (strstr(path, "%builtin") != NULL)
12964 act |= DO_ALTBLTIN;
12967 /* If name is in the table, check answer will be ok */
12968 cmdp = cmdlookup(name, 0);
12969 if (cmdp != NULL) {
12972 switch (cmdp->cmdtype) {
12990 } else if (cmdp->rehash == 0)
12991 /* if not invalidated by cd, we're done */
12995 /* If %builtin not in path, check for builtin next */
12996 bcmd = find_builtin(name);
12998 if (IS_BUILTIN_REGULAR(bcmd))
12999 goto builtin_success;
13000 if (act & DO_ALTPATH) {
13001 if (!(act & DO_ALTBLTIN))
13002 goto builtin_success;
13003 } else if (builtinloc <= 0) {
13004 goto builtin_success;
13008 #if ENABLE_FEATURE_SH_STANDALONE
13010 int applet_no = find_applet_by_name(name);
13011 if (applet_no >= 0) {
13012 entry->cmdtype = CMDNORMAL;
13013 entry->u.index = -2 - applet_no;
13019 /* We have to search path. */
13020 prev = -1; /* where to start */
13021 if (cmdp && cmdp->rehash) { /* doing a rehash */
13022 if (cmdp->cmdtype == CMDBUILTIN)
13025 prev = cmdp->param.index;
13031 while ((fullname = path_advance(&path, name)) != NULL) {
13032 stunalloc(fullname);
13033 /* NB: code below will still use fullname
13034 * despite it being "unallocated" */
13037 if (prefix(pathopt, "builtin")) {
13039 goto builtin_success;
13042 if ((act & DO_NOFUNC)
13043 || !prefix(pathopt, "func")
13044 ) { /* ignore unimplemented options */
13048 /* if rehash, don't redo absolute path names */
13049 if (fullname[0] == '/' && idx <= prev) {
13052 TRACE(("searchexec \"%s\": no change\n", name));
13055 while (stat(fullname, &statb) < 0) {
13057 if (errno == EINTR)
13060 if (errno != ENOENT && errno != ENOTDIR)
13064 e = EACCES; /* if we fail, this will be the error */
13065 if (!S_ISREG(statb.st_mode))
13067 if (pathopt) { /* this is a %func directory */
13068 stalloc(strlen(fullname) + 1);
13069 /* NB: stalloc will return space pointed by fullname
13070 * (because we don't have any intervening allocations
13071 * between stunalloc above and this stalloc) */
13072 readcmdfile(fullname);
13073 cmdp = cmdlookup(name, 0);
13074 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
13075 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
13076 stunalloc(fullname);
13079 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
13081 entry->cmdtype = CMDNORMAL;
13082 entry->u.index = idx;
13086 cmdp = cmdlookup(name, 1);
13087 cmdp->cmdtype = CMDNORMAL;
13088 cmdp->param.index = idx;
13093 /* We failed. If there was an entry for this command, delete it */
13094 if (cmdp && updatetbl)
13095 delete_cmd_entry();
13097 ash_msg("%s: %s", name, errmsg(e, "not found"));
13098 entry->cmdtype = CMDUNKNOWN;
13103 entry->cmdtype = CMDBUILTIN;
13104 entry->u.cmd = bcmd;
13108 cmdp = cmdlookup(name, 1);
13109 cmdp->cmdtype = CMDBUILTIN;
13110 cmdp->param.cmd = bcmd;
13114 entry->cmdtype = cmdp->cmdtype;
13115 entry->u = cmdp->param;
13120 * The trap builtin.
13122 static int FAST_FUNC
13123 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13127 int signo, exitcode;
13132 for (signo = 0; signo < NSIG; signo++) {
13133 char *tr = trap_ptr[signo];
13135 /* note: bash adds "SIG", but only if invoked
13136 * as "bash". If called as "sh", or if set -o posix,
13137 * then it prints short signal names.
13138 * We are printing short names: */
13139 out1fmt("trap -- %s %s\n",
13141 get_signame(signo));
13142 /* trap_ptr != trap only if we are in special-cased `trap` code.
13143 * In this case, we will exit very soon, no need to free(). */
13144 /* if (trap_ptr != trap && tp[0]) */
13149 if (trap_ptr != trap) {
13157 /* Why the second check?
13158 * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
13159 * In this case, NUM is signal no, not an action.
13162 if (ap[1] && !is_number(ap[0]))
13167 signo = get_signum(*ap);
13169 /* Mimic bash message exactly */
13170 ash_msg("%s: invalid signal specification", *ap);
13176 if (LONE_DASH(action))
13179 if (action[0]) /* not NULL and not "" and not "-" */
13180 may_have_traps = 1;
13181 action = ckstrdup(action);
13185 trap[signo] = action;
13196 /* ============ Builtins */
13198 #if ENABLE_ASH_HELP
13199 static int FAST_FUNC
13200 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13206 "Built-in commands:\n"
13207 "------------------\n");
13208 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
13209 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
13210 builtintab[i].name + 1);
13216 # if ENABLE_FEATURE_SH_STANDALONE
13218 const char *a = applet_names;
13220 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
13225 while (*a++ != '\0')
13230 newline_and_flush(stdout);
13231 return EXIT_SUCCESS;
13236 static int FAST_FUNC
13237 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13239 show_history(line_input_state);
13240 return EXIT_SUCCESS;
13245 * The export and readonly commands.
13247 static int FAST_FUNC
13248 exportcmd(int argc UNUSED_PARAM, char **argv)
13258 /* "readonly" in bash accepts, but ignores -n.
13259 * We do the same: it saves a conditional in nextopt's param.
13262 while ((opt = nextopt("np")) != '\0') {
13264 flag_off = VEXPORT;
13267 if (argv[0][0] == 'r') {
13269 flag_off = 0; /* readonly ignores -n */
13271 flag_off = ~flag_off;
13273 /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
13279 p = strchr(name, '=');
13283 vp = *findvar(hashvar(name), name);
13285 vp->flags = ((vp->flags | flag) & flag_off);
13289 setvar(name, p, (flag & flag_off));
13290 } while ((name = *++aptr) != NULL);
13295 /* No arguments. Show the list of exported or readonly vars.
13298 showvars(argv[0], flag, 0);
13303 * Delete a function if it exists.
13306 unsetfunc(const char *name)
13308 struct tblentry *cmdp;
13310 cmdp = cmdlookup(name, 0);
13311 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
13312 delete_cmd_entry();
13316 * The unset builtin command. We unset the function before we unset the
13317 * variable to allow a function to be unset when there is a readonly variable
13318 * with the same name.
13320 static int FAST_FUNC
13321 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13327 while ((i = nextopt("vf")) != 0) {
13331 for (ap = argptr; *ap; ap++) {
13342 static const unsigned char timescmd_str[] ALIGN1 = {
13343 ' ', offsetof(struct tms, tms_utime),
13344 '\n', offsetof(struct tms, tms_stime),
13345 ' ', offsetof(struct tms, tms_cutime),
13346 '\n', offsetof(struct tms, tms_cstime),
13349 static int FAST_FUNC
13350 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13352 unsigned long clk_tck, s, t;
13353 const unsigned char *p;
13356 clk_tck = bb_clk_tck();
13361 t = *(clock_t *)(((char *) &buf) + p[1]);
13364 out1fmt("%lum%lu.%03lus%c",
13366 (t * 1000) / clk_tck,
13374 #if ENABLE_FEATURE_SH_MATH
13376 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13377 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13379 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13381 static int FAST_FUNC
13382 letcmd(int argc UNUSED_PARAM, char **argv)
13388 ash_msg_and_raise_error("expression expected");
13390 i = ash_arith(*argv);
13398 * The read builtin. Options:
13399 * -r Do not interpret '\' specially
13400 * -s Turn off echo (tty only)
13401 * -n NCHARS Read NCHARS max
13402 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13403 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13404 * -u FD Read from given FD instead of fd 0
13405 * This uses unbuffered input, which may be avoidable in some cases.
13406 * TODO: bash also has:
13407 * -a ARRAY Read into array[0],[1],etc
13408 * -d DELIM End on DELIM char, not newline
13409 * -e Use line editing (tty only)
13411 static int FAST_FUNC
13412 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13414 char *opt_n = NULL;
13415 char *opt_p = NULL;
13416 char *opt_t = NULL;
13417 char *opt_u = NULL;
13418 int read_flags = 0;
13422 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
13431 read_flags |= BUILTIN_READ_SILENT;
13437 read_flags |= BUILTIN_READ_RAW;
13447 /* "read -s" needs to save/restore termios, can't allow ^C
13448 * to jump out of it.
13452 r = shell_builtin_read(setvar0,
13454 bltinlookup("IFS"), /* can be NULL */
13463 if ((uintptr_t)r == 1 && errno == EINTR) {
13464 /* To get SIGCHLD: sleep 1 & read x; echo $x
13465 * Correct behavior is to not exit "read"
13467 if (pending_sig == 0)
13471 if ((uintptr_t)r > 1)
13472 ash_msg_and_raise_error(r);
13474 return (uintptr_t)r;
13477 static int FAST_FUNC
13478 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13480 static const char permuser[3] ALIGN1 = "ogu";
13483 int symbolic_mode = 0;
13485 while (nextopt("S") != '\0') {
13494 if (*argptr == NULL) {
13495 if (symbolic_mode) {
13496 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13503 *p++ = permuser[i];
13505 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13506 if (!(mask & 0400)) *p++ = 'r';
13507 if (!(mask & 0200)) *p++ = 'w';
13508 if (!(mask & 0100)) *p++ = 'x';
13516 out1fmt("%04o\n", mask);
13519 char *modestr = *argptr;
13520 /* numeric umasks are taken as-is */
13521 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13522 if (!isdigit(modestr[0]))
13524 mask = bb_parse_mode(modestr, mask);
13525 if ((unsigned)mask > 0777) {
13526 ash_msg_and_raise_error("illegal mode: %s", modestr);
13528 if (!isdigit(modestr[0]))
13535 static int FAST_FUNC
13536 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13538 return shell_builtin_ulimit(argv);
13541 /* ============ main() and helpers */
13544 * Called to exit the shell.
13553 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13554 save_history(line_input_state);
13556 status = exitstatus;
13557 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13558 if (setjmp(loc.loc)) {
13559 if (exception_type == EXEXIT)
13560 status = exitstatus;
13563 exception_handler = &loc;
13569 /*free(p); - we'll exit soon */
13572 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13573 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13576 flush_stdout_stderr();
13581 /* Don't inline: conserve stack of caller from having our locals too */
13582 static NOINLINE void
13585 /* we will never free this */
13586 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13588 sigmode[SIGCHLD - 1] = S_DFL; /* ensure we install handler even if it is SIG_IGNed */
13589 setsignal(SIGCHLD);
13591 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13592 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13594 signal(SIGHUP, SIG_DFL);
13601 for (envp = environ; envp && *envp; envp++) {
13602 p = endofname(*envp);
13603 if (p != *envp && *p == '=') {
13604 setvareq(*envp, VEXPORT|VTEXTFIXED);
13608 setvareq((char*)defoptindvar, VTEXTFIXED);
13610 setvar0("PPID", utoa(getppid()));
13612 p = lookupvar("SHLVL");
13613 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13615 #if BASH_HOSTNAME_VAR
13616 if (!lookupvar("HOSTNAME")) {
13617 struct utsname uts;
13619 setvar0("HOSTNAME", uts.nodename);
13622 p = lookupvar("PWD");
13624 struct stat st1, st2;
13625 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13626 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13636 //usage:#define ash_trivial_usage
13637 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13638 //usage:#define ash_full_usage "\n\n"
13639 //usage: "Unix shell interpreter"
13642 * Process the shell command line arguments.
13645 procargs(char **argv)
13648 const char *xminusc;
13653 login_sh = xargv[0] && xargv[0][0] == '-';
13655 /* if (xargv[0]) - mmm, this is always true! */
13657 for (i = 0; i < NOPTS; i++)
13660 if (options(/*cmdline:*/ 1, &login_sh)) {
13661 /* it already printed err message */
13662 raise_exception(EXERROR);
13666 if (*xargv == NULL) {
13668 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13671 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13675 for (i = 0; i < NOPTS; i++)
13676 if (optlist[i] == 2)
13681 /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
13686 } else if (!sflag) {
13687 setinputfile(*xargv, 0);
13690 commandname = arg0;
13693 shellparam.p = xargv;
13694 #if ENABLE_ASH_GETOPTS
13695 shellparam.optind = 1;
13696 shellparam.optoff = -1;
13698 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13700 shellparam.nparam++;
13709 * Read /etc/profile, ~/.profile, $ENV.
13712 read_profile(const char *name)
13714 name = expandstr(name, DQSYNTAX);
13715 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13722 * This routine is called when an error or an interrupt occurs in an
13723 * interactive shell and control is returned to the main command loop.
13724 * (In dash, this function is auto-generated by build machinery).
13733 /* from expand.c: */
13736 /* from input.c: */
13737 g_parsefile->left_in_buffer = 0;
13738 g_parsefile->left_in_line = 0; /* clear input buffer */
13741 /* from redir.c: */
13745 unwindlocalvars(NULL);
13749 static short profile_buf[16384];
13750 extern int etext();
13754 * Main routine. We initialize things, parse the arguments, execute
13755 * profiles if we're a login shell, and then call cmdloop to execute
13756 * commands. The setjmp call sets up the location to jump to when an
13757 * exception occurs. When an exception occurs the variable "state"
13758 * is used to figure out how far we had gotten.
13760 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13761 int ash_main(int argc UNUSED_PARAM, char **argv)
13763 volatile smallint state;
13764 struct jmploc jmploc;
13765 struct stackmark smark;
13768 /* Initialize global data */
13772 #if ENABLE_ASH_ALIAS
13778 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13781 #if ENABLE_FEATURE_EDITING
13782 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13785 if (setjmp(jmploc.loc)) {
13791 e = exception_type;
13793 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13797 newline_and_flush(stderr);
13800 popstackmark(&smark);
13801 FORCE_INT_ON; /* enable interrupts */
13810 exception_handler = &jmploc;
13811 rootpid = getpid();
13814 setstackmark(&smark);
13815 login_sh = procargs(argv);
13817 TRACE(("Shell args: "));
13818 trace_puts_args(argv);
13825 read_profile("/etc/profile");
13828 hp = lookupvar("HOME");
13830 read_profile("$HOME/.profile");
13836 getuid() == geteuid() && getgid() == getegid() &&
13840 const char *shinit = lookupvar("ENV");
13841 if (shinit != NULL && *shinit != '\0')
13842 read_profile(shinit);
13844 popstackmark(&smark);
13848 /* evalstring pushes parsefile stack.
13849 * Ensure we don't falsely claim that 0 (stdin)
13850 * is one of stacked source fds.
13851 * Testcase: ash -c 'exec 1>&0' must not complain. */
13852 // if (!sflag) g_parsefile->pf_fd = -1;
13853 // ^^ not necessary since now we special-case fd 0
13854 // in save_fd_on_redirect()
13855 evalstring(minusc, sflag ? 0 : EV_EXIT);
13858 if (sflag || minusc == NULL) {
13859 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13861 const char *hp = lookupvar("HISTFILE");
13863 hp = lookupvar("HOME");
13866 hp = concat_path_file(hp, ".ash_history");
13867 setvar0("HISTFILE", hp);
13870 hp = lookupvar("HISTFILE");
13874 line_input_state->hist_file = hp;
13875 # if ENABLE_FEATURE_SH_HISTFILESIZE
13876 hp = lookupvar("HISTFILESIZE");
13877 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13881 state4: /* XXX ??? - why isn't this before the "if" statement */
13889 extern void _mcleanup(void);
13893 TRACE(("End of main reached\n"));
13900 * Copyright (c) 1989, 1991, 1993, 1994
13901 * The Regents of the University of California. All rights reserved.
13903 * This code is derived from software contributed to Berkeley by
13904 * Kenneth Almquist.
13906 * Redistribution and use in source and binary forms, with or without
13907 * modification, are permitted provided that the following conditions
13909 * 1. Redistributions of source code must retain the above copyright
13910 * notice, this list of conditions and the following disclaimer.
13911 * 2. Redistributions in binary form must reproduce the above copyright
13912 * notice, this list of conditions and the following disclaimer in the
13913 * documentation and/or other materials provided with the distribution.
13914 * 3. Neither the name of the University nor the names of its contributors
13915 * may be used to endorse or promote products derived from this software
13916 * without specific prior written permission.
13918 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
13919 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13920 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13921 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13922 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13923 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13924 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13925 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13926 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13927 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF