1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * This code is derived from software contributed to Berkeley by
8 * Original BSD copyright notice is retained at the end of this file.
10 * Copyright (c) 1989, 1991, 1993, 1994
11 * The Regents of the University of California. All rights reserved.
13 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
14 * was re-ported from NetBSD and debianized.
16 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
19 //config: bool "ash (77 kb)"
21 //config: depends on !NOMMU
23 //config: The most complete and most pedantically correct shell included with
24 //config: busybox. This shell is actually a derivative of the Debian 'dash'
25 //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
26 //config: (written by Kenneth Almquist) from NetBSD.
28 //config:# ash options
29 //config:# note: Don't remove !NOMMU part in the next line; it would break
30 //config:# menuconfig's indenting.
31 //config:if !NOMMU && (ASH || SH_IS_ASH || BASH_IS_ASH)
33 //config:config ASH_OPTIMIZE_FOR_SIZE
34 //config: bool "Optimize for size instead of speed"
36 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
38 //config:config ASH_INTERNAL_GLOB
39 //config: bool "Use internal glob() implementation"
40 //config: default y # Y is bigger, but because of uclibc glob() bug, let Y be default for now
41 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
43 //config: Do not use glob() function from libc, use internal implementation.
44 //config: Use this if you are getting "glob.h: No such file or directory"
45 //config: or similar build errors.
46 //config: Note that as of now (2017-01), uclibc and musl glob() both have bugs
47 //config: which would break ash if you select N here.
49 //config:config ASH_BASH_COMPAT
50 //config: bool "bash-compatible extensions"
52 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
54 //config:config ASH_JOB_CONTROL
55 //config: bool "Job control"
57 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
59 //config:config ASH_ALIAS
60 //config: bool "Alias support"
62 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
64 //config:config ASH_RANDOM_SUPPORT
65 //config: bool "Pseudorandom generator and $RANDOM variable"
67 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
69 //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
70 //config: Each read of "$RANDOM" will generate a new pseudorandom value.
71 //config: You can reset the generator by using a specified start value.
72 //config: After "unset RANDOM" the generator will switch off and this
73 //config: variable will no longer have special treatment.
75 //config:config ASH_EXPAND_PRMT
76 //config: bool "Expand prompt string"
78 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
80 //config: $PS# may contain volatile content, such as backquote commands.
81 //config: This option recreates the prompt string from the environment
82 //config: variable each time it is displayed.
84 //config:config ASH_IDLE_TIMEOUT
85 //config: bool "Idle timeout variable $TMOUT"
87 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
89 //config: Enable bash-like auto-logout after $TMOUT seconds of idle time.
91 //config:config ASH_MAIL
92 //config: bool "Check for new mail in interactive shell"
94 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
96 //config: Enable "check for new mail" function:
97 //config: if set, $MAIL file and $MAILPATH list of files
98 //config: are checked for mtime changes, and "you have mail"
99 //config: message is printed if change is detected.
101 //config:config ASH_ECHO
102 //config: bool "echo builtin"
104 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
106 //config:config ASH_PRINTF
107 //config: bool "printf builtin"
109 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
111 //config:config ASH_TEST
112 //config: bool "test builtin"
114 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
116 //config:config ASH_HELP
117 //config: bool "help builtin"
119 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
121 //config:config ASH_GETOPTS
122 //config: bool "getopts builtin"
124 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
126 //config:config ASH_CMDCMD
127 //config: bool "command builtin"
129 //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
131 //config: Enable support for the 'command' builtin, which allows
132 //config: you to run the specified command or builtin,
133 //config: even when there is a function with the same name.
135 //config:endif # ash options
137 //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
138 // APPLET_ODDNAME:name main location suid_type help
139 //applet:IF_SH_IS_ASH( APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
140 //applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
142 //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
143 //kbuild:lib-$(CONFIG_SH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
144 //kbuild:lib-$(CONFIG_BASH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
145 //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
148 * DEBUG=1 to compile in debugging ('set -o debug' turns on)
149 * DEBUG=2 to compile in and turn on debugging.
150 * When debugging is on ("set -o debug" was executed, or DEBUG=2),
151 * debugging info is written to ./trace, quit signal generates core dump.
154 /* Tweak debug output verbosity here */
158 #define DEBUG_INTONOFF 0
162 #define JOBS ENABLE_ASH_JOB_CONTROL
166 #include <sys/times.h>
167 #include <sys/utsname.h> /* for setting $HOSTNAME */
168 #include "busybox.h" /* for applet_names */
170 /* So far, all bash compat is controlled by one config option */
171 /* Separate defines document which part of code implements what */
172 /* function keyword */
173 #define BASH_FUNCTION ENABLE_ASH_BASH_COMPAT
174 #define IF_BASH_FUNCTION IF_ASH_BASH_COMPAT
176 #define BASH_REDIR_OUTPUT ENABLE_ASH_BASH_COMPAT
177 #define IF_BASH_REDIR_OUTPUT IF_ASH_BASH_COMPAT
179 #define BASH_DOLLAR_SQUOTE ENABLE_ASH_BASH_COMPAT
180 #define IF_BASH_DOLLAR_SQUOTE IF_ASH_BASH_COMPAT
181 #define BASH_PATTERN_SUBST ENABLE_ASH_BASH_COMPAT
182 #define IF_BASH_PATTERN_SUBST IF_ASH_BASH_COMPAT
183 #define BASH_SUBSTR ENABLE_ASH_BASH_COMPAT
184 #define IF_BASH_SUBSTR IF_ASH_BASH_COMPAT
186 #define BASH_TEST2 (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)
187 #define BASH_SOURCE ENABLE_ASH_BASH_COMPAT
188 #define BASH_PIPEFAIL ENABLE_ASH_BASH_COMPAT
189 #define BASH_HOSTNAME_VAR ENABLE_ASH_BASH_COMPAT
190 #define BASH_SHLVL_VAR ENABLE_ASH_BASH_COMPAT
192 #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
193 /* Bionic at least up to version 24 has no glob() */
194 # undef ENABLE_ASH_INTERNAL_GLOB
195 # define ENABLE_ASH_INTERNAL_GLOB 1
198 #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
199 # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
200 # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
201 # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
202 # error glob() should unbackslash them and match. uClibc does not unbackslash,
203 # error fails to match dirname, subsequently not expanding <pattern> in it.
205 // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
206 // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
209 #if !ENABLE_ASH_INTERNAL_GLOB
214 #include "shell_common.h"
215 #if ENABLE_FEATURE_SH_MATH
218 typedef long arith_t;
219 # define ARITH_FMT "%ld"
221 #if ENABLE_ASH_RANDOM_SUPPORT
224 # define CLEAR_RANDOM_T(rnd) ((void)0)
227 #include "NUM_APPLETS.h"
229 /* STANDALONE does not make sense, and won't compile */
230 # undef CONFIG_FEATURE_SH_STANDALONE
231 # undef ENABLE_FEATURE_SH_STANDALONE
232 # undef IF_FEATURE_SH_STANDALONE
233 # undef IF_NOT_FEATURE_SH_STANDALONE
234 # define ENABLE_FEATURE_SH_STANDALONE 0
235 # define IF_FEATURE_SH_STANDALONE(...)
236 # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
240 # define PIPE_BUF 4096 /* amount of buffering in a pipe */
244 # error "Do not even bother, ash will not run on NOMMU machine"
248 /* ============ Hash table sizes. Configurable. */
252 #define CMDTABLESIZE 31 /* should be prime */
255 /* ============ Shell options */
257 static const char *const optletters_optnames[] = {
281 #define optletters(n) optletters_optnames[n][0]
282 #define optnames(n) (optletters_optnames[n] + 1)
284 enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
287 /* ============ Misc data */
289 #define msg_illnum "Illegal number: %s"
292 * We enclose jmp_buf in a structure so that we can declare pointers to
293 * jump locations. The global variable handler contains the location to
294 * jump to when an exception occurs, and the global variable exception_type
295 * contains a code identifying the exception. To implement nested
296 * exception handlers, the user should save the value of handler on entry
297 * to an inner scope, set handler to point to a jmploc structure for the
298 * inner scope, and restore handler on exit from the scope.
304 struct globals_misc {
305 uint8_t exitstatus; /* exit status of last command */
306 uint8_t back_exitstatus;/* exit status of backquoted command */
307 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
308 int rootpid; /* pid of main shell */
309 /* shell level: 0 for the main shell, 1 for its children, and so on */
311 #define rootshell (!shlvl)
312 char *minusc; /* argument to -c option */
314 char *curdir; // = nullstr; /* current working directory */
315 char *physdir; // = nullstr; /* physical working directory */
317 char *arg0; /* value of $0 */
319 struct jmploc *exception_handler;
321 volatile int suppress_int; /* counter */
322 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
323 volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
324 volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
325 smallint exception_type; /* kind of exception (0..5) */
327 #define EXINT 0 /* SIGINT received */
328 #define EXERROR 1 /* a generic error */
329 #define EXEXIT 4 /* exit the shell */
332 char nullstr[1]; /* zero length string */
335 #define eflag optlist[0]
336 #define fflag optlist[1]
337 #define Iflag optlist[2]
338 #define iflag optlist[3]
339 #define mflag optlist[4]
340 #define nflag optlist[5]
341 #define sflag optlist[6]
342 #define xflag optlist[7]
343 #define vflag optlist[8]
344 #define Cflag optlist[9]
345 #define aflag optlist[10]
346 #define bflag optlist[11]
347 #define uflag optlist[12]
348 #define viflag optlist[13]
350 # define pipefail optlist[14]
355 # define nolog optlist[14 + BASH_PIPEFAIL]
356 # define debug optlist[15 + BASH_PIPEFAIL]
359 /* trap handler commands */
361 * Sigmode records the current value of the signal handlers for the various
362 * modes. A value of zero means that the current handler is not known.
363 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
365 char sigmode[NSIG - 1];
366 #define S_DFL 1 /* default signal handling (SIG_DFL) */
367 #define S_CATCH 2 /* signal is caught */
368 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
369 #define S_HARD_IGN 4 /* signal is ignored permanently */
371 /* indicates specified signal received */
372 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
373 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
375 char **trap_ptr; /* used only by "trap hack" */
377 /* Rarely referenced stuff */
378 #if ENABLE_ASH_RANDOM_SUPPORT
381 pid_t backgndpid; /* pid of last background process */
383 extern struct globals_misc *const ash_ptr_to_globals_misc;
384 #define G_misc (*ash_ptr_to_globals_misc)
385 #define exitstatus (G_misc.exitstatus )
386 #define back_exitstatus (G_misc.back_exitstatus )
387 #define job_warning (G_misc.job_warning)
388 #define rootpid (G_misc.rootpid )
389 #define shlvl (G_misc.shlvl )
390 #define minusc (G_misc.minusc )
391 #define curdir (G_misc.curdir )
392 #define physdir (G_misc.physdir )
393 #define arg0 (G_misc.arg0 )
394 #define exception_handler (G_misc.exception_handler)
395 #define exception_type (G_misc.exception_type )
396 #define suppress_int (G_misc.suppress_int )
397 #define pending_int (G_misc.pending_int )
398 #define got_sigchld (G_misc.got_sigchld )
399 #define pending_sig (G_misc.pending_sig )
400 #define isloginsh (G_misc.isloginsh )
401 #define nullstr (G_misc.nullstr )
402 #define optlist (G_misc.optlist )
403 #define sigmode (G_misc.sigmode )
404 #define gotsig (G_misc.gotsig )
405 #define may_have_traps (G_misc.may_have_traps )
406 #define trap (G_misc.trap )
407 #define trap_ptr (G_misc.trap_ptr )
408 #define random_gen (G_misc.random_gen )
409 #define backgndpid (G_misc.backgndpid )
410 #define INIT_G_misc() do { \
411 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
419 /* ============ DEBUG */
421 static void trace_printf(const char *fmt, ...);
422 static void trace_vprintf(const char *fmt, va_list va);
423 # define TRACE(param) trace_printf param
424 # define TRACEV(param) trace_vprintf param
425 # define close(fd) do { \
427 if (close(dfd) < 0) \
428 bb_error_msg("bug on %d: closing %d(0x%x)", \
429 __LINE__, dfd, dfd); \
432 # define TRACE(param)
433 # define TRACEV(param)
437 /* ============ Utility functions */
438 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
439 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
442 isdigit_str9(const char *str)
444 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
445 while (--maxlen && isdigit(*str))
447 return (*str == '\0');
451 var_end(const char *var)
460 /* ============ Interrupts / exceptions */
462 static void exitshell(void) NORETURN;
465 * These macros allow the user to suspend the handling of interrupt signals
466 * over a period of time. This is similar to SIGHOLD or to sigblock, but
467 * much more efficient and portable. (But hacking the kernel is so much
468 * more fun than worrying about efficiency and portability. :-))
471 # define INT_OFF do { \
472 TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
477 # define INT_OFF do { \
484 * Called to raise an exception. Since C doesn't include exceptions, we
485 * just do a longjmp to the exception handler. The type of exception is
486 * stored in the global variable "exception_type".
488 static void raise_exception(int) NORETURN;
490 raise_exception(int e)
493 if (exception_handler == NULL)
498 longjmp(exception_handler->loc, 1);
501 #define raise_exception(e) do { \
502 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
503 raise_exception(e); \
508 * Called when a SIGINT is received. (If the user specifies
509 * that SIGINT is to be trapped or ignored using the trap builtin, then
510 * this routine is not called.) Suppressint is nonzero when interrupts
511 * are held using the INT_OFF macro. (The test for iflag is just
512 * defensive programming.)
514 static void raise_interrupt(void) NORETURN;
516 raise_interrupt(void)
519 /* Signal is not automatically unmasked after it is raised,
520 * do it ourself - unmask all signals */
521 sigprocmask_allsigs(SIG_UNBLOCK);
522 /* pending_sig = 0; - now done in signal_handler() */
524 if (!(rootshell && iflag)) {
525 /* Kill ourself with SIGINT */
526 signal(SIGINT, SIG_DFL);
529 /* bash: ^C even on empty command line sets $? */
530 exitstatus = SIGINT + 128;
531 raise_exception(EXINT);
535 #define raise_interrupt() do { \
536 TRACE(("raising interrupt on line %d\n", __LINE__)); \
541 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
545 if (--suppress_int == 0 && pending_int) {
550 # define INT_ON do { \
551 TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
555 # define INT_ON int_on()
557 static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
565 #define FORCE_INT_ON force_int_on()
567 #define SAVE_INT(v) ((v) = suppress_int)
569 #define RESTORE_INT(v) do { \
571 suppress_int = (v); \
572 if (suppress_int == 0 && pending_int) \
577 /* ============ Stdout/stderr output */
580 outstr(const char *p, FILE *file)
588 flush_stdout_stderr(void)
595 /* Was called outcslow(c,FILE*), but c was always '\n' */
597 newline_and_flush(FILE *dest)
605 static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
607 out1fmt(const char *fmt, ...)
614 r = vprintf(fmt, ap);
620 static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
622 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
629 ret = vsnprintf(outbuf, length, fmt, ap);
636 out1str(const char *p)
642 out2str(const char *p)
645 flush_stdout_stderr();
649 /* ============ Parser structures */
651 /* control characters in argument strings */
652 #define CTL_FIRST CTLESC
653 #define CTLESC ((unsigned char)'\201') /* escape next character */
654 #define CTLVAR ((unsigned char)'\202') /* variable defn */
655 #define CTLENDVAR ((unsigned char)'\203')
656 #define CTLBACKQ ((unsigned char)'\204')
657 #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
658 #define CTLENDARI ((unsigned char)'\207')
659 #define CTLQUOTEMARK ((unsigned char)'\210')
660 #define CTL_LAST CTLQUOTEMARK
662 /* variable substitution byte (follows CTLVAR) */
663 #define VSTYPE 0x0f /* type of variable substitution */
664 #define VSNUL 0x10 /* colon--treat the empty string as unset */
666 /* values of VSTYPE field */
667 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
668 #define VSMINUS 0x2 /* ${var-text} */
669 #define VSPLUS 0x3 /* ${var+text} */
670 #define VSQUESTION 0x4 /* ${var?message} */
671 #define VSASSIGN 0x5 /* ${var=text} */
672 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
673 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
674 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
675 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
676 #define VSLENGTH 0xa /* ${#var} */
678 #define VSSUBSTR 0xc /* ${var:position:length} */
680 #if BASH_PATTERN_SUBST
681 #define VSREPLACE 0xd /* ${var/pattern/replacement} */
682 #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
685 static const char dolatstr[] ALIGN1 = {
686 CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
688 #define DOLATSTRLEN 6
707 #if BASH_REDIR_OUTPUT
724 smallint type; /* Nxxxx */
727 union node *redirect;
732 smallint pipe_backgnd;
733 struct nodelist *cmdlist;
739 union node *redirect;
752 union node *elsepart;
779 struct nodelist *backquote;
782 /* nfile and ndup layout must match!
783 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
784 * that it is actually NTO2 (>&file), and change its type.
801 char *_unused_expfname;
820 struct nredir nredir;
821 struct nbinary nbinary;
825 struct nclist nclist;
834 * NODE_EOF is returned by parsecmd when it encounters an end of file.
835 * It must be distinct from NULL.
837 #define NODE_EOF ((union node *) -1L)
840 struct nodelist *next;
853 freefunc(struct funcnode *f)
855 if (f && --f->count < 0)
860 /* ============ Debugging output */
864 static FILE *tracefile;
867 trace_printf(const char *fmt, ...)
874 fprintf(tracefile, "%u ", (int) time(NULL));
876 fprintf(tracefile, "[%u] ", (int) getpid());
878 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
880 vfprintf(tracefile, fmt, va);
885 trace_vprintf(const char *fmt, va_list va)
889 vfprintf(tracefile, fmt, va);
890 fprintf(tracefile, "\n");
894 trace_puts(const char *s)
902 trace_puts_quoted(char *s)
909 putc('"', tracefile);
910 for (p = s; *p; p++) {
911 switch ((unsigned char)*p) {
912 case '\n': c = 'n'; goto backslash;
913 case '\t': c = 't'; goto backslash;
914 case '\r': c = 'r'; goto backslash;
915 case '\"': c = '\"'; goto backslash;
916 case '\\': c = '\\'; goto backslash;
917 case CTLESC: c = 'e'; goto backslash;
918 case CTLVAR: c = 'v'; goto backslash;
919 case CTLBACKQ: c = 'q'; goto backslash;
921 putc('\\', tracefile);
925 if (*p >= ' ' && *p <= '~')
928 putc('\\', tracefile);
929 putc((*p >> 6) & 03, tracefile);
930 putc((*p >> 3) & 07, tracefile);
931 putc(*p & 07, tracefile);
936 putc('"', tracefile);
940 trace_puts_args(char **ap)
947 trace_puts_quoted(*ap);
949 putc('\n', tracefile);
952 putc(' ', tracefile);
967 /* leave open because libedit might be using it */
970 strcpy(s, "./trace");
972 if (!freopen(s, "a", tracefile)) {
973 fprintf(stderr, "Can't re-open %s\n", s);
978 tracefile = fopen(s, "a");
979 if (tracefile == NULL) {
980 fprintf(stderr, "Can't open %s\n", s);
986 flags = fcntl(fileno(tracefile), F_GETFL);
988 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
990 setlinebuf(tracefile);
991 fputs("\nTracing started.\n", tracefile);
995 indent(int amount, char *pfx, FILE *fp)
999 for (i = 0; i < amount; i++) {
1000 if (pfx && i == amount - 1)
1006 /* little circular references here... */
1007 static void shtree(union node *n, int ind, char *pfx, FILE *fp);
1010 sharg(union node *arg, FILE *fp)
1013 struct nodelist *bqlist;
1014 unsigned char subtype;
1016 if (arg->type != NARG) {
1017 out1fmt("<node type %d>\n", arg->type);
1020 bqlist = arg->narg.backquote;
1021 for (p = arg->narg.text; *p; p++) {
1022 switch ((unsigned char)*p) {
1031 if (subtype == VSLENGTH)
1039 if (subtype & VSNUL)
1042 switch (subtype & VSTYPE) {
1068 case VSTRIMRIGHTMAX:
1075 out1fmt("<subtype %d>", subtype);
1084 shtree(bqlist->n, -1, NULL, fp);
1095 shcmd(union node *cmd, FILE *fp)
1103 for (np = cmd->ncmd.args; np; np = np->narg.next) {
1109 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
1113 switch (np->nfile.type) {
1114 case NTO: s = ">>"+1; dftfd = 1; break;
1115 case NCLOBBER: s = ">|"; dftfd = 1; break;
1116 case NAPPEND: s = ">>"; dftfd = 1; break;
1117 #if BASH_REDIR_OUTPUT
1120 case NTOFD: s = ">&"; dftfd = 1; break;
1121 case NFROM: s = "<"; break;
1122 case NFROMFD: s = "<&"; break;
1123 case NFROMTO: s = "<>"; break;
1124 default: s = "*error*"; break;
1126 if (np->nfile.fd != dftfd)
1127 fprintf(fp, "%d", np->nfile.fd);
1129 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
1130 fprintf(fp, "%d", np->ndup.dupfd);
1132 sharg(np->nfile.fname, fp);
1139 shtree(union node *n, int ind, char *pfx, FILE *fp)
1141 struct nodelist *lp;
1147 indent(ind, pfx, fp);
1149 if (n == NODE_EOF) {
1164 shtree(n->nbinary.ch1, ind, NULL, fp);
1167 shtree(n->nbinary.ch2, ind, NULL, fp);
1175 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
1176 shtree(lp->n, 0, NULL, fp);
1180 if (n->npipe.pipe_backgnd)
1186 fprintf(fp, "<node type %d>", n->type);
1194 showtree(union node *n)
1196 trace_puts("showtree called\n");
1197 shtree(n, 1, NULL, stderr);
1203 /* ============ Parser data */
1206 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1209 struct strlist *next;
1216 struct strpush *prev; /* preceding string on stack */
1218 int prev_left_in_line;
1219 #if ENABLE_ASH_ALIAS
1220 struct alias *ap; /* if push was associated with an alias */
1222 char *string; /* remember the string since it may change */
1224 /* Remember last two characters for pungetc. */
1227 /* Number of outstanding calls to pungetc. */
1232 struct parsefile *prev; /* preceding file on stack */
1233 int linno; /* current line */
1234 int pf_fd; /* file descriptor (or -1 if string) */
1235 int left_in_line; /* number of chars left in this line */
1236 int left_in_buffer; /* number of chars left in this buffer past the line */
1237 char *next_to_pgetc; /* next char in buffer */
1238 char *buf; /* input buffer */
1239 struct strpush *strpush; /* for pushing strings at this level */
1240 struct strpush basestrpush; /* so pushing one is fast */
1242 /* Remember last two characters for pungetc. */
1245 /* Number of outstanding calls to pungetc. */
1249 static struct parsefile basepf; /* top level input file */
1250 static struct parsefile *g_parsefile = &basepf; /* current input file */
1251 static int startlinno; /* line # where last token started */
1252 static char *commandname; /* currently executing command */
1255 /* ============ Message printing */
1258 ash_vmsg(const char *msg, va_list ap)
1260 fprintf(stderr, "%s: ", arg0);
1262 if (strcmp(arg0, commandname))
1263 fprintf(stderr, "%s: ", commandname);
1264 if (!iflag || g_parsefile->pf_fd > 0)
1265 fprintf(stderr, "line %d: ", startlinno);
1267 vfprintf(stderr, msg, ap);
1268 newline_and_flush(stderr);
1272 * Exverror is called to raise the error exception. If the second argument
1273 * is not NULL then error prints an error message using printf style
1274 * formatting. It then raises the error exception.
1276 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1278 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1282 TRACE(("ash_vmsg_and_raise(%d):", cond));
1285 TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
1290 flush_stdout_stderr();
1291 raise_exception(cond);
1295 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1297 ash_msg_and_raise_error(const char *msg, ...)
1304 ash_vmsg_and_raise(EXERROR, msg, ap);
1310 * Use '%m' to append error string on platforms that support it, '%s' and
1311 * strerror() on those that don't.
1313 * 'fmt' must be a string literal.
1315 #ifdef HAVE_PRINTF_PERCENTM
1316 #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": %m", ##__VA_ARGS__)
1318 #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": %s", ##__VA_ARGS__, strerror(errno))
1321 static void raise_error_syntax(const char *) NORETURN;
1323 raise_error_syntax(const char *msg)
1325 ash_msg_and_raise_error("syntax error: %s", msg);
1329 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1331 ash_msg_and_raise(int cond, const char *msg, ...)
1336 ash_vmsg_and_raise(cond, msg, ap);
1342 * error/warning routines for external builtins
1345 ash_msg(const char *fmt, ...)
1355 * Return a string describing an error. The returned string may be a
1356 * pointer to a static buffer that will be overwritten on the next call.
1357 * Action describes the operation that got the error.
1360 errmsg(int e, const char *em)
1362 if (e == ENOENT || e == ENOTDIR) {
1369 /* ============ Memory allocation */
1372 /* I consider these wrappers nearly useless:
1373 * ok, they return you to nearest exception handler, but
1374 * how much memory do you leak in the process, making
1375 * memory starvation worse?
1378 ckrealloc(void * p, size_t nbytes)
1380 p = realloc(p, nbytes);
1382 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1387 ckmalloc(size_t nbytes)
1389 return ckrealloc(NULL, nbytes);
1393 ckzalloc(size_t nbytes)
1395 return memset(ckmalloc(nbytes), 0, nbytes);
1399 ckstrdup(const char *s)
1401 char *p = strdup(s);
1403 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1407 /* Using bbox equivalents. They exit if out of memory */
1408 # define ckrealloc xrealloc
1409 # define ckmalloc xmalloc
1410 # define ckzalloc xzalloc
1411 # define ckstrdup xstrdup
1415 * It appears that grabstackstr() will barf with such alignments
1416 * because stalloc() will return a string allocated in a new stackblock.
1418 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1420 /* Most machines require the value returned from malloc to be aligned
1421 * in some way. The following macro will get this right
1422 * on many machines. */
1423 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1424 /* Minimum size of a block */
1425 MINSIZE = SHELL_ALIGN(504),
1428 struct stack_block {
1429 struct stack_block *prev;
1430 char space[MINSIZE];
1434 struct stack_block *stackp;
1440 struct globals_memstack {
1441 struct stack_block *g_stackp; // = &stackbase;
1442 char *g_stacknxt; // = stackbase.space;
1443 char *sstrend; // = stackbase.space + MINSIZE;
1444 size_t g_stacknleft; // = MINSIZE;
1445 struct stack_block stackbase;
1447 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1448 #define G_memstack (*ash_ptr_to_globals_memstack)
1449 #define g_stackp (G_memstack.g_stackp )
1450 #define g_stacknxt (G_memstack.g_stacknxt )
1451 #define sstrend (G_memstack.sstrend )
1452 #define g_stacknleft (G_memstack.g_stacknleft)
1453 #define stackbase (G_memstack.stackbase )
1454 #define INIT_G_memstack() do { \
1455 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1457 g_stackp = &stackbase; \
1458 g_stacknxt = stackbase.space; \
1459 g_stacknleft = MINSIZE; \
1460 sstrend = stackbase.space + MINSIZE; \
1464 #define stackblock() ((void *)g_stacknxt)
1465 #define stackblocksize() g_stacknleft
1468 * Parse trees for commands are allocated in lifo order, so we use a stack
1469 * to make this more efficient, and also to avoid all sorts of exception
1470 * handling code to handle interrupts in the middle of a parse.
1472 * The size 504 was chosen because the Ultrix malloc handles that size
1476 stalloc(size_t nbytes)
1481 aligned = SHELL_ALIGN(nbytes);
1482 if (aligned > g_stacknleft) {
1485 struct stack_block *sp;
1487 blocksize = aligned;
1488 if (blocksize < MINSIZE)
1489 blocksize = MINSIZE;
1490 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1491 if (len < blocksize)
1492 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1495 sp->prev = g_stackp;
1496 g_stacknxt = sp->space;
1497 g_stacknleft = blocksize;
1498 sstrend = g_stacknxt + blocksize;
1503 g_stacknxt += aligned;
1504 g_stacknleft -= aligned;
1509 stzalloc(size_t nbytes)
1511 return memset(stalloc(nbytes), 0, nbytes);
1518 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1519 write(STDERR_FILENO, "stunalloc\n", 10);
1523 g_stacknleft += g_stacknxt - (char *)p;
1528 * Like strdup but works with the ash stack.
1531 sstrdup(const char *p)
1533 size_t len = strlen(p) + 1;
1534 return memcpy(stalloc(len), p, len);
1538 grabstackblock(size_t len)
1544 pushstackmark(struct stackmark *mark, size_t len)
1546 mark->stackp = g_stackp;
1547 mark->stacknxt = g_stacknxt;
1548 mark->stacknleft = g_stacknleft;
1549 grabstackblock(len);
1553 setstackmark(struct stackmark *mark)
1555 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1559 popstackmark(struct stackmark *mark)
1561 struct stack_block *sp;
1567 while (g_stackp != mark->stackp) {
1569 g_stackp = sp->prev;
1572 g_stacknxt = mark->stacknxt;
1573 g_stacknleft = mark->stacknleft;
1574 sstrend = mark->stacknxt + mark->stacknleft;
1579 * When the parser reads in a string, it wants to stick the string on the
1580 * stack and only adjust the stack pointer when it knows how big the
1581 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1582 * of space on top of the stack and stackblocklen returns the length of
1583 * this block. Growstackblock will grow this space by at least one byte,
1584 * possibly moving it (like realloc). Grabstackblock actually allocates the
1585 * part of the block that has been used.
1588 growstackblock(void)
1592 newlen = g_stacknleft * 2;
1593 if (newlen < g_stacknleft)
1594 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1598 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1599 struct stack_block *sp;
1600 struct stack_block *prevstackp;
1605 prevstackp = sp->prev;
1606 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1607 sp = ckrealloc(sp, grosslen);
1608 sp->prev = prevstackp;
1610 g_stacknxt = sp->space;
1611 g_stacknleft = newlen;
1612 sstrend = sp->space + newlen;
1615 char *oldspace = g_stacknxt;
1616 size_t oldlen = g_stacknleft;
1617 char *p = stalloc(newlen);
1619 /* free the space we just allocated */
1620 g_stacknxt = memcpy(p, oldspace, oldlen);
1621 g_stacknleft += newlen;
1626 * The following routines are somewhat easier to use than the above.
1627 * The user declares a variable of type STACKSTR, which may be declared
1628 * to be a register. The macro STARTSTACKSTR initializes things. Then
1629 * the user uses the macro STPUTC to add characters to the string. In
1630 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1631 * grown as necessary. When the user is done, she can just leave the
1632 * string there and refer to it using stackblock(). Or she can allocate
1633 * the space for it using grabstackstr(). If it is necessary to allow
1634 * someone else to use the stack temporarily and then continue to grow
1635 * the string, the user should use grabstack to allocate the space, and
1636 * then call ungrabstr(p) to return to the previous mode of operation.
1638 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1639 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1640 * is space for at least one character.
1645 size_t len = stackblocksize();
1647 return (char *)stackblock() + len;
1651 * Called from CHECKSTRSPACE.
1654 makestrspace(size_t newlen, char *p)
1656 size_t len = p - g_stacknxt;
1662 size = stackblocksize();
1664 if (nleft >= newlen)
1668 return (char *)stackblock() + len;
1672 stack_nputstr(const char *s, size_t n, char *p)
1674 p = makestrspace(n, p);
1675 p = (char *)mempcpy(p, s, n);
1680 stack_putstr(const char *s, char *p)
1682 return stack_nputstr(s, strlen(s), p);
1686 _STPUTC(int c, char *p)
1694 #define STARTSTACKSTR(p) ((p) = stackblock())
1695 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1696 #define CHECKSTRSPACE(n, p) do { \
1699 size_t m = sstrend - q; \
1701 (p) = makestrspace(l, q); \
1703 #define USTPUTC(c, p) (*(p)++ = (c))
1704 #define STACKSTRNUL(p) do { \
1705 if ((p) == sstrend) \
1706 (p) = growstackstr(); \
1709 #define STUNPUTC(p) (--(p))
1710 #define STTOPC(p) ((p)[-1])
1711 #define STADJUST(amount, p) ((p) += (amount))
1713 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1714 #define ungrabstackstr(s, p) stunalloc(s)
1715 #define stackstrend() ((void *)sstrend)
1718 /* ============ String helpers */
1721 * prefix -- see if pfx is a prefix of string.
1724 prefix(const char *string, const char *pfx)
1727 if (*pfx++ != *string++)
1730 return (char *) string;
1734 * Check for a valid number. This should be elsewhere.
1737 is_number(const char *p)
1742 } while (*++p != '\0');
1747 * Convert a string of digits to an integer, printing an error message on
1751 number(const char *s)
1754 ash_msg_and_raise_error(msg_illnum, s);
1759 * Produce a single quoted string suitable as input to the shell.
1760 * The return string is allocated on the stack.
1763 single_quote(const char *s)
1773 len = strchrnul(s, '\'') - s;
1775 q = p = makestrspace(len + 3, p);
1778 q = (char *)mempcpy(q, s, len);
1787 do len++; while (*++s == '\'');
1789 q = p = makestrspace(len + 3, p);
1792 q = (char *)mempcpy(q, s - len, len);
1800 return stackblock();
1804 * Produce a possibly single quoted string suitable as input to the shell.
1805 * If quoting was done, the return string is allocated on the stack,
1806 * otherwise a pointer to the original string is returned.
1809 maybe_single_quote(const char *s)
1814 /* Assuming ACSII */
1815 /* quote ctrl_chars space !"#$%&'()* */
1819 if (*p >= ';' && *p <= '?')
1828 /* quote {|}~ DEL and high bytes */
1831 /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
1832 /* TODO: maybe avoid quoting % */
1838 return single_quote(s);
1842 /* ============ nextopt */
1844 static char **argptr; /* argument list for builtin commands */
1845 static char *optionarg; /* set by nextopt (like getopt) */
1846 static char *optptr; /* used by nextopt */
1849 * XXX - should get rid of. Have all builtins use getopt(3).
1850 * The library getopt must have the BSD extension static variable
1851 * "optreset", otherwise it can't be used within the shell safely.
1853 * Standard option processing (a la getopt) for builtin routines.
1854 * The only argument that is passed to nextopt is the option string;
1855 * the other arguments are unnecessary. It returns the character,
1856 * or '\0' on end of input.
1859 nextopt(const char *optstring)
1866 if (p == NULL || *p == '\0') {
1867 /* We ate entire "-param", take next one */
1873 if (*++p == '\0') /* just "-" ? */
1876 if (LONE_DASH(p)) /* "--" ? */
1878 /* p => next "-param" */
1880 /* p => some option char in the middle of a "-param" */
1882 for (q = optstring; *q != c;) {
1884 ash_msg_and_raise_error("illegal option -%c", c);
1892 ash_msg_and_raise_error("no arg for -%c option", c);
1902 /* ============ Shell variables */
1905 * The parsefile structure pointed to by the global variable parsefile
1906 * contains information about the current file being read.
1909 int nparam; /* # of positional parameters (without $0) */
1910 #if ENABLE_ASH_GETOPTS
1911 int optind; /* next parameter to be processed by getopts */
1912 int optoff; /* used by getopts */
1914 unsigned char malloced; /* if parameter list dynamically allocated */
1915 char **p; /* parameter list */
1919 * Free the list of positional parameters.
1922 freeparam(volatile struct shparam *param)
1924 if (param->malloced) {
1926 ap = ap1 = param->p;
1933 #if ENABLE_ASH_GETOPTS
1934 static void FAST_FUNC getoptsreset(const char *value);
1938 struct var *next; /* next entry in hash list */
1939 int flags; /* flags are defined above */
1940 const char *var_text; /* name=value */
1941 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1942 /* the variable gets set/unset */
1946 struct localvar *next; /* next local variable in list */
1947 struct var *vp; /* the variable that was made local */
1948 int flags; /* saved flags */
1949 const char *text; /* saved text */
1953 #define VEXPORT 0x01 /* variable is exported */
1954 #define VREADONLY 0x02 /* variable cannot be modified */
1955 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1956 #define VTEXTFIXED 0x08 /* text is statically allocated */
1957 #define VSTACK 0x10 /* text is allocated on the stack */
1958 #define VUNSET 0x20 /* the variable is not set */
1959 #define VNOFUNC 0x40 /* don't call the callback function */
1960 #define VNOSET 0x80 /* do not set variable - just readonly test */
1961 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1962 #if ENABLE_ASH_RANDOM_SUPPORT
1963 # define VDYNAMIC 0x200 /* dynamic variable */
1969 /* Need to be before varinit_data[] */
1970 #if ENABLE_LOCALE_SUPPORT
1971 static void FAST_FUNC
1972 change_lc_all(const char *value)
1974 if (value && *value != '\0')
1975 setlocale(LC_ALL, value);
1977 static void FAST_FUNC
1978 change_lc_ctype(const char *value)
1980 if (value && *value != '\0')
1981 setlocale(LC_CTYPE, value);
1985 static void chkmail(void);
1986 static void changemail(const char *var_value) FAST_FUNC;
1988 # define chkmail() ((void)0)
1990 static void changepath(const char *) FAST_FUNC;
1991 #if ENABLE_ASH_RANDOM_SUPPORT
1992 static void change_random(const char *) FAST_FUNC;
1995 static const struct {
1997 const char *var_text;
1998 void (*var_func)(const char *) FAST_FUNC;
1999 } varinit_data[] = {
2001 * Note: VEXPORT would not work correctly here for NOFORK applets:
2002 * some environment strings may be constant.
2004 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
2006 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
2007 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
2009 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
2010 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
2011 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
2012 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
2013 #if ENABLE_ASH_GETOPTS
2014 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
2016 #if ENABLE_ASH_RANDOM_SUPPORT
2017 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
2019 #if ENABLE_LOCALE_SUPPORT
2020 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
2021 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
2023 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
2024 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
2030 struct globals_var {
2031 struct shparam shellparam; /* $@ current positional parameters */
2032 struct redirtab *redirlist;
2033 int preverrout_fd; /* stderr fd: usually 2, unless redirect moved it */
2034 struct var *vartab[VTABSIZE];
2035 struct var varinit[ARRAY_SIZE(varinit_data)];
2037 extern struct globals_var *const ash_ptr_to_globals_var;
2038 #define G_var (*ash_ptr_to_globals_var)
2039 #define shellparam (G_var.shellparam )
2040 //#define redirlist (G_var.redirlist )
2041 #define preverrout_fd (G_var.preverrout_fd)
2042 #define vartab (G_var.vartab )
2043 #define varinit (G_var.varinit )
2044 #define INIT_G_var() do { \
2046 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
2048 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
2049 varinit[i].flags = varinit_data[i].flags; \
2050 varinit[i].var_text = varinit_data[i].var_text; \
2051 varinit[i].var_func = varinit_data[i].var_func; \
2055 #define vifs varinit[0]
2057 # define vmail (&vifs)[1]
2058 # define vmpath (&vmail)[1]
2059 # define vpath (&vmpath)[1]
2061 # define vpath (&vifs)[1]
2063 #define vps1 (&vpath)[1]
2064 #define vps2 (&vps1)[1]
2065 #define vps4 (&vps2)[1]
2066 #if ENABLE_ASH_GETOPTS
2067 # define voptind (&vps4)[1]
2068 # if ENABLE_ASH_RANDOM_SUPPORT
2069 # define vrandom (&voptind)[1]
2072 # if ENABLE_ASH_RANDOM_SUPPORT
2073 # define vrandom (&vps4)[1]
2078 * The following macros access the values of the above variables.
2079 * They have to skip over the name. They return the null string
2080 * for unset variables.
2082 #define ifsval() (vifs.var_text + 4)
2083 #define ifsset() ((vifs.flags & VUNSET) == 0)
2085 # define mailval() (vmail.var_text + 5)
2086 # define mpathval() (vmpath.var_text + 9)
2087 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2089 #define pathval() (vpath.var_text + 5)
2090 #define ps1val() (vps1.var_text + 4)
2091 #define ps2val() (vps2.var_text + 4)
2092 #define ps4val() (vps4.var_text + 4)
2093 #if ENABLE_ASH_GETOPTS
2094 # define optindval() (voptind.var_text + 7)
2097 #if ENABLE_ASH_GETOPTS
2098 static void FAST_FUNC
2099 getoptsreset(const char *value)
2101 shellparam.optind = number(value) ?: 1;
2102 shellparam.optoff = -1;
2107 * Compares two strings up to the first = or '\0'. The first
2108 * string must be terminated by '='; the second may be terminated by
2109 * either '=' or '\0'.
2112 varcmp(const char *p, const char *q)
2116 while ((c = *p) == (d = *q)) {
2117 if (c == '\0' || c == '=')
2131 * Find the appropriate entry in the hash table from the name.
2133 static struct var **
2134 hashvar(const char *p)
2138 hashval = ((unsigned char) *p) << 4;
2139 while (*p && *p != '=')
2140 hashval += (unsigned char) *p++;
2141 return &vartab[hashval % VTABSIZE];
2145 vpcmp(const void *a, const void *b)
2147 return varcmp(*(const char **)a, *(const char **)b);
2151 * This routine initializes the builtin variables.
2161 * PS1 depends on uid
2163 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2164 vps1.var_text = "PS1=\\w \\$ ";
2167 vps1.var_text = "PS1=# ";
2170 end = vp + ARRAY_SIZE(varinit);
2172 vpp = hashvar(vp->var_text);
2175 } while (++vp < end);
2178 static struct var **
2179 findvar(struct var **vpp, const char *name)
2181 for (; *vpp; vpp = &(*vpp)->next) {
2182 if (varcmp((*vpp)->var_text, name) == 0) {
2190 * Find the value of a variable. Returns NULL if not set.
2192 static const char* FAST_FUNC
2193 lookupvar(const char *name)
2197 v = *findvar(hashvar(name), name);
2199 #if ENABLE_ASH_RANDOM_SUPPORT
2201 * Dynamic variables are implemented roughly the same way they are
2202 * in bash. Namely, they're "special" so long as they aren't unset.
2203 * As soon as they're unset, they're no longer dynamic, and dynamic
2204 * lookup will no longer happen at that point. -- PFM.
2206 if (v->flags & VDYNAMIC)
2209 if (!(v->flags & VUNSET))
2210 return var_end(v->var_text);
2215 #if ENABLE_UNICODE_SUPPORT
2217 reinit_unicode_for_ash(void)
2219 /* Unicode support should be activated even if LANG is set
2220 * _during_ shell execution, not only if it was set when
2221 * shell was started. Therefore, re-check LANG every time:
2223 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2224 || ENABLE_UNICODE_USING_LOCALE
2226 const char *s = lookupvar("LC_ALL");
2227 if (!s) s = lookupvar("LC_CTYPE");
2228 if (!s) s = lookupvar("LANG");
2233 # define reinit_unicode_for_ash() ((void)0)
2237 * Search the environment of a builtin command.
2239 static ALWAYS_INLINE const char *
2240 bltinlookup(const char *name)
2242 return lookupvar(name);
2246 * Same as setvar except that the variable and value are passed in
2247 * the first argument as name=value. Since the first argument will
2248 * be actually stored in the table, it should not be a string that
2250 * Called with interrupts off.
2253 setvareq(char *s, int flags)
2255 struct var *vp, **vpp;
2258 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2259 vpp = findvar(vpp, s);
2262 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2265 if (flags & VNOSAVE)
2269 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2275 if (vp->var_func && !(flags & VNOFUNC))
2276 vp->var_func(var_end(s));
2278 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2279 free((char*)vp->var_text);
2281 if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
2285 if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
2290 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2292 /* variable s is not found */
2295 if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
2297 vp = ckzalloc(sizeof(*vp));
2299 /*vp->func = NULL; - ckzalloc did it */
2302 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2312 * Set the value of a variable. The flags argument is ored with the
2313 * flags of the variable. If val is NULL, the variable is unset.
2316 setvar(const char *name, const char *val, int flags)
2325 q = endofname(name);
2326 p = strchrnul(q, '=');
2328 if (!namelen || p != q)
2329 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2334 vallen = strlen(val);
2338 nameeq = ckmalloc(namelen + vallen + 2);
2339 p = mempcpy(nameeq, name, namelen);
2342 p = mempcpy(p, val, vallen);
2345 vp = setvareq(nameeq, flags | VNOSAVE);
2351 static void FAST_FUNC
2352 setvar0(const char *name, const char *val)
2354 setvar(name, val, 0);
2358 * Unset the specified variable.
2361 unsetvar(const char *s)
2367 * Process a linked list of variable assignments.
2370 listsetvar(struct strlist *list_set_var, int flags)
2372 struct strlist *lp = list_set_var;
2378 setvareq(lp->text, flags);
2385 * Generate a list of variables satisfying the given conditions.
2388 listvars(int on, int off, char ***end)
2399 for (vp = *vpp; vp; vp = vp->next) {
2400 if ((vp->flags & mask) == on) {
2401 if (ep == stackstrend())
2402 ep = growstackstr();
2403 *ep++ = (char*)vp->var_text;
2406 } while (++vpp < vartab + VTABSIZE);
2407 if (ep == stackstrend())
2408 ep = growstackstr();
2412 return grabstackstr(ep);
2416 /* ============ Path search helper
2418 * The variable path (passed by reference) should be set to the start
2419 * of the path before the first call; path_advance will update
2420 * this value as it proceeds. Successive calls to path_advance will return
2421 * the possible path expansions in sequence. If an option (indicated by
2422 * a percent sign) appears in the path entry then the global variable
2423 * pathopt will be set to point to it; otherwise pathopt will be set to
2426 static const char *pathopt; /* set by path_advance */
2429 path_advance(const char **path, const char *name)
2439 for (p = start; *p && *p != ':' && *p != '%'; p++)
2441 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2442 while (stackblocksize() < len)
2446 q = mempcpy(q, start, p - start);
2453 while (*p && *p != ':')
2460 return stalloc(len);
2464 /* ============ Prompt */
2466 static smallint doprompt; /* if set, prompt the user */
2467 static smallint needprompt; /* true if interactive and at start of line */
2469 #if ENABLE_FEATURE_EDITING
2470 static line_input_t *line_input_state;
2471 static const char *cmdedit_prompt;
2473 putprompt(const char *s)
2475 if (ENABLE_ASH_EXPAND_PRMT) {
2476 free((char*)cmdedit_prompt);
2477 cmdedit_prompt = ckstrdup(s);
2484 putprompt(const char *s)
2490 /* expandstr() needs parsing machinery, so it is far away ahead... */
2491 static const char *expandstr(const char *ps, int syntax_type);
2492 /* Values for syntax param */
2493 #define BASESYNTAX 0 /* not in quotes */
2494 #define DQSYNTAX 1 /* in double quotes */
2495 #define SQSYNTAX 2 /* in single quotes */
2496 #define ARISYNTAX 3 /* in arithmetic */
2497 #if ENABLE_ASH_EXPAND_PRMT
2498 # define PSSYNTAX 4 /* prompt. never passed to SIT() */
2500 /* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
2503 * called by editline -- any expansions to the prompt should be added here.
2506 setprompt_if(smallint do_set, int whichprompt)
2509 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2516 switch (whichprompt) {
2526 #if ENABLE_ASH_EXPAND_PRMT
2527 pushstackmark(&smark, stackblocksize());
2528 putprompt(expandstr(prompt, PSSYNTAX));
2529 popstackmark(&smark);
2536 /* ============ The cd and pwd commands */
2538 #define CD_PHYSICAL 1
2548 while ((i = nextopt("LP")) != '\0') {
2550 flags ^= CD_PHYSICAL;
2559 * Update curdir (the name of the current directory) in response to a
2563 updatepwd(const char *dir)
2570 cdcomppath = sstrdup(dir);
2573 if (curdir == nullstr)
2575 new = stack_putstr(curdir, new);
2577 new = makestrspace(strlen(dir) + 2, new);
2578 lim = (char *)stackblock() + 1;
2582 if (new > lim && *lim == '/')
2587 if (dir[1] == '/' && dir[2] != '/') {
2593 p = strtok(cdcomppath, "/");
2597 if (p[1] == '.' && p[2] == '\0') {
2609 new = stack_putstr(p, new);
2612 p = strtok(NULL, "/");
2617 return stackblock();
2621 * Find out what the current directory is. If we already know the current
2622 * directory, this routine returns immediately.
2627 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2628 return dir ? dir : nullstr;
2632 setpwd(const char *val, int setold)
2636 oldcur = dir = curdir;
2639 setvar("OLDPWD", oldcur, VEXPORT);
2642 if (physdir != nullstr) {
2643 if (physdir != oldcur)
2647 if (oldcur == val || !val) {
2653 dir = ckstrdup(val);
2654 if (oldcur != dir && oldcur != nullstr) {
2659 setvar("PWD", dir, VEXPORT);
2662 static void hashcd(void);
2665 * Actually do the chdir. We also call hashcd to let other routines
2666 * know that the current directory has changed.
2669 docd(const char *dest, int flags)
2671 const char *dir = NULL;
2674 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2677 if (!(flags & CD_PHYSICAL)) {
2678 dir = updatepwd(dest);
2692 static int FAST_FUNC
2693 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2705 dest = bltinlookup("HOME");
2706 else if (LONE_DASH(dest)) {
2707 dest = bltinlookup("OLDPWD");
2729 path = bltinlookup("CDPATH");
2732 p = path_advance(&path, dest);
2733 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2737 if (!docd(p, flags))
2748 ash_msg_and_raise_error("can't cd to %s", dest);
2751 if (flags & CD_PRINT)
2752 out1fmt("%s\n", curdir);
2756 static int FAST_FUNC
2757 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2760 const char *dir = curdir;
2764 if (physdir == nullstr)
2768 out1fmt("%s\n", dir);
2773 /* ============ ... */
2776 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2778 /* Syntax classes */
2779 #define CWORD 0 /* character is nothing special */
2780 #define CNL 1 /* newline character */
2781 #define CBACK 2 /* a backslash character */
2782 #define CSQUOTE 3 /* single quote */
2783 #define CDQUOTE 4 /* double quote */
2784 #define CENDQUOTE 5 /* a terminating quote */
2785 #define CBQUOTE 6 /* backwards single quote */
2786 #define CVAR 7 /* a dollar sign */
2787 #define CENDVAR 8 /* a '}' character */
2788 #define CLP 9 /* a left paren in arithmetic */
2789 #define CRP 10 /* a right paren in arithmetic */
2790 #define CENDFILE 11 /* end of file */
2791 #define CCTL 12 /* like CWORD, except it must be escaped */
2792 #define CSPCL 13 /* these terminate a word */
2793 #define CIGN 14 /* character should be ignored */
2796 #if ENABLE_ASH_ALIAS
2800 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2802 #if ENABLE_FEATURE_SH_MATH
2803 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2805 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2807 static const uint16_t S_I_T[] ALIGN2 = {
2808 #if ENABLE_ASH_ALIAS
2809 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2811 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2812 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2813 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2814 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2815 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2816 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2817 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2818 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2819 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2820 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2821 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2822 #if !USE_SIT_FUNCTION
2823 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2824 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2825 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2829 /* Constants below must match table above */
2831 #if ENABLE_ASH_ALIAS
2832 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2834 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2835 CNL_CNL_CNL_CNL , /* 2 */
2836 CWORD_CCTL_CCTL_CWORD , /* 3 */
2837 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2838 CVAR_CVAR_CWORD_CVAR , /* 5 */
2839 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2840 CSPCL_CWORD_CWORD_CLP , /* 7 */
2841 CSPCL_CWORD_CWORD_CRP , /* 8 */
2842 CBACK_CBACK_CCTL_CBACK , /* 9 */
2843 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2844 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2845 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2846 CWORD_CWORD_CWORD_CWORD , /* 13 */
2847 CCTL_CCTL_CCTL_CCTL , /* 14 */
2850 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2851 * caller must ensure proper cast on it if c is *char_ptr!
2853 #if USE_SIT_FUNCTION
2856 SIT(int c, int syntax)
2858 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2859 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2861 * This causes '/' to be prepended with CTLESC in dquoted string,
2862 * making "./file"* treated incorrectly because we feed
2863 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2864 * The "homegrown" glob implementation is okay with that,
2865 * but glibc one isn't. With '/' always treated as CWORD,
2868 # if ENABLE_ASH_ALIAS
2869 static const uint8_t syntax_index_table[] ALIGN1 = {
2870 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2871 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2872 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2876 static const uint8_t syntax_index_table[] ALIGN1 = {
2877 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2878 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2879 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2888 # if ENABLE_ASH_ALIAS
2894 /* Cast is purely for paranoia here,
2895 * just in case someone passed signed char to us */
2896 if ((unsigned char)c >= CTL_FIRST
2897 && (unsigned char)c <= CTL_LAST
2901 s = strchrnul(spec_symbls, c);
2904 indx = syntax_index_table[s - spec_symbls];
2906 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2909 #else /* !USE_SIT_FUNCTION */
2911 static const uint8_t syntax_index_table[] ALIGN1 = {
2912 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2913 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2923 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2924 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2945 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2946 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2947 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2948 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2950 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2952 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2953 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2954 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2955 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2956 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2958 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2959 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2960 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2961 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2973 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2974 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2975 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2976 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2977 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2978 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2993 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
3004 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
3005 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
3006 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
3007 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
3008 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
3009 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
3010 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
3011 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
3012 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
3013 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
3014 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
3015 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
3016 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
3017 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
3018 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
3019 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
3020 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
3021 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
3022 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
3023 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
3024 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
3025 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3026 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3027 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3028 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3029 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3030 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3031 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3032 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3033 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3034 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3035 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3036 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3037 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3038 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3039 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3040 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3041 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
3042 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
3044 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
3045 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
3046 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
3047 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
3048 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3049 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3050 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3051 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3113 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3114 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3115 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3116 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3117 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3118 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3119 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3120 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3121 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3122 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3123 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3124 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3125 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3126 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3127 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3128 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3129 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3130 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3131 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3132 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3133 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3134 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3135 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3136 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3137 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3138 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3139 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3140 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3141 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3142 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3143 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3144 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3145 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3146 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3147 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3148 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3149 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3150 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3151 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3152 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3153 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3154 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3155 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3156 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3157 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3158 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3159 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3160 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3161 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3162 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3163 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3164 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3165 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3166 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3167 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3168 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3169 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3170 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3171 # if ENABLE_ASH_ALIAS
3172 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3177 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3178 #else /* debug version, caught one signed char bug */
3179 # define SIT(c, syntax) \
3181 if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
3182 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3183 if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
3184 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3185 ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
3189 #endif /* !USE_SIT_FUNCTION */
3192 /* ============ Alias handling */
3194 #if ENABLE_ASH_ALIAS
3196 #define ALIASINUSE 1
3207 static struct alias **atab; // [ATABSIZE];
3208 #define INIT_G_alias() do { \
3209 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3213 static struct alias **
3214 __lookupalias(const char *name)
3216 unsigned int hashval;
3223 ch = (unsigned char)*p;
3227 ch = (unsigned char)*++p;
3229 app = &atab[hashval % ATABSIZE];
3231 for (; *app; app = &(*app)->next) {
3232 if (strcmp(name, (*app)->name) == 0) {
3240 static struct alias *
3241 lookupalias(const char *name, int check)
3243 struct alias *ap = *__lookupalias(name);
3245 if (check && ap && (ap->flag & ALIASINUSE))
3250 static struct alias *
3251 freealias(struct alias *ap)
3255 if (ap->flag & ALIASINUSE) {
3256 ap->flag |= ALIASDEAD;
3268 setalias(const char *name, const char *val)
3270 struct alias *ap, **app;
3272 app = __lookupalias(name);
3276 if (!(ap->flag & ALIASINUSE)) {
3279 ap->val = ckstrdup(val);
3280 ap->flag &= ~ALIASDEAD;
3283 ap = ckzalloc(sizeof(struct alias));
3284 ap->name = ckstrdup(name);
3285 ap->val = ckstrdup(val);
3286 /*ap->flag = 0; - ckzalloc did it */
3287 /*ap->next = NULL;*/
3294 unalias(const char *name)
3298 app = __lookupalias(name);
3302 *app = freealias(*app);
3313 struct alias *ap, **app;
3317 for (i = 0; i < ATABSIZE; i++) {
3319 for (ap = *app; ap; ap = *app) {
3320 *app = freealias(*app);
3330 printalias(const struct alias *ap)
3332 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3336 * TODO - sort output
3338 static int FAST_FUNC
3339 aliascmd(int argc UNUSED_PARAM, char **argv)
3348 for (i = 0; i < ATABSIZE; i++) {
3349 for (ap = atab[i]; ap; ap = ap->next) {
3355 while ((n = *++argv) != NULL) {
3356 v = strchr(n+1, '=');
3357 if (v == NULL) { /* n+1: funny ksh stuff */
3358 ap = *__lookupalias(n);
3360 fprintf(stderr, "%s: %s not found\n", "alias", n);
3373 static int FAST_FUNC
3374 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3378 while (nextopt("a") != '\0') {
3382 for (i = 0; *argptr; argptr++) {
3383 if (unalias(*argptr)) {
3384 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3392 #endif /* ASH_ALIAS */
3395 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3398 #define FORK_NOJOB 2
3400 /* mode flags for showjob(s) */
3401 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3402 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3403 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3404 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3407 * A job structure contains information about a job. A job is either a
3408 * single process or a set of processes contained in a pipeline. In the
3409 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3413 pid_t ps_pid; /* process id */
3414 int ps_status; /* last process status from wait() */
3415 char *ps_cmd; /* text of command being run */
3419 struct procstat ps0; /* status of process */
3420 struct procstat *ps; /* status or processes when more than one */
3422 int stopstatus; /* status of a stopped job */
3424 unsigned nprocs; /* number of processes */
3426 #define JOBRUNNING 0 /* at least one proc running */
3427 #define JOBSTOPPED 1 /* all procs are stopped */
3428 #define JOBDONE 2 /* all procs are completed */
3432 sigint: 1, /* job was killed by SIGINT */
3433 jobctl: 1, /* job running under job control */
3435 waited: 1, /* true if this entry has been waited for */
3436 used: 1, /* true if this entry is in used */
3437 changed: 1; /* true if status has changed */
3438 struct job *prev_job; /* previous job */
3441 static struct job *makejob(/*union node *,*/ int);
3442 static int forkshell(struct job *, union node *, int);
3443 static int waitforjob(struct job *);
3446 enum { doing_jobctl = 0 };
3447 #define setjobctl(on) do {} while (0)
3449 static smallint doing_jobctl; //references:8
3450 static void setjobctl(int);
3457 ignoresig(int signo)
3459 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3460 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3461 /* No, need to do it */
3462 signal(signo, SIG_IGN);
3464 sigmode[signo - 1] = S_HARD_IGN;
3468 * Only one usage site - in setsignal()
3471 signal_handler(int signo)
3473 if (signo == SIGCHLD) {
3479 gotsig[signo - 1] = 1;
3480 pending_sig = signo;
3482 if (signo == SIGINT && !trap[SIGINT]) {
3483 if (!suppress_int) {
3485 raise_interrupt(); /* does not return */
3492 * Set the signal handler for the specified signal. The routine figures
3493 * out what it should be set to.
3496 setsignal(int signo)
3499 char cur_act, new_act;
3500 struct sigaction act;
3504 if (t != NULL) { /* trap for this sig is set */
3506 if (t[0] == '\0') /* trap is "": ignore this sig */
3510 if (rootshell && new_act == S_DFL) {
3513 if (iflag || minusc || sflag == 0)
3522 * "In all cases, bash ignores SIGQUIT. Non-builtin
3523 * commands run by bash have signal handlers
3524 * set to the values inherited by the shell
3525 * from its parent". */
3541 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3542 //whereas we have to restore it to what shell got on entry
3543 //from the parent. See comment above
3545 if (signo == SIGCHLD)
3548 t = &sigmode[signo - 1];
3551 /* current setting is not yet known */
3552 if (sigaction(signo, NULL, &act)) {
3553 /* pretend it worked; maybe we should give a warning,
3554 * but other shells don't. We don't alter sigmode,
3555 * so we retry every time.
3556 * btw, in Linux it never fails. --vda */
3559 if (act.sa_handler == SIG_IGN) {
3560 cur_act = S_HARD_IGN;
3562 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3564 cur_act = S_IGN; /* don't hard ignore these */
3568 if (cur_act == S_HARD_IGN || cur_act == new_act)
3571 act.sa_handler = SIG_DFL;
3574 act.sa_handler = signal_handler;
3577 act.sa_handler = SIG_IGN;
3581 /* flags and mask matter only if !DFL and !IGN, but we do it
3582 * for all cases for more deterministic behavior:
3585 sigfillset(&act.sa_mask);
3587 sigaction_set(signo, &act);
3592 /* mode flags for set_curjob */
3593 #define CUR_DELETE 2
3594 #define CUR_RUNNING 1
3595 #define CUR_STOPPED 0
3598 /* pgrp of shell on invocation */
3599 static int initialpgrp; //references:2
3600 static int ttyfd = -1; //5
3603 static struct job *jobtab; //5
3605 static unsigned njobs; //4
3607 static struct job *curjob; //lots
3608 /* number of presumed living untracked jobs */
3609 static int jobless; //4
3612 /* Bash has a feature: it restores termios after a successful wait for
3613 * a foreground job which had at least one stopped or sigkilled member.
3614 * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
3615 * properly restoring tty state. Should we do this too?
3616 * A reproducer: ^Z an interactive python:
3619 * Python 2.7.12 (...)
3621 * { python leaves tty in -icanon -echo state. We do survive that... }
3622 * [1]+ Stopped python
3623 * { ...however, next program (python #2) does not survive it well: }
3625 * Python 2.7.12 (...)
3626 * >>> Traceback (most recent call last):
3627 * { above, I typed "qwerty<CR>", but -echo state is still in effect }
3628 * File "<stdin>", line 1, in <module>
3629 * NameError: name 'qwerty' is not defined
3631 * The implementation below is modeled on bash code and seems to work.
3632 * However, I'm not sure we should do this. For one: what if I'd fg
3633 * the stopped python instead? It'll be confused by "restored" tty state.
3635 static struct termios shell_tty_info;
3639 if (rootshell && ttyfd >= 0)
3640 tcgetattr(ttyfd, &shell_tty_info);
3645 /* if (rootshell) - caller ensures this */
3647 tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
3650 job_signal_status(struct job *jp)
3654 struct procstat *ps = jp->ps;
3655 for (i = 0; i < jp->nprocs; i++) {
3656 status = ps[i].ps_status;
3657 if (WIFSIGNALED(status) || WIFSTOPPED(status))
3663 restore_tty_if_stopped_or_signaled(struct job *jp)
3665 //TODO: check what happens if we come from waitforjob() in expbackq()
3667 int s = job_signal_status(jp);
3668 if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
3673 # define get_tty_state() ((void)0)
3674 # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
3678 set_curjob(struct job *jp, unsigned mode)
3681 struct job **jpp, **curp;
3683 /* first remove from list */
3684 jpp = curp = &curjob;
3689 jpp = &jp1->prev_job;
3691 *jpp = jp1->prev_job;
3693 /* Then re-insert in correct position */
3701 /* job being deleted */
3704 /* newly created job or backgrounded job,
3705 * put after all stopped jobs.
3710 if (!jp1 || jp1->state != JOBSTOPPED)
3713 jpp = &jp1->prev_job;
3719 /* newly stopped job - becomes curjob */
3720 jp->prev_job = *jpp;
3728 jobno(const struct job *jp)
3730 return jp - jobtab + 1;
3735 * Convert a job name to a job structure.
3738 #define getjob(name, getctl) getjob(name)
3741 getjob(const char *name, int getctl)
3745 const char *err_msg = "%s: no such job";
3749 char *(*match)(const char *, const char *);
3764 if (c == '+' || c == '%') {
3766 err_msg = "No current job";
3772 err_msg = "No previous job";
3782 if (num > 0 && num <= njobs) {
3783 jp = jobtab + num - 1;
3798 if (match(jp->ps[0].ps_cmd, p)) {
3802 err_msg = "%s: ambiguous";
3812 err_msg = "job %s not created under job control";
3813 if (getctl && jp->jobctl == 0)
3818 ash_msg_and_raise_error(err_msg, name);
3822 * Mark a job structure as unused.
3825 freejob(struct job *jp)
3827 struct procstat *ps;
3831 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3832 if (ps->ps_cmd != nullstr)
3835 if (jp->ps != &jp->ps0)
3838 set_curjob(jp, CUR_DELETE);
3844 xtcsetpgrp(int fd, pid_t pgrp)
3846 if (tcsetpgrp(fd, pgrp))
3847 ash_msg_and_raise_perror("can't set tty process group");
3851 * Turn job control on and off.
3853 * Note: This code assumes that the third arg to ioctl is a character
3854 * pointer, which is true on Berkeley systems but not System V. Since
3855 * System V doesn't have job control yet, this isn't a problem now.
3857 * Called with interrupts off.
3865 if (on == doing_jobctl || rootshell == 0)
3869 ofd = fd = open(_PATH_TTY, O_RDWR);
3871 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3872 * That sometimes helps to acquire controlling tty.
3873 * Obviously, a workaround for bugs when someone
3874 * failed to provide a controlling tty to bash! :) */
3880 /* fd is a tty at this point */
3881 fd = fcntl(fd, F_DUPFD, 10);
3882 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
3885 goto out; /* F_DUPFD failed */
3886 close_on_exec_on(fd);
3887 while (1) { /* while we are in the background */
3888 pgrp = tcgetpgrp(fd);
3891 ash_msg("can't access tty; job control turned off");
3895 if (pgrp == getpgrp())
3906 xtcsetpgrp(fd, pgrp);
3908 /* turning job control off */
3911 /* was xtcsetpgrp, but this can make exiting ash
3912 * loop forever if pty is already deleted */
3913 tcsetpgrp(fd, pgrp);
3927 static int FAST_FUNC
3928 killcmd(int argc, char **argv)
3930 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3933 if (argv[i][0] == '%') {
3935 * "kill %N" - job kill
3936 * Converting to pgrp / pid kill
3942 jp = getjob(argv[i], 0);
3944 * In jobs started under job control, we signal
3945 * entire process group by kill -PGRP_ID.
3946 * This happens, f.e., in interactive shell.
3948 * Otherwise, we signal each child via
3949 * kill PID1 PID2 PID3.
3951 * sh -c 'sleep 1|sleep 1 & kill %1'
3952 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3953 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3955 n = jp->nprocs; /* can't be 0 (I hope) */
3958 dst = alloca(n * sizeof(int)*4);
3960 for (j = 0; j < n; j++) {
3961 struct procstat *ps = &jp->ps[j];
3962 /* Skip non-running and not-stopped members
3963 * (i.e. dead members) of the job
3965 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3968 * kill_main has matching code to expect
3969 * leading space. Needed to not confuse
3970 * negative pids with "kill -SIGNAL_NO" syntax
3972 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3976 } while (argv[++i]);
3978 return kill_main(argc, argv);
3982 showpipe(struct job *jp /*, FILE *out*/)
3984 struct procstat *ps;
3985 struct procstat *psend;
3987 psend = jp->ps + jp->nprocs;
3988 for (ps = jp->ps + 1; ps < psend; ps++)
3989 printf(" | %s", ps->ps_cmd);
3990 newline_and_flush(stdout);
3991 flush_stdout_stderr();
3996 restartjob(struct job *jp, int mode)
3998 struct procstat *ps;
4004 if (jp->state == JOBDONE)
4006 jp->state = JOBRUNNING;
4007 pgid = jp->ps[0].ps_pid;
4008 if (mode == FORK_FG) {
4010 xtcsetpgrp(ttyfd, pgid);
4012 killpg(pgid, SIGCONT);
4016 if (WIFSTOPPED(ps->ps_status)) {
4022 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
4027 static int FAST_FUNC
4028 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
4034 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
4038 jp = getjob(*argv, 1);
4039 if (mode == FORK_BG) {
4040 set_curjob(jp, CUR_RUNNING);
4041 printf("[%d] ", jobno(jp));
4043 out1str(jp->ps[0].ps_cmd);
4044 showpipe(jp /*, stdout*/);
4045 retval = restartjob(jp, mode);
4046 } while (*argv && *++argv);
4052 sprint_status48(char *s, int status, int sigonly)
4058 if (!WIFEXITED(status)) {
4060 if (WIFSTOPPED(status))
4061 st = WSTOPSIG(status);
4064 st = WTERMSIG(status);
4066 if (st == SIGINT || st == SIGPIPE)
4069 if (WIFSTOPPED(status))
4074 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
4075 col = fmtstr(s, 32, strsignal(st));
4076 if (WCOREDUMP(status)) {
4077 strcpy(s + col, " (core dumped)");
4078 col += sizeof(" (core dumped)")-1;
4080 } else if (!sigonly) {
4081 st = WEXITSTATUS(status);
4082 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
4089 wait_block_or_sig(int *status)
4096 /* Poll all children for changes in their state */
4098 /* if job control is active, accept stopped processes too */
4099 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
4101 break; /* Error (e.g. EINTR, ECHILD) or pid */
4103 /* Children exist, but none are ready. Sleep until interesting signal */
4106 sigprocmask(SIG_SETMASK, &mask, &mask);
4107 while (!got_sigchld && !pending_sig)
4109 sigprocmask(SIG_SETMASK, &mask, NULL);
4110 #else /* unsafe: a signal can set pending_sig after check, but before pause() */
4111 while (!got_sigchld && !pending_sig)
4115 /* If it was SIGCHLD, poll children again */
4116 } while (got_sigchld);
4121 #define DOWAIT_NONBLOCK 0
4122 #define DOWAIT_BLOCK 1
4123 #define DOWAIT_BLOCK_OR_SIG 2
4126 dowait(int block, struct job *job)
4131 struct job *thisjob = NULL;
4133 TRACE(("dowait(0x%x) called\n", block));
4135 /* It's wrong to call waitpid() outside of INT_OFF region:
4136 * signal can arrive just after syscall return and handler can
4137 * longjmp away, losing stop/exit notification processing.
4138 * Thus, for "jobs" builtin, and for waiting for a fg job,
4139 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
4141 * However, for "wait" builtin it is wrong to simply call waitpid()
4142 * in INT_OFF region: "wait" needs to wait for any running job
4143 * to change state, but should exit on any trap too.
4144 * In INT_OFF region, a signal just before syscall entry can set
4145 * pending_sig variables, but we can't check them, and we would
4146 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
4148 * Because of this, we run inside INT_OFF, but use a special routine
4149 * which combines waitpid() and sigsuspend().
4150 * This is the reason why we need to have a handler for SIGCHLD:
4151 * SIG_DFL handler does not wake sigsuspend().
4154 if (block == DOWAIT_BLOCK_OR_SIG) {
4155 pid = wait_block_or_sig(&status);
4158 if (block == DOWAIT_NONBLOCK)
4159 wait_flags = WNOHANG;
4160 /* if job control is active, accept stopped processes too */
4162 wait_flags |= WUNTRACED;
4163 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4164 pid = waitpid(-1, &status, wait_flags);
4166 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4167 pid, status, errno, strerror(errno)));
4172 for (jp = curjob; jp; jp = jp->prev_job) {
4174 struct procstat *ps;
4175 struct procstat *psend;
4176 if (jp->state == JOBDONE)
4180 psend = ps + jp->nprocs;
4182 if (ps->ps_pid == pid) {
4183 TRACE(("Job %d: changing status of proc %d "
4184 "from 0x%x to 0x%x\n",
4185 jobno(jp), pid, ps->ps_status, status));
4186 ps->ps_status = status;
4189 if (ps->ps_status == -1)
4190 jobstate = JOBRUNNING;
4192 if (jobstate == JOBRUNNING)
4194 if (WIFSTOPPED(ps->ps_status)) {
4195 jp->stopstatus = ps->ps_status;
4196 jobstate = JOBSTOPPED;
4199 } while (++ps < psend);
4203 /* Found the job where one of its processes changed its state.
4204 * Is there at least one live and running process in this job? */
4205 if (jobstate != JOBRUNNING) {
4206 /* No. All live processes in the job are stopped
4207 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4209 thisjob->changed = 1;
4210 if (thisjob->state != jobstate) {
4211 TRACE(("Job %d: changing state from %d to %d\n",
4212 jobno(thisjob), thisjob->state, jobstate));
4213 thisjob->state = jobstate;
4215 if (jobstate == JOBSTOPPED)
4216 set_curjob(thisjob, CUR_STOPPED);
4222 /* The process wasn't found in job list */
4224 if (!WIFSTOPPED(status))
4230 if (thisjob && thisjob == job) {
4234 len = sprint_status48(s, status, 1);
4246 showjob(struct job *jp, int mode)
4248 struct procstat *ps;
4249 struct procstat *psend;
4252 char s[16 + 16 + 48];
4253 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4257 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4258 /* just output process (group) id of pipeline */
4259 fprintf(out, "%d\n", ps->ps_pid);
4263 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4268 else if (curjob && jp == curjob->prev_job)
4271 if (mode & SHOW_PIDS)
4272 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4274 psend = ps + jp->nprocs;
4276 if (jp->state == JOBRUNNING) {
4277 strcpy(s + col, "Running");
4278 col += sizeof("Running") - 1;
4280 int status = psend[-1].ps_status;
4281 if (jp->state == JOBSTOPPED)
4282 status = jp->stopstatus;
4283 col += sprint_status48(s + col, status, 0);
4285 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4287 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4288 * or prints several "PID | <cmdN>" lines,
4289 * depending on SHOW_PIDS bit.
4290 * We do not print status of individual processes
4291 * between PID and <cmdN>. bash does it, but not very well:
4292 * first line shows overall job status, not process status,
4293 * making it impossible to know 1st process status.
4297 /* for each process */
4300 if (mode & SHOW_PIDS)
4301 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4303 fprintf(out, "%s%*c%s%s",
4305 33 - col >= 0 ? 33 - col : 0, ' ',
4306 ps == jp->ps ? "" : "| ",
4309 } while (++ps != psend);
4310 newline_and_flush(out);
4314 if (jp->state == JOBDONE) {
4315 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4321 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4322 * statuses have changed since the last call to showjobs.
4329 TRACE(("showjobs(0x%x) called\n", mode));
4331 /* Handle all finished jobs */
4332 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4335 for (jp = curjob; jp; jp = jp->prev_job) {
4336 if (!(mode & SHOW_CHANGED) || jp->changed) {
4342 static int FAST_FUNC
4343 jobscmd(int argc UNUSED_PARAM, char **argv)
4348 while ((m = nextopt("lp")) != '\0') {
4352 mode |= SHOW_ONLY_PGID;
4358 showjob(getjob(*argv, 0), mode);
4368 /* Called only on finished or stopped jobs (no members are running) */
4370 getstatus(struct job *job)
4374 struct procstat *ps;
4376 /* Fetch last member's status */
4377 ps = job->ps + job->nprocs - 1;
4378 status = ps->ps_status;
4380 /* "set -o pipefail" mode: use last _nonzero_ status */
4381 while (status == 0 && --ps >= job->ps)
4382 status = ps->ps_status;
4385 retval = WEXITSTATUS(status);
4386 if (!WIFEXITED(status)) {
4388 retval = WSTOPSIG(status);
4389 if (!WIFSTOPPED(status))
4392 /* XXX: limits number of signals */
4393 retval = WTERMSIG(status);
4395 if (retval == SIGINT)
4401 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4402 jobno(job), job->nprocs, status, retval));
4406 static int FAST_FUNC
4407 waitcmd(int argc UNUSED_PARAM, char **argv)
4418 /* wait for all jobs */
4422 if (!jp) /* no running procs */
4424 if (jp->state == JOBRUNNING)
4430 * "When bash is waiting for an asynchronous command via
4431 * the wait builtin, the reception of a signal for which a trap
4432 * has been set will cause the wait builtin to return immediately
4433 * with an exit status greater than 128, immediately after which
4434 * the trap is executed."
4436 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4437 /* if child sends us a signal *and immediately exits*,
4438 * dowait() returns pid > 0. Check this case,
4439 * not "if (dowait() < 0)"!
4448 if (**argv != '%') {
4449 pid_t pid = number(*argv);
4454 if (job->ps[job->nprocs - 1].ps_pid == pid)
4456 job = job->prev_job;
4459 job = getjob(*argv, 0);
4461 /* loop until process terminated or stopped */
4462 while (job->state == JOBRUNNING) {
4463 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4468 retval = getstatus(job);
4475 retval = 128 + pending_sig;
4484 struct job *jp, *jq;
4486 len = njobs * sizeof(*jp);
4488 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4490 offset = (char *)jp - (char *)jq;
4492 /* Relocate pointers */
4495 jq = (struct job *)((char *)jq + l);
4499 #define joff(p) ((struct job *)((char *)(p) + l))
4500 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4501 if (joff(jp)->ps == &jq->ps0)
4502 jmove(joff(jp)->ps);
4503 if (joff(jp)->prev_job)
4504 jmove(joff(jp)->prev_job);
4514 jp = (struct job *)((char *)jp + len);
4518 } while (--jq >= jp);
4523 * Return a new job structure.
4524 * Called with interrupts off.
4527 makejob(/*union node *node,*/ int nprocs)
4532 for (i = njobs, jp = jobtab; ; jp++) {
4539 if (jp->state != JOBDONE || !jp->waited)
4548 memset(jp, 0, sizeof(*jp));
4550 /* jp->jobctl is a bitfield.
4551 * "jp->jobctl |= doing_jobctl" likely to give awful code */
4555 jp->prev_job = curjob;
4560 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4562 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4569 * Return a string identifying a command (to be printed by the
4572 static char *cmdnextc;
4575 cmdputs(const char *s)
4577 static const char vstype[VSTYPE + 1][3] = {
4578 "", "}", "-", "+", "?", "=",
4579 "%", "%%", "#", "##"
4580 IF_BASH_SUBSTR(, ":")
4581 IF_BASH_PATTERN_SUBST(, "/", "//")
4584 const char *p, *str;
4588 unsigned char subtype = 0;
4592 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4594 while ((c = *p++) != '\0') {
4602 if ((subtype & VSTYPE) == VSLENGTH)
4608 str = "\"}" + !(quoted & 1);
4615 #if ENABLE_FEATURE_SH_MATH
4630 if ((subtype & VSTYPE) != VSNORMAL)
4632 str = vstype[subtype & VSTYPE];
4633 if (subtype & VSNUL)
4642 /* These can only happen inside quotes */
4655 while ((c = *str++) != '\0') {
4658 } /* while *p++ not NUL */
4661 USTPUTC('"', nextc);
4667 /* cmdtxt() and cmdlist() call each other */
4668 static void cmdtxt(union node *n);
4671 cmdlist(union node *np, int sep)
4673 for (; np; np = np->narg.next) {
4677 if (sep && np->narg.next)
4683 cmdtxt(union node *n)
4686 struct nodelist *lp;
4697 lp = n->npipe.cmdlist;
4715 cmdtxt(n->nbinary.ch1);
4731 cmdtxt(n->nif.test);
4733 if (n->nif.elsepart) {
4734 cmdtxt(n->nif.ifpart);
4736 n = n->nif.elsepart;
4754 cmdtxt(n->nbinary.ch1);
4764 cmdputs(n->nfor.var);
4766 cmdlist(n->nfor.args, 1);
4771 cmdputs(n->narg.text);
4775 cmdlist(n->ncmd.args, 1);
4776 cmdlist(n->ncmd.redirect, 0);
4789 cmdputs(n->ncase.expr->narg.text);
4791 for (np = n->ncase.cases; np; np = np->nclist.next) {
4792 cmdtxt(np->nclist.pattern);
4794 cmdtxt(np->nclist.body);
4808 #if BASH_REDIR_OUTPUT
4823 cmdputs(utoa(n->nfile.fd));
4825 if (n->type == NTOFD || n->type == NFROMFD) {
4826 cmdputs(utoa(n->ndup.dupfd));
4835 commandtext(union node *n)
4839 STARTSTACKSTR(cmdnextc);
4841 name = stackblock();
4842 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4843 return ckstrdup(name);
4848 * Fork off a subshell. If we are doing job control, give the subshell its
4849 * own process group. Jp is a job structure that the job is to be added to.
4850 * N is the command that will be evaluated by the child. Both jp and n may
4851 * be NULL. The mode parameter can be one of the following:
4852 * FORK_FG - Fork off a foreground process.
4853 * FORK_BG - Fork off a background process.
4854 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4855 * process group even if job control is on.
4857 * When job control is turned off, background processes have their standard
4858 * input redirected to /dev/null (except for the second and later processes
4861 * Called with interrupts off.
4864 * Clear traps on a fork.
4872 for (tp = trap; tp < &trap[NSIG]; tp++) {
4873 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4874 if (trap_ptr == trap)
4876 /* else: it "belongs" to trap_ptr vector, don't free */
4878 if ((tp - trap) != 0)
4879 setsignal(tp - trap);
4886 /* Lives far away from here, needed for forkchild */
4887 static void closescript(void);
4889 /* Called after fork(), in child */
4890 /* jp and n are NULL when called by openhere() for heredoc support */
4891 static NOINLINE void
4892 forkchild(struct job *jp, union node *n, int mode)
4896 TRACE(("Child shell %d\n", getpid()));
4900 /* man bash: "Non-builtin commands run by bash have signal handlers
4901 * set to the values inherited by the shell from its parent".
4902 * Do we do it correctly? */
4906 if (mode == FORK_NOJOB /* is it `xxx` ? */
4907 && n && n->type == NCMD /* is it single cmd? */
4908 /* && n->ncmd.args->type == NARG - always true? */
4909 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4910 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4911 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4913 TRACE(("Trap hack\n"));
4914 /* Awful hack for `trap` or $(trap).
4916 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4917 * contains an example where "trap" is executed in a subshell:
4919 * save_traps=$(trap)
4921 * eval "$save_traps"
4923 * Standard does not say that "trap" in subshell shall print
4924 * parent shell's traps. It only says that its output
4925 * must have suitable form, but then, in the above example
4926 * (which is not supposed to be normative), it implies that.
4928 * bash (and probably other shell) does implement it
4929 * (traps are reset to defaults, but "trap" still shows them),
4930 * but as a result, "trap" logic is hopelessly messed up:
4933 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4934 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4935 * # true | trap <--- trap is in subshell - no output (ditto)
4936 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4937 * trap -- 'echo Ho' SIGWINCH
4938 * # echo `(trap)` <--- in subshell in subshell - output
4939 * trap -- 'echo Ho' SIGWINCH
4940 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4941 * trap -- 'echo Ho' SIGWINCH
4943 * The rules when to forget and when to not forget traps
4944 * get really complex and nonsensical.
4946 * Our solution: ONLY bare $(trap) or `trap` is special.
4948 /* Save trap handler strings for trap builtin to print */
4949 trap_ptr = xmemdup(trap, sizeof(trap));
4950 /* Fall through into clearing traps */
4954 /* do job control only in root shell */
4956 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4959 if (jp->nprocs == 0)
4962 pgrp = jp->ps[0].ps_pid;
4963 /* this can fail because we are doing it in the parent also */
4965 if (mode == FORK_FG)
4966 xtcsetpgrp(ttyfd, pgrp);
4971 if (mode == FORK_BG) {
4972 /* man bash: "When job control is not in effect,
4973 * asynchronous commands ignore SIGINT and SIGQUIT" */
4976 if (jp->nprocs == 0) {
4978 if (open(bb_dev_null, O_RDONLY) != 0)
4979 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4983 if (iflag) { /* why if iflag only? */
4988 * "In all cases, bash ignores SIGQUIT. Non-builtin
4989 * commands run by bash have signal handlers
4990 * set to the values inherited by the shell
4992 * Take care of the second rule: */
4996 if (n && n->type == NCMD
4997 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4999 TRACE(("Job hack\n"));
5000 /* "jobs": we do not want to clear job list for it,
5001 * instead we remove only _its_ own_ job from job list.
5002 * This makes "jobs .... | cat" more useful.
5008 for (jp = curjob; jp; jp = jp->prev_job)
5013 /* Called after fork(), in parent */
5015 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
5018 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
5020 TRACE(("In parent shell: child = %d\n", pid));
5022 /* jp is NULL when called by openhere() for heredoc support */
5023 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
5029 if (mode != FORK_NOJOB && jp->jobctl) {
5032 if (jp->nprocs == 0)
5035 pgrp = jp->ps[0].ps_pid;
5036 /* This can fail because we are doing it in the child also */
5040 if (mode == FORK_BG) {
5041 backgndpid = pid; /* set $! */
5042 set_curjob(jp, CUR_RUNNING);
5045 struct procstat *ps = &jp->ps[jp->nprocs++];
5048 ps->ps_cmd = nullstr;
5050 if (doing_jobctl && n)
5051 ps->ps_cmd = commandtext(n);
5056 /* jp and n are NULL when called by openhere() for heredoc support */
5058 forkshell(struct job *jp, union node *n, int mode)
5062 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
5065 TRACE(("Fork failed, errno=%d", errno));
5068 ash_msg_and_raise_error("can't fork");
5071 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
5072 forkchild(jp, n, mode);
5074 forkparent(jp, n, mode, pid);
5080 * Wait for job to finish.
5082 * Under job control we have the problem that while a child process
5083 * is running interrupts generated by the user are sent to the child
5084 * but not to the shell. This means that an infinite loop started by
5085 * an interactive user may be hard to kill. With job control turned off,
5086 * an interactive user may place an interactive program inside a loop.
5087 * If the interactive program catches interrupts, the user doesn't want
5088 * these interrupts to also abort the loop. The approach we take here
5089 * is to have the shell ignore interrupt signals while waiting for a
5090 * foreground process to terminate, and then send itself an interrupt
5091 * signal if the child process was terminated by an interrupt signal.
5092 * Unfortunately, some programs want to do a bit of cleanup and then
5093 * exit on interrupt; unless these processes terminate themselves by
5094 * sending a signal to themselves (instead of calling exit) they will
5095 * confuse this approach.
5097 * Called with interrupts off.
5100 waitforjob(struct job *jp)
5104 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
5107 while (jp->state == JOBRUNNING) {
5108 /* In non-interactive shells, we _can_ get
5109 * a keyboard signal here and be EINTRed,
5110 * but we just loop back, waiting for command to complete.
5113 * "If bash is waiting for a command to complete and receives
5114 * a signal for which a trap has been set, the trap
5115 * will not be executed until the command completes."
5117 * Reality is that even if trap is not set, bash
5118 * will not act on the signal until command completes.
5119 * Try this. sleep5intoff.c:
5120 * #include <signal.h>
5121 * #include <unistd.h>
5124 * sigemptyset(&set);
5125 * sigaddset(&set, SIGINT);
5126 * sigaddset(&set, SIGQUIT);
5127 * sigprocmask(SIG_BLOCK, &set, NULL);
5131 * $ bash -c './sleep5intoff; echo hi'
5132 * ^C^C^C^C <--- pressing ^C once a second
5134 * $ bash -c './sleep5intoff; echo hi'
5135 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
5138 dowait(DOWAIT_BLOCK, jp);
5145 xtcsetpgrp(ttyfd, rootpid);
5146 restore_tty_if_stopped_or_signaled(jp);
5149 * This is truly gross.
5150 * If we're doing job control, then we did a TIOCSPGRP which
5151 * caused us (the shell) to no longer be in the controlling
5152 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
5153 * intuit from the subprocess exit status whether a SIGINT
5154 * occurred, and if so interrupt ourselves. Yuck. - mycroft
5156 if (jp->sigint) /* TODO: do the same with all signals */
5157 raise(SIGINT); /* ... by raise(jp->sig) instead? */
5159 if (jp->state == JOBDONE)
5166 * return 1 if there are stopped jobs, otherwise 0
5178 if (jp && jp->state == JOBSTOPPED) {
5179 out2str("You have stopped jobs.\n");
5189 * Code for dealing with input/output redirection.
5194 #define EMPTY -2 /* marks an unused slot in redirtab */
5195 #define CLOSED -1 /* marks a slot of previously-closed fd */
5198 * Handle here documents. Normally we fork off a process to write the
5199 * data to a pipe. If the document is short, we can stuff the data in
5200 * the pipe without forking.
5202 /* openhere needs this forward reference */
5203 static void expandhere(union node *arg, int fd);
5205 openhere(union node *redir)
5211 ash_msg_and_raise_error("pipe call failed");
5212 if (redir->type == NHERE) {
5213 len = strlen(redir->nhere.doc->narg.text);
5214 if (len <= PIPE_BUF) {
5215 full_write(pip[1], redir->nhere.doc->narg.text, len);
5219 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5222 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5223 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5224 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5225 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5226 signal(SIGPIPE, SIG_DFL);
5227 if (redir->type == NHERE)
5228 full_write(pip[1], redir->nhere.doc->narg.text, len);
5230 expandhere(redir->nhere.doc, pip[1]);
5231 _exit(EXIT_SUCCESS);
5239 openredirect(union node *redir)
5245 switch (redir->nfile.type) {
5246 /* Can't happen, our single caller does this itself */
5252 return openhere(redir);
5255 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5256 * allocated space. Do it only when we know it is safe.
5258 fname = redir->nfile.expfname;
5260 switch (redir->nfile.type) {
5266 f = open(fname, O_RDONLY);
5271 f = open(fname, O_RDWR|O_CREAT, 0666);
5276 #if BASH_REDIR_OUTPUT
5279 /* Take care of noclobber mode. */
5281 if (stat(fname, &sb) < 0) {
5282 f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5285 } else if (!S_ISREG(sb.st_mode)) {
5286 f = open(fname, O_WRONLY, 0666);
5289 if (fstat(f, &sb) < 0 && S_ISREG(sb.st_mode)) {
5302 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5307 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5315 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5317 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5321 * Copy a file descriptor to be >= 10. Throws exception on error.
5329 newfd = fcntl(from, F_DUPFD, 10);
5330 err = newfd < 0 ? errno : 0;
5333 ash_msg_and_raise_perror("%d", from);
5335 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5341 dup2_or_raise(int from, int to)
5345 newfd = (from != to) ? dup2(from, to) : to;
5347 /* Happens when source fd is not open: try "echo >&99" */
5348 ash_msg_and_raise_perror("%d", from);
5353 fcntl_F_DUPFD(int fd, int avoid_fd)
5357 newfd = fcntl(fd, F_DUPFD, avoid_fd + 1);
5367 xdup_CLOEXEC_and_close(int fd, int avoid_fd)
5371 newfd = fcntl(fd, F_DUPFD, avoid_fd + 1);
5377 /* fd was not open? */
5380 ash_msg_and_raise_perror("%d", newfd);
5382 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5387 /* Struct def and variable are moved down to the first usage site */
5393 struct redirtab *next;
5395 struct squirrel two_fd[];
5397 #define redirlist (G_var.redirlist)
5400 add_squirrel_closed(struct redirtab *sq, int fd)
5407 for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
5408 /* If we collide with an already moved fd... */
5409 if (fd == sq->two_fd[i].orig_fd) {
5411 * "echo 3>FILE 3>&- 3>FILE"
5412 * "echo 3>&- 3>FILE"
5413 * No need for last redirect to insert
5414 * another "need to close 3" indicator.
5416 TRACE(("redirect_fd %d: already moved or closed\n", fd));
5420 TRACE(("redirect_fd %d: previous fd was closed\n", fd));
5421 sq->two_fd[i].orig_fd = fd;
5422 sq->two_fd[i].moved_to = CLOSED;
5426 save_fd_on_redirect(int fd, int avoid_fd, struct redirtab *sq)
5430 if (avoid_fd < 9) /* the important case here is that it can be -1 */
5435 /* Testcase: "ls -l /proc/$$/fd 10>&-" should work */
5436 ttyfd = xdup_CLOEXEC_and_close(ttyfd, avoid_fd);
5437 TRACE(("redirect_fd %d: matches ttyfd, moving it to %d\n", fd, ttyfd));
5438 return 1; /* "we closed fd" */
5441 /* Are we called from redirect(0)? E.g. redirect
5442 * in a forked child. No need to save fds,
5443 * we aren't going to use them anymore, ok to trash.
5448 /* If this one of script's fds? */
5450 struct parsefile *pf = g_parsefile;
5452 /* We skip fd == 0 case because of the following:
5453 * $ ash # running ash interactively
5455 * and in script.sh: "exec 9>&0".
5456 * Even though top-level pf_fd _is_ 0,
5457 * it's still ok to use it: "read" builtin uses it,
5458 * why should we cripple "exec" builtin?
5460 if (fd == pf->pf_fd) {
5461 pf->pf_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
5462 return 1; /* "we closed fd" */
5468 /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
5470 /* First: do we collide with some already moved fds? */
5471 for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
5472 /* If we collide with an already moved fd... */
5473 if (fd == sq->two_fd[i].moved_to) {
5474 new_fd = fcntl_F_DUPFD(fd, avoid_fd);
5475 sq->two_fd[i].moved_to = new_fd;
5476 TRACE(("redirect_fd %d: already busy, moving to %d\n", fd, new_fd));
5477 if (new_fd < 0) /* what? */
5479 return 0; /* "we did not close fd" */
5481 if (fd == sq->two_fd[i].orig_fd) {
5482 /* Example: echo Hello >/dev/null 1>&2 */
5483 TRACE(("redirect_fd %d: already moved\n", fd));
5484 return 0; /* "we did not close fd" */
5488 /* If this fd is open, we move and remember it; if it's closed, new_fd = CLOSED (-1) */
5489 new_fd = fcntl_F_DUPFD(fd, avoid_fd);
5490 TRACE(("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, new_fd));
5494 /* new_fd = CLOSED; - already is -1 */
5496 sq->two_fd[i].moved_to = new_fd;
5497 sq->two_fd[i].orig_fd = fd;
5499 /* if we move stderr, let "set -x" code know */
5500 if (fd == preverrout_fd)
5501 preverrout_fd = new_fd;
5503 return 0; /* "we did not close fd" */
5507 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5508 * old file descriptors are stashed away so that the redirection can be
5509 * undone by calling popredir.
5511 /* flags passed to redirect */
5512 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5514 redirect(union node *redir, int flags)
5516 struct redirtab *sv;
5525 if (flags & REDIR_PUSH)
5533 fd = redir->nfile.fd;
5534 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5535 //bb_error_msg("doing %d > %d", fd, newfd);
5536 newfd = redir->ndup.dupfd;
5539 newfd = openredirect(redir); /* always >= 0 */
5541 /* open() gave us precisely the fd we wanted.
5542 * This means that this fd was not busy
5543 * (not opened to anywhere).
5544 * Remember to close it on restore:
5546 add_squirrel_closed(sv, fd);
5555 /* if "N>FILE": move newfd to fd */
5556 /* if "N>&M": dup newfd to fd */
5557 /* if "N>&-": close fd (newfd is -1) */
5559 IF_BASH_REDIR_OUTPUT(redirect_more:)
5561 closed = save_fd_on_redirect(fd, /*avoid:*/ newfd, sv);
5563 /* "N>&-" means "close me" */
5565 /* ^^^ optimization: saving may already
5566 * have closed it. If not... */
5570 ///TODO: if _newfd_ is a script fd or saved fd, then simulate EBADF!
5571 //if (newfd == ttyfd) {
5573 // ash_msg_and_raise_perror("A %d", newfd);
5575 //if (newfd == g_parsefile->pf_fd) {
5577 // ash_msg_and_raise_perror("B %d", newfd);
5579 dup2_or_raise(newfd, fd);
5580 if (close_fd >= 0) /* "N>FILE" or ">&FILE" or heredoc? */
5582 #if BASH_REDIR_OUTPUT
5583 if (redir->nfile.type == NTO2 && fd == 1) {
5584 /* ">&FILE". we already redirected to 1, now copy 1 to 2 */
5592 } while ((redir = redir->nfile.next) != NULL);
5595 //dash:#define REDIR_SAVEFD2 03 /* set preverrout */
5596 #define REDIR_SAVEFD2 0
5597 // dash has a bug: since REDIR_SAVEFD2=3 and REDIR_PUSH=1, this test
5598 // triggers for pure REDIR_PUSH too. Thus, this is done almost always,
5599 // not only for calls with flags containing REDIR_SAVEFD2.
5600 // We do this unconditionally (see save_fd_on_redirect()).
5601 //if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5602 // preverrout_fd = copied_fd2;
5606 redirectsafe(union node *redir, int flags)
5609 volatile int saveint;
5610 struct jmploc *volatile savehandler = exception_handler;
5611 struct jmploc jmploc;
5614 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5615 err = setjmp(jmploc.loc); /* was = setjmp(jmploc.loc) * 2; */
5617 exception_handler = &jmploc;
5618 redirect(redir, flags);
5620 exception_handler = savehandler;
5621 if (err && exception_type != EXERROR)
5622 longjmp(exception_handler->loc, 1);
5623 RESTORE_INT(saveint);
5627 static struct redirtab*
5628 pushredir(union node *redir)
5630 struct redirtab *sv;
5639 #if BASH_REDIR_OUTPUT
5640 if (redir->nfile.type == NTO2)
5643 redir = redir->nfile.next;
5646 sv = ckzalloc(sizeof(*sv) + i * sizeof(sv->two_fd[0]));
5649 sv->two_fd[i].orig_fd = sv->two_fd[i].moved_to = EMPTY;
5650 sv->next = redirlist;
5656 * Undo the effects of the last redirection.
5661 struct redirtab *rp;
5664 if (redirlist == NULL)
5668 for (i = 0; i < rp->pair_count; i++) {
5669 int fd = rp->two_fd[i].orig_fd;
5670 int copy = rp->two_fd[i].moved_to;
5671 if (copy == CLOSED) {
5676 if (copy != EMPTY) {
5679 dup2_or_raise(copy, fd);
5684 redirlist = rp->next;
5690 unwindredir(struct redirtab *stop)
5692 while (redirlist != stop)
5693 popredir(/*drop:*/ 0);
5697 /* ============ Routines to expand arguments to commands
5699 * We have to deal with backquotes, shell variables, and file metacharacters.
5702 #if ENABLE_FEATURE_SH_MATH
5704 ash_arith(const char *s)
5706 arith_state_t math_state;
5709 math_state.lookupvar = lookupvar;
5710 math_state.setvar = setvar0;
5711 //math_state.endofname = endofname;
5714 result = arith(&math_state, s);
5715 if (math_state.errmsg)
5716 ash_msg_and_raise_error(math_state.errmsg);
5726 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5727 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5728 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5729 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5730 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5731 * POSIX says for this case:
5732 * Pathname expansion shall not be performed on the word by a
5733 * non-interactive shell; an interactive shell may perform it, but shall
5734 * do so only when the expansion would result in one word.
5735 * Currently, our code complies to the above rule by never globbing
5736 * redirection filenames.
5737 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5738 * (this means that on a typical Linux distro, bash almost always
5739 * performs globbing, and thus diverges from what we do).
5741 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5742 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5743 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5744 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5745 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5749 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5750 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5751 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5752 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5753 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5755 /* Add CTLESC when necessary. */
5756 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT)
5757 /* Do not skip NUL characters. */
5758 #define QUOTES_KEEPNUL EXP_TILDE
5761 * Structure specifying which parts of the string should be searched
5762 * for IFS characters.
5765 struct ifsregion *next; /* next region in list */
5766 int begoff; /* offset of start of region */
5767 int endoff; /* offset of end of region */
5768 int nulonly; /* search for nul bytes only */
5772 struct strlist *list;
5773 struct strlist **lastp;
5776 /* output of current string */
5777 static char *expdest;
5778 /* list of back quote expressions */
5779 static struct nodelist *argbackq;
5780 /* first struct in list of ifs regions */
5781 static struct ifsregion ifsfirst;
5782 /* last struct in list */
5783 static struct ifsregion *ifslastp;
5784 /* holds expanded arg list */
5785 static struct arglist exparg;
5789 * cvtnum() is used even if math support is off (to prepare $? values and such).
5796 /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
5797 len = sizeof(arith_t) * 3;
5798 /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
5799 if (sizeof(arith_t) < 4) len += 2;
5801 expdest = makestrspace(len, expdest);
5802 len = fmtstr(expdest, len, ARITH_FMT, num);
5803 STADJUST(len, expdest);
5808 * Break the argument string into pieces based upon IFS and add the
5809 * strings to the argument list. The regions of the string to be
5810 * searched for IFS characters have been stored by recordregion.
5813 ifsbreakup(char *string, struct arglist *arglist)
5815 struct ifsregion *ifsp;
5820 const char *ifs, *realifs;
5825 if (ifslastp != NULL) {
5828 realifs = ifsset() ? ifsval() : defifs;
5831 p = string + ifsp->begoff;
5832 nulonly = ifsp->nulonly;
5833 ifs = nulonly ? nullstr : realifs;
5835 while (p < string + ifsp->endoff) {
5837 if ((unsigned char)*p == CTLESC)
5839 if (!strchr(ifs, *p)) {
5844 ifsspc = (strchr(defifs, *p) != NULL);
5845 /* Ignore IFS whitespace at start */
5846 if (q == start && ifsspc) {
5852 sp = stzalloc(sizeof(*sp));
5854 *arglist->lastp = sp;
5855 arglist->lastp = &sp->next;
5859 if (p >= string + ifsp->endoff) {
5863 if ((unsigned char)*p == CTLESC)
5865 if (strchr(ifs, *p) == NULL) {
5869 if (strchr(defifs, *p) == NULL) {
5884 } while (ifsp != NULL);
5893 sp = stzalloc(sizeof(*sp));
5895 *arglist->lastp = sp;
5896 arglist->lastp = &sp->next;
5902 struct ifsregion *p = ifsfirst.next;
5909 struct ifsregion *ifsp;
5914 ifsfirst.next = NULL;
5921 esclen(const char *start, const char *p)
5925 while (p > start && (unsigned char)*--p == CTLESC) {
5932 * Remove any CTLESC characters from a string.
5935 rmescapes(char *str, int flag)
5937 static const char qchars[] ALIGN1 = {
5938 IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
5942 unsigned protect_against_glob;
5944 IF_BASH_PATTERN_SUBST(unsigned slash = flag & RMESCAPE_SLASH;)
5946 p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash));
5952 if (flag & RMESCAPE_ALLOC) {
5953 size_t len = p - str;
5954 size_t fulllen = len + strlen(p) + 1;
5956 if (flag & RMESCAPE_GROW) {
5957 int strloc = str - (char *)stackblock();
5958 r = makestrspace(fulllen, expdest);
5959 /* p and str may be invalidated by makestrspace */
5960 str = (char *)stackblock() + strloc;
5962 } else if (flag & RMESCAPE_HEAP) {
5963 r = ckmalloc(fulllen);
5965 r = stalloc(fulllen);
5969 q = (char *)mempcpy(q, str, len);
5974 globbing = flag & RMESCAPE_GLOB;
5975 protect_against_glob = globbing;
5977 if ((unsigned char)*p == CTLQUOTEMARK) {
5978 // Note: both inquotes and protect_against_glob only affect whether
5979 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5980 inquotes = ~inquotes;
5982 protect_against_glob = globbing;
5985 if ((unsigned char)*p == CTLESC) {
5989 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5991 if (protect_against_glob) {
5993 * We used to trust glob() and fnmatch() to eat
5994 * superfluous escapes (\z where z has no
5995 * special meaning anyway). But this causes
5996 * bugs such as string of one greek letter rho
5997 * (unicode-encoded as two bytes "cf,81")
5998 * getting encoded as "cf,CTLESC,81"
5999 * and here, converted to "cf,\,81" -
6000 * which does not go well with some flavors
6001 * of fnmatch() in unicode locales
6002 * (for example, glibc <= 2.22).
6004 * Lets add "\" only on the chars which need it.
6005 * Testcases for less obvious chars are shown.
6010 || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
6011 || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
6012 || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
6013 || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
6014 /* Some libc support [^negate], that's why "^" also needs love */
6015 || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
6020 } else if (*p == '\\' && !inquotes) {
6021 /* naked back slash */
6022 protect_against_glob = 0;
6025 #if BASH_PATTERN_SUBST
6026 else if (*p == '/' && slash) {
6027 /* stop handling globbing and mark location of slash */
6028 globbing = slash = 0;
6032 protect_against_glob = globbing;
6037 if (flag & RMESCAPE_GROW) {
6039 STADJUST(q - r + 1, expdest);
6043 #define pmatch(a, b) !fnmatch((a), (b), 0)
6046 * Prepare a pattern for a expmeta (internal glob(3)) call.
6048 * Returns an stalloced string.
6051 preglob(const char *pattern, int flag)
6053 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
6057 * Put a string on the stack.
6060 memtodest(const char *p, size_t len, int syntax, int quotes)
6067 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
6070 unsigned char c = *p++;
6072 if (quotes & QUOTES_ESC) {
6073 int n = SIT(c, syntax);
6075 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
6082 } else if (!(quotes & QUOTES_KEEPNUL))
6091 strtodest(const char *p, int syntax, int quotes)
6093 size_t len = strlen(p);
6094 memtodest(p, len, syntax, quotes);
6099 * Record the fact that we have to scan this region of the
6100 * string for IFS characters.
6103 recordregion(int start, int end, int nulonly)
6105 struct ifsregion *ifsp;
6107 if (ifslastp == NULL) {
6111 ifsp = ckzalloc(sizeof(*ifsp));
6112 /*ifsp->next = NULL; - ckzalloc did it */
6113 ifslastp->next = ifsp;
6117 ifslastp->begoff = start;
6118 ifslastp->endoff = end;
6119 ifslastp->nulonly = nulonly;
6123 removerecordregions(int endoff)
6125 if (ifslastp == NULL)
6128 if (ifsfirst.endoff > endoff) {
6129 while (ifsfirst.next) {
6130 struct ifsregion *ifsp;
6132 ifsp = ifsfirst.next->next;
6133 free(ifsfirst.next);
6134 ifsfirst.next = ifsp;
6137 if (ifsfirst.begoff > endoff) {
6140 ifslastp = &ifsfirst;
6141 ifsfirst.endoff = endoff;
6146 ifslastp = &ifsfirst;
6147 while (ifslastp->next && ifslastp->next->begoff < endoff)
6148 ifslastp = ifslastp->next;
6149 while (ifslastp->next) {
6150 struct ifsregion *ifsp;
6152 ifsp = ifslastp->next->next;
6153 free(ifslastp->next);
6154 ifslastp->next = ifsp;
6157 if (ifslastp->endoff > endoff)
6158 ifslastp->endoff = endoff;
6162 exptilde(char *startp, char *p, int flags)
6168 int quotes = flags & QUOTES_ESC;
6172 while ((c = *++p) != '\0') {
6179 if (flags & EXP_VARTILDE)
6189 if (*name == '\0') {
6190 home = lookupvar("HOME");
6192 pw = getpwnam(name);
6197 if (!home || !*home)
6200 strtodest(home, SQSYNTAX, quotes);
6208 * Execute a command inside back quotes. If it's a builtin command, we
6209 * want to save its output in a block obtained from malloc. Otherwise
6210 * we fork off a subprocess and get the output of the command via a pipe.
6211 * Should be called with interrupts off.
6213 struct backcmd { /* result of evalbackcmd */
6214 int fd; /* file descriptor to read from */
6215 int nleft; /* number of chars in buffer */
6216 char *buf; /* buffer */
6217 struct job *jp; /* job structure for command */
6220 /* These forward decls are needed to use "eval" code for backticks handling: */
6221 /* flags in argument to evaltree */
6222 #define EV_EXIT 01 /* exit after evaluating tree */
6223 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
6224 static int evaltree(union node *, int);
6226 /* An evaltree() which is known to never return.
6227 * Used to use an alias:
6228 * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
6229 * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
6231 static ALWAYS_INLINE NORETURN void
6232 evaltreenr(union node *n, int flags)
6235 bb_unreachable(abort());
6239 static void FAST_FUNC
6240 evalbackcmd(union node *n, struct backcmd *result)
6254 ash_msg_and_raise_error("pipe call failed");
6255 jp = makejob(/*n,*/ 1);
6256 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6262 dup2_or_raise(pip[1], 1);
6265 /* TODO: eflag clearing makes the following not abort:
6266 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6267 * which is what bash does (unless it is in POSIX mode).
6268 * dash deleted "eflag = 0" line in the commit
6269 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6270 * [EVAL] Don't clear eflag in evalbackcmd
6271 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6275 evaltreenr(n, EV_EXIT);
6280 result->fd = pip[0];
6284 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6285 result->fd, result->buf, result->nleft, result->jp));
6289 * Expand stuff in backwards quotes.
6292 expbackq(union node *cmd, int flag)
6300 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6301 struct stackmark smark;
6304 startloc = expdest - (char *)stackblock();
6305 pushstackmark(&smark, startloc);
6306 evalbackcmd(cmd, &in);
6307 popstackmark(&smark);
6314 memtodest(p, i, syntax, flag & QUOTES_ESC);
6318 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6319 TRACE(("expbackq: read returns %d\n", i));
6328 back_exitstatus = waitforjob(in.jp);
6332 /* Eat all trailing newlines */
6334 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6338 if (!(flag & EXP_QUOTED))
6339 recordregion(startloc, dest - (char *)stackblock(), 0);
6340 TRACE(("evalbackq: size:%d:'%.*s'\n",
6341 (int)((dest - (char *)stackblock()) - startloc),
6342 (int)((dest - (char *)stackblock()) - startloc),
6343 stackblock() + startloc));
6346 #if ENABLE_FEATURE_SH_MATH
6348 * Expand arithmetic expression. Backup to start of expression,
6349 * evaluate, place result in (backed up) result, adjust string position.
6361 * This routine is slightly over-complicated for
6362 * efficiency. Next we scan backwards looking for the
6363 * start of arithmetic.
6365 start = stackblock();
6372 while ((unsigned char)*p != CTLARI) {
6376 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6381 esc = esclen(start, p);
6391 removerecordregions(begoff);
6395 if (flag & QUOTES_ESC)
6396 rmescapes(p + 1, 0);
6398 len = cvtnum(ash_arith(p + 1));
6400 if (!(flag & EXP_QUOTED))
6401 recordregion(begoff, begoff + len, 0);
6405 /* argstr needs it */
6406 static char *evalvar(char *p, int flags);
6409 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6410 * characters to allow for further processing. Otherwise treat
6411 * $@ like $* since no splitting will be performed.
6414 argstr(char *p, int flags)
6416 static const char spclchars[] ALIGN1 = {
6424 #if ENABLE_FEATURE_SH_MATH
6429 const char *reject = spclchars;
6430 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6435 if (!(flags & EXP_VARTILDE)) {
6437 } else if (flags & EXP_VARTILDE2) {
6442 if (flags & EXP_TILDE) {
6445 flags &= ~EXP_TILDE;
6449 p = exptilde(p, q, flags);
6452 startloc = expdest - (char *)stackblock();
6456 length += strcspn(p + length, reject);
6460 IF_FEATURE_SH_MATH(|| c == CTLENDARI)
6462 /* c == '=' || c == ':' || c == CTLENDARI */
6468 expdest = stack_nputstr(p, length, expdest);
6469 newloc = expdest - (char *)stackblock();
6470 if (breakall && !inquotes && newloc > startloc) {
6471 recordregion(startloc, newloc, 0);
6482 if (flags & EXP_VARTILDE2) {
6486 flags |= EXP_VARTILDE2;
6491 * sort of a hack - expand tildes in variable
6492 * assignments (after the first '=' and after ':'s).
6501 case CTLENDVAR: /* ??? */
6504 inquotes ^= EXP_QUOTED;
6505 /* "$@" syntax adherence hack */
6506 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6507 p = evalvar(p + 1, flags | inquotes) + 1;
6511 if (flags & QUOTES_ESC) {
6522 * Quoted parameter expansion pattern: remove quote
6523 * unless inside inner quotes or we have a literal
6526 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6527 EXP_QPAT && *p != '\\')
6532 TRACE(("argstr: evalvar('%s')\n", p));
6533 p = evalvar(p, flags | inquotes);
6534 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6537 expbackq(argbackq->n, flags | inquotes);
6538 argbackq = argbackq->next;
6540 #if ENABLE_FEATURE_SH_MATH
6543 expari(flags | inquotes);
6552 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6553 char *pattern, int quotes, int zero)
6562 const char *s = loc2;
6569 match = pmatch(pattern, s);
6574 if (quotes && (unsigned char)*loc == CTLESC)
6583 scanright(char *startp, char *rmesc, char *rmescend,
6584 char *pattern, int quotes, int match_at_start)
6586 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6587 int try2optimize = match_at_start;
6593 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6594 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6595 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6597 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6598 * and on each iteration they go back two/one char until they reach the beginning.
6599 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6601 /* TODO: document in what other circumstances we are called. */
6603 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6606 const char *s = loc2;
6607 if (match_at_start) {
6611 match = pmatch(pattern, s);
6612 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6616 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6618 /* Maybe we can optimize this:
6619 * if pattern ends with unescaped *, we can avoid checking
6620 * shorter strings: if "foo*" doesn't match "raw_value_of_v",
6621 * it won't match truncated "raw_value_of_" strings too.
6623 unsigned plen = strlen(pattern);
6624 /* Does it end with "*"? */
6625 if (plen != 0 && pattern[--plen] == '*') {
6626 /* "xxxx*" is not escaped */
6627 /* "xxx\*" is escaped */
6628 /* "xx\\*" is not escaped */
6629 /* "x\\\*" is escaped */
6631 while (plen != 0 && pattern[--plen] == '\\')
6634 break; /* ends with unescaped "*" */
6642 esc = esclen(startp, loc);
6653 static void varunset(const char *, const char *, const char *, int) NORETURN;
6655 varunset(const char *end, const char *var, const char *umsg, int varflags)
6661 msg = "parameter not set";
6663 if ((unsigned char)*end == CTLENDVAR) {
6664 if (varflags & VSNUL)
6670 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6674 subevalvar(char *p, char *varname, int strloc, int subtype,
6675 int startloc, int varflags, int flag)
6677 struct nodelist *saveargbackq = argbackq;
6678 int quotes = flag & QUOTES_ESC;
6681 char *rmesc, *rmescend;
6683 int amount, resetloc;
6684 IF_BASH_PATTERN_SUBST(int workloc;)
6685 IF_BASH_PATTERN_SUBST(char *repl = NULL;)
6687 char *(*scan)(char*, char*, char*, char*, int, int);
6689 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6690 // p, varname, strloc, subtype, startloc, varflags, quotes);
6692 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6693 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0)
6695 STPUTC('\0', expdest);
6696 argbackq = saveargbackq;
6697 startp = (char *)stackblock() + startloc;
6701 setvar0(varname, startp);
6702 amount = startp - expdest;
6703 STADJUST(amount, expdest);
6707 varunset(p, varname, startp, varflags);
6712 int pos, len, orig_len;
6715 loc = str = stackblock() + strloc;
6717 # if !ENABLE_FEATURE_SH_MATH
6718 # define ash_arith number
6720 /* Read POS in ${var:POS:LEN} */
6721 colon = strchr(loc, ':');
6722 if (colon) *colon = '\0';
6723 pos = ash_arith(loc);
6724 if (colon) *colon = ':';
6726 /* Read LEN in ${var:POS:LEN} */
6727 len = str - startp - 1;
6728 /* *loc != '\0', guaranteed by parser */
6732 /* Adjust the length by the number of escapes */
6733 for (ptr = startp; ptr < (str - 1); ptr++) {
6734 if ((unsigned char)*ptr == CTLESC) {
6741 if (*loc++ == ':') {
6743 len = ash_arith(loc);
6745 /* Skip POS in ${var:POS:LEN} */
6747 while (*loc && *loc != ':') {
6750 if (*loc++ == ':') {
6751 len = ash_arith(loc);
6757 /* ${VAR:$((-n)):l} starts n chars from the end */
6758 pos = orig_len + pos;
6760 if ((unsigned)pos >= orig_len) {
6761 /* apart from obvious ${VAR:999999:l},
6762 * covers ${VAR:$((-9999999)):l} - result is ""
6769 /* ${VAR:N:-M} sets LEN to strlen()-M */
6770 len = (orig_len - pos) + len;
6772 if ((unsigned)len > (orig_len - pos))
6773 len = orig_len - pos;
6775 for (str = startp; pos; str++, pos--) {
6776 if (quotes && (unsigned char)*str == CTLESC)
6779 for (loc = startp; len; len--) {
6780 if (quotes && (unsigned char)*str == CTLESC)
6785 amount = loc - expdest;
6786 STADJUST(amount, expdest);
6789 #endif /* BASH_SUBSTR */
6792 resetloc = expdest - (char *)stackblock();
6794 #if BASH_PATTERN_SUBST
6795 /* We'll comeback here if we grow the stack while handling
6796 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6797 * stack will need rebasing, and we'll need to remove our work
6803 amount = expdest - ((char *)stackblock() + resetloc);
6804 STADJUST(-amount, expdest);
6805 startp = (char *)stackblock() + startloc;
6808 rmescend = (char *)stackblock() + strloc;
6810 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6811 if (rmesc != startp) {
6813 startp = (char *)stackblock() + startloc;
6817 str = (char *)stackblock() + strloc;
6819 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6820 * The result is a_\_z_c (not a\_\_z_c)!
6822 * The search pattern and replace string treat backslashes differently!
6823 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6824 * and string. It's only used on the first call.
6826 preglob(str, IF_BASH_PATTERN_SUBST(
6827 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6828 RMESCAPE_SLASH : ) 0);
6830 #if BASH_PATTERN_SUBST
6831 workloc = expdest - (char *)stackblock();
6832 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6837 repl = strchr(str, CTLESC);
6843 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6845 /* If there's no pattern to match, return the expansion unmolested */
6854 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6855 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6857 /* No match, advance */
6858 char *restart_detect = stackblock();
6860 STPUTC(*idx, expdest);
6861 if (quotes && (unsigned char)*idx == CTLESC) {
6864 STPUTC(*idx, expdest);
6866 if (stackblock() != restart_detect)
6871 /* continue; - prone to quadratic behavior, smarter code: */
6874 if (str[0] == '*') {
6875 /* Pattern is "*foo". If "*foo" does not match "long_string",
6876 * it would never match "ong_string" etc, no point in trying.
6883 if (subtype == VSREPLACEALL) {
6885 if (quotes && (unsigned char)*idx == CTLESC)
6894 //bb_error_msg("repl:'%s'", repl);
6895 for (loc = (char*)repl; *loc; loc++) {
6896 char *restart_detect = stackblock();
6897 if (quotes && *loc == '\\') {
6898 STPUTC(CTLESC, expdest);
6901 STPUTC(*loc, expdest);
6902 if (stackblock() != restart_detect)
6907 if (subtype == VSREPLACE) {
6908 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6910 char *restart_detect = stackblock();
6911 STPUTC(*idx, expdest);
6912 if (stackblock() != restart_detect)
6921 /* We've put the replaced text into a buffer at workloc, now
6922 * move it to the right place and adjust the stack.
6924 STPUTC('\0', expdest);
6925 startp = (char *)stackblock() + startloc;
6926 memmove(startp, (char *)stackblock() + workloc, len + 1);
6927 //bb_error_msg("startp:'%s'", startp);
6928 amount = expdest - (startp + len);
6929 STADJUST(-amount, expdest);
6932 #endif /* BASH_PATTERN_SUBST */
6934 subtype -= VSTRIMRIGHT;
6936 if (subtype < 0 || subtype > 7)
6939 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6940 zero = subtype >> 1;
6941 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6942 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6944 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6947 memmove(startp, loc, str - loc);
6948 loc = startp + (str - loc) - 1;
6951 amount = loc - expdest;
6952 STADJUST(amount, expdest);
6958 * Add the value of a specialized variable to the stack string.
6959 * name parameter (examples):
6960 * ash -c 'echo $1' name:'1='
6961 * ash -c 'echo $qwe' name:'qwe='
6962 * ash -c 'echo $$' name:'$='
6963 * ash -c 'echo ${$}' name:'$='
6964 * ash -c 'echo ${$##q}' name:'$=q'
6965 * ash -c 'echo ${#$}' name:'$='
6966 * note: examples with bad shell syntax:
6967 * ash -c 'echo ${#$1}' name:'$=1'
6968 * ash -c 'echo ${#1#}' name:'1=#'
6970 static NOINLINE ssize_t
6971 varvalue(char *name, int varflags, int flags, int *quotedp)
6978 int quoted = *quotedp;
6979 int subtype = varflags & VSTYPE;
6980 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6981 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6984 sep = (flags & EXP_FULL) << CHAR_BIT;
6985 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6995 num = shellparam.nparam;
7003 goto check_1char_name;
7005 expdest = makestrspace(NOPTS, expdest);
7006 for (i = NOPTS - 1; i >= 0; i--) {
7008 USTPUTC(optletters(i), expdest);
7014 /* handles cases similar to ${#$1} */
7015 if (name[2] != '\0')
7016 raise_error_syntax("bad substitution");
7029 sep |= ifsset() ? ifsval()[0] : ' ';
7036 while ((p = *ap++) != NULL) {
7037 len += strtodest(p, syntax, quotes);
7041 memtodest(&sepc, 1, syntax, quotes);
7056 num = atoi(name); /* number(name) fails on ${N#str} etc */
7057 if (num < 0 || num > shellparam.nparam)
7059 p = num ? shellparam.p[num - 1] : arg0;
7062 /* NB: name has form "VAR=..." */
7063 p = lookupvar(name);
7068 len = strtodest(p, syntax, quotes);
7069 #if ENABLE_UNICODE_SUPPORT
7070 if (subtype == VSLENGTH && len > 0) {
7071 reinit_unicode_for_ash();
7072 if (unicode_status == UNICODE_ON) {
7073 STADJUST(-len, expdest);
7075 len = unicode_strlen(p);
7083 STADJUST(-len, expdest);
7088 * Expand a variable, and return a pointer to the next character in the
7092 evalvar(char *p, int flag)
7103 varflags = (unsigned char) *p++;
7104 subtype = varflags & VSTYPE;
7107 raise_error_syntax("bad substitution");
7109 quoted = flag & EXP_QUOTED;
7111 easy = (!quoted || (*var == '@' && shellparam.nparam));
7112 startloc = expdest - (char *)stackblock();
7113 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
7116 varlen = varvalue(var, varflags, flag, "ed);
7117 if (varflags & VSNUL)
7120 if (subtype == VSPLUS) {
7121 varlen = -1 - varlen;
7125 if (subtype == VSMINUS) {
7130 flag | EXP_TILDE | EXP_WORD
7137 if (subtype == VSASSIGN || subtype == VSQUESTION) {
7141 subevalvar(p, var, 0, subtype, startloc, varflags,
7142 flag & ~QUOTES_ESC);
7145 * Remove any recorded regions beyond
7148 removerecordregions(startloc);
7152 if (varlen < 0 && uflag)
7153 varunset(p, var, 0, 0);
7155 if (subtype == VSLENGTH) {
7156 cvtnum(varlen > 0 ? varlen : 0);
7160 if (subtype == VSNORMAL) {
7164 recordregion(startloc, expdest - (char *)stackblock(), quoted);
7173 case VSTRIMRIGHTMAX:
7177 #if BASH_PATTERN_SUBST
7189 * Terminate the string and start recording the pattern
7192 STPUTC('\0', expdest);
7193 patloc = expdest - (char *)stackblock();
7194 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
7195 startloc, varflags, flag)) {
7196 int amount = expdest - (
7197 (char *)stackblock() + patloc - 1
7199 STADJUST(-amount, expdest);
7201 /* Remove any recorded regions beyond start of variable */
7202 removerecordregions(startloc);
7207 if (subtype != VSNORMAL) { /* skip to end of alternative */
7210 unsigned char c = *p++;
7213 else if (c == CTLBACKQ) {
7215 argbackq = argbackq->next;
7216 } else if (c == CTLVAR) {
7217 if ((*p++ & VSTYPE) != VSNORMAL)
7219 } else if (c == CTLENDVAR) {
7229 * Add a file name to the list.
7232 addfname(const char *name)
7236 sp = stzalloc(sizeof(*sp));
7237 sp->text = sstrdup(name);
7239 exparg.lastp = &sp->next;
7242 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7244 hasmeta(const char *p)
7246 static const char chars[] ALIGN1 = {
7247 '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
7251 p = strpbrk(p, chars);
7254 switch ((unsigned char) *p) {
7258 if (*p == CTLQUOTEMARK)
7262 if (*p == '\0') /* huh? */
7273 if (!strchr(p + 1, ']')) {
7274 /* It's not a properly closed [] pattern,
7275 * but other metas may follow. Continue checking.
7276 * my[file* _is_ globbed by bash
7277 * and matches filenames like "my[file1".
7293 /* If we want to use glob() from libc... */
7294 #if !ENABLE_ASH_INTERNAL_GLOB
7296 /* Add the result of glob() to the list */
7298 addglob(const glob_t *pglob)
7300 char **p = pglob->gl_pathv;
7307 expandmeta(struct strlist *str /*, int flag*/)
7309 /* TODO - EXP_REDIR */
7319 if (!hasmeta(str->text))
7323 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7324 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7325 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7327 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7328 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7329 // Which means you need to unescape the string, right? Not so fast:
7330 // if there _is_ a file named "file\?" (with backslash), it is returned
7331 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7332 // You DON'T KNOW by looking at the result whether you need to unescape it.
7334 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7335 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7336 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7337 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7338 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7339 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7340 i = glob(p, 0, NULL, &pglob);
7341 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7346 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7347 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7348 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7360 *exparg.lastp = str;
7361 rmescapes(str->text, 0);
7362 exparg.lastp = &str->next;
7364 default: /* GLOB_NOSPACE */
7367 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7374 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7377 * Do metacharacter (i.e. *, ?, [...]) expansion.
7380 expmeta(char *expdir, char *enddir, char *name)
7396 for (p = name; esc = 0, *p; p += esc + 1) {
7397 if (*p == '*' || *p == '?')
7399 else if (*p == '[') {
7406 if (*q == '/' || *q == '\0')
7416 if (p[esc] == '/') {
7419 start = p + esc + 1;
7423 if (metaflag == 0) { /* we've reached the end of the file name */
7424 if (enddir != expdir)
7432 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7443 } while (p < start);
7445 if (enddir == expdir) {
7447 } else if (enddir == expdir + 1 && *expdir == '/') {
7456 if (enddir != expdir)
7458 if (*endname == 0) {
7471 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7472 if (dp->d_name[0] == '.' && !matchdot)
7474 if (pmatch(start, dp->d_name)) {
7476 strcpy(enddir, dp->d_name);
7479 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7482 expmeta(expdir, p, endname);
7488 endname[-esc - 1] = esc ? '\\' : '/';
7491 static struct strlist *
7492 msort(struct strlist *list, int len)
7494 struct strlist *p, *q = NULL;
7495 struct strlist **lpp;
7503 for (n = half; --n >= 0;) {
7507 q->next = NULL; /* terminate first half of list */
7508 q = msort(list, half); /* sort first half of list */
7509 p = msort(p, len - half); /* sort second half */
7512 #if ENABLE_LOCALE_SUPPORT
7513 if (strcoll(p->text, q->text) < 0)
7515 if (strcmp(p->text, q->text) < 0)
7539 * Sort the results of file name expansion. It calculates the number of
7540 * strings to sort and then calls msort (short for merge sort) to do the
7543 static struct strlist *
7544 expsort(struct strlist *str)
7550 for (sp = str; sp; sp = sp->next)
7552 return msort(str, len);
7556 expandmeta(struct strlist *str /*, int flag*/)
7558 /* TODO - EXP_REDIR */
7562 struct strlist **savelastp;
7568 if (!hasmeta(str->text))
7570 savelastp = exparg.lastp;
7573 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7575 int i = strlen(str->text);
7576 //BUGGY estimation of how long expanded name can be
7577 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7579 expmeta(expdir, expdir, p);
7584 if (exparg.lastp == savelastp) {
7589 *exparg.lastp = str;
7590 rmescapes(str->text, 0);
7591 exparg.lastp = &str->next;
7593 *exparg.lastp = NULL;
7594 *savelastp = sp = expsort(*savelastp);
7595 while (sp->next != NULL)
7597 exparg.lastp = &sp->next;
7602 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7605 * Perform variable substitution and command substitution on an argument,
7606 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7607 * perform splitting and file name expansion. When arglist is NULL, perform
7608 * here document expansion.
7611 expandarg(union node *arg, struct arglist *arglist, int flag)
7616 argbackq = arg->narg.backquote;
7617 STARTSTACKSTR(expdest);
7618 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7619 argstr(arg->narg.text, flag);
7620 p = _STPUTC('\0', expdest);
7622 if (arglist == NULL) {
7623 /* here document expanded */
7626 p = grabstackstr(p);
7627 TRACE(("expandarg: p:'%s'\n", p));
7628 exparg.lastp = &exparg.list;
7632 if (flag & EXP_FULL) {
7633 ifsbreakup(p, &exparg);
7634 *exparg.lastp = NULL;
7635 exparg.lastp = &exparg.list;
7636 expandmeta(exparg.list /*, flag*/);
7638 sp = stzalloc(sizeof(*sp));
7641 exparg.lastp = &sp->next;
7643 *exparg.lastp = NULL;
7645 *arglist->lastp = exparg.list;
7646 arglist->lastp = exparg.lastp;
7654 * Expand shell variables and backquotes inside a here document.
7657 expandhere(union node *arg, int fd)
7659 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7660 full_write(fd, stackblock(), expdest - (char *)stackblock());
7664 * Returns true if the pattern matches the string.
7667 patmatch(char *pattern, const char *string)
7669 char *p = preglob(pattern, 0);
7670 //bb_error_msg("fnmatch(pattern:'%s',str:'%s')", p, string);
7671 return pmatch(p, string);
7675 * See if a pattern matches in a case statement.
7678 casematch(union node *pattern, char *val)
7680 struct stackmark smark;
7683 setstackmark(&smark);
7684 argbackq = pattern->narg.backquote;
7685 STARTSTACKSTR(expdest);
7686 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
7687 STACKSTRNUL(expdest);
7689 result = patmatch(stackblock(), val);
7690 popstackmark(&smark);
7695 /* ============ find_command */
7699 int (*builtin)(int, char **) FAST_FUNC;
7700 /* unsigned flags; */
7702 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7703 /* "regular" builtins always take precedence over commands,
7704 * regardless of PATH=....%builtin... position */
7705 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7706 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7709 smallint cmdtype; /* CMDxxx */
7712 /* index >= 0 for commands without path (slashes) */
7713 /* (TODO: what exactly does the value mean? PATH position?) */
7714 /* index == -1 for commands with slashes */
7715 /* index == (-2 - applet_no) for NOFORK applets */
7716 const struct builtincmd *cmd;
7717 struct funcnode *func;
7720 /* values of cmdtype */
7721 #define CMDUNKNOWN -1 /* no entry in table for command */
7722 #define CMDNORMAL 0 /* command is an executable program */
7723 #define CMDFUNCTION 1 /* command is a shell function */
7724 #define CMDBUILTIN 2 /* command is a shell builtin */
7726 /* action to find_command() */
7727 #define DO_ERR 0x01 /* prints errors */
7728 #define DO_ABS 0x02 /* checks absolute paths */
7729 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7730 #define DO_ALTPATH 0x08 /* using alternate path */
7731 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7733 static void find_command(char *, struct cmdentry *, int, const char *);
7736 /* ============ Hashing commands */
7739 * When commands are first encountered, they are entered in a hash table.
7740 * This ensures that a full path search will not have to be done for them
7741 * on each invocation.
7743 * We should investigate converting to a linear search, even though that
7744 * would make the command name "hash" a misnomer.
7748 struct tblentry *next; /* next entry in hash chain */
7749 union param param; /* definition of builtin function */
7750 smallint cmdtype; /* CMDxxx */
7751 char rehash; /* if set, cd done since entry created */
7752 char cmdname[1]; /* name of command */
7755 static struct tblentry **cmdtable;
7756 #define INIT_G_cmdtable() do { \
7757 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7760 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7764 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
7766 #if ENABLE_FEATURE_SH_STANDALONE
7767 if (applet_no >= 0) {
7768 if (APPLET_IS_NOEXEC(applet_no)) {
7772 popredir(/*drop:*/ 1);
7773 run_applet_no_and_exit(applet_no, cmd, argv);
7775 /* re-exec ourselves with the new arguments */
7776 execve(bb_busybox_exec_path, argv, envp);
7777 /* If they called chroot or otherwise made the binary no longer
7778 * executable, fall through */
7785 execve(cmd, argv, envp);
7786 } while (errno == EINTR);
7788 execve(cmd, argv, envp);
7790 if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
7791 /* Run "cmd" as a shell script:
7792 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7793 * "If the execve() function fails with ENOEXEC, the shell
7794 * shall execute a command equivalent to having a shell invoked
7795 * with the command name as its first operand,
7796 * with any remaining arguments passed to the new shell"
7798 * That is, do not use $SHELL, user's shell, or /bin/sh;
7799 * just call ourselves.
7801 * Note that bash reads ~80 chars of the file, and if it sees
7802 * a zero byte before it sees newline, it doesn't try to
7803 * interpret it, but fails with "cannot execute binary file"
7804 * message and exit code 126. For one, this prevents attempts
7805 * to interpret foreign ELF binaries as shell scripts.
7807 argv[0] = (char*) cmd;
7808 cmd = bb_busybox_exec_path;
7809 /* NB: this is only possible because all callers of shellexec()
7810 * ensure that the argv[-1] slot exists!
7813 argv[0] = (char*) "ash";
7819 * Exec a program. Never returns. If you change this routine, you may
7820 * have to change the find_command routine as well.
7821 * argv[-1] must exist and be writable! See tryexec() for why.
7823 static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
7824 static void shellexec(char *prog, char **argv, const char *path, int idx)
7830 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7832 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7833 if (strchr(prog, '/') != NULL
7834 #if ENABLE_FEATURE_SH_STANDALONE
7835 || (applet_no = find_applet_by_name(prog)) >= 0
7838 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
7839 if (applet_no >= 0) {
7840 /* We tried execing ourself, but it didn't work.
7841 * Maybe /proc/self/exe doesn't exist?
7850 while ((cmdname = path_advance(&path, prog)) != NULL) {
7851 if (--idx < 0 && pathopt == NULL) {
7852 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7853 if (errno != ENOENT && errno != ENOTDIR)
7860 /* Map to POSIX errors */
7872 exitstatus = exerrno;
7873 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7874 prog, e, suppress_int));
7875 ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
7880 printentry(struct tblentry *cmdp)
7886 idx = cmdp->param.index;
7889 name = path_advance(&path, cmdp->cmdname);
7891 } while (--idx >= 0);
7892 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7896 * Clear out command entries. The argument specifies the first entry in
7897 * PATH which has changed.
7900 clearcmdentry(int firstchange)
7902 struct tblentry **tblp;
7903 struct tblentry **pp;
7904 struct tblentry *cmdp;
7907 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7909 while ((cmdp = *pp) != NULL) {
7910 if ((cmdp->cmdtype == CMDNORMAL &&
7911 cmdp->param.index >= firstchange)
7912 || (cmdp->cmdtype == CMDBUILTIN &&
7913 builtinloc >= firstchange)
7926 * Locate a command in the command hash table. If "add" is nonzero,
7927 * add the command to the table if it is not already present. The
7928 * variable "lastcmdentry" is set to point to the address of the link
7929 * pointing to the entry, so that delete_cmd_entry can delete the
7932 * Interrupts must be off if called with add != 0.
7934 static struct tblentry **lastcmdentry;
7936 static struct tblentry *
7937 cmdlookup(const char *name, int add)
7939 unsigned int hashval;
7941 struct tblentry *cmdp;
7942 struct tblentry **pp;
7945 hashval = (unsigned char)*p << 4;
7947 hashval += (unsigned char)*p++;
7949 pp = &cmdtable[hashval % CMDTABLESIZE];
7950 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7951 if (strcmp(cmdp->cmdname, name) == 0)
7955 if (add && cmdp == NULL) {
7956 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7958 /* + 1 - already done because
7959 * tblentry::cmdname is char[1] */);
7960 /*cmdp->next = NULL; - ckzalloc did it */
7961 cmdp->cmdtype = CMDUNKNOWN;
7962 strcpy(cmdp->cmdname, name);
7969 * Delete the command entry returned on the last lookup.
7972 delete_cmd_entry(void)
7974 struct tblentry *cmdp;
7977 cmdp = *lastcmdentry;
7978 *lastcmdentry = cmdp->next;
7979 if (cmdp->cmdtype == CMDFUNCTION)
7980 freefunc(cmdp->param.func);
7986 * Add a new command entry, replacing any existing command entry for
7987 * the same name - except special builtins.
7990 addcmdentry(char *name, struct cmdentry *entry)
7992 struct tblentry *cmdp;
7994 cmdp = cmdlookup(name, 1);
7995 if (cmdp->cmdtype == CMDFUNCTION) {
7996 freefunc(cmdp->param.func);
7998 cmdp->cmdtype = entry->cmdtype;
7999 cmdp->param = entry->u;
8003 static int FAST_FUNC
8004 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8006 struct tblentry **pp;
8007 struct tblentry *cmdp;
8009 struct cmdentry entry;
8012 if (nextopt("r") != '\0') {
8017 if (*argptr == NULL) {
8018 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8019 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8020 if (cmdp->cmdtype == CMDNORMAL)
8028 while ((name = *argptr) != NULL) {
8029 cmdp = cmdlookup(name, 0);
8031 && (cmdp->cmdtype == CMDNORMAL
8032 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
8036 find_command(name, &entry, DO_ERR, pathval());
8037 if (entry.cmdtype == CMDUNKNOWN)
8045 * Called when a cd is done. Marks all commands so the next time they
8046 * are executed they will be rehashed.
8051 struct tblentry **pp;
8052 struct tblentry *cmdp;
8054 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
8055 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
8056 if (cmdp->cmdtype == CMDNORMAL
8057 || (cmdp->cmdtype == CMDBUILTIN
8058 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
8068 * Fix command hash table when PATH changed.
8069 * Called before PATH is changed. The argument is the new value of PATH;
8070 * pathval() still returns the old value at this point.
8071 * Called with interrupts off.
8073 static void FAST_FUNC
8074 changepath(const char *new)
8082 firstchange = 9999; /* assume no change */
8088 if ((*old == '\0' && *new == ':')
8089 || (*old == ':' && *new == '\0')
8093 old = new; /* ignore subsequent differences */
8097 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
8104 if (builtinloc < 0 && idx_bltin >= 0)
8105 builtinloc = idx_bltin; /* zap builtins */
8106 if (builtinloc >= 0 && idx_bltin < 0)
8108 clearcmdentry(firstchange);
8109 builtinloc = idx_bltin;
8145 typedef smallint token_id_t;
8147 /* Nth bit indicates if token marks the end of a list */
8150 /* 0 */ | (1u << TEOF)
8151 /* 1 */ | (0u << TNL)
8152 /* 2 */ | (0u << TREDIR)
8153 /* 3 */ | (0u << TWORD)
8154 /* 4 */ | (0u << TSEMI)
8155 /* 5 */ | (0u << TBACKGND)
8156 /* 6 */ | (0u << TAND)
8157 /* 7 */ | (0u << TOR)
8158 /* 8 */ | (0u << TPIPE)
8159 /* 9 */ | (0u << TLP)
8160 /* 10 */ | (1u << TRP)
8161 /* 11 */ | (1u << TENDCASE)
8162 /* 12 */ | (1u << TENDBQUOTE)
8163 /* 13 */ | (0u << TNOT)
8164 /* 14 */ | (0u << TCASE)
8165 /* 15 */ | (1u << TDO)
8166 /* 16 */ | (1u << TDONE)
8167 /* 17 */ | (1u << TELIF)
8168 /* 18 */ | (1u << TELSE)
8169 /* 19 */ | (1u << TESAC)
8170 /* 20 */ | (1u << TFI)
8171 /* 21 */ | (0u << TFOR)
8173 /* 22 */ | (0u << TFUNCTION)
8175 /* 23 */ | (0u << TIF)
8176 /* 24 */ | (0u << TIN)
8177 /* 25 */ | (1u << TTHEN)
8178 /* 26 */ | (0u << TUNTIL)
8179 /* 27 */ | (0u << TWHILE)
8180 /* 28 */ | (0u << TBEGIN)
8181 /* 29 */ | (1u << TEND)
8182 , /* thus far 29 bits used */
8185 static const char *const tokname_array[] = {
8199 #define KWDOFFSET 13
8200 /* the following are keywords */
8222 /* Wrapper around strcmp for qsort/bsearch/... */
8224 pstrcmp(const void *a, const void *b)
8226 return strcmp((char*)a, *(char**)b);
8229 static const char *const *
8230 findkwd(const char *s)
8232 return bsearch(s, tokname_array + KWDOFFSET,
8233 ARRAY_SIZE(tokname_array) - KWDOFFSET,
8234 sizeof(tokname_array[0]), pstrcmp);
8238 * Locate and print what a word is...
8241 describe_command(char *command, const char *path, int describe_command_verbose)
8243 struct cmdentry entry;
8244 #if ENABLE_ASH_ALIAS
8245 const struct alias *ap;
8248 path = path ? path : pathval();
8250 if (describe_command_verbose) {
8254 /* First look at the keywords */
8255 if (findkwd(command)) {
8256 out1str(describe_command_verbose ? " is a shell keyword" : command);
8260 #if ENABLE_ASH_ALIAS
8261 /* Then look at the aliases */
8262 ap = lookupalias(command, 0);
8264 if (!describe_command_verbose) {
8269 out1fmt(" is an alias for %s", ap->val);
8274 find_command(command, &entry, DO_ABS, path);
8276 switch (entry.cmdtype) {
8278 int j = entry.u.index;
8284 p = path_advance(&path, command);
8288 if (describe_command_verbose) {
8289 out1fmt(" is %s", p);
8297 if (describe_command_verbose) {
8298 out1str(" is a shell function");
8305 if (describe_command_verbose) {
8306 out1fmt(" is a %sshell builtin",
8307 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8308 "special " : nullstr
8316 if (describe_command_verbose) {
8317 out1str(": not found\n");
8326 static int FAST_FUNC
8327 typecmd(int argc UNUSED_PARAM, char **argv)
8333 /* type -p ... ? (we don't bother checking for 'p') */
8334 if (argv[1] && argv[1][0] == '-') {
8339 err |= describe_command(argv[i++], NULL, verbose);
8344 #if ENABLE_ASH_CMDCMD
8345 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8347 parse_command_args(char **argv, const char **path)
8360 if (c == '-' && !*cp) {
8368 *path = bb_default_path;
8371 /* run 'typecmd' for other options */
8380 static int FAST_FUNC
8381 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8389 const char *path = NULL;
8391 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8392 * never reaches this function.
8395 while ((c = nextopt("pvV")) != '\0')
8397 verify |= VERIFY_VERBOSE;
8399 /*verify |= VERIFY_BRIEF*/;
8405 path = bb_default_path;
8407 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8409 if (/*verify && */ cmd)
8410 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8417 /*static int funcblocksize; // size of structures in function */
8418 /*static int funcstringsize; // size of strings in node */
8419 static void *funcblock; /* block to allocate function from */
8420 static char *funcstring_end; /* end of block to allocate strings from */
8422 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8423 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8424 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8425 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8426 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8427 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8428 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8429 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8430 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8431 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8432 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8433 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8434 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8435 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8436 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8437 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8438 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8439 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8440 #if BASH_REDIR_OUTPUT
8441 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8443 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8444 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8445 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8446 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8447 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8448 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8449 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8450 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8451 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8454 static int calcsize(int funcblocksize, union node *n);
8457 sizenodelist(int funcblocksize, struct nodelist *lp)
8460 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8461 funcblocksize = calcsize(funcblocksize, lp->n);
8464 return funcblocksize;
8468 calcsize(int funcblocksize, union node *n)
8471 return funcblocksize;
8472 funcblocksize += nodesize[n->type];
8475 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8476 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8477 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8480 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8485 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8486 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8493 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8494 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8497 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8498 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8499 funcblocksize = calcsize(funcblocksize, n->nif.test);
8502 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8503 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8504 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8507 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8508 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8511 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8512 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8513 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8517 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8518 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8519 funcblocksize = calcsize(funcblocksize, n->narg.next);
8522 #if BASH_REDIR_OUTPUT
8529 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8530 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8534 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8535 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8539 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8540 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8543 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8546 return funcblocksize;
8550 nodeckstrdup(char *s)
8552 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8553 return strcpy(funcstring_end, s);
8556 static union node *copynode(union node *);
8558 static struct nodelist *
8559 copynodelist(struct nodelist *lp)
8561 struct nodelist *start;
8562 struct nodelist **lpp;
8567 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8568 (*lpp)->n = copynode(lp->n);
8570 lpp = &(*lpp)->next;
8577 copynode(union node *n)
8584 funcblock = (char *) funcblock + nodesize[n->type];
8588 new->ncmd.redirect = copynode(n->ncmd.redirect);
8589 new->ncmd.args = copynode(n->ncmd.args);
8590 new->ncmd.assign = copynode(n->ncmd.assign);
8593 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8594 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8599 new->nredir.redirect = copynode(n->nredir.redirect);
8600 new->nredir.n = copynode(n->nredir.n);
8607 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8608 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8611 new->nif.elsepart = copynode(n->nif.elsepart);
8612 new->nif.ifpart = copynode(n->nif.ifpart);
8613 new->nif.test = copynode(n->nif.test);
8616 new->nfor.var = nodeckstrdup(n->nfor.var);
8617 new->nfor.body = copynode(n->nfor.body);
8618 new->nfor.args = copynode(n->nfor.args);
8621 new->ncase.cases = copynode(n->ncase.cases);
8622 new->ncase.expr = copynode(n->ncase.expr);
8625 new->nclist.body = copynode(n->nclist.body);
8626 new->nclist.pattern = copynode(n->nclist.pattern);
8627 new->nclist.next = copynode(n->nclist.next);
8631 new->narg.backquote = copynodelist(n->narg.backquote);
8632 new->narg.text = nodeckstrdup(n->narg.text);
8633 new->narg.next = copynode(n->narg.next);
8636 #if BASH_REDIR_OUTPUT
8643 new->nfile.fname = copynode(n->nfile.fname);
8644 new->nfile.fd = n->nfile.fd;
8645 new->nfile.next = copynode(n->nfile.next);
8649 new->ndup.vname = copynode(n->ndup.vname);
8650 new->ndup.dupfd = n->ndup.dupfd;
8651 new->ndup.fd = n->ndup.fd;
8652 new->ndup.next = copynode(n->ndup.next);
8656 new->nhere.doc = copynode(n->nhere.doc);
8657 new->nhere.fd = n->nhere.fd;
8658 new->nhere.next = copynode(n->nhere.next);
8661 new->nnot.com = copynode(n->nnot.com);
8664 new->type = n->type;
8669 * Make a copy of a parse tree.
8671 static struct funcnode *
8672 copyfunc(union node *n)
8677 /*funcstringsize = 0;*/
8678 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8679 f = ckzalloc(blocksize /* + funcstringsize */);
8680 funcblock = (char *) f + offsetof(struct funcnode, n);
8681 funcstring_end = (char *) f + blocksize;
8683 /* f->count = 0; - ckzalloc did it */
8688 * Define a shell function.
8691 defun(union node *func)
8693 struct cmdentry entry;
8696 entry.cmdtype = CMDFUNCTION;
8697 entry.u.func = copyfunc(func);
8698 addcmdentry(func->narg.text, &entry);
8702 /* Reasons for skipping commands (see comment on breakcmd routine) */
8703 #define SKIPBREAK (1 << 0)
8704 #define SKIPCONT (1 << 1)
8705 #define SKIPFUNC (1 << 2)
8706 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8707 static int skipcount; /* number of levels to skip */
8708 static int funcnest; /* depth of function calls */
8709 static int loopnest; /* current loop nesting level */
8711 /* Forward decl way out to parsing code - dotrap needs it */
8712 static int evalstring(char *s, int flags);
8714 /* Called to execute a trap.
8715 * Single callsite - at the end of evaltree().
8716 * If we return non-zero, evaltree raises EXEXIT exception.
8718 * Perhaps we should avoid entering new trap handlers
8719 * while we are executing a trap handler. [is it a TODO?]
8726 uint8_t last_status;
8731 last_status = exitstatus;
8735 TRACE(("dotrap entered\n"));
8736 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8748 /* non-trapped SIGINT is handled separately by raise_interrupt,
8749 * don't upset it by resetting gotsig[SIGINT-1] */
8750 if (sig == SIGINT && !p)
8753 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8759 exitstatus = last_status;
8760 TRACE(("dotrap returns\n"));
8763 /* forward declarations - evaluation is fairly recursive business... */
8764 static int evalloop(union node *, int);
8765 static int evalfor(union node *, int);
8766 static int evalcase(union node *, int);
8767 static int evalsubshell(union node *, int);
8768 static void expredir(union node *);
8769 static int evalpipe(union node *, int);
8770 static int evalcommand(union node *, int);
8771 static int evalbltin(const struct builtincmd *, int, char **, int);
8772 static void prehash(union node *);
8775 * Evaluate a parse tree. The value is left in the global variable
8779 evaltree(union node *n, int flags)
8782 int (*evalfn)(union node *, int);
8786 TRACE(("evaltree(NULL) called\n"));
8789 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8796 out1fmt("Node type = %d\n", n->type);
8801 status = !evaltree(n->nnot.com, EV_TESTED);
8804 expredir(n->nredir.redirect);
8805 pushredir(n->nredir.redirect);
8806 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8808 status = evaltree(n->nredir.n, flags & EV_TESTED);
8810 if (n->nredir.redirect)
8811 popredir(/*drop:*/ 0);
8814 evalfn = evalcommand;
8816 if (eflag && !(flags & EV_TESTED))
8828 evalfn = evalsubshell;
8841 #error NAND + 1 != NOR
8843 #if NOR + 1 != NSEMI
8844 #error NOR + 1 != NSEMI
8846 unsigned is_or = n->type - NAND;
8849 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8851 if ((!status) == is_or || evalskip)
8857 status = evalfn(n, flags);
8861 status = evaltree(n->nif.test, EV_TESTED);
8868 if (n->nif.elsepart) {
8869 n = n->nif.elsepart;
8876 /* Not necessary. To test it:
8877 * "false; f() { qwerty; }; echo $?" should print 0.
8881 exitstatus = status;
8885 /* Order of checks below is important:
8886 * signal handlers trigger before exit caused by "set -e".
8890 if (checkexit & status)
8891 raise_exception(EXEXIT);
8892 if (flags & EV_EXIT)
8893 raise_exception(EXEXIT);
8895 TRACE(("leaving evaltree (no interrupts)\n"));
8902 int skip = evalskip;
8909 if (--skipcount <= 0) {
8920 evalloop(union node *n, int flags)
8931 i = evaltree(n->nbinary.ch1, EV_TESTED);
8933 if (skip == SKIPFUNC)
8937 if (n->type != NWHILE)
8941 status = evaltree(n->nbinary.ch2, flags);
8943 } while (!(skip & ~SKIPCONT));
8950 evalfor(union node *n, int flags)
8952 struct arglist arglist;
8955 struct stackmark smark;
8958 setstackmark(&smark);
8959 arglist.list = NULL;
8960 arglist.lastp = &arglist.list;
8961 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8962 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8964 *arglist.lastp = NULL;
8968 for (sp = arglist.list; sp; sp = sp->next) {
8969 setvar0(n->nfor.var, sp->text);
8970 status = evaltree(n->nfor.body, flags);
8971 if (skiploop() & ~SKIPCONT)
8975 popstackmark(&smark);
8981 evalcase(union node *n, int flags)
8985 struct arglist arglist;
8986 struct stackmark smark;
8989 setstackmark(&smark);
8990 arglist.list = NULL;
8991 arglist.lastp = &arglist.list;
8992 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8993 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8994 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8995 if (casematch(patp, arglist.list->text)) {
8996 /* Ensure body is non-empty as otherwise
8997 * EV_EXIT may prevent us from setting the
9000 if (evalskip == 0 && cp->nclist.body) {
9001 status = evaltree(cp->nclist.body, flags);
9008 popstackmark(&smark);
9014 * Kick off a subshell to evaluate a tree.
9017 evalsubshell(union node *n, int flags)
9020 int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
9023 expredir(n->nredir.redirect);
9024 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
9027 if (backgnd == FORK_FG)
9029 jp = makejob(/*n,*/ 1);
9030 if (forkshell(jp, n, backgnd) == 0) {
9035 flags &= ~EV_TESTED;
9037 redirect(n->nredir.redirect, 0);
9038 evaltreenr(n->nredir.n, flags);
9043 if (backgnd == FORK_FG)
9044 status = waitforjob(jp);
9050 * Compute the names of the files in a redirection list.
9052 static void fixredir(union node *, const char *, int);
9054 expredir(union node *n)
9058 for (redir = n; redir; redir = redir->nfile.next) {
9062 fn.lastp = &fn.list;
9063 switch (redir->type) {
9067 #if BASH_REDIR_OUTPUT
9072 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
9073 TRACE(("expredir expanded to '%s'\n", fn.list->text));
9074 #if BASH_REDIR_OUTPUT
9078 // By the design of stack allocator, the loop of this kind:
9079 // while true; do while true; do break; done </dev/null; done
9080 // will look like a memory leak: ash plans to free expfname's
9081 // of "/dev/null" as soon as it finishes running the loop
9082 // (in this case, never).
9083 // This "fix" is wrong:
9084 if (redir->nfile.expfname)
9085 stunalloc(redir->nfile.expfname);
9086 // It results in corrupted state of stacked allocations.
9088 redir->nfile.expfname = fn.list->text;
9091 case NTOFD: /* >& */
9092 if (redir->ndup.vname) {
9093 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
9094 if (fn.list == NULL)
9095 ash_msg_and_raise_error("redir error");
9096 #if BASH_REDIR_OUTPUT
9097 //FIXME: we used expandarg with different args!
9098 if (!isdigit_str9(fn.list->text)) {
9099 /* >&file, not >&fd */
9100 if (redir->nfile.fd != 1) /* 123>&file - BAD */
9101 ash_msg_and_raise_error("redir error");
9103 goto store_expfname;
9106 fixredir(redir, fn.list->text, 1);
9114 * Evaluate a pipeline. All the processes in the pipeline are children
9115 * of the process creating the pipeline. (This differs from some versions
9116 * of the shell, which make the last process in a pipeline the parent
9120 evalpipe(union node *n, int flags)
9123 struct nodelist *lp;
9129 TRACE(("evalpipe(0x%lx) called\n", (long)n));
9131 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
9135 if (n->npipe.pipe_backgnd == 0)
9137 jp = makejob(/*n,*/ pipelen);
9139 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
9143 if (pipe(pip) < 0) {
9145 ash_msg_and_raise_error("pipe call failed");
9148 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
9162 evaltreenr(lp->n, flags);
9169 /* Don't want to trigger debugging */
9173 if (n->npipe.pipe_backgnd == 0) {
9174 status = waitforjob(jp);
9175 TRACE(("evalpipe: job done exit status %d\n", status));
9183 * Controls whether the shell is interactive or not.
9186 setinteractive(int on)
9188 static smallint is_interactive;
9190 if (++on == is_interactive)
9192 is_interactive = on;
9196 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9197 if (is_interactive > 1) {
9198 /* Looks like they want an interactive shell */
9199 static smallint did_banner;
9202 /* note: ash and hush share this string */
9203 out1fmt("\n\n%s %s\n"
9204 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
9207 "built-in shell (ash)"
9221 setinteractive(iflag);
9223 #if ENABLE_FEATURE_EDITING_VI
9225 line_input_state->flags |= VI_MODE;
9227 line_input_state->flags &= ~VI_MODE;
9229 viflag = 0; /* forcibly keep the option off */
9233 struct localvar_list {
9234 struct localvar_list *next;
9235 struct localvar *lv;
9238 static struct localvar_list *localvar_stack;
9241 * Called after a function returns.
9242 * Interrupts must be off.
9245 poplocalvars(int keep)
9247 struct localvar_list *ll;
9248 struct localvar *lvp, *next;
9252 ll = localvar_stack;
9253 localvar_stack = ll->next;
9258 while ((lvp = next) != NULL) {
9261 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9263 int bits = VSTRFIXED;
9265 if (lvp->flags != VUNSET) {
9266 if (vp->var_text == lvp->text)
9268 else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
9269 free((char*)lvp->text);
9273 vp->flags |= (lvp->flags & bits);
9276 (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
9277 unsetvar(vp->var_text);
9278 } else if (vp == NULL) { /* $- saved */
9279 memcpy(optlist, lvp->text, sizeof(optlist));
9280 free((char*)lvp->text);
9282 } else if (lvp->flags == VUNSET) {
9283 vp->flags &= ~(VSTRFIXED|VREADONLY);
9284 unsetvar(vp->var_text);
9287 vp->var_func(var_end(lvp->text));
9288 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9289 free((char*)vp->var_text);
9290 vp->flags = lvp->flags;
9291 vp->var_text = lvp->text;
9299 * Create a new localvar environment.
9301 static struct localvar_list *
9304 struct localvar_list *ll;
9307 ll = ckzalloc(sizeof(*ll));
9308 /*ll->lv = NULL; - zalloc did it */
9309 ll->next = localvar_stack;
9310 localvar_stack = ll;
9317 unwindlocalvars(struct localvar_list *stop)
9319 while (localvar_stack != stop)
9324 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9326 volatile struct shparam saveparam;
9327 struct jmploc *volatile savehandler;
9328 struct jmploc jmploc;
9331 saveparam = shellparam;
9332 savehandler = exception_handler;
9333 e = setjmp(jmploc.loc);
9338 exception_handler = &jmploc;
9339 shellparam.malloced = 0;
9343 shellparam.nparam = argc - 1;
9344 shellparam.p = argv + 1;
9345 #if ENABLE_ASH_GETOPTS
9346 shellparam.optind = 1;
9347 shellparam.optoff = -1;
9350 evaltree(func->n.narg.next, flags & EV_TESTED);
9356 freeparam(&shellparam);
9357 shellparam = saveparam;
9358 exception_handler = savehandler;
9360 evalskip &= ~SKIPFUNC;
9365 * Make a variable a local variable. When a variable is made local, it's
9366 * value and flags are saved in a localvar structure. The saved values
9367 * will be restored when the shell function returns. We handle the name
9368 * "-" as a special case: it makes changes to "set +-options" local
9369 * (options will be restored on return from the function).
9374 struct localvar *lvp;
9377 char *eq = strchr(name, '=');
9380 /* Cater for duplicate "local". Examples:
9381 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9382 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9384 lvp = localvar_stack->lv;
9386 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9390 * it's a duplicate "local VAR" declaration, do nothing
9397 lvp = ckzalloc(sizeof(*lvp));
9398 if (LONE_DASH(name)) {
9400 p = ckmalloc(sizeof(optlist));
9401 lvp->text = memcpy(p, optlist, sizeof(optlist));
9404 vpp = hashvar(name);
9405 vp = *findvar(vpp, name);
9407 /* variable did not exist yet */
9409 vp = setvareq(name, VSTRFIXED);
9411 vp = setvar(name, NULL, VSTRFIXED);
9412 lvp->flags = VUNSET;
9414 lvp->text = vp->var_text;
9415 lvp->flags = vp->flags;
9416 /* make sure neither "struct var" nor string gets freed
9417 * during (un)setting:
9419 vp->flags |= VSTRFIXED|VTEXTFIXED;
9423 /* "local VAR" unsets VAR: */
9424 setvar0(name, NULL);
9428 lvp->next = localvar_stack->lv;
9429 localvar_stack->lv = lvp;
9435 * The "local" command.
9437 static int FAST_FUNC
9438 localcmd(int argc UNUSED_PARAM, char **argv)
9442 if (!localvar_stack)
9443 ash_msg_and_raise_error("not in a function");
9446 while ((name = *argv++) != NULL) {
9452 static int FAST_FUNC
9453 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9458 static int FAST_FUNC
9459 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9464 static int FAST_FUNC
9465 execcmd(int argc UNUSED_PARAM, char **argv)
9468 while (nextopt("a:") != '\0')
9469 /* nextopt() sets optionarg to "-a ARGV0" */;
9475 iflag = 0; /* exit on error */
9478 /* We should set up signals for "exec CMD"
9479 * the same way as for "CMD" without "exec".
9480 * But optschanged->setinteractive->setsignal
9481 * still thought we are a root shell. Therefore, for example,
9482 * SIGQUIT is still set to IGN. Fix it:
9486 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9487 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9488 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9492 argv[0] = optionarg;
9493 shellexec(prog, argv, pathval(), 0);
9500 * The return command.
9502 static int FAST_FUNC
9503 returncmd(int argc UNUSED_PARAM, char **argv)
9506 * If called outside a function, do what ksh does;
9507 * skip the rest of the file.
9509 evalskip = SKIPFUNC;
9510 return argv[1] ? number(argv[1]) : exitstatus;
9513 /* Forward declarations for builtintab[] */
9514 static int breakcmd(int, char **) FAST_FUNC;
9515 static int dotcmd(int, char **) FAST_FUNC;
9516 static int evalcmd(int, char **, int) FAST_FUNC;
9517 static int exitcmd(int, char **) FAST_FUNC;
9518 static int exportcmd(int, char **) FAST_FUNC;
9519 #if ENABLE_ASH_GETOPTS
9520 static int getoptscmd(int, char **) FAST_FUNC;
9523 static int helpcmd(int, char **) FAST_FUNC;
9526 static int historycmd(int, char **) FAST_FUNC;
9528 #if ENABLE_FEATURE_SH_MATH
9529 static int letcmd(int, char **) FAST_FUNC;
9531 static int readcmd(int, char **) FAST_FUNC;
9532 static int setcmd(int, char **) FAST_FUNC;
9533 static int shiftcmd(int, char **) FAST_FUNC;
9534 static int timescmd(int, char **) FAST_FUNC;
9535 static int trapcmd(int, char **) FAST_FUNC;
9536 static int umaskcmd(int, char **) FAST_FUNC;
9537 static int unsetcmd(int, char **) FAST_FUNC;
9538 static int ulimitcmd(int, char **) FAST_FUNC;
9540 #define BUILTIN_NOSPEC "0"
9541 #define BUILTIN_SPECIAL "1"
9542 #define BUILTIN_REGULAR "2"
9543 #define BUILTIN_SPEC_REG "3"
9544 #define BUILTIN_ASSIGN "4"
9545 #define BUILTIN_SPEC_ASSG "5"
9546 #define BUILTIN_REG_ASSG "6"
9547 #define BUILTIN_SPEC_REG_ASSG "7"
9549 /* Stubs for calling non-FAST_FUNC's */
9551 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9553 #if ENABLE_ASH_PRINTF
9554 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9556 #if ENABLE_ASH_TEST || BASH_TEST2
9557 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9560 /* Keep these in proper order since it is searched via bsearch() */
9561 static const struct builtincmd builtintab[] = {
9562 { BUILTIN_SPEC_REG "." , dotcmd },
9563 { BUILTIN_SPEC_REG ":" , truecmd },
9565 { BUILTIN_REGULAR "[" , testcmd },
9568 { BUILTIN_REGULAR "[[" , testcmd },
9570 #if ENABLE_ASH_ALIAS
9571 { BUILTIN_REG_ASSG "alias" , aliascmd },
9574 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9576 { BUILTIN_SPEC_REG "break" , breakcmd },
9577 { BUILTIN_REGULAR "cd" , cdcmd },
9578 { BUILTIN_NOSPEC "chdir" , cdcmd },
9579 #if ENABLE_ASH_CMDCMD
9580 { BUILTIN_REGULAR "command" , commandcmd },
9582 { BUILTIN_SPEC_REG "continue", breakcmd },
9584 { BUILTIN_REGULAR "echo" , echocmd },
9586 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9587 { BUILTIN_SPEC_REG "exec" , execcmd },
9588 { BUILTIN_SPEC_REG "exit" , exitcmd },
9589 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9590 { BUILTIN_REGULAR "false" , falsecmd },
9592 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9594 #if ENABLE_ASH_GETOPTS
9595 { BUILTIN_REGULAR "getopts" , getoptscmd },
9597 { BUILTIN_NOSPEC "hash" , hashcmd },
9599 { BUILTIN_NOSPEC "help" , helpcmd },
9602 { BUILTIN_NOSPEC "history" , historycmd },
9605 { BUILTIN_REGULAR "jobs" , jobscmd },
9606 { BUILTIN_REGULAR "kill" , killcmd },
9608 #if ENABLE_FEATURE_SH_MATH
9609 { BUILTIN_NOSPEC "let" , letcmd },
9611 { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
9612 #if ENABLE_ASH_PRINTF
9613 { BUILTIN_REGULAR "printf" , printfcmd },
9615 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9616 { BUILTIN_REGULAR "read" , readcmd },
9617 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9618 { BUILTIN_SPEC_REG "return" , returncmd },
9619 { BUILTIN_SPEC_REG "set" , setcmd },
9620 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9622 { BUILTIN_SPEC_REG "source" , dotcmd },
9625 { BUILTIN_REGULAR "test" , testcmd },
9627 { BUILTIN_SPEC_REG "times" , timescmd },
9628 { BUILTIN_SPEC_REG "trap" , trapcmd },
9629 { BUILTIN_REGULAR "true" , truecmd },
9630 { BUILTIN_NOSPEC "type" , typecmd },
9631 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9632 { BUILTIN_REGULAR "umask" , umaskcmd },
9633 #if ENABLE_ASH_ALIAS
9634 { BUILTIN_REGULAR "unalias" , unaliascmd },
9636 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9637 { BUILTIN_REGULAR "wait" , waitcmd },
9640 /* Should match the above table! */
9641 #define COMMANDCMD (builtintab + \
9643 /* [ */ 1 * ENABLE_ASH_TEST + \
9644 /* [[ */ 1 * BASH_TEST2 + \
9645 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9646 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9647 /* break cd cddir */ 3)
9648 #define EVALCMD (COMMANDCMD + \
9649 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9650 /* continue */ 1 + \
9651 /* echo */ 1 * ENABLE_ASH_ECHO + \
9653 #define EXECCMD (EVALCMD + \
9657 * Search the table of builtin commands.
9660 pstrcmp1(const void *a, const void *b)
9662 return strcmp((char*)a, *(char**)b + 1);
9664 static struct builtincmd *
9665 find_builtin(const char *name)
9667 struct builtincmd *bp;
9670 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9677 * Execute a simple command.
9680 isassignment(const char *p)
9682 const char *q = endofname(p);
9687 static int FAST_FUNC
9688 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9690 /* Preserve exitstatus of a previous possible redirection
9691 * as POSIX mandates */
9692 return back_exitstatus;
9695 evalcommand(union node *cmd, int flags)
9697 static const struct builtincmd null_bltin = {
9698 "\0\0", bltincmd /* why three NULs? */
9700 struct localvar_list *localvar_stop;
9701 struct redirtab *redir_stop;
9702 struct stackmark smark;
9704 struct arglist arglist;
9705 struct arglist varlist;
9708 const struct strlist *sp;
9709 struct cmdentry cmdentry;
9716 smallint cmd_is_exec;
9718 /* First expand the arguments. */
9719 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9720 setstackmark(&smark);
9721 localvar_stop = pushlocalvars();
9722 back_exitstatus = 0;
9724 cmdentry.cmdtype = CMDBUILTIN;
9725 cmdentry.u.cmd = &null_bltin;
9726 varlist.lastp = &varlist.list;
9727 *varlist.lastp = NULL;
9728 arglist.lastp = &arglist.list;
9729 *arglist.lastp = NULL;
9732 if (cmd->ncmd.args) {
9733 struct builtincmd *bcmd;
9734 smallint pseudovarflag;
9736 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9737 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9739 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9740 struct strlist **spp;
9742 spp = arglist.lastp;
9743 if (pseudovarflag && isassignment(argp->narg.text))
9744 expandarg(argp, &arglist, EXP_VARTILDE);
9746 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9748 for (sp = *spp; sp; sp = sp->next)
9753 /* Reserve one extra spot at the front for shellexec. */
9754 nargv = stalloc(sizeof(char *) * (argc + 2));
9756 for (sp = arglist.list; sp; sp = sp->next) {
9757 TRACE(("evalcommand arg: %s\n", sp->text));
9758 *nargv++ = sp->text;
9763 if (iflag && funcnest == 0 && argc > 0)
9764 lastarg = nargv[-1];
9766 expredir(cmd->ncmd.redirect);
9767 redir_stop = pushredir(cmd->ncmd.redirect);
9769 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9771 path = vpath.var_text;
9772 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9773 struct strlist **spp;
9776 spp = varlist.lastp;
9777 expandarg(argp, &varlist, EXP_VARTILDE);
9779 mklocal((*spp)->text);
9782 * Modify the command lookup path, if a PATH= assignment
9786 if (varcmp(p, path) == 0)
9790 /* Print the command if xflag is set. */
9792 const char *pfx = "";
9794 fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
9798 char *varval = sp->text;
9799 char *eq = strchrnul(varval, '=');
9802 fdprintf(preverrout_fd, "%s%.*s%s",
9804 (int)(eq - varval), varval,
9805 maybe_single_quote(eq)
9813 fdprintf(preverrout_fd, "%s%s",
9815 /* always quote if matches reserved word: */
9817 ? single_quote(sp->text)
9818 : maybe_single_quote(sp->text)
9823 safe_write(preverrout_fd, "\n", 1);
9829 /* Now locate the command. */
9831 int cmd_flag = DO_ERR;
9832 #if ENABLE_ASH_CMDCMD
9833 const char *oldpath = path + 5;
9837 find_command(argv[0], &cmdentry, cmd_flag, path);
9838 if (cmdentry.cmdtype == CMDUNKNOWN) {
9839 flush_stdout_stderr();
9844 /* implement bltin and command here */
9845 if (cmdentry.cmdtype != CMDBUILTIN)
9848 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9849 if (cmdentry.u.cmd == EXECCMD)
9851 #if ENABLE_ASH_CMDCMD
9852 if (cmdentry.u.cmd == COMMANDCMD) {
9854 nargv = parse_command_args(argv, &path);
9857 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9858 * nargv => "PROG". path is updated if -p.
9860 argc -= nargv - argv;
9862 cmd_flag |= DO_NOFUNC;
9871 exitstatus = status;
9873 /* We have a redirection error. */
9875 raise_exception(EXERROR);
9880 /* Execute the command. */
9881 switch (cmdentry.cmdtype) {
9884 #if ENABLE_FEATURE_SH_NOFORK
9885 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9886 * around run_nofork_applet() call.
9887 * (2) Should this check also be done in forkshell()?
9888 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9890 /* find_command() encodes applet_no as (-2 - applet_no) */
9891 int applet_no = (- cmdentry.u.index - 2);
9892 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9893 listsetvar(varlist.list, VEXPORT|VSTACK);
9894 /* run <applet>_main() */
9895 status = run_nofork_applet(applet_no, argv);
9899 /* Can we avoid forking off? For example, very last command
9900 * in a script or a subshell does not need forking,
9901 * we can just exec it.
9903 if (!(flags & EV_EXIT) || may_have_traps) {
9904 /* No, forking off a child is necessary */
9907 jp = makejob(/*cmd,*/ 1);
9908 if (forkshell(jp, cmd, FORK_FG) != 0) {
9910 status = waitforjob(jp);
9912 TRACE(("forked child exited with %d\n", status));
9917 /* fall through to exec'ing external program */
9919 listsetvar(varlist.list, VEXPORT|VSTACK);
9920 shellexec(argv[0], argv, path, cmdentry.u.index);
9924 if (spclbltin > 0 || argc == 0) {
9926 if (cmd_is_exec && argc > 1)
9927 listsetvar(varlist.list, VEXPORT);
9930 /* Tight loop with builtins only:
9931 * "while kill -0 $child; do true; done"
9932 * will never exit even if $child died, unless we do this
9933 * to reap the zombie and make kill detect that it's gone: */
9934 dowait(DOWAIT_NONBLOCK, NULL);
9936 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
9937 if (exception_type == EXERROR && spclbltin <= 0) {
9942 longjmp(exception_handler->loc, 1);
9948 /* See above for the rationale */
9949 dowait(DOWAIT_NONBLOCK, NULL);
9950 if (evalfun(cmdentry.u.func, argc, argv, flags))
9953 status = exitstatus;
9958 if (cmd->ncmd.redirect)
9959 popredir(/*drop:*/ cmd_is_exec);
9960 unwindredir(redir_stop);
9961 unwindlocalvars(localvar_stop);
9963 /* dsl: I think this is intended to be used to support
9964 * '_' in 'vi' command mode during line editing...
9965 * However I implemented that within libedit itself.
9967 setvar0("_", lastarg);
9969 popstackmark(&smark);
9975 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
9977 char *volatile savecmdname;
9978 struct jmploc *volatile savehandler;
9979 struct jmploc jmploc;
9983 savecmdname = commandname;
9984 savehandler = exception_handler;
9985 i = setjmp(jmploc.loc);
9988 exception_handler = &jmploc;
9989 commandname = argv[0];
9991 optptr = NULL; /* initialize nextopt */
9993 status = evalcmd(argc, argv, flags);
9995 status = (*cmd->builtin)(argc, argv);
9996 flush_stdout_stderr();
9997 status |= ferror(stdout);
9998 exitstatus = status;
10001 commandname = savecmdname;
10002 exception_handler = savehandler;
10008 goodname(const char *p)
10010 return endofname(p)[0] == '\0';
10015 * Search for a command. This is called before we fork so that the
10016 * location of the command will be available in the parent as well as
10017 * the child. The check for "goodname" is an overly conservative
10018 * check that the name will not be subject to expansion.
10021 prehash(union node *n)
10023 struct cmdentry entry;
10025 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
10026 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
10030 /* ============ Builtin commands
10032 * Builtin commands whose functions are closely tied to evaluation
10033 * are implemented here.
10037 * Handle break and continue commands. Break, continue, and return are
10038 * all handled by setting the evalskip flag. The evaluation routines
10039 * above all check this flag, and if it is set they start skipping
10040 * commands rather than executing them. The variable skipcount is
10041 * the number of loops to break/continue, or the number of function
10042 * levels to return. (The latter is always 1.) It should probably
10043 * be an error to break out of more loops than exist, but it isn't
10044 * in the standard shell so we don't make it one here.
10046 static int FAST_FUNC
10047 breakcmd(int argc UNUSED_PARAM, char **argv)
10049 int n = argv[1] ? number(argv[1]) : 1;
10052 ash_msg_and_raise_error(msg_illnum, argv[1]);
10056 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
10064 * This implements the input routines used by the parser.
10068 INPUT_PUSH_FILE = 1,
10069 INPUT_NOFILE_OK = 2,
10072 static smallint checkkwd;
10073 /* values of checkkwd variable */
10074 #define CHKALIAS 0x1
10077 #define CHKEOFMARK 0x8
10080 * Push a string back onto the input at this current parsefile level.
10081 * We handle aliases this way.
10083 #if !ENABLE_ASH_ALIAS
10084 #define pushstring(s, ap) pushstring(s)
10087 pushstring(char *s, struct alias *ap)
10089 struct strpush *sp;
10094 if (g_parsefile->strpush) {
10095 sp = ckzalloc(sizeof(*sp));
10096 sp->prev = g_parsefile->strpush;
10098 sp = &(g_parsefile->basestrpush);
10100 g_parsefile->strpush = sp;
10101 sp->prev_string = g_parsefile->next_to_pgetc;
10102 sp->prev_left_in_line = g_parsefile->left_in_line;
10103 sp->unget = g_parsefile->unget;
10104 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
10105 #if ENABLE_ASH_ALIAS
10108 ap->flag |= ALIASINUSE;
10112 g_parsefile->next_to_pgetc = s;
10113 g_parsefile->left_in_line = len;
10114 g_parsefile->unget = 0;
10121 struct strpush *sp = g_parsefile->strpush;
10124 #if ENABLE_ASH_ALIAS
10126 if (g_parsefile->next_to_pgetc[-1] == ' '
10127 || g_parsefile->next_to_pgetc[-1] == '\t'
10129 checkkwd |= CHKALIAS;
10131 if (sp->string != sp->ap->val) {
10134 sp->ap->flag &= ~ALIASINUSE;
10135 if (sp->ap->flag & ALIASDEAD) {
10136 unalias(sp->ap->name);
10140 g_parsefile->next_to_pgetc = sp->prev_string;
10141 g_parsefile->left_in_line = sp->prev_left_in_line;
10142 g_parsefile->unget = sp->unget;
10143 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
10144 g_parsefile->strpush = sp->prev;
10145 if (sp != &(g_parsefile->basestrpush))
10154 char *buf = g_parsefile->buf;
10156 g_parsefile->next_to_pgetc = buf;
10157 #if ENABLE_FEATURE_EDITING
10159 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
10160 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10163 # if ENABLE_ASH_IDLE_TIMEOUT
10165 const char *tmout_var = lookupvar("TMOUT");
10167 timeout = atoi(tmout_var) * 1000;
10173 # if ENABLE_FEATURE_TAB_COMPLETION
10174 line_input_state->path_lookup = pathval();
10176 reinit_unicode_for_ash();
10177 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
10179 /* ^C pressed, "convert" to SIGINT */
10180 write(STDOUT_FILENO, "^C", 2);
10181 if (trap[SIGINT]) {
10187 exitstatus = 128 + SIGINT;
10193 /* Ctrl+D pressed */
10196 # if ENABLE_ASH_IDLE_TIMEOUT
10197 else if (errno == EAGAIN && timeout > 0) {
10198 puts("\007timed out waiting for input: auto-logout");
10205 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10208 #if 0 /* disabled: nonblock_immune_read() handles this problem */
10210 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
10211 int flags = fcntl(0, F_GETFL);
10212 if (flags >= 0 && (flags & O_NONBLOCK)) {
10213 flags &= ~O_NONBLOCK;
10214 if (fcntl(0, F_SETFL, flags) >= 0) {
10215 out2str("sh: turning off NDELAY mode\n");
10226 * Refill the input buffer and return the next input character:
10228 * 1) If a string was pushed back on the input, pop it;
10229 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
10230 * or we are reading from a string so we can't refill the buffer,
10232 * 3) If there is more stuff in this buffer, use it else call read to fill it.
10233 * 4) Process input up to the next newline, deleting nul characters.
10235 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
10236 #define pgetc_debug(...) ((void)0)
10237 static int pgetc(void);
10244 if (g_parsefile->strpush) {
10245 #if ENABLE_ASH_ALIAS
10246 if (g_parsefile->left_in_line == -1
10247 && g_parsefile->strpush->ap
10248 && g_parsefile->next_to_pgetc[-1] != ' '
10249 && g_parsefile->next_to_pgetc[-1] != '\t'
10251 pgetc_debug("preadbuffer PEOA");
10258 /* on both branches above g_parsefile->left_in_line < 0.
10259 * "pgetc" needs refilling.
10262 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
10263 * pungetc() may increment it a few times.
10264 * Assuming it won't increment it to less than -90.
10266 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
10267 pgetc_debug("preadbuffer PEOF1");
10268 /* even in failure keep left_in_line and next_to_pgetc
10269 * in lock step, for correct multi-layer pungetc.
10270 * left_in_line was decremented before preadbuffer(),
10271 * must inc next_to_pgetc: */
10272 g_parsefile->next_to_pgetc++;
10276 more = g_parsefile->left_in_buffer;
10278 flush_stdout_stderr();
10282 /* don't try reading again */
10283 g_parsefile->left_in_line = -99;
10284 pgetc_debug("preadbuffer PEOF2");
10285 g_parsefile->next_to_pgetc++;
10290 /* Find out where's the end of line.
10291 * Set g_parsefile->left_in_line
10292 * and g_parsefile->left_in_buffer acordingly.
10293 * NUL chars are deleted.
10295 q = g_parsefile->next_to_pgetc;
10303 memmove(q, q + 1, more);
10307 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10313 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10314 if (g_parsefile->left_in_line < 0)
10319 g_parsefile->left_in_buffer = more;
10324 out2str(g_parsefile->next_to_pgetc);
10328 pgetc_debug("preadbuffer at %d:%p'%s'",
10329 g_parsefile->left_in_line,
10330 g_parsefile->next_to_pgetc,
10331 g_parsefile->next_to_pgetc);
10332 return (unsigned char)*g_parsefile->next_to_pgetc++;
10338 g_parsefile->linno++;
10339 setprompt_if(doprompt, 2);
10344 g_parsefile->linno++;
10345 needprompt = doprompt;
10353 pgetc_debug("pgetc at %d:%p'%s'",
10354 g_parsefile->left_in_line,
10355 g_parsefile->next_to_pgetc,
10356 g_parsefile->next_to_pgetc);
10357 if (g_parsefile->unget)
10358 return g_parsefile->lastc[--g_parsefile->unget];
10360 if (--g_parsefile->left_in_line >= 0)
10361 c = (unsigned char)*g_parsefile->next_to_pgetc++;
10365 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10366 g_parsefile->lastc[0] = c;
10371 #if ENABLE_ASH_ALIAS
10373 pgetc_without_PEOA(void)
10377 pgetc_debug("pgetc at %d:%p'%s'",
10378 g_parsefile->left_in_line,
10379 g_parsefile->next_to_pgetc,
10380 g_parsefile->next_to_pgetc);
10382 } while (c == PEOA);
10386 # define pgetc_without_PEOA() pgetc()
10390 * Undo a call to pgetc. Only two characters may be pushed back.
10391 * PEOF may be pushed back.
10396 g_parsefile->unget++;
10399 /* This one eats backslash+newline */
10405 while ((c = pgetc()) == '\\') {
10406 if (pgetc() != '\n') {
10418 * To handle the "." command, a stack of input files is used. Pushfile
10419 * adds a new entry to the stack and popfile restores the previous level.
10424 struct parsefile *pf;
10426 pf = ckzalloc(sizeof(*pf));
10427 pf->prev = g_parsefile;
10429 /*pf->strpush = NULL; - ckzalloc did it */
10430 /*pf->basestrpush.prev = NULL;*/
10438 struct parsefile *pf = g_parsefile;
10444 if (pf->pf_fd >= 0)
10447 while (pf->strpush)
10449 g_parsefile = pf->prev;
10455 * Return to top level.
10460 while (g_parsefile != &basepf)
10465 * Close the file(s) that the shell is reading commands from. Called
10466 * after a fork is done.
10472 if (g_parsefile->pf_fd > 0) {
10473 close(g_parsefile->pf_fd);
10474 g_parsefile->pf_fd = 0;
10479 * Like setinputfile, but takes an open file descriptor. Call this with
10483 setinputfd(int fd, int push)
10487 g_parsefile->buf = NULL;
10489 g_parsefile->pf_fd = fd;
10490 if (g_parsefile->buf == NULL)
10491 g_parsefile->buf = ckmalloc(IBUFSIZ);
10492 g_parsefile->left_in_buffer = 0;
10493 g_parsefile->left_in_line = 0;
10494 g_parsefile->linno = 1;
10498 * Set the input to take input from a file. If push is set, push the
10499 * old input onto the stack first.
10502 setinputfile(const char *fname, int flags)
10507 fd = open(fname, O_RDONLY);
10509 if (flags & INPUT_NOFILE_OK)
10512 ash_msg_and_raise_error("can't open '%s'", fname);
10517 close_on_exec_on(fd);
10518 setinputfd(fd, flags & INPUT_PUSH_FILE);
10525 * Like setinputfile, but takes input from a string.
10528 setinputstring(char *string)
10532 g_parsefile->next_to_pgetc = string;
10533 g_parsefile->left_in_line = strlen(string);
10534 g_parsefile->buf = NULL;
10535 g_parsefile->linno = 1;
10541 * Routines to check for mail.
10544 #if ENABLE_ASH_MAIL
10546 /* Hash of mtimes of mailboxes */
10547 static unsigned mailtime_hash;
10548 /* Set if MAIL or MAILPATH is changed. */
10549 static smallint mail_var_path_changed;
10552 * Print appropriate message(s) if mail has arrived.
10553 * If mail_var_path_changed is set,
10554 * then the value of MAIL has mail_var_path_changed,
10555 * so we just update the values.
10564 struct stackmark smark;
10567 setstackmark(&smark);
10568 mpath = mpathset() ? mpathval() : mailval();
10571 p = path_advance(&mpath, nullstr);
10576 for (q = p; *q; q++)
10582 q[-1] = '\0'; /* delete trailing '/' */
10583 if (stat(p, &statb) < 0) {
10586 /* Very simplistic "hash": just a sum of all mtimes */
10587 new_hash += (unsigned)statb.st_mtime;
10589 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10590 if (mailtime_hash != 0)
10591 out2str("you have mail\n");
10592 mailtime_hash = new_hash;
10594 mail_var_path_changed = 0;
10595 popstackmark(&smark);
10598 static void FAST_FUNC
10599 changemail(const char *val UNUSED_PARAM)
10601 mail_var_path_changed = 1;
10604 #endif /* ASH_MAIL */
10607 /* ============ ??? */
10610 * Set the shell parameters.
10613 setparam(char **argv)
10619 for (nparam = 0; argv[nparam]; nparam++)
10621 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10623 *ap++ = ckstrdup(*argv++);
10626 freeparam(&shellparam);
10627 shellparam.malloced = 1;
10628 shellparam.nparam = nparam;
10629 shellparam.p = newparam;
10630 #if ENABLE_ASH_GETOPTS
10631 shellparam.optind = 1;
10632 shellparam.optoff = -1;
10637 * Process shell options. The global variable argptr contains a pointer
10638 * to the argument list; we advance it past the options.
10640 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10641 * For a non-interactive shell, an error condition encountered
10642 * by a special built-in ... shall cause the shell to write a diagnostic message
10643 * to standard error and exit as shown in the following table:
10644 * Error Special Built-In
10646 * Utility syntax error (option or operand error) Shall exit
10648 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10649 * we see that bash does not do that (set "finishes" with error code 1 instead,
10650 * and shell continues), and people rely on this behavior!
10652 * set -o barfoo 2>/dev/null
10655 * Oh well. Let's mimic that.
10658 plus_minus_o(char *name, int val)
10663 for (i = 0; i < NOPTS; i++) {
10664 if (strcmp(name, optnames(i)) == 0) {
10669 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10672 for (i = 0; i < NOPTS; i++) {
10674 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10676 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10682 setoption(int flag, int val)
10686 for (i = 0; i < NOPTS; i++) {
10687 if (optletters(i) == flag) {
10692 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10696 options(int cmdline)
10704 while ((p = *argptr) != NULL) {
10706 if (c != '-' && c != '+')
10709 val = 0; /* val = 0 if c == '+' */
10712 if (p[0] == '\0' || LONE_DASH(p)) {
10714 /* "-" means turn off -x and -v */
10717 /* "--" means reset params */
10718 else if (*argptr == NULL)
10721 break; /* "-" or "--" terminates options */
10724 /* first char was + or - */
10725 while ((c = *p++) != '\0') {
10726 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10727 if (c == 'c' && cmdline) {
10728 minusc = p; /* command is after shell args */
10729 } else if (c == 'o') {
10730 if (plus_minus_o(*argptr, val)) {
10731 /* it already printed err message */
10732 return 1; /* error */
10736 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10738 /* bash does not accept +-login, we also won't */
10739 } else if (cmdline && val && (c == '-')) { /* long options */
10740 if (strcmp(p, "login") == 0)
10752 * The shift builtin command.
10754 static int FAST_FUNC
10755 shiftcmd(int argc UNUSED_PARAM, char **argv)
10762 n = number(argv[1]);
10763 if (n > shellparam.nparam)
10764 n = 0; /* bash compat, was = shellparam.nparam; */
10766 shellparam.nparam -= n;
10767 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10768 if (shellparam.malloced)
10771 ap2 = shellparam.p;
10772 while ((*ap2++ = *ap1++) != NULL)
10774 #if ENABLE_ASH_GETOPTS
10775 shellparam.optind = 1;
10776 shellparam.optoff = -1;
10783 * POSIX requires that 'set' (but not export or readonly) output the
10784 * variables in lexicographic order - by the locale's collating order (sigh).
10785 * Maybe we could keep them in an ordered balanced binary tree
10786 * instead of hashed lists.
10787 * For now just roll 'em through qsort for printing...
10790 showvars(const char *sep_prefix, int on, int off)
10793 char **ep, **epend;
10795 ep = listvars(on, off, &epend);
10796 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10798 sep = *sep_prefix ? " " : sep_prefix;
10800 for (; ep < epend; ep++) {
10804 p = strchrnul(*ep, '=');
10807 q = single_quote(++p);
10808 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10814 * The set command builtin.
10816 static int FAST_FUNC
10817 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10822 return showvars(nullstr, 0, VUNSET);
10825 retval = options(/*cmdline:*/ 0);
10826 if (retval == 0) { /* if no parse error... */
10828 if (*argptr != NULL) {
10836 #if ENABLE_ASH_RANDOM_SUPPORT
10837 static void FAST_FUNC
10838 change_random(const char *value)
10842 if (value == NULL) {
10843 /* "get", generate */
10844 t = next_random(&random_gen);
10845 /* set without recursion */
10846 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10847 vrandom.flags &= ~VNOFUNC;
10850 t = strtoul(value, NULL, 10);
10851 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10856 #if ENABLE_ASH_GETOPTS
10858 getopts(char *optstr, char *optvar, char **optfirst)
10865 int ind = shellparam.optind;
10866 int off = shellparam.optoff;
10870 shellparam.optind = -1;
10871 optnext = optfirst + ind - 1;
10873 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
10876 p = optnext[-1] + off;
10877 if (p == NULL || *p == '\0') {
10878 /* Current word is done, advance */
10880 if (p == NULL || *p != '-' || *++p == '\0') {
10887 if (LONE_DASH(p)) /* check for "--" */
10892 for (q = optstr; *q != c;) {
10894 if (optstr[0] == ':') {
10896 /*sbuf[1] = '\0'; - already is */
10897 setvar0("OPTARG", sbuf);
10899 fprintf(stderr, "Illegal option -%c\n", c);
10900 unsetvar("OPTARG");
10910 if (*p == '\0' && (p = *optnext) == NULL) {
10911 if (optstr[0] == ':') {
10913 /*sbuf[1] = '\0'; - already is */
10914 setvar0("OPTARG", sbuf);
10917 fprintf(stderr, "No arg for -%c option\n", c);
10918 unsetvar("OPTARG");
10926 setvar0("OPTARG", p);
10929 setvar0("OPTARG", nullstr);
10931 ind = optnext - optfirst + 1;
10932 setvar("OPTIND", itoa(ind), VNOFUNC);
10934 /*sbuf[1] = '\0'; - already is */
10935 setvar0(optvar, sbuf);
10937 shellparam.optoff = p ? p - *(optnext - 1) : -1;
10938 shellparam.optind = ind;
10944 * The getopts builtin. Shellparam.optnext points to the next argument
10945 * to be processed. Shellparam.optptr points to the next character to
10946 * be processed in the current argument. If shellparam.optnext is NULL,
10947 * then it's the first time getopts has been called.
10949 static int FAST_FUNC
10950 getoptscmd(int argc, char **argv)
10955 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10957 optbase = shellparam.p;
10958 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
10959 shellparam.optind = 1;
10960 shellparam.optoff = -1;
10963 optbase = &argv[3];
10964 if ((unsigned)shellparam.optind > argc - 2) {
10965 shellparam.optind = 1;
10966 shellparam.optoff = -1;
10970 return getopts(argv[1], argv[2], optbase);
10972 #endif /* ASH_GETOPTS */
10975 /* ============ Shell parser */
10978 struct heredoc *next; /* next here document in list */
10979 union node *here; /* redirection node */
10980 char *eofmark; /* string indicating end of input */
10981 smallint striptabs; /* if set, strip leading tabs */
10984 static smallint tokpushback; /* last token pushed back */
10985 static smallint quoteflag; /* set if (part of) last token was quoted */
10986 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10987 static struct heredoc *heredoclist; /* list of here documents to read */
10988 static char *wordtext; /* text of last word returned by readtoken */
10989 static struct nodelist *backquotelist;
10990 static union node *redirnode;
10991 static struct heredoc *heredoc;
10993 static const char *
10994 tokname(char *buf, int tok)
10997 return tokname_array[tok];
10998 sprintf(buf, "\"%s\"", tokname_array[tok]);
11002 /* raise_error_unexpected_syntax:
11003 * Called when an unexpected token is read during the parse. The argument
11004 * is the token that is expected, or -1 if more than one type of token can
11005 * occur at this point.
11007 static void raise_error_unexpected_syntax(int) NORETURN;
11009 raise_error_unexpected_syntax(int token)
11015 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
11017 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
11018 raise_error_syntax(msg);
11022 /* parsing is heavily cross-recursive, need these forward decls */
11023 static union node *andor(void);
11024 static union node *pipeline(void);
11025 static union node *parse_command(void);
11026 static void parseheredoc(void);
11027 static int peektoken(void);
11028 static int readtoken(void);
11030 static union node *
11033 union node *n1, *n2, *n3;
11038 switch (peektoken()) {
11046 if (!n1 && (nlflag & 1))
11052 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11053 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
11059 if (tok == TBACKGND) {
11060 if (n2->type == NPIPE) {
11061 n2->npipe.pipe_backgnd = 1;
11063 if (n2->type != NREDIR) {
11064 n3 = stzalloc(sizeof(struct nredir));
11066 /*n3->nredir.redirect = NULL; - stzalloc did it */
11069 n2->type = NBACKGND;
11075 n3 = stzalloc(sizeof(struct nbinary));
11077 n3->nbinary.ch1 = n1;
11078 n3->nbinary.ch2 = n2;
11091 raise_error_unexpected_syntax(-1);
11098 static union node *
11101 union node *n1, *n2, *n3;
11109 } else if (t == TOR) {
11115 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11117 n3 = stzalloc(sizeof(struct nbinary));
11119 n3->nbinary.ch1 = n1;
11120 n3->nbinary.ch2 = n2;
11125 static union node *
11128 union node *n1, *n2, *pipenode;
11129 struct nodelist *lp, *prev;
11133 TRACE(("pipeline: entered\n"));
11134 if (readtoken() == TNOT) {
11136 checkkwd = CHKKWD | CHKALIAS;
11139 n1 = parse_command();
11140 if (readtoken() == TPIPE) {
11141 pipenode = stzalloc(sizeof(struct npipe));
11142 pipenode->type = NPIPE;
11143 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
11144 lp = stzalloc(sizeof(struct nodelist));
11145 pipenode->npipe.cmdlist = lp;
11149 lp = stzalloc(sizeof(struct nodelist));
11150 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11151 lp->n = parse_command();
11153 } while (readtoken() == TPIPE);
11159 n2 = stzalloc(sizeof(struct nnot));
11167 static union node *
11172 n = stzalloc(sizeof(struct narg));
11174 /*n->narg.next = NULL; - stzalloc did it */
11175 n->narg.text = wordtext;
11176 n->narg.backquote = backquotelist;
11181 fixredir(union node *n, const char *text, int err)
11185 TRACE(("Fix redir %s %d\n", text, err));
11187 n->ndup.vname = NULL;
11189 fd = bb_strtou(text, NULL, 10);
11190 if (!errno && fd >= 0)
11191 n->ndup.dupfd = fd;
11192 else if (LONE_DASH(text))
11193 n->ndup.dupfd = -1;
11196 raise_error_syntax("bad fd number");
11197 n->ndup.vname = makename();
11204 union node *n = redirnode;
11206 if (n->type == NHERE)
11207 checkkwd = CHKEOFMARK;
11208 if (readtoken() != TWORD)
11209 raise_error_unexpected_syntax(-1);
11210 if (n->type == NHERE) {
11211 struct heredoc *here = heredoc;
11214 if (quoteflag == 0)
11216 TRACE(("Here document %d\n", n->type));
11217 rmescapes(wordtext, 0);
11218 here->eofmark = wordtext;
11220 if (heredoclist == NULL)
11221 heredoclist = here;
11223 for (p = heredoclist; p->next; p = p->next)
11227 } else if (n->type == NTOFD || n->type == NFROMFD) {
11228 fixredir(n, wordtext, 0);
11230 n->nfile.fname = makename();
11234 static union node *
11237 union node *args, **app;
11238 union node *n = NULL;
11239 union node *vars, **vpp;
11240 union node **rpp, *redir;
11243 smallint double_brackets_flag = 0;
11245 IF_BASH_FUNCTION(smallint function_flag = 0;)
11254 savecheckkwd = CHKALIAS;
11257 checkkwd = savecheckkwd;
11262 if (peektoken() != TWORD)
11263 raise_error_unexpected_syntax(TWORD);
11268 case TAND: /* "&&" */
11269 case TOR: /* "||" */
11270 if (!double_brackets_flag) {
11274 wordtext = (char *) (t == TAND ? "-a" : "-o");
11277 n = stzalloc(sizeof(struct narg));
11279 /*n->narg.next = NULL; - stzalloc did it */
11280 n->narg.text = wordtext;
11282 if (strcmp("[[", wordtext) == 0)
11283 double_brackets_flag = 1;
11284 else if (strcmp("]]", wordtext) == 0)
11285 double_brackets_flag = 0;
11287 n->narg.backquote = backquotelist;
11288 if (savecheckkwd && isassignment(wordtext)) {
11290 vpp = &n->narg.next;
11293 app = &n->narg.next;
11297 if (function_flag) {
11298 checkkwd = CHKNL | CHKKWD;
11299 switch (peektoken()) {
11311 if (strcmp("[[", wordtext) == 0)
11315 raise_error_unexpected_syntax(-1);
11321 *rpp = n = redirnode;
11322 rpp = &n->nfile.next;
11323 parsefname(); /* read name of redirection file */
11326 IF_BASH_FUNCTION(do_func:)
11327 if (args && app == &args->narg.next
11330 struct builtincmd *bcmd;
11333 /* We have a function */
11334 if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
11335 raise_error_unexpected_syntax(TRP);
11336 name = n->narg.text;
11337 if (!goodname(name)
11338 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11340 raise_error_syntax("bad function name");
11343 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11344 n->narg.next = parse_command();
11347 IF_BASH_FUNCTION(function_flag = 0;)
11358 n = stzalloc(sizeof(struct ncmd));
11360 n->ncmd.args = args;
11361 n->ncmd.assign = vars;
11362 n->ncmd.redirect = redir;
11366 static union node *
11367 parse_command(void)
11369 union node *n1, *n2;
11370 union node *ap, **app;
11371 union node *cp, **cpp;
11372 union node *redir, **rpp;
11379 switch (readtoken()) {
11381 raise_error_unexpected_syntax(-1);
11384 n1 = stzalloc(sizeof(struct nif));
11386 n1->nif.test = list(0);
11387 if (readtoken() != TTHEN)
11388 raise_error_unexpected_syntax(TTHEN);
11389 n1->nif.ifpart = list(0);
11391 while (readtoken() == TELIF) {
11392 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11393 n2 = n2->nif.elsepart;
11395 n2->nif.test = list(0);
11396 if (readtoken() != TTHEN)
11397 raise_error_unexpected_syntax(TTHEN);
11398 n2->nif.ifpart = list(0);
11400 if (lasttoken == TELSE)
11401 n2->nif.elsepart = list(0);
11403 n2->nif.elsepart = NULL;
11411 n1 = stzalloc(sizeof(struct nbinary));
11412 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11413 n1->nbinary.ch1 = list(0);
11416 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11417 got == TWORD ? wordtext : ""));
11418 raise_error_unexpected_syntax(TDO);
11420 n1->nbinary.ch2 = list(0);
11425 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11426 raise_error_syntax("bad for loop variable");
11427 n1 = stzalloc(sizeof(struct nfor));
11429 n1->nfor.var = wordtext;
11430 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11431 if (readtoken() == TIN) {
11433 while (readtoken() == TWORD) {
11434 n2 = stzalloc(sizeof(struct narg));
11436 /*n2->narg.next = NULL; - stzalloc did it */
11437 n2->narg.text = wordtext;
11438 n2->narg.backquote = backquotelist;
11440 app = &n2->narg.next;
11443 n1->nfor.args = ap;
11444 if (lasttoken != TNL && lasttoken != TSEMI)
11445 raise_error_unexpected_syntax(-1);
11447 n2 = stzalloc(sizeof(struct narg));
11449 /*n2->narg.next = NULL; - stzalloc did it */
11450 n2->narg.text = (char *)dolatstr;
11451 /*n2->narg.backquote = NULL;*/
11452 n1->nfor.args = n2;
11454 * Newline or semicolon here is optional (but note
11455 * that the original Bourne shell only allowed NL).
11457 if (lasttoken != TSEMI)
11460 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11461 if (readtoken() != TDO)
11462 raise_error_unexpected_syntax(TDO);
11463 n1->nfor.body = list(0);
11467 n1 = stzalloc(sizeof(struct ncase));
11469 if (readtoken() != TWORD)
11470 raise_error_unexpected_syntax(TWORD);
11471 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11473 /*n2->narg.next = NULL; - stzalloc did it */
11474 n2->narg.text = wordtext;
11475 n2->narg.backquote = backquotelist;
11476 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11477 if (readtoken() != TIN)
11478 raise_error_unexpected_syntax(TIN);
11479 cpp = &n1->ncase.cases;
11481 checkkwd = CHKNL | CHKKWD;
11483 while (t != TESAC) {
11484 if (lasttoken == TLP)
11486 *cpp = cp = stzalloc(sizeof(struct nclist));
11488 app = &cp->nclist.pattern;
11490 *app = ap = stzalloc(sizeof(struct narg));
11492 /*ap->narg.next = NULL; - stzalloc did it */
11493 ap->narg.text = wordtext;
11494 ap->narg.backquote = backquotelist;
11495 if (readtoken() != TPIPE)
11497 app = &ap->narg.next;
11500 //ap->narg.next = NULL;
11501 if (lasttoken != TRP)
11502 raise_error_unexpected_syntax(TRP);
11503 cp->nclist.body = list(2);
11505 cpp = &cp->nclist.next;
11507 checkkwd = CHKNL | CHKKWD;
11511 raise_error_unexpected_syntax(TENDCASE);
11518 n1 = stzalloc(sizeof(struct nredir));
11519 n1->type = NSUBSHELL;
11520 n1->nredir.n = list(0);
11521 /*n1->nredir.redirect = NULL; - stzalloc did it */
11528 IF_BASH_FUNCTION(case TFUNCTION:)
11532 return simplecmd();
11535 if (readtoken() != t)
11536 raise_error_unexpected_syntax(t);
11539 /* Now check for redirection which may follow command */
11540 checkkwd = CHKKWD | CHKALIAS;
11542 while (readtoken() == TREDIR) {
11543 *rpp = n2 = redirnode;
11544 rpp = &n2->nfile.next;
11550 if (n1->type != NSUBSHELL) {
11551 n2 = stzalloc(sizeof(struct nredir));
11556 n1->nredir.redirect = redir;
11561 #if BASH_DOLLAR_SQUOTE
11563 decode_dollar_squote(void)
11565 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11571 p = strchr(C_escapes, c);
11576 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11580 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11582 } else if (c == 'x') { /* \xHH */
11586 } while (isxdigit(c) && --cnt);
11588 if (cnt == 3) { /* \x but next char is "bad" */
11592 } else { /* simple seq like \\ or \t */
11597 c = bb_process_escape_sequence((void*)&p);
11598 } else { /* unrecognized "\z": print both chars unless ' or " */
11599 if (c != '\'' && c != '"') {
11601 c |= 0x100; /* "please encode \, then me" */
11608 /* Used by expandstr to get here-doc like behaviour. */
11609 #define FAKEEOFMARK ((char*)(uintptr_t)1)
11611 static ALWAYS_INLINE int
11612 realeofmark(const char *eofmark)
11614 return eofmark && eofmark != FAKEEOFMARK;
11618 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11619 * is not NULL, read a here document. In the latter case, eofmark is the
11620 * word which marks the end of the document and striptabs is true if
11621 * leading tabs should be stripped from the document. The argument c
11622 * is the first character of the input token or document.
11624 * Because C does not have internal subroutines, I have simulated them
11625 * using goto's to implement the subroutine linkage. The following macros
11626 * will run code that appears at the end of readtoken1.
11628 #define CHECKEND() {goto checkend; checkend_return:;}
11629 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11630 #define PARSESUB() {goto parsesub; parsesub_return:;}
11631 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11632 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11633 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11635 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11637 /* NB: syntax parameter fits into smallint */
11638 /* c parameter is an unsigned char or PEOF or PEOA */
11641 struct nodelist *bqlist;
11645 IF_FEATURE_SH_MATH(smallint prevsyntax;) /* syntax before arithmetic */
11646 smallint pssyntax; /* we are expanding a prompt string */
11647 int varnest; /* levels of variables expansion */
11648 IF_FEATURE_SH_MATH(int arinest;) /* levels of arithmetic expansion */
11649 IF_FEATURE_SH_MATH(int parenlevel;) /* levels of parens in arithmetic */
11650 int dqvarnest; /* levels of variables expansion within double quotes */
11652 IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
11654 startlinno = g_parsefile->linno;
11657 IF_FEATURE_SH_MATH(prevsyntax = 0;)
11658 #if ENABLE_ASH_EXPAND_PRMT
11659 pssyntax = (syntax == PSSYNTAX);
11663 pssyntax = 0; /* constant */
11665 dblquote = (syntax == DQSYNTAX);
11667 IF_FEATURE_SH_MATH(arinest = 0;)
11668 IF_FEATURE_SH_MATH(parenlevel = 0;)
11671 STARTSTACKSTR(out);
11673 /* For each line, until end of word */
11674 CHECKEND(); /* set c to PEOF if at end of here document */
11675 for (;;) { /* until end of line or end of word */
11676 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11677 switch (SIT(c, syntax)) {
11678 case CNL: /* '\n' */
11679 if (syntax == BASESYNTAX)
11680 goto endword; /* exit outer loop */
11684 goto loop; /* continue outer loop */
11689 #if BASH_DOLLAR_SQUOTE
11690 if (c == '\\' && bash_dollar_squote) {
11691 c = decode_dollar_squote();
11693 /* skip $'\000', $'\x00' (like bash) */
11697 /* Unknown escape. Encode as '\z' */
11698 c = (unsigned char)c;
11699 if (eofmark == NULL || dblquote)
11700 USTPUTC(CTLESC, out);
11701 USTPUTC('\\', out);
11705 if (eofmark == NULL || dblquote)
11706 USTPUTC(CTLESC, out);
11709 case CBACK: /* backslash */
11710 c = pgetc_without_PEOA();
11712 USTPUTC(CTLESC, out);
11713 USTPUTC('\\', out);
11715 } else if (c == '\n') {
11718 if (pssyntax && c == '$') {
11719 USTPUTC(CTLESC, out);
11720 USTPUTC('\\', out);
11722 /* Backslash is retained if we are in "str" and next char isn't special */
11727 && (c != '"' || eofmark != NULL)
11729 USTPUTC('\\', out);
11731 USTPUTC(CTLESC, out);
11739 if (eofmark == NULL) {
11740 USTPUTC(CTLQUOTEMARK, out);
11748 IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
11749 if (eofmark != NULL && varnest == 0) {
11752 if (dqvarnest == 0) {
11753 syntax = BASESYNTAX;
11760 case CVAR: /* '$' */
11761 PARSESUB(); /* parse substitution */
11763 case CENDVAR: /* '}' */
11766 if (dqvarnest > 0) {
11773 #if ENABLE_FEATURE_SH_MATH
11774 case CLP: /* '(' in arithmetic */
11778 case CRP: /* ')' in arithmetic */
11779 if (parenlevel > 0) {
11782 if (pgetc_eatbnl() == ')') {
11784 if (--arinest == 0) {
11785 syntax = prevsyntax;
11789 * unbalanced parens
11790 * (don't 2nd guess - no error)
11798 case CBQUOTE: /* '`' */
11802 goto endword; /* exit outer loop */
11806 if (varnest == 0) {
11807 #if BASH_REDIR_OUTPUT
11809 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11810 if (pgetc() == '>')
11811 c = 0x100 + '>'; /* flag &> */
11815 goto endword; /* exit outer loop */
11817 IF_ASH_ALIAS(if (c != PEOA))
11824 #if ENABLE_FEATURE_SH_MATH
11825 if (syntax == ARISYNTAX)
11826 raise_error_syntax("missing '))'");
11828 if (syntax != BASESYNTAX && eofmark == NULL)
11829 raise_error_syntax("unterminated quoted string");
11830 if (varnest != 0) {
11831 startlinno = g_parsefile->linno;
11833 raise_error_syntax("missing '}'");
11835 USTPUTC('\0', out);
11836 len = out - (char *)stackblock();
11837 out = stackblock();
11838 if (eofmark == NULL) {
11839 if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
11842 if (isdigit_str9(out)) {
11843 PARSEREDIR(); /* passed as params: out, c */
11844 lasttoken = TREDIR;
11847 /* else: non-number X seen, interpret it
11848 * as "NNNX>file" = "NNNX >file" */
11852 quoteflag = quotef;
11853 backquotelist = bqlist;
11854 grabstackblock(len);
11858 /* end of readtoken routine */
11861 * Check to see whether we are at the end of the here document. When this
11862 * is called, c is set to the first character of the next input line. If
11863 * we are at the end of the here document, this routine sets the c to PEOF.
11866 if (realeofmark(eofmark)) {
11870 #if ENABLE_ASH_ALIAS
11872 c = pgetc_without_PEOA();
11875 while (c == '\t') {
11876 c = pgetc_without_PEOA();
11880 markloc = out - (char *)stackblock();
11881 for (p = eofmark; STPUTC(c, out), *p; p++) {
11885 c = pgetc_without_PEOA();
11888 if (c == '\n' || c == PEOF) {
11890 g_parsefile->linno++;
11891 needprompt = doprompt;
11896 p = (char *)stackblock() + markloc + 1;
11897 len_here = out - p;
11900 len_here -= (c >= PEOF);
11906 str = alloca(len_here + 1);
11907 *(char *)mempcpy(str, p, len_here) = '\0';
11909 pushstring(str, NULL);
11914 STADJUST((char *)stackblock() + markloc - out, out);
11916 goto checkend_return;
11920 * Parse a redirection operator. The variable "out" points to a string
11921 * specifying the fd to be redirected. The variable "c" contains the
11922 * first character of the redirection operator.
11925 /* out is already checked to be a valid number or "" */
11926 int fd = (*out == '\0' ? -1 : atoi(out));
11929 np = stzalloc(sizeof(struct nfile));
11934 np->type = NAPPEND;
11936 np->type = NCLOBBER;
11939 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11945 #if BASH_REDIR_OUTPUT
11946 else if (c == 0x100 + '>') { /* this flags &> redirection */
11948 pgetc(); /* this is '>', no need to check */
11952 else { /* c == '<' */
11953 /*np->nfile.fd = 0; - stzalloc did it */
11957 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11958 np = stzalloc(sizeof(struct nhere));
11959 /*np->nfile.fd = 0; - stzalloc did it */
11962 heredoc = stzalloc(sizeof(struct heredoc));
11963 heredoc->here = np;
11966 heredoc->striptabs = 1;
11968 /*heredoc->striptabs = 0; - stzalloc did it */
11974 np->type = NFROMFD;
11978 np->type = NFROMTO;
11990 goto parseredir_return;
11994 * Parse a substitution. At this point, we have read the dollar sign
11995 * and nothing else.
11998 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11999 * (assuming ascii char codes, as the original implementation did) */
12000 #define is_special(c) \
12001 (((unsigned)(c) - 33 < 32) \
12002 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
12004 unsigned char subtype;
12007 c = pgetc_eatbnl();
12008 if ((checkkwd & CHKEOFMARK)
12009 || c > 255 /* PEOA or PEOF */
12010 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
12012 #if BASH_DOLLAR_SQUOTE
12013 if (syntax != DQSYNTAX && c == '\'')
12014 bash_dollar_squote = 1;
12019 } else if (c == '(') {
12020 /* $(command) or $((arith)) */
12021 if (pgetc_eatbnl() == '(') {
12022 #if ENABLE_FEATURE_SH_MATH
12025 raise_error_syntax("support for $((arith)) is disabled");
12032 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
12033 USTPUTC(CTLVAR, out);
12034 typeloc = out - (char *)stackblock();
12036 subtype = VSNORMAL;
12038 c = pgetc_eatbnl();
12043 /* $[{[#]]NAME[}] */
12046 c = pgetc_eatbnl();
12047 } while (is_in_name(c));
12048 } else if (isdigit(c)) {
12049 /* $[{[#]]NUM[}] */
12052 c = pgetc_eatbnl();
12053 } while (isdigit(c));
12054 } else if (is_special(c)) {
12055 /* $[{[#]]<specialchar>[}] */
12058 c = pgetc_eatbnl();
12059 if (!subtype && cc == '#') {
12060 subtype = VSLENGTH;
12061 if (c == '_' || isalnum(c))
12064 c = pgetc_eatbnl();
12065 if (cc == '}' || c != '}') {
12076 if (c != '}' && subtype == VSLENGTH) {
12077 /* ${#VAR didn't end with } */
12081 if (subtype == 0) {
12082 static const char types[] ALIGN1 = "}-+?=";
12083 /* ${VAR...} but not $VAR or ${#VAR} */
12084 /* c == first char after VAR */
12087 c = pgetc_eatbnl();
12089 /* This check is only needed to not misinterpret
12090 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
12093 if (!strchr(types, c)) {
12094 subtype = VSSUBSTR;
12096 break; /* "goto badsub" is bigger (!) */
12102 const char *p = strchr(types, c);
12105 subtype |= p - types + VSNORMAL;
12111 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
12112 c = pgetc_eatbnl();
12118 #if BASH_PATTERN_SUBST
12120 /* ${v/[/]pattern/repl} */
12121 //TODO: encode pattern and repl separately.
12122 // Currently ${v/$var_with_slash/repl} is horribly broken
12123 subtype = VSREPLACE;
12124 c = pgetc_eatbnl();
12127 subtype++; /* VSREPLACEALL */
12135 ((unsigned char *)stackblock())[typeloc] = subtype;
12136 if (subtype != VSNORMAL) {
12143 goto parsesub_return;
12147 * Called to parse command substitutions. Newstyle is set if the command
12148 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
12149 * list of commands (passed by reference), and savelen is the number of
12150 * characters on the top of the stack which must be preserved.
12153 struct nodelist **nlpp;
12157 smallint saveprompt = 0;
12160 savelen = out - (char *)stackblock();
12163 * FIXME: this can allocate very large block on stack and SEGV.
12165 * echo "..<100kbytes>..`true` $(true) `true` ..."
12166 * allocates 100kb for every command subst. With about
12167 * a hundred command substitutions stack overflows.
12168 * With larger prepended string, SEGV happens sooner.
12170 str = alloca(savelen);
12171 memcpy(str, stackblock(), savelen);
12175 /* We must read until the closing backquote, giving special
12176 * treatment to some slashes, and then push the string and
12177 * reread it as input, interpreting it normally.
12183 STARTSTACKSTR(pout);
12187 setprompt_if(needprompt, 2);
12198 * If eating a newline, avoid putting
12199 * the newline into the new character
12200 * stream (via the STPUTC after the
12205 if (pc != '\\' && pc != '`' && pc != '$'
12206 && (!dblquote || pc != '"')
12208 STPUTC('\\', pout);
12210 if (pc <= 255 /* not PEOA or PEOF */) {
12216 IF_ASH_ALIAS(case PEOA:)
12217 startlinno = g_parsefile->linno;
12218 raise_error_syntax("EOF in backquote substitution");
12230 STPUTC('\0', pout);
12231 psavelen = pout - (char *)stackblock();
12232 if (psavelen > 0) {
12233 pstr = grabstackstr(pout);
12234 setinputstring(pstr);
12239 nlpp = &(*nlpp)->next;
12240 *nlpp = stzalloc(sizeof(**nlpp));
12241 /* (*nlpp)->next = NULL; - stzalloc did it */
12244 saveprompt = doprompt;
12251 doprompt = saveprompt;
12252 else if (readtoken() != TRP)
12253 raise_error_unexpected_syntax(TRP);
12258 * Start reading from old file again, ignoring any pushed back
12259 * tokens left from the backquote parsing
12264 while (stackblocksize() <= savelen)
12266 STARTSTACKSTR(out);
12268 memcpy(out, str, savelen);
12269 STADJUST(savelen, out);
12271 USTPUTC(CTLBACKQ, out);
12273 goto parsebackq_oldreturn;
12274 goto parsebackq_newreturn;
12277 #if ENABLE_FEATURE_SH_MATH
12279 * Parse an arithmetic expansion (indicate start of one and set state)
12282 if (++arinest == 1) {
12283 prevsyntax = syntax;
12284 syntax = ARISYNTAX;
12286 USTPUTC(CTLARI, out);
12287 goto parsearith_return;
12290 } /* end of readtoken */
12293 * Read the next input token.
12294 * If the token is a word, we set backquotelist to the list of cmds in
12295 * backquotes. We set quoteflag to true if any part of the word was
12297 * If the token is TREDIR, then we set redirnode to a structure containing
12299 * In all cases, the variable startlinno is set to the number of the line
12300 * on which the token starts.
12302 * [Change comment: here documents and internal procedures]
12303 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12304 * word parsing code into a separate routine. In this case, readtoken
12305 * doesn't need to have any internal procedures, but parseword does.
12306 * We could also make parseoperator in essence the main routine, and
12307 * have parseword (readtoken1?) handle both words and redirection.]
12309 #define NEW_xxreadtoken
12310 #ifdef NEW_xxreadtoken
12311 /* singles must be first! */
12312 static const char xxreadtoken_chars[7] ALIGN1 = {
12313 '\n', '(', ')', /* singles */
12314 '&', '|', ';', /* doubles */
12318 #define xxreadtoken_singles 3
12319 #define xxreadtoken_doubles 3
12321 static const char xxreadtoken_tokens[] ALIGN1 = {
12322 TNL, TLP, TRP, /* only single occurrence allowed */
12323 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12324 TEOF, /* corresponds to trailing nul */
12325 TAND, TOR, TENDCASE /* if double occurrence */
12337 setprompt_if(needprompt, 2);
12338 startlinno = g_parsefile->linno;
12339 for (;;) { /* until token or start of word found */
12341 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12345 while ((c = pgetc()) != '\n' && c != PEOF)
12348 } else if (c == '\\') {
12349 if (pgetc() != '\n') {
12351 break; /* return readtoken1(...) */
12357 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12363 p = strchr(xxreadtoken_chars, c);
12365 break; /* return readtoken1(...) */
12367 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12369 if (cc == c) { /* double occurrence? */
12370 p += xxreadtoken_doubles + 1;
12373 #if BASH_REDIR_OUTPUT
12374 if (c == '&' && cc == '>') /* &> */
12375 break; /* return readtoken1(...) */
12380 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12385 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12387 #else /* old xxreadtoken */
12388 #define RETURN(token) return lasttoken = token
12398 setprompt_if(needprompt, 2);
12399 startlinno = g_parsefile->linno;
12400 for (;;) { /* until token or start of word found */
12403 case ' ': case '\t':
12404 IF_ASH_ALIAS(case PEOA:)
12407 while ((c = pgetc()) != '\n' && c != PEOF)
12412 if (pgetc() == '\n') {
12424 if (pgetc() == '&')
12429 if (pgetc() == '|')
12434 if (pgetc() == ';')
12447 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12450 #endif /* old xxreadtoken */
12456 int kwd = checkkwd;
12458 smallint alreadyseen = tokpushback;
12461 #if ENABLE_ASH_ALIAS
12477 if (t != TWORD || quoteflag) {
12482 * check for keywords
12484 if (kwd & CHKKWD) {
12485 const char *const *pp;
12487 pp = findkwd(wordtext);
12489 lasttoken = t = pp - tokname_array;
12490 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12495 if (checkkwd & CHKALIAS) {
12496 #if ENABLE_ASH_ALIAS
12498 ap = lookupalias(wordtext, 1);
12501 pushstring(ap->val, ap);
12511 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12513 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12529 * Read and parse a command. Returns NODE_EOF on end of file.
12530 * (NULL is a valid parse tree indicating a blank line.)
12532 static union node *
12533 parsecmd(int interact)
12538 doprompt = interact;
12539 setprompt_if(doprompt, doprompt);
12545 * Input any here documents.
12550 struct heredoc *here;
12553 here = heredoclist;
12554 heredoclist = NULL;
12557 setprompt_if(needprompt, 2);
12558 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12559 here->eofmark, here->striptabs);
12560 n = stzalloc(sizeof(struct narg));
12561 n->narg.type = NARG;
12562 /*n->narg.next = NULL; - stzalloc did it */
12563 n->narg.text = wordtext;
12564 n->narg.backquote = backquotelist;
12565 here->here->nhere.doc = n;
12571 static const char *
12572 expandstr(const char *ps, int syntax_type)
12577 /* XXX Fix (char *) cast. */
12578 setinputstring((char *)ps);
12580 saveprompt = doprompt;
12582 readtoken1(pgetc(), syntax_type, FAKEEOFMARK, 0);
12583 doprompt = saveprompt;
12587 n.narg.type = NARG;
12588 n.narg.next = NULL;
12589 n.narg.text = wordtext;
12590 n.narg.backquote = backquotelist;
12592 expandarg(&n, NULL, EXP_QUOTED);
12593 return stackblock();
12599 return tokpushback && lasttoken == TEOF;
12603 * Execute a command or commands contained in a string.
12606 evalstring(char *s, int flags)
12608 struct jmploc *volatile savehandler;
12609 struct jmploc jmploc;
12613 struct stackmark smark;
12618 setstackmark(&smark);
12621 /* On exception inside execution loop, we must popfile().
12622 * Try interactively:
12624 * command eval "a=b" # throws "is read only" error
12625 * "command BLTIN" is not supposed to abort (even in non-interactive use).
12626 * But if we skip popfile(), we hit EOF in eval's string, and exit.
12628 savehandler = exception_handler;
12629 ex = setjmp(jmploc.loc);
12632 exception_handler = &jmploc;
12634 while ((n = parsecmd(0)) != NODE_EOF) {
12637 i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
12640 popstackmark(&smark);
12645 popstackmark(&smark);
12649 exception_handler = savehandler;
12651 longjmp(exception_handler->loc, ex);
12657 * The eval command.
12659 static int FAST_FUNC
12660 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12669 STARTSTACKSTR(concat);
12671 concat = stack_putstr(p, concat);
12675 STPUTC(' ', concat);
12677 STPUTC('\0', concat);
12678 p = grabstackstr(concat);
12680 return evalstring(p, flags & EV_TESTED);
12686 * Read and execute commands.
12687 * "Top" is nonzero for the top level command loop;
12688 * it turns on prompting if the shell is interactive.
12694 struct stackmark smark;
12699 TRACE(("cmdloop(%d) called\n", top));
12703 setstackmark(&smark);
12706 showjobs(SHOW_CHANGED|SHOW_STDERR);
12709 if (iflag && top) {
12713 n = parsecmd(inter);
12715 if (DEBUG > 2 && debug && (n != NODE_EOF))
12718 if (n == NODE_EOF) {
12719 if (!top || numeof >= 50)
12721 if (!stoppedjobs()) {
12724 out2str("\nUse \"exit\" to leave shell.\n");
12727 } else if (nflag == 0) {
12730 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12733 i = evaltree(n, 0);
12737 popstackmark(&smark);
12741 evalskip &= ~SKIPFUNC;
12749 * Take commands from a file. To be compatible we should do a path
12750 * search for the file, which is necessary to find sub-commands.
12753 find_dot_file(char *name)
12756 const char *path = pathval();
12759 /* don't try this for absolute or relative paths */
12760 if (strchr(name, '/'))
12763 while ((fullname = path_advance(&path, name)) != NULL) {
12764 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12766 * Don't bother freeing here, since it will
12767 * be freed by the caller.
12771 if (fullname != name)
12772 stunalloc(fullname);
12775 /* not found in the PATH */
12776 ash_msg_and_raise_error("%s: not found", name);
12780 static int FAST_FUNC
12781 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12783 /* "false; . empty_file; echo $?" should print 0, not 1: */
12787 char *args_need_save;
12788 volatile struct shparam saveparam;
12791 // struct strlist *sp;
12792 // for (sp = cmdenviron; sp; sp = sp->next)
12793 // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12795 nextopt(nullstr); /* handle possible "--" */
12799 /* bash says: "bash: .: filename argument required" */
12800 return 2; /* bash compat */
12803 /* This aborts if file isn't found, which is POSIXly correct.
12804 * bash returns exitcode 1 instead.
12806 fullname = find_dot_file(argv[0]);
12808 args_need_save = argv[0];
12809 if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
12811 saveparam = shellparam;
12812 shellparam.malloced = 0;
12816 shellparam.nparam = argc;
12817 shellparam.p = argv;
12820 /* This aborts if file can't be opened, which is POSIXly correct.
12821 * bash returns exitcode 1 instead.
12823 setinputfile(fullname, INPUT_PUSH_FILE);
12824 commandname = fullname;
12825 status = cmdloop(0);
12828 if (args_need_save) {
12829 freeparam(&shellparam);
12830 shellparam = saveparam;
12836 static int FAST_FUNC
12837 exitcmd(int argc UNUSED_PARAM, char **argv)
12842 exitstatus = number(argv[1]);
12843 raise_exception(EXEXIT);
12848 * Read a file containing shell functions.
12851 readcmdfile(char *name)
12853 setinputfile(name, INPUT_PUSH_FILE);
12859 /* ============ find_command inplementation */
12862 * Resolve a command name. If you change this routine, you may have to
12863 * change the shellexec routine as well.
12866 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12868 struct tblentry *cmdp;
12875 struct builtincmd *bcmd;
12877 /* If name contains a slash, don't use PATH or hash table */
12878 if (strchr(name, '/') != NULL) {
12879 entry->u.index = -1;
12880 if (act & DO_ABS) {
12881 while (stat(name, &statb) < 0) {
12883 if (errno == EINTR)
12886 entry->cmdtype = CMDUNKNOWN;
12890 entry->cmdtype = CMDNORMAL;
12894 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12896 updatetbl = (path == pathval());
12899 if (strstr(path, "%builtin") != NULL)
12900 act |= DO_ALTBLTIN;
12903 /* If name is in the table, check answer will be ok */
12904 cmdp = cmdlookup(name, 0);
12905 if (cmdp != NULL) {
12908 switch (cmdp->cmdtype) {
12926 } else if (cmdp->rehash == 0)
12927 /* if not invalidated by cd, we're done */
12931 /* If %builtin not in path, check for builtin next */
12932 bcmd = find_builtin(name);
12934 if (IS_BUILTIN_REGULAR(bcmd))
12935 goto builtin_success;
12936 if (act & DO_ALTPATH) {
12937 if (!(act & DO_ALTBLTIN))
12938 goto builtin_success;
12939 } else if (builtinloc <= 0) {
12940 goto builtin_success;
12944 #if ENABLE_FEATURE_SH_STANDALONE
12946 int applet_no = find_applet_by_name(name);
12947 if (applet_no >= 0) {
12948 entry->cmdtype = CMDNORMAL;
12949 entry->u.index = -2 - applet_no;
12955 /* We have to search path. */
12956 prev = -1; /* where to start */
12957 if (cmdp && cmdp->rehash) { /* doing a rehash */
12958 if (cmdp->cmdtype == CMDBUILTIN)
12961 prev = cmdp->param.index;
12967 while ((fullname = path_advance(&path, name)) != NULL) {
12968 stunalloc(fullname);
12969 /* NB: code below will still use fullname
12970 * despite it being "unallocated" */
12973 if (prefix(pathopt, "builtin")) {
12975 goto builtin_success;
12978 if ((act & DO_NOFUNC)
12979 || !prefix(pathopt, "func")
12980 ) { /* ignore unimplemented options */
12984 /* if rehash, don't redo absolute path names */
12985 if (fullname[0] == '/' && idx <= prev) {
12988 TRACE(("searchexec \"%s\": no change\n", name));
12991 while (stat(fullname, &statb) < 0) {
12993 if (errno == EINTR)
12996 if (errno != ENOENT && errno != ENOTDIR)
13000 e = EACCES; /* if we fail, this will be the error */
13001 if (!S_ISREG(statb.st_mode))
13003 if (pathopt) { /* this is a %func directory */
13004 stalloc(strlen(fullname) + 1);
13005 /* NB: stalloc will return space pointed by fullname
13006 * (because we don't have any intervening allocations
13007 * between stunalloc above and this stalloc) */
13008 readcmdfile(fullname);
13009 cmdp = cmdlookup(name, 0);
13010 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
13011 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
13012 stunalloc(fullname);
13015 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
13017 entry->cmdtype = CMDNORMAL;
13018 entry->u.index = idx;
13022 cmdp = cmdlookup(name, 1);
13023 cmdp->cmdtype = CMDNORMAL;
13024 cmdp->param.index = idx;
13029 /* We failed. If there was an entry for this command, delete it */
13030 if (cmdp && updatetbl)
13031 delete_cmd_entry();
13033 ash_msg("%s: %s", name, errmsg(e, "not found"));
13034 entry->cmdtype = CMDUNKNOWN;
13039 entry->cmdtype = CMDBUILTIN;
13040 entry->u.cmd = bcmd;
13044 cmdp = cmdlookup(name, 1);
13045 cmdp->cmdtype = CMDBUILTIN;
13046 cmdp->param.cmd = bcmd;
13050 entry->cmdtype = cmdp->cmdtype;
13051 entry->u = cmdp->param;
13056 * The trap builtin.
13058 static int FAST_FUNC
13059 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13063 int signo, exitcode;
13068 for (signo = 0; signo < NSIG; signo++) {
13069 char *tr = trap_ptr[signo];
13071 /* note: bash adds "SIG", but only if invoked
13072 * as "bash". If called as "sh", or if set -o posix,
13073 * then it prints short signal names.
13074 * We are printing short names: */
13075 out1fmt("trap -- %s %s\n",
13077 get_signame(signo));
13078 /* trap_ptr != trap only if we are in special-cased `trap` code.
13079 * In this case, we will exit very soon, no need to free(). */
13080 /* if (trap_ptr != trap && tp[0]) */
13085 if (trap_ptr != trap) {
13093 /* Why the second check?
13094 * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
13095 * In this case, NUM is signal no, not an action.
13098 if (ap[1] && !is_number(ap[0]))
13103 signo = get_signum(*ap);
13105 /* Mimic bash message exactly */
13106 ash_msg("%s: invalid signal specification", *ap);
13112 if (LONE_DASH(action))
13115 if (action[0]) /* not NULL and not "" and not "-" */
13116 may_have_traps = 1;
13117 action = ckstrdup(action);
13121 trap[signo] = action;
13132 /* ============ Builtins */
13134 #if ENABLE_ASH_HELP
13135 static int FAST_FUNC
13136 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13142 "Built-in commands:\n"
13143 "------------------\n");
13144 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
13145 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
13146 builtintab[i].name + 1);
13152 # if ENABLE_FEATURE_SH_STANDALONE
13154 const char *a = applet_names;
13156 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
13161 while (*a++ != '\0')
13166 newline_and_flush(stdout);
13167 return EXIT_SUCCESS;
13172 static int FAST_FUNC
13173 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13175 show_history(line_input_state);
13176 return EXIT_SUCCESS;
13181 * The export and readonly commands.
13183 static int FAST_FUNC
13184 exportcmd(int argc UNUSED_PARAM, char **argv)
13194 /* "readonly" in bash accepts, but ignores -n.
13195 * We do the same: it saves a conditional in nextopt's param.
13198 while ((opt = nextopt("np")) != '\0') {
13200 flag_off = VEXPORT;
13203 if (argv[0][0] == 'r') {
13205 flag_off = 0; /* readonly ignores -n */
13207 flag_off = ~flag_off;
13209 /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
13215 p = strchr(name, '=');
13219 vp = *findvar(hashvar(name), name);
13221 vp->flags = ((vp->flags | flag) & flag_off);
13225 setvar(name, p, (flag & flag_off));
13226 } while ((name = *++aptr) != NULL);
13231 /* No arguments. Show the list of exported or readonly vars.
13234 showvars(argv[0], flag, 0);
13239 * Delete a function if it exists.
13242 unsetfunc(const char *name)
13244 struct tblentry *cmdp;
13246 cmdp = cmdlookup(name, 0);
13247 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
13248 delete_cmd_entry();
13252 * The unset builtin command. We unset the function before we unset the
13253 * variable to allow a function to be unset when there is a readonly variable
13254 * with the same name.
13256 static int FAST_FUNC
13257 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13263 while ((i = nextopt("vf")) != 0) {
13267 for (ap = argptr; *ap; ap++) {
13278 static const unsigned char timescmd_str[] ALIGN1 = {
13279 ' ', offsetof(struct tms, tms_utime),
13280 '\n', offsetof(struct tms, tms_stime),
13281 ' ', offsetof(struct tms, tms_cutime),
13282 '\n', offsetof(struct tms, tms_cstime),
13285 static int FAST_FUNC
13286 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13288 unsigned long clk_tck, s, t;
13289 const unsigned char *p;
13292 clk_tck = bb_clk_tck();
13297 t = *(clock_t *)(((char *) &buf) + p[1]);
13300 out1fmt("%lum%lu.%03lus%c",
13302 (t * 1000) / clk_tck,
13310 #if ENABLE_FEATURE_SH_MATH
13312 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13313 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13315 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13317 static int FAST_FUNC
13318 letcmd(int argc UNUSED_PARAM, char **argv)
13324 ash_msg_and_raise_error("expression expected");
13326 i = ash_arith(*argv);
13334 * The read builtin. Options:
13335 * -r Do not interpret '\' specially
13336 * -s Turn off echo (tty only)
13337 * -n NCHARS Read NCHARS max
13338 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13339 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13340 * -u FD Read from given FD instead of fd 0
13341 * This uses unbuffered input, which may be avoidable in some cases.
13342 * TODO: bash also has:
13343 * -a ARRAY Read into array[0],[1],etc
13344 * -d DELIM End on DELIM char, not newline
13345 * -e Use line editing (tty only)
13347 static int FAST_FUNC
13348 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13350 char *opt_n = NULL;
13351 char *opt_p = NULL;
13352 char *opt_t = NULL;
13353 char *opt_u = NULL;
13354 int read_flags = 0;
13358 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
13367 read_flags |= BUILTIN_READ_SILENT;
13373 read_flags |= BUILTIN_READ_RAW;
13383 /* "read -s" needs to save/restore termios, can't allow ^C
13384 * to jump out of it.
13388 r = shell_builtin_read(setvar0,
13390 bltinlookup("IFS"), /* can be NULL */
13399 if ((uintptr_t)r == 1 && errno == EINTR) {
13400 /* to get SIGCHLD: sleep 1 & read x; echo $x */
13401 if (pending_sig == 0)
13405 if ((uintptr_t)r > 1)
13406 ash_msg_and_raise_error(r);
13408 return (uintptr_t)r;
13411 static int FAST_FUNC
13412 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13414 static const char permuser[3] ALIGN1 = "ogu";
13417 int symbolic_mode = 0;
13419 while (nextopt("S") != '\0') {
13428 if (*argptr == NULL) {
13429 if (symbolic_mode) {
13430 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13437 *p++ = permuser[i];
13439 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13440 if (!(mask & 0400)) *p++ = 'r';
13441 if (!(mask & 0200)) *p++ = 'w';
13442 if (!(mask & 0100)) *p++ = 'x';
13450 out1fmt("%04o\n", mask);
13453 char *modestr = *argptr;
13454 /* numeric umasks are taken as-is */
13455 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13456 if (!isdigit(modestr[0]))
13458 mask = bb_parse_mode(modestr, mask);
13459 if ((unsigned)mask > 0777) {
13460 ash_msg_and_raise_error("illegal mode: %s", modestr);
13462 if (!isdigit(modestr[0]))
13469 static int FAST_FUNC
13470 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13472 return shell_builtin_ulimit(argv);
13475 /* ============ main() and helpers */
13478 * Called to exit the shell.
13487 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13488 save_history(line_input_state);
13490 status = exitstatus;
13491 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13492 if (setjmp(loc.loc)) {
13493 if (exception_type == EXEXIT)
13494 status = exitstatus;
13497 exception_handler = &loc;
13503 /*free(p); - we'll exit soon */
13506 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13507 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13510 flush_stdout_stderr();
13518 /* we will never free this */
13519 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13521 sigmode[SIGCHLD - 1] = S_DFL;
13522 setsignal(SIGCHLD);
13524 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13525 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13527 signal(SIGHUP, SIG_DFL);
13532 struct stat st1, st2;
13535 for (envp = environ; envp && *envp; envp++) {
13536 p = endofname(*envp);
13537 if (p != *envp && *p == '=') {
13538 setvareq(*envp, VEXPORT|VTEXTFIXED);
13542 setvareq((char*)defoptindvar, VTEXTFIXED);
13544 setvar0("PPID", utoa(getppid()));
13546 p = lookupvar("SHLVL");
13547 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13549 #if BASH_HOSTNAME_VAR
13550 if (!lookupvar("HOSTNAME")) {
13551 struct utsname uts;
13553 setvar0("HOSTNAME", uts.nodename);
13556 p = lookupvar("PWD");
13558 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13559 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13569 //usage:#define ash_trivial_usage
13570 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13571 //usage:#define ash_full_usage "\n\n"
13572 //usage: "Unix shell interpreter"
13575 * Process the shell command line arguments.
13578 procargs(char **argv)
13581 const char *xminusc;
13586 /* if (xargv[0]) - mmm, this is always true! */
13588 for (i = 0; i < NOPTS; i++)
13591 if (options(/*cmdline:*/ 1)) {
13592 /* it already printed err message */
13593 raise_exception(EXERROR);
13597 if (*xargv == NULL) {
13599 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13602 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13606 for (i = 0; i < NOPTS; i++)
13607 if (optlist[i] == 2)
13612 /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
13617 } else if (!sflag) {
13618 setinputfile(*xargv, 0);
13621 commandname = arg0;
13624 shellparam.p = xargv;
13625 #if ENABLE_ASH_GETOPTS
13626 shellparam.optind = 1;
13627 shellparam.optoff = -1;
13629 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13631 shellparam.nparam++;
13638 * Read /etc/profile, ~/.profile, $ENV.
13641 read_profile(const char *name)
13643 name = expandstr(name, DQSYNTAX);
13644 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13651 * This routine is called when an error or an interrupt occurs in an
13652 * interactive shell and control is returned to the main command loop.
13653 * (In dash, this function is auto-generated by build machinery).
13662 /* from expand.c: */
13665 /* from input.c: */
13666 g_parsefile->left_in_buffer = 0;
13667 g_parsefile->left_in_line = 0; /* clear input buffer */
13670 /* from redir.c: */
13674 unwindlocalvars(NULL);
13678 static short profile_buf[16384];
13679 extern int etext();
13683 * Main routine. We initialize things, parse the arguments, execute
13684 * profiles if we're a login shell, and then call cmdloop to execute
13685 * commands. The setjmp call sets up the location to jump to when an
13686 * exception occurs. When an exception occurs the variable "state"
13687 * is used to figure out how far we had gotten.
13689 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13690 int ash_main(int argc UNUSED_PARAM, char **argv)
13692 volatile smallint state;
13693 struct jmploc jmploc;
13694 struct stackmark smark;
13696 /* Initialize global data */
13700 #if ENABLE_ASH_ALIAS
13706 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13709 #if ENABLE_FEATURE_EDITING
13710 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13713 if (setjmp(jmploc.loc)) {
13719 e = exception_type;
13721 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13725 newline_and_flush(stderr);
13728 popstackmark(&smark);
13729 FORCE_INT_ON; /* enable interrupts */
13738 exception_handler = &jmploc;
13739 rootpid = getpid();
13742 setstackmark(&smark);
13745 TRACE(("Shell args: "));
13746 trace_puts_args(argv);
13749 if (argv[0] && argv[0][0] == '-')
13755 read_profile("/etc/profile");
13758 hp = lookupvar("HOME");
13760 read_profile("$HOME/.profile");
13766 getuid() == geteuid() && getgid() == getegid() &&
13770 const char *shinit = lookupvar("ENV");
13771 if (shinit != NULL && *shinit != '\0')
13772 read_profile(shinit);
13774 popstackmark(&smark);
13778 /* evalstring pushes parsefile stack.
13779 * Ensure we don't falsely claim that 0 (stdin)
13780 * is one of stacked source fds.
13781 * Testcase: ash -c 'exec 1>&0' must not complain. */
13782 // if (!sflag) g_parsefile->pf_fd = -1;
13783 // ^^ not necessary since now we special-case fd 0
13784 // in save_fd_on_redirect()
13785 evalstring(minusc, sflag ? 0 : EV_EXIT);
13788 if (sflag || minusc == NULL) {
13789 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13791 const char *hp = lookupvar("HISTFILE");
13793 hp = lookupvar("HOME");
13796 hp = concat_path_file(hp, ".ash_history");
13797 setvar0("HISTFILE", hp);
13800 hp = lookupvar("HISTFILE");
13804 line_input_state->hist_file = hp;
13805 # if ENABLE_FEATURE_SH_HISTFILESIZE
13806 hp = lookupvar("HISTFILESIZE");
13807 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13811 state4: /* XXX ??? - why isn't this before the "if" statement */
13819 extern void _mcleanup(void);
13823 TRACE(("End of main reached\n"));
13830 * Copyright (c) 1989, 1991, 1993, 1994
13831 * The Regents of the University of California. All rights reserved.
13833 * This code is derived from software contributed to Berkeley by
13834 * Kenneth Almquist.
13836 * Redistribution and use in source and binary forms, with or without
13837 * modification, are permitted provided that the following conditions
13839 * 1. Redistributions of source code must retain the above copyright
13840 * notice, this list of conditions and the following disclaimer.
13841 * 2. Redistributions in binary form must reproduce the above copyright
13842 * notice, this list of conditions and the following disclaimer in the
13843 * documentation and/or other materials provided with the distribution.
13844 * 3. Neither the name of the University nor the names of its contributors
13845 * may be used to endorse or promote products derived from this software
13846 * without specific prior written permission.
13848 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13849 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13850 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13851 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13852 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13853 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13854 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13855 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13856 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13857 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF