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 */
1253 static struct strlist *cmdenviron; /* environment for builtin command */
1256 /* ============ Message printing */
1259 ash_vmsg(const char *msg, va_list ap)
1261 fprintf(stderr, "%s: ", arg0);
1263 if (strcmp(arg0, commandname))
1264 fprintf(stderr, "%s: ", commandname);
1265 if (!iflag || g_parsefile->pf_fd > 0)
1266 fprintf(stderr, "line %d: ", startlinno);
1268 vfprintf(stderr, msg, ap);
1269 newline_and_flush(stderr);
1273 * Exverror is called to raise the error exception. If the second argument
1274 * is not NULL then error prints an error message using printf style
1275 * formatting. It then raises the error exception.
1277 static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
1279 ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
1283 TRACE(("ash_vmsg_and_raise(%d):", cond));
1286 TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
1291 flush_stdout_stderr();
1292 raise_exception(cond);
1296 static void ash_msg_and_raise_error(const char *, ...) NORETURN;
1298 ash_msg_and_raise_error(const char *msg, ...)
1305 ash_vmsg_and_raise(EXERROR, msg, ap);
1310 static void raise_error_syntax(const char *) NORETURN;
1312 raise_error_syntax(const char *msg)
1314 ash_msg_and_raise_error("syntax error: %s", msg);
1318 static void ash_msg_and_raise(int, const char *, ...) NORETURN;
1320 ash_msg_and_raise(int cond, const char *msg, ...)
1325 ash_vmsg_and_raise(cond, msg, ap);
1331 * error/warning routines for external builtins
1334 ash_msg(const char *fmt, ...)
1344 * Return a string describing an error. The returned string may be a
1345 * pointer to a static buffer that will be overwritten on the next call.
1346 * Action describes the operation that got the error.
1349 errmsg(int e, const char *em)
1351 if (e == ENOENT || e == ENOTDIR) {
1358 /* ============ Memory allocation */
1361 /* I consider these wrappers nearly useless:
1362 * ok, they return you to nearest exception handler, but
1363 * how much memory do you leak in the process, making
1364 * memory starvation worse?
1367 ckrealloc(void * p, size_t nbytes)
1369 p = realloc(p, nbytes);
1371 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1376 ckmalloc(size_t nbytes)
1378 return ckrealloc(NULL, nbytes);
1382 ckzalloc(size_t nbytes)
1384 return memset(ckmalloc(nbytes), 0, nbytes);
1388 ckstrdup(const char *s)
1390 char *p = strdup(s);
1392 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1396 /* Using bbox equivalents. They exit if out of memory */
1397 # define ckrealloc xrealloc
1398 # define ckmalloc xmalloc
1399 # define ckzalloc xzalloc
1400 # define ckstrdup xstrdup
1404 * It appears that grabstackstr() will barf with such alignments
1405 * because stalloc() will return a string allocated in a new stackblock.
1407 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1409 /* Most machines require the value returned from malloc to be aligned
1410 * in some way. The following macro will get this right
1411 * on many machines. */
1412 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
1413 /* Minimum size of a block */
1414 MINSIZE = SHELL_ALIGN(504),
1417 struct stack_block {
1418 struct stack_block *prev;
1419 char space[MINSIZE];
1423 struct stack_block *stackp;
1429 struct globals_memstack {
1430 struct stack_block *g_stackp; // = &stackbase;
1431 char *g_stacknxt; // = stackbase.space;
1432 char *sstrend; // = stackbase.space + MINSIZE;
1433 size_t g_stacknleft; // = MINSIZE;
1434 struct stack_block stackbase;
1436 extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1437 #define G_memstack (*ash_ptr_to_globals_memstack)
1438 #define g_stackp (G_memstack.g_stackp )
1439 #define g_stacknxt (G_memstack.g_stacknxt )
1440 #define sstrend (G_memstack.sstrend )
1441 #define g_stacknleft (G_memstack.g_stacknleft)
1442 #define stackbase (G_memstack.stackbase )
1443 #define INIT_G_memstack() do { \
1444 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1446 g_stackp = &stackbase; \
1447 g_stacknxt = stackbase.space; \
1448 g_stacknleft = MINSIZE; \
1449 sstrend = stackbase.space + MINSIZE; \
1453 #define stackblock() ((void *)g_stacknxt)
1454 #define stackblocksize() g_stacknleft
1457 * Parse trees for commands are allocated in lifo order, so we use a stack
1458 * to make this more efficient, and also to avoid all sorts of exception
1459 * handling code to handle interrupts in the middle of a parse.
1461 * The size 504 was chosen because the Ultrix malloc handles that size
1465 stalloc(size_t nbytes)
1470 aligned = SHELL_ALIGN(nbytes);
1471 if (aligned > g_stacknleft) {
1474 struct stack_block *sp;
1476 blocksize = aligned;
1477 if (blocksize < MINSIZE)
1478 blocksize = MINSIZE;
1479 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1480 if (len < blocksize)
1481 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1484 sp->prev = g_stackp;
1485 g_stacknxt = sp->space;
1486 g_stacknleft = blocksize;
1487 sstrend = g_stacknxt + blocksize;
1492 g_stacknxt += aligned;
1493 g_stacknleft -= aligned;
1498 stzalloc(size_t nbytes)
1500 return memset(stalloc(nbytes), 0, nbytes);
1507 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
1508 write(STDERR_FILENO, "stunalloc\n", 10);
1512 g_stacknleft += g_stacknxt - (char *)p;
1517 * Like strdup but works with the ash stack.
1520 sstrdup(const char *p)
1522 size_t len = strlen(p) + 1;
1523 return memcpy(stalloc(len), p, len);
1527 grabstackblock(size_t len)
1533 pushstackmark(struct stackmark *mark, size_t len)
1535 mark->stackp = g_stackp;
1536 mark->stacknxt = g_stacknxt;
1537 mark->stacknleft = g_stacknleft;
1538 grabstackblock(len);
1542 setstackmark(struct stackmark *mark)
1544 pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
1548 popstackmark(struct stackmark *mark)
1550 struct stack_block *sp;
1556 while (g_stackp != mark->stackp) {
1558 g_stackp = sp->prev;
1561 g_stacknxt = mark->stacknxt;
1562 g_stacknleft = mark->stacknleft;
1563 sstrend = mark->stacknxt + mark->stacknleft;
1568 * When the parser reads in a string, it wants to stick the string on the
1569 * stack and only adjust the stack pointer when it knows how big the
1570 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1571 * of space on top of the stack and stackblocklen returns the length of
1572 * this block. Growstackblock will grow this space by at least one byte,
1573 * possibly moving it (like realloc). Grabstackblock actually allocates the
1574 * part of the block that has been used.
1577 growstackblock(void)
1581 newlen = g_stacknleft * 2;
1582 if (newlen < g_stacknleft)
1583 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1587 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
1588 struct stack_block *sp;
1589 struct stack_block *prevstackp;
1594 prevstackp = sp->prev;
1595 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1596 sp = ckrealloc(sp, grosslen);
1597 sp->prev = prevstackp;
1599 g_stacknxt = sp->space;
1600 g_stacknleft = newlen;
1601 sstrend = sp->space + newlen;
1604 char *oldspace = g_stacknxt;
1605 size_t oldlen = g_stacknleft;
1606 char *p = stalloc(newlen);
1608 /* free the space we just allocated */
1609 g_stacknxt = memcpy(p, oldspace, oldlen);
1610 g_stacknleft += newlen;
1615 * The following routines are somewhat easier to use than the above.
1616 * The user declares a variable of type STACKSTR, which may be declared
1617 * to be a register. The macro STARTSTACKSTR initializes things. Then
1618 * the user uses the macro STPUTC to add characters to the string. In
1619 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1620 * grown as necessary. When the user is done, she can just leave the
1621 * string there and refer to it using stackblock(). Or she can allocate
1622 * the space for it using grabstackstr(). If it is necessary to allow
1623 * someone else to use the stack temporarily and then continue to grow
1624 * the string, the user should use grabstack to allocate the space, and
1625 * then call ungrabstr(p) to return to the previous mode of operation.
1627 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1628 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1629 * is space for at least one character.
1634 size_t len = stackblocksize();
1636 return (char *)stackblock() + len;
1640 * Called from CHECKSTRSPACE.
1643 makestrspace(size_t newlen, char *p)
1645 size_t len = p - g_stacknxt;
1651 size = stackblocksize();
1653 if (nleft >= newlen)
1657 return (char *)stackblock() + len;
1661 stack_nputstr(const char *s, size_t n, char *p)
1663 p = makestrspace(n, p);
1664 p = (char *)mempcpy(p, s, n);
1669 stack_putstr(const char *s, char *p)
1671 return stack_nputstr(s, strlen(s), p);
1675 _STPUTC(int c, char *p)
1683 #define STARTSTACKSTR(p) ((p) = stackblock())
1684 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1685 #define CHECKSTRSPACE(n, p) do { \
1688 size_t m = sstrend - q; \
1690 (p) = makestrspace(l, q); \
1692 #define USTPUTC(c, p) (*(p)++ = (c))
1693 #define STACKSTRNUL(p) do { \
1694 if ((p) == sstrend) \
1695 (p) = growstackstr(); \
1698 #define STUNPUTC(p) (--(p))
1699 #define STTOPC(p) ((p)[-1])
1700 #define STADJUST(amount, p) ((p) += (amount))
1702 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1703 #define ungrabstackstr(s, p) stunalloc(s)
1704 #define stackstrend() ((void *)sstrend)
1707 /* ============ String helpers */
1710 * prefix -- see if pfx is a prefix of string.
1713 prefix(const char *string, const char *pfx)
1716 if (*pfx++ != *string++)
1719 return (char *) string;
1723 * Check for a valid number. This should be elsewhere.
1726 is_number(const char *p)
1731 } while (*++p != '\0');
1736 * Convert a string of digits to an integer, printing an error message on
1740 number(const char *s)
1743 ash_msg_and_raise_error(msg_illnum, s);
1748 * Produce a single quoted string suitable as input to the shell.
1749 * The return string is allocated on the stack.
1752 single_quote(const char *s)
1762 len = strchrnul(s, '\'') - s;
1764 q = p = makestrspace(len + 3, p);
1767 q = (char *)mempcpy(q, s, len);
1776 do len++; while (*++s == '\'');
1778 q = p = makestrspace(len + 3, p);
1781 q = (char *)mempcpy(q, s - len, len);
1789 return stackblock();
1793 * Produce a possibly single quoted string suitable as input to the shell.
1794 * If quoting was done, the return string is allocated on the stack,
1795 * otherwise a pointer to the original string is returned.
1798 maybe_single_quote(const char *s)
1803 /* Assuming ACSII */
1804 /* quote ctrl_chars space !"#$%&'()* */
1808 if (*p >= ';' && *p <= '?')
1817 /* quote {|}~ DEL and high bytes */
1820 /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
1821 /* TODO: maybe avoid quoting % */
1827 return single_quote(s);
1831 /* ============ nextopt */
1833 static char **argptr; /* argument list for builtin commands */
1834 static char *optionarg; /* set by nextopt (like getopt) */
1835 static char *optptr; /* used by nextopt */
1838 * XXX - should get rid of. Have all builtins use getopt(3).
1839 * The library getopt must have the BSD extension static variable
1840 * "optreset", otherwise it can't be used within the shell safely.
1842 * Standard option processing (a la getopt) for builtin routines.
1843 * The only argument that is passed to nextopt is the option string;
1844 * the other arguments are unnecessary. It returns the character,
1845 * or '\0' on end of input.
1848 nextopt(const char *optstring)
1855 if (p == NULL || *p == '\0') {
1856 /* We ate entire "-param", take next one */
1862 if (*++p == '\0') /* just "-" ? */
1865 if (LONE_DASH(p)) /* "--" ? */
1867 /* p => next "-param" */
1869 /* p => some option char in the middle of a "-param" */
1871 for (q = optstring; *q != c;) {
1873 ash_msg_and_raise_error("illegal option -%c", c);
1881 ash_msg_and_raise_error("no arg for -%c option", c);
1891 /* ============ Shell variables */
1894 * The parsefile structure pointed to by the global variable parsefile
1895 * contains information about the current file being read.
1898 int nparam; /* # of positional parameters (without $0) */
1899 #if ENABLE_ASH_GETOPTS
1900 int optind; /* next parameter to be processed by getopts */
1901 int optoff; /* used by getopts */
1903 unsigned char malloced; /* if parameter list dynamically allocated */
1904 char **p; /* parameter list */
1908 * Free the list of positional parameters.
1911 freeparam(volatile struct shparam *param)
1913 if (param->malloced) {
1915 ap = ap1 = param->p;
1922 #if ENABLE_ASH_GETOPTS
1923 static void FAST_FUNC getoptsreset(const char *value);
1927 struct var *next; /* next entry in hash list */
1928 int flags; /* flags are defined above */
1929 const char *var_text; /* name=value */
1930 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
1931 /* the variable gets set/unset */
1935 struct localvar *next; /* next local variable in list */
1936 struct var *vp; /* the variable that was made local */
1937 int flags; /* saved flags */
1938 const char *text; /* saved text */
1942 #define VEXPORT 0x01 /* variable is exported */
1943 #define VREADONLY 0x02 /* variable cannot be modified */
1944 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1945 #define VTEXTFIXED 0x08 /* text is statically allocated */
1946 #define VSTACK 0x10 /* text is allocated on the stack */
1947 #define VUNSET 0x20 /* the variable is not set */
1948 #define VNOFUNC 0x40 /* don't call the callback function */
1949 #define VNOSET 0x80 /* do not set variable - just readonly test */
1950 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1951 #if ENABLE_ASH_RANDOM_SUPPORT
1952 # define VDYNAMIC 0x200 /* dynamic variable */
1958 /* Need to be before varinit_data[] */
1959 #if ENABLE_LOCALE_SUPPORT
1960 static void FAST_FUNC
1961 change_lc_all(const char *value)
1963 if (value && *value != '\0')
1964 setlocale(LC_ALL, value);
1966 static void FAST_FUNC
1967 change_lc_ctype(const char *value)
1969 if (value && *value != '\0')
1970 setlocale(LC_CTYPE, value);
1974 static void chkmail(void);
1975 static void changemail(const char *var_value) FAST_FUNC;
1977 # define chkmail() ((void)0)
1979 static void changepath(const char *) FAST_FUNC;
1980 #if ENABLE_ASH_RANDOM_SUPPORT
1981 static void change_random(const char *) FAST_FUNC;
1984 static const struct {
1986 const char *var_text;
1987 void (*var_func)(const char *) FAST_FUNC;
1988 } varinit_data[] = {
1990 * Note: VEXPORT would not work correctly here for NOFORK applets:
1991 * some environment strings may be constant.
1993 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
1995 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1996 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
1998 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1999 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
2000 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
2001 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
2002 #if ENABLE_ASH_GETOPTS
2003 { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
2005 #if ENABLE_ASH_RANDOM_SUPPORT
2006 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
2008 #if ENABLE_LOCALE_SUPPORT
2009 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
2010 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
2012 #if ENABLE_FEATURE_EDITING_SAVEHISTORY
2013 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
2019 struct globals_var {
2020 struct shparam shellparam; /* $@ current positional parameters */
2021 struct redirtab *redirlist;
2022 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
2023 struct var *vartab[VTABSIZE];
2024 struct var varinit[ARRAY_SIZE(varinit_data)];
2026 extern struct globals_var *const ash_ptr_to_globals_var;
2027 #define G_var (*ash_ptr_to_globals_var)
2028 #define shellparam (G_var.shellparam )
2029 //#define redirlist (G_var.redirlist )
2030 #define preverrout_fd (G_var.preverrout_fd)
2031 #define vartab (G_var.vartab )
2032 #define varinit (G_var.varinit )
2033 #define INIT_G_var() do { \
2035 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
2037 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
2038 varinit[i].flags = varinit_data[i].flags; \
2039 varinit[i].var_text = varinit_data[i].var_text; \
2040 varinit[i].var_func = varinit_data[i].var_func; \
2044 #define vifs varinit[0]
2046 # define vmail (&vifs)[1]
2047 # define vmpath (&vmail)[1]
2048 # define vpath (&vmpath)[1]
2050 # define vpath (&vifs)[1]
2052 #define vps1 (&vpath)[1]
2053 #define vps2 (&vps1)[1]
2054 #define vps4 (&vps2)[1]
2055 #if ENABLE_ASH_GETOPTS
2056 # define voptind (&vps4)[1]
2057 # if ENABLE_ASH_RANDOM_SUPPORT
2058 # define vrandom (&voptind)[1]
2061 # if ENABLE_ASH_RANDOM_SUPPORT
2062 # define vrandom (&vps4)[1]
2067 * The following macros access the values of the above variables.
2068 * They have to skip over the name. They return the null string
2069 * for unset variables.
2071 #define ifsval() (vifs.var_text + 4)
2072 #define ifsset() ((vifs.flags & VUNSET) == 0)
2074 # define mailval() (vmail.var_text + 5)
2075 # define mpathval() (vmpath.var_text + 9)
2076 # define mpathset() ((vmpath.flags & VUNSET) == 0)
2078 #define pathval() (vpath.var_text + 5)
2079 #define ps1val() (vps1.var_text + 4)
2080 #define ps2val() (vps2.var_text + 4)
2081 #define ps4val() (vps4.var_text + 4)
2082 #if ENABLE_ASH_GETOPTS
2083 # define optindval() (voptind.var_text + 7)
2086 #if ENABLE_ASH_GETOPTS
2087 static void FAST_FUNC
2088 getoptsreset(const char *value)
2090 shellparam.optind = number(value) ?: 1;
2091 shellparam.optoff = -1;
2096 * Compares two strings up to the first = or '\0'. The first
2097 * string must be terminated by '='; the second may be terminated by
2098 * either '=' or '\0'.
2101 varcmp(const char *p, const char *q)
2105 while ((c = *p) == (d = *q)) {
2106 if (c == '\0' || c == '=')
2120 * Find the appropriate entry in the hash table from the name.
2122 static struct var **
2123 hashvar(const char *p)
2127 hashval = ((unsigned char) *p) << 4;
2128 while (*p && *p != '=')
2129 hashval += (unsigned char) *p++;
2130 return &vartab[hashval % VTABSIZE];
2134 vpcmp(const void *a, const void *b)
2136 return varcmp(*(const char **)a, *(const char **)b);
2140 * This routine initializes the builtin variables.
2150 * PS1 depends on uid
2152 #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
2153 vps1.var_text = "PS1=\\w \\$ ";
2156 vps1.var_text = "PS1=# ";
2159 end = vp + ARRAY_SIZE(varinit);
2161 vpp = hashvar(vp->var_text);
2164 } while (++vp < end);
2167 static struct var **
2168 findvar(struct var **vpp, const char *name)
2170 for (; *vpp; vpp = &(*vpp)->next) {
2171 if (varcmp((*vpp)->var_text, name) == 0) {
2179 * Find the value of a variable. Returns NULL if not set.
2181 static const char* FAST_FUNC
2182 lookupvar(const char *name)
2186 v = *findvar(hashvar(name), name);
2188 #if ENABLE_ASH_RANDOM_SUPPORT
2190 * Dynamic variables are implemented roughly the same way they are
2191 * in bash. Namely, they're "special" so long as they aren't unset.
2192 * As soon as they're unset, they're no longer dynamic, and dynamic
2193 * lookup will no longer happen at that point. -- PFM.
2195 if (v->flags & VDYNAMIC)
2198 if (!(v->flags & VUNSET))
2199 return var_end(v->var_text);
2204 #if ENABLE_UNICODE_SUPPORT
2206 reinit_unicode_for_ash(void)
2208 /* Unicode support should be activated even if LANG is set
2209 * _during_ shell execution, not only if it was set when
2210 * shell was started. Therefore, re-check LANG every time:
2212 if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
2213 || ENABLE_UNICODE_USING_LOCALE
2215 const char *s = lookupvar("LC_ALL");
2216 if (!s) s = lookupvar("LC_CTYPE");
2217 if (!s) s = lookupvar("LANG");
2222 # define reinit_unicode_for_ash() ((void)0)
2226 * Search the environment of a builtin command.
2229 bltinlookup(const char *name)
2233 for (sp = cmdenviron; sp; sp = sp->next) {
2234 if (varcmp(sp->text, name) == 0)
2235 return var_end(sp->text);
2237 return lookupvar(name);
2241 * Same as setvar except that the variable and value are passed in
2242 * the first argument as name=value. Since the first argument will
2243 * be actually stored in the table, it should not be a string that
2245 * Called with interrupts off.
2248 setvareq(char *s, int flags)
2250 struct var *vp, **vpp;
2253 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2254 vp = *findvar(vpp, s);
2256 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2259 if (flags & VNOSAVE)
2263 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2269 if (vp->var_func && !(flags & VNOFUNC))
2270 vp->var_func(var_end(s));
2272 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2273 free((char*)vp->var_text);
2275 if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
2279 if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
2284 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2286 /* variable s is not found */
2289 if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
2291 vp = ckzalloc(sizeof(*vp));
2293 /*vp->func = NULL; - ckzalloc did it */
2296 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2303 * Set the value of a variable. The flags argument is ored with the
2304 * flags of the variable. If val is NULL, the variable is unset.
2307 setvar(const char *name, const char *val, int flags)
2315 q = endofname(name);
2316 p = strchrnul(q, '=');
2318 if (!namelen || p != q)
2319 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2324 vallen = strlen(val);
2328 nameeq = ckmalloc(namelen + vallen + 2);
2329 p = mempcpy(nameeq, name, namelen);
2332 p = mempcpy(p, val, vallen);
2335 setvareq(nameeq, flags | VNOSAVE);
2339 static void FAST_FUNC
2340 setvar0(const char *name, const char *val)
2342 setvar(name, val, 0);
2346 * Unset the specified variable.
2349 unsetvar(const char *s)
2355 * Process a linked list of variable assignments.
2358 listsetvar(struct strlist *list_set_var, int flags)
2360 struct strlist *lp = list_set_var;
2366 setvareq(lp->text, flags);
2373 * Generate a list of variables satisfying the given conditions.
2376 listvars(int on, int off, char ***end)
2387 for (vp = *vpp; vp; vp = vp->next) {
2388 if ((vp->flags & mask) == on) {
2389 if (ep == stackstrend())
2390 ep = growstackstr();
2391 *ep++ = (char*)vp->var_text;
2394 } while (++vpp < vartab + VTABSIZE);
2395 if (ep == stackstrend())
2396 ep = growstackstr();
2400 return grabstackstr(ep);
2404 /* ============ Path search helper
2406 * The variable path (passed by reference) should be set to the start
2407 * of the path before the first call; path_advance will update
2408 * this value as it proceeds. Successive calls to path_advance will return
2409 * the possible path expansions in sequence. If an option (indicated by
2410 * a percent sign) appears in the path entry then the global variable
2411 * pathopt will be set to point to it; otherwise pathopt will be set to
2414 static const char *pathopt; /* set by path_advance */
2417 path_advance(const char **path, const char *name)
2427 for (p = start; *p && *p != ':' && *p != '%'; p++)
2429 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2430 while (stackblocksize() < len)
2434 q = mempcpy(q, start, p - start);
2441 while (*p && *p != ':')
2448 return stalloc(len);
2452 /* ============ Prompt */
2454 static smallint doprompt; /* if set, prompt the user */
2455 static smallint needprompt; /* true if interactive and at start of line */
2457 #if ENABLE_FEATURE_EDITING
2458 static line_input_t *line_input_state;
2459 static const char *cmdedit_prompt;
2461 putprompt(const char *s)
2463 if (ENABLE_ASH_EXPAND_PRMT) {
2464 free((char*)cmdedit_prompt);
2465 cmdedit_prompt = ckstrdup(s);
2472 putprompt(const char *s)
2478 /* expandstr() needs parsing machinery, so it is far away ahead... */
2479 static const char *expandstr(const char *ps);
2482 setprompt_if(smallint do_set, int whichprompt)
2485 IF_ASH_EXPAND_PRMT(struct stackmark smark;)
2492 switch (whichprompt) {
2502 #if ENABLE_ASH_EXPAND_PRMT
2503 pushstackmark(&smark, stackblocksize());
2504 putprompt(expandstr(prompt));
2505 popstackmark(&smark);
2512 /* ============ The cd and pwd commands */
2514 #define CD_PHYSICAL 1
2524 while ((i = nextopt("LP")) != '\0') {
2526 flags ^= CD_PHYSICAL;
2535 * Update curdir (the name of the current directory) in response to a
2539 updatepwd(const char *dir)
2546 cdcomppath = sstrdup(dir);
2549 if (curdir == nullstr)
2551 new = stack_putstr(curdir, new);
2553 new = makestrspace(strlen(dir) + 2, new);
2554 lim = (char *)stackblock() + 1;
2558 if (new > lim && *lim == '/')
2563 if (dir[1] == '/' && dir[2] != '/') {
2569 p = strtok(cdcomppath, "/");
2573 if (p[1] == '.' && p[2] == '\0') {
2585 new = stack_putstr(p, new);
2588 p = strtok(NULL, "/");
2593 return stackblock();
2597 * Find out what the current directory is. If we already know the current
2598 * directory, this routine returns immediately.
2603 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
2604 return dir ? dir : nullstr;
2608 setpwd(const char *val, int setold)
2612 oldcur = dir = curdir;
2615 setvar("OLDPWD", oldcur, VEXPORT);
2618 if (physdir != nullstr) {
2619 if (physdir != oldcur)
2623 if (oldcur == val || !val) {
2629 dir = ckstrdup(val);
2630 if (oldcur != dir && oldcur != nullstr) {
2635 setvar("PWD", dir, VEXPORT);
2638 static void hashcd(void);
2641 * Actually do the chdir. We also call hashcd to let other routines
2642 * know that the current directory has changed.
2645 docd(const char *dest, int flags)
2647 const char *dir = NULL;
2650 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2653 if (!(flags & CD_PHYSICAL)) {
2654 dir = updatepwd(dest);
2668 static int FAST_FUNC
2669 cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2681 dest = bltinlookup("HOME");
2682 else if (LONE_DASH(dest)) {
2683 dest = bltinlookup("OLDPWD");
2705 path = bltinlookup("CDPATH");
2708 p = path_advance(&path, dest);
2709 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2713 if (!docd(p, flags))
2724 ash_msg_and_raise_error("can't cd to %s", dest);
2727 if (flags & CD_PRINT)
2728 out1fmt("%s\n", curdir);
2732 static int FAST_FUNC
2733 pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2736 const char *dir = curdir;
2740 if (physdir == nullstr)
2744 out1fmt("%s\n", dir);
2749 /* ============ ... */
2752 #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
2754 /* Syntax classes */
2755 #define CWORD 0 /* character is nothing special */
2756 #define CNL 1 /* newline character */
2757 #define CBACK 2 /* a backslash character */
2758 #define CSQUOTE 3 /* single quote */
2759 #define CDQUOTE 4 /* double quote */
2760 #define CENDQUOTE 5 /* a terminating quote */
2761 #define CBQUOTE 6 /* backwards single quote */
2762 #define CVAR 7 /* a dollar sign */
2763 #define CENDVAR 8 /* a '}' character */
2764 #define CLP 9 /* a left paren in arithmetic */
2765 #define CRP 10 /* a right paren in arithmetic */
2766 #define CENDFILE 11 /* end of file */
2767 #define CCTL 12 /* like CWORD, except it must be escaped */
2768 #define CSPCL 13 /* these terminate a word */
2769 #define CIGN 14 /* character should be ignored */
2772 #if ENABLE_ASH_ALIAS
2776 #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
2778 #if ENABLE_FEATURE_SH_MATH
2779 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
2781 # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
2783 static const uint16_t S_I_T[] ALIGN2 = {
2784 #if ENABLE_ASH_ALIAS
2785 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2787 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2788 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2789 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2790 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2791 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2792 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2793 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2794 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2795 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2796 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2797 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
2798 #if !USE_SIT_FUNCTION
2799 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2800 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2801 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2805 /* Constants below must match table above */
2807 #if ENABLE_ASH_ALIAS
2808 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2810 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2811 CNL_CNL_CNL_CNL , /* 2 */
2812 CWORD_CCTL_CCTL_CWORD , /* 3 */
2813 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2814 CVAR_CVAR_CWORD_CVAR , /* 5 */
2815 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2816 CSPCL_CWORD_CWORD_CLP , /* 7 */
2817 CSPCL_CWORD_CWORD_CRP , /* 8 */
2818 CBACK_CBACK_CCTL_CBACK , /* 9 */
2819 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2820 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2821 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2822 CWORD_CWORD_CWORD_CWORD , /* 13 */
2823 CCTL_CCTL_CCTL_CCTL , /* 14 */
2826 /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2827 * caller must ensure proper cast on it if c is *char_ptr!
2829 /* Values for syntax param */
2830 #define BASESYNTAX 0 /* not in quotes */
2831 #define DQSYNTAX 1 /* in double quotes */
2832 #define SQSYNTAX 2 /* in single quotes */
2833 #define ARISYNTAX 3 /* in arithmetic */
2834 #define PSSYNTAX 4 /* prompt. never passed to SIT() */
2836 #if USE_SIT_FUNCTION
2839 SIT(int c, int syntax)
2841 /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
2842 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
2844 * This causes '/' to be prepended with CTLESC in dquoted string,
2845 * making "./file"* treated incorrectly because we feed
2846 * ".\/file*" string to glob(), confusing it (see expandmeta func).
2847 * The "homegrown" glob implementation is okay with that,
2848 * but glibc one isn't. With '/' always treated as CWORD,
2851 # if ENABLE_ASH_ALIAS
2852 static const uint8_t syntax_index_table[] ALIGN1 = {
2853 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2854 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
2855 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2859 static const uint8_t syntax_index_table[] ALIGN1 = {
2860 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2861 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
2862 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2871 # if ENABLE_ASH_ALIAS
2877 /* Cast is purely for paranoia here,
2878 * just in case someone passed signed char to us */
2879 if ((unsigned char)c >= CTL_FIRST
2880 && (unsigned char)c <= CTL_LAST
2884 s = strchrnul(spec_symbls, c);
2887 indx = syntax_index_table[s - spec_symbls];
2889 return (S_I_T[indx] >> (syntax*4)) & 0xf;
2892 #else /* !USE_SIT_FUNCTION */
2894 static const uint8_t syntax_index_table[] ALIGN1 = {
2895 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
2896 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2906 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2907 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2929 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2930 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2931 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2933 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2935 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2936 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2937 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2938 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2939 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2941 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2942 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2943 /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
2944 /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2956 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2957 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2958 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2959 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2960 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2961 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2989 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2990 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2991 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2993 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2994 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
3004 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
3005 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
3006 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
3007 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
3008 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3009 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3010 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3011 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3012 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3013 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3014 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3015 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3016 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3017 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3018 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3019 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3020 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3021 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3022 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3023 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3024 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
3025 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
3026 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
3027 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
3028 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
3029 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
3030 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
3031 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
3032 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
3033 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
3034 /* 137 */ CWORD_CWORD_CWORD_CWORD,
3035 /* 138 */ CWORD_CWORD_CWORD_CWORD,
3036 /* 139 */ CWORD_CWORD_CWORD_CWORD,
3037 /* 140 */ CWORD_CWORD_CWORD_CWORD,
3038 /* 141 */ CWORD_CWORD_CWORD_CWORD,
3039 /* 142 */ CWORD_CWORD_CWORD_CWORD,
3040 /* 143 */ CWORD_CWORD_CWORD_CWORD,
3041 /* 144 */ CWORD_CWORD_CWORD_CWORD,
3042 /* 145 */ CWORD_CWORD_CWORD_CWORD,
3043 /* 146 */ CWORD_CWORD_CWORD_CWORD,
3044 /* 147 */ CWORD_CWORD_CWORD_CWORD,
3045 /* 148 */ CWORD_CWORD_CWORD_CWORD,
3046 /* 149 */ CWORD_CWORD_CWORD_CWORD,
3047 /* 150 */ CWORD_CWORD_CWORD_CWORD,
3048 /* 151 */ CWORD_CWORD_CWORD_CWORD,
3049 /* 152 */ CWORD_CWORD_CWORD_CWORD,
3050 /* 153 */ CWORD_CWORD_CWORD_CWORD,
3051 /* 154 */ CWORD_CWORD_CWORD_CWORD,
3052 /* 155 */ CWORD_CWORD_CWORD_CWORD,
3053 /* 156 */ CWORD_CWORD_CWORD_CWORD,
3054 /* 157 */ CWORD_CWORD_CWORD_CWORD,
3055 /* 158 */ CWORD_CWORD_CWORD_CWORD,
3056 /* 159 */ CWORD_CWORD_CWORD_CWORD,
3057 /* 160 */ CWORD_CWORD_CWORD_CWORD,
3058 /* 161 */ CWORD_CWORD_CWORD_CWORD,
3059 /* 162 */ CWORD_CWORD_CWORD_CWORD,
3060 /* 163 */ CWORD_CWORD_CWORD_CWORD,
3061 /* 164 */ CWORD_CWORD_CWORD_CWORD,
3062 /* 165 */ CWORD_CWORD_CWORD_CWORD,
3063 /* 166 */ CWORD_CWORD_CWORD_CWORD,
3064 /* 167 */ CWORD_CWORD_CWORD_CWORD,
3065 /* 168 */ CWORD_CWORD_CWORD_CWORD,
3066 /* 169 */ CWORD_CWORD_CWORD_CWORD,
3067 /* 170 */ CWORD_CWORD_CWORD_CWORD,
3068 /* 171 */ CWORD_CWORD_CWORD_CWORD,
3069 /* 172 */ CWORD_CWORD_CWORD_CWORD,
3070 /* 173 */ CWORD_CWORD_CWORD_CWORD,
3071 /* 174 */ CWORD_CWORD_CWORD_CWORD,
3072 /* 175 */ CWORD_CWORD_CWORD_CWORD,
3073 /* 176 */ CWORD_CWORD_CWORD_CWORD,
3074 /* 177 */ CWORD_CWORD_CWORD_CWORD,
3075 /* 178 */ CWORD_CWORD_CWORD_CWORD,
3076 /* 179 */ CWORD_CWORD_CWORD_CWORD,
3077 /* 180 */ CWORD_CWORD_CWORD_CWORD,
3078 /* 181 */ CWORD_CWORD_CWORD_CWORD,
3079 /* 182 */ CWORD_CWORD_CWORD_CWORD,
3080 /* 183 */ CWORD_CWORD_CWORD_CWORD,
3081 /* 184 */ CWORD_CWORD_CWORD_CWORD,
3082 /* 185 */ CWORD_CWORD_CWORD_CWORD,
3083 /* 186 */ CWORD_CWORD_CWORD_CWORD,
3084 /* 187 */ CWORD_CWORD_CWORD_CWORD,
3085 /* 188 */ CWORD_CWORD_CWORD_CWORD,
3086 /* 189 */ CWORD_CWORD_CWORD_CWORD,
3087 /* 190 */ CWORD_CWORD_CWORD_CWORD,
3088 /* 191 */ CWORD_CWORD_CWORD_CWORD,
3089 /* 192 */ CWORD_CWORD_CWORD_CWORD,
3090 /* 193 */ CWORD_CWORD_CWORD_CWORD,
3091 /* 194 */ CWORD_CWORD_CWORD_CWORD,
3092 /* 195 */ CWORD_CWORD_CWORD_CWORD,
3093 /* 196 */ CWORD_CWORD_CWORD_CWORD,
3094 /* 197 */ CWORD_CWORD_CWORD_CWORD,
3095 /* 198 */ CWORD_CWORD_CWORD_CWORD,
3096 /* 199 */ CWORD_CWORD_CWORD_CWORD,
3097 /* 200 */ CWORD_CWORD_CWORD_CWORD,
3098 /* 201 */ CWORD_CWORD_CWORD_CWORD,
3099 /* 202 */ CWORD_CWORD_CWORD_CWORD,
3100 /* 203 */ CWORD_CWORD_CWORD_CWORD,
3101 /* 204 */ CWORD_CWORD_CWORD_CWORD,
3102 /* 205 */ CWORD_CWORD_CWORD_CWORD,
3103 /* 206 */ CWORD_CWORD_CWORD_CWORD,
3104 /* 207 */ CWORD_CWORD_CWORD_CWORD,
3105 /* 208 */ CWORD_CWORD_CWORD_CWORD,
3106 /* 209 */ CWORD_CWORD_CWORD_CWORD,
3107 /* 210 */ CWORD_CWORD_CWORD_CWORD,
3108 /* 211 */ CWORD_CWORD_CWORD_CWORD,
3109 /* 212 */ CWORD_CWORD_CWORD_CWORD,
3110 /* 213 */ CWORD_CWORD_CWORD_CWORD,
3111 /* 214 */ CWORD_CWORD_CWORD_CWORD,
3112 /* 215 */ CWORD_CWORD_CWORD_CWORD,
3113 /* 216 */ CWORD_CWORD_CWORD_CWORD,
3114 /* 217 */ CWORD_CWORD_CWORD_CWORD,
3115 /* 218 */ CWORD_CWORD_CWORD_CWORD,
3116 /* 219 */ CWORD_CWORD_CWORD_CWORD,
3117 /* 220 */ CWORD_CWORD_CWORD_CWORD,
3118 /* 221 */ CWORD_CWORD_CWORD_CWORD,
3119 /* 222 */ CWORD_CWORD_CWORD_CWORD,
3120 /* 223 */ CWORD_CWORD_CWORD_CWORD,
3121 /* 224 */ CWORD_CWORD_CWORD_CWORD,
3122 /* 225 */ CWORD_CWORD_CWORD_CWORD,
3123 /* 226 */ CWORD_CWORD_CWORD_CWORD,
3124 /* 227 */ CWORD_CWORD_CWORD_CWORD,
3125 /* 228 */ CWORD_CWORD_CWORD_CWORD,
3126 /* 229 */ CWORD_CWORD_CWORD_CWORD,
3127 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3128 /* 231 */ CWORD_CWORD_CWORD_CWORD,
3129 /* 232 */ CWORD_CWORD_CWORD_CWORD,
3130 /* 233 */ CWORD_CWORD_CWORD_CWORD,
3131 /* 234 */ CWORD_CWORD_CWORD_CWORD,
3132 /* 235 */ CWORD_CWORD_CWORD_CWORD,
3133 /* 236 */ CWORD_CWORD_CWORD_CWORD,
3134 /* 237 */ CWORD_CWORD_CWORD_CWORD,
3135 /* 238 */ CWORD_CWORD_CWORD_CWORD,
3136 /* 239 */ CWORD_CWORD_CWORD_CWORD,
3137 /* 230 */ CWORD_CWORD_CWORD_CWORD,
3138 /* 241 */ CWORD_CWORD_CWORD_CWORD,
3139 /* 242 */ CWORD_CWORD_CWORD_CWORD,
3140 /* 243 */ CWORD_CWORD_CWORD_CWORD,
3141 /* 244 */ CWORD_CWORD_CWORD_CWORD,
3142 /* 245 */ CWORD_CWORD_CWORD_CWORD,
3143 /* 246 */ CWORD_CWORD_CWORD_CWORD,
3144 /* 247 */ CWORD_CWORD_CWORD_CWORD,
3145 /* 248 */ CWORD_CWORD_CWORD_CWORD,
3146 /* 249 */ CWORD_CWORD_CWORD_CWORD,
3147 /* 250 */ CWORD_CWORD_CWORD_CWORD,
3148 /* 251 */ CWORD_CWORD_CWORD_CWORD,
3149 /* 252 */ CWORD_CWORD_CWORD_CWORD,
3150 /* 253 */ CWORD_CWORD_CWORD_CWORD,
3151 /* 254 */ CWORD_CWORD_CWORD_CWORD,
3152 /* 255 */ CWORD_CWORD_CWORD_CWORD,
3153 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
3154 # if ENABLE_ASH_ALIAS
3155 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
3160 # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
3161 #else /* debug version, caught one signed char bug */
3162 # define SIT(c, syntax) \
3164 if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
3165 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3166 if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
3167 bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
3168 ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
3172 #endif /* !USE_SIT_FUNCTION */
3175 /* ============ Alias handling */
3177 #if ENABLE_ASH_ALIAS
3179 #define ALIASINUSE 1
3190 static struct alias **atab; // [ATABSIZE];
3191 #define INIT_G_alias() do { \
3192 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3196 static struct alias **
3197 __lookupalias(const char *name)
3199 unsigned int hashval;
3206 ch = (unsigned char)*p;
3210 ch = (unsigned char)*++p;
3212 app = &atab[hashval % ATABSIZE];
3214 for (; *app; app = &(*app)->next) {
3215 if (strcmp(name, (*app)->name) == 0) {
3223 static struct alias *
3224 lookupalias(const char *name, int check)
3226 struct alias *ap = *__lookupalias(name);
3228 if (check && ap && (ap->flag & ALIASINUSE))
3233 static struct alias *
3234 freealias(struct alias *ap)
3238 if (ap->flag & ALIASINUSE) {
3239 ap->flag |= ALIASDEAD;
3251 setalias(const char *name, const char *val)
3253 struct alias *ap, **app;
3255 app = __lookupalias(name);
3259 if (!(ap->flag & ALIASINUSE)) {
3262 ap->val = ckstrdup(val);
3263 ap->flag &= ~ALIASDEAD;
3266 ap = ckzalloc(sizeof(struct alias));
3267 ap->name = ckstrdup(name);
3268 ap->val = ckstrdup(val);
3269 /*ap->flag = 0; - ckzalloc did it */
3270 /*ap->next = NULL;*/
3277 unalias(const char *name)
3281 app = __lookupalias(name);
3285 *app = freealias(*app);
3296 struct alias *ap, **app;
3300 for (i = 0; i < ATABSIZE; i++) {
3302 for (ap = *app; ap; ap = *app) {
3303 *app = freealias(*app);
3313 printalias(const struct alias *ap)
3315 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3319 * TODO - sort output
3321 static int FAST_FUNC
3322 aliascmd(int argc UNUSED_PARAM, char **argv)
3331 for (i = 0; i < ATABSIZE; i++) {
3332 for (ap = atab[i]; ap; ap = ap->next) {
3338 while ((n = *++argv) != NULL) {
3339 v = strchr(n+1, '=');
3340 if (v == NULL) { /* n+1: funny ksh stuff */
3341 ap = *__lookupalias(n);
3343 fprintf(stderr, "%s: %s not found\n", "alias", n);
3356 static int FAST_FUNC
3357 unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3361 while (nextopt("a") != '\0') {
3365 for (i = 0; *argptr; argptr++) {
3366 if (unalias(*argptr)) {
3367 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
3375 #endif /* ASH_ALIAS */
3378 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3381 #define FORK_NOJOB 2
3383 /* mode flags for showjob(s) */
3384 #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3385 #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3386 #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
3387 #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
3390 * A job structure contains information about a job. A job is either a
3391 * single process or a set of processes contained in a pipeline. In the
3392 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3396 pid_t ps_pid; /* process id */
3397 int ps_status; /* last process status from wait() */
3398 char *ps_cmd; /* text of command being run */
3402 struct procstat ps0; /* status of process */
3403 struct procstat *ps; /* status or processes when more than one */
3405 int stopstatus; /* status of a stopped job */
3407 unsigned nprocs; /* number of processes */
3409 #define JOBRUNNING 0 /* at least one proc running */
3410 #define JOBSTOPPED 1 /* all procs are stopped */
3411 #define JOBDONE 2 /* all procs are completed */
3415 sigint: 1, /* job was killed by SIGINT */
3416 jobctl: 1, /* job running under job control */
3418 waited: 1, /* true if this entry has been waited for */
3419 used: 1, /* true if this entry is in used */
3420 changed: 1; /* true if status has changed */
3421 struct job *prev_job; /* previous job */
3424 static struct job *makejob(/*union node *,*/ int);
3425 static int forkshell(struct job *, union node *, int);
3426 static int waitforjob(struct job *);
3429 enum { doing_jobctl = 0 };
3430 #define setjobctl(on) do {} while (0)
3432 static smallint doing_jobctl; //references:8
3433 static void setjobctl(int);
3440 ignoresig(int signo)
3442 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3443 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3444 /* No, need to do it */
3445 signal(signo, SIG_IGN);
3447 sigmode[signo - 1] = S_HARD_IGN;
3451 * Only one usage site - in setsignal()
3454 signal_handler(int signo)
3456 if (signo == SIGCHLD) {
3462 gotsig[signo - 1] = 1;
3463 pending_sig = signo;
3465 if (signo == SIGINT && !trap[SIGINT]) {
3466 if (!suppress_int) {
3468 raise_interrupt(); /* does not return */
3475 * Set the signal handler for the specified signal. The routine figures
3476 * out what it should be set to.
3479 setsignal(int signo)
3482 char cur_act, new_act;
3483 struct sigaction act;
3487 if (t != NULL) { /* trap for this sig is set */
3489 if (t[0] == '\0') /* trap is "": ignore this sig */
3493 if (rootshell && new_act == S_DFL) {
3496 if (iflag || minusc || sflag == 0)
3505 * "In all cases, bash ignores SIGQUIT. Non-builtin
3506 * commands run by bash have signal handlers
3507 * set to the values inherited by the shell
3508 * from its parent". */
3524 //TODO: if !rootshell, we reset SIGQUIT to DFL,
3525 //whereas we have to restore it to what shell got on entry
3526 //from the parent. See comment above
3528 if (signo == SIGCHLD)
3531 t = &sigmode[signo - 1];
3534 /* current setting is not yet known */
3535 if (sigaction(signo, NULL, &act)) {
3536 /* pretend it worked; maybe we should give a warning,
3537 * but other shells don't. We don't alter sigmode,
3538 * so we retry every time.
3539 * btw, in Linux it never fails. --vda */
3542 if (act.sa_handler == SIG_IGN) {
3543 cur_act = S_HARD_IGN;
3545 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3547 cur_act = S_IGN; /* don't hard ignore these */
3551 if (cur_act == S_HARD_IGN || cur_act == new_act)
3554 act.sa_handler = SIG_DFL;
3557 act.sa_handler = signal_handler;
3560 act.sa_handler = SIG_IGN;
3564 /* flags and mask matter only if !DFL and !IGN, but we do it
3565 * for all cases for more deterministic behavior:
3568 sigfillset(&act.sa_mask);
3570 sigaction_set(signo, &act);
3575 /* mode flags for set_curjob */
3576 #define CUR_DELETE 2
3577 #define CUR_RUNNING 1
3578 #define CUR_STOPPED 0
3581 /* pgrp of shell on invocation */
3582 static int initialpgrp; //references:2
3583 static int ttyfd = -1; //5
3586 static struct job *jobtab; //5
3588 static unsigned njobs; //4
3590 static struct job *curjob; //lots
3591 /* number of presumed living untracked jobs */
3592 static int jobless; //4
3595 /* Bash has a feature: it restores termios after a successful wait for
3596 * a foreground job which had at least one stopped or sigkilled member.
3597 * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
3598 * properly restoring tty state. Should we do this too?
3599 * A reproducer: ^Z an interactive python:
3602 * Python 2.7.12 (...)
3604 * { python leaves tty in -icanon -echo state. We do survive that... }
3605 * [1]+ Stopped python
3606 * { ...however, next program (python #2) does not survive it well: }
3608 * Python 2.7.12 (...)
3609 * >>> Traceback (most recent call last):
3610 * { above, I typed "qwerty<CR>", but -echo state is still in effect }
3611 * File "<stdin>", line 1, in <module>
3612 * NameError: name 'qwerty' is not defined
3614 * The implementation below is modeled on bash code and seems to work.
3615 * However, I'm not sure we should do this. For one: what if I'd fg
3616 * the stopped python instead? It'll be confused by "restored" tty state.
3618 static struct termios shell_tty_info;
3622 if (rootshell && ttyfd >= 0)
3623 tcgetattr(ttyfd, &shell_tty_info);
3628 /* if (rootshell) - caller ensures this */
3630 tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
3633 job_signal_status(struct job *jp)
3637 struct procstat *ps = jp->ps;
3638 for (i = 0; i < jp->nprocs; i++) {
3639 status = ps[i].ps_status;
3640 if (WIFSIGNALED(status) || WIFSTOPPED(status))
3646 restore_tty_if_stopped_or_signaled(struct job *jp)
3648 //TODO: check what happens if we come from waitforjob() in expbackq()
3650 int s = job_signal_status(jp);
3651 if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
3656 # define get_tty_state() ((void)0)
3657 # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
3661 set_curjob(struct job *jp, unsigned mode)
3664 struct job **jpp, **curp;
3666 /* first remove from list */
3667 jpp = curp = &curjob;
3672 jpp = &jp1->prev_job;
3674 *jpp = jp1->prev_job;
3676 /* Then re-insert in correct position */
3684 /* job being deleted */
3687 /* newly created job or backgrounded job,
3688 * put after all stopped jobs.
3693 if (!jp1 || jp1->state != JOBSTOPPED)
3696 jpp = &jp1->prev_job;
3702 /* newly stopped job - becomes curjob */
3703 jp->prev_job = *jpp;
3711 jobno(const struct job *jp)
3713 return jp - jobtab + 1;
3718 * Convert a job name to a job structure.
3721 #define getjob(name, getctl) getjob(name)
3724 getjob(const char *name, int getctl)
3728 const char *err_msg = "%s: no such job";
3732 char *(*match)(const char *, const char *);
3747 if (c == '+' || c == '%') {
3749 err_msg = "No current job";
3755 err_msg = "No previous job";
3765 if (num > 0 && num <= njobs) {
3766 jp = jobtab + num - 1;
3781 if (match(jp->ps[0].ps_cmd, p)) {
3785 err_msg = "%s: ambiguous";
3795 err_msg = "job %s not created under job control";
3796 if (getctl && jp->jobctl == 0)
3801 ash_msg_and_raise_error(err_msg, name);
3805 * Mark a job structure as unused.
3808 freejob(struct job *jp)
3810 struct procstat *ps;
3814 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3815 if (ps->ps_cmd != nullstr)
3818 if (jp->ps != &jp->ps0)
3821 set_curjob(jp, CUR_DELETE);
3827 xtcsetpgrp(int fd, pid_t pgrp)
3829 if (tcsetpgrp(fd, pgrp))
3830 ash_msg_and_raise_error("can't set tty process group (%m)");
3834 * Turn job control on and off.
3836 * Note: This code assumes that the third arg to ioctl is a character
3837 * pointer, which is true on Berkeley systems but not System V. Since
3838 * System V doesn't have job control yet, this isn't a problem now.
3840 * Called with interrupts off.
3848 if (on == doing_jobctl || rootshell == 0)
3852 ofd = fd = open(_PATH_TTY, O_RDWR);
3854 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3855 * That sometimes helps to acquire controlling tty.
3856 * Obviously, a workaround for bugs when someone
3857 * failed to provide a controlling tty to bash! :) */
3863 /* fd is a tty at this point */
3864 fd = fcntl(fd, F_DUPFD, 10);
3865 if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
3868 goto out; /* F_DUPFD failed */
3869 close_on_exec_on(fd);
3870 while (1) { /* while we are in the background */
3871 pgrp = tcgetpgrp(fd);
3874 ash_msg("can't access tty; job control turned off");
3878 if (pgrp == getpgrp())
3889 xtcsetpgrp(fd, pgrp);
3891 /* turning job control off */
3894 /* was xtcsetpgrp, but this can make exiting ash
3895 * loop forever if pty is already deleted */
3896 tcsetpgrp(fd, pgrp);
3910 static int FAST_FUNC
3911 killcmd(int argc, char **argv)
3913 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3916 if (argv[i][0] == '%') {
3918 * "kill %N" - job kill
3919 * Converting to pgrp / pid kill
3925 jp = getjob(argv[i], 0);
3927 * In jobs started under job control, we signal
3928 * entire process group by kill -PGRP_ID.
3929 * This happens, f.e., in interactive shell.
3931 * Otherwise, we signal each child via
3932 * kill PID1 PID2 PID3.
3934 * sh -c 'sleep 1|sleep 1 & kill %1'
3935 * sh -c 'true|sleep 2 & sleep 1; kill %1'
3936 * sh -c 'true|sleep 1 & sleep 2; kill %1'
3938 n = jp->nprocs; /* can't be 0 (I hope) */
3941 dst = alloca(n * sizeof(int)*4);
3943 for (j = 0; j < n; j++) {
3944 struct procstat *ps = &jp->ps[j];
3945 /* Skip non-running and not-stopped members
3946 * (i.e. dead members) of the job
3948 if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
3951 * kill_main has matching code to expect
3952 * leading space. Needed to not confuse
3953 * negative pids with "kill -SIGNAL_NO" syntax
3955 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
3959 } while (argv[++i]);
3961 return kill_main(argc, argv);
3965 showpipe(struct job *jp /*, FILE *out*/)
3967 struct procstat *ps;
3968 struct procstat *psend;
3970 psend = jp->ps + jp->nprocs;
3971 for (ps = jp->ps + 1; ps < psend; ps++)
3972 printf(" | %s", ps->ps_cmd);
3973 newline_and_flush(stdout);
3974 flush_stdout_stderr();
3979 restartjob(struct job *jp, int mode)
3981 struct procstat *ps;
3987 if (jp->state == JOBDONE)
3989 jp->state = JOBRUNNING;
3990 pgid = jp->ps[0].ps_pid;
3991 if (mode == FORK_FG) {
3993 xtcsetpgrp(ttyfd, pgid);
3995 killpg(pgid, SIGCONT);
3999 if (WIFSTOPPED(ps->ps_status)) {
4005 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
4010 static int FAST_FUNC
4011 fg_bgcmd(int argc UNUSED_PARAM, char **argv)
4017 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
4021 jp = getjob(*argv, 1);
4022 if (mode == FORK_BG) {
4023 set_curjob(jp, CUR_RUNNING);
4024 printf("[%d] ", jobno(jp));
4026 out1str(jp->ps[0].ps_cmd);
4027 showpipe(jp /*, stdout*/);
4028 retval = restartjob(jp, mode);
4029 } while (*argv && *++argv);
4035 sprint_status48(char *s, int status, int sigonly)
4041 if (!WIFEXITED(status)) {
4043 if (WIFSTOPPED(status))
4044 st = WSTOPSIG(status);
4047 st = WTERMSIG(status);
4049 if (st == SIGINT || st == SIGPIPE)
4052 if (WIFSTOPPED(status))
4057 //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
4058 col = fmtstr(s, 32, strsignal(st));
4059 if (WCOREDUMP(status)) {
4060 strcpy(s + col, " (core dumped)");
4061 col += sizeof(" (core dumped)")-1;
4063 } else if (!sigonly) {
4064 st = WEXITSTATUS(status);
4065 col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
4072 wait_block_or_sig(int *status)
4079 /* Poll all children for changes in their state */
4081 /* if job control is active, accept stopped processes too */
4082 pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
4084 break; /* Error (e.g. EINTR, ECHILD) or pid */
4086 /* Children exist, but none are ready. Sleep until interesting signal */
4089 sigprocmask(SIG_SETMASK, &mask, &mask);
4090 while (!got_sigchld && !pending_sig)
4092 sigprocmask(SIG_SETMASK, &mask, NULL);
4093 #else /* unsafe: a signal can set pending_sig after check, but before pause() */
4094 while (!got_sigchld && !pending_sig)
4098 /* If it was SIGCHLD, poll children again */
4099 } while (got_sigchld);
4104 #define DOWAIT_NONBLOCK 0
4105 #define DOWAIT_BLOCK 1
4106 #define DOWAIT_BLOCK_OR_SIG 2
4109 dowait(int block, struct job *job)
4114 struct job *thisjob = NULL;
4116 TRACE(("dowait(0x%x) called\n", block));
4118 /* It's wrong to call waitpid() outside of INT_OFF region:
4119 * signal can arrive just after syscall return and handler can
4120 * longjmp away, losing stop/exit notification processing.
4121 * Thus, for "jobs" builtin, and for waiting for a fg job,
4122 * we call waitpid() (blocking or non-blocking) inside INT_OFF.
4124 * However, for "wait" builtin it is wrong to simply call waitpid()
4125 * in INT_OFF region: "wait" needs to wait for any running job
4126 * to change state, but should exit on any trap too.
4127 * In INT_OFF region, a signal just before syscall entry can set
4128 * pending_sig variables, but we can't check them, and we would
4129 * either enter a sleeping waitpid() (BUG), or need to busy-loop.
4131 * Because of this, we run inside INT_OFF, but use a special routine
4132 * which combines waitpid() and sigsuspend().
4133 * This is the reason why we need to have a handler for SIGCHLD:
4134 * SIG_DFL handler does not wake sigsuspend().
4137 if (block == DOWAIT_BLOCK_OR_SIG) {
4138 pid = wait_block_or_sig(&status);
4141 if (block == DOWAIT_NONBLOCK)
4142 wait_flags = WNOHANG;
4143 /* if job control is active, accept stopped processes too */
4145 wait_flags |= WUNTRACED;
4146 /* NB: _not_ safe_waitpid, we need to detect EINTR */
4147 pid = waitpid(-1, &status, wait_flags);
4149 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
4150 pid, status, errno, strerror(errno)));
4155 for (jp = curjob; jp; jp = jp->prev_job) {
4157 struct procstat *ps;
4158 struct procstat *psend;
4159 if (jp->state == JOBDONE)
4163 psend = ps + jp->nprocs;
4165 if (ps->ps_pid == pid) {
4166 TRACE(("Job %d: changing status of proc %d "
4167 "from 0x%x to 0x%x\n",
4168 jobno(jp), pid, ps->ps_status, status));
4169 ps->ps_status = status;
4172 if (ps->ps_status == -1)
4173 jobstate = JOBRUNNING;
4175 if (jobstate == JOBRUNNING)
4177 if (WIFSTOPPED(ps->ps_status)) {
4178 jp->stopstatus = ps->ps_status;
4179 jobstate = JOBSTOPPED;
4182 } while (++ps < psend);
4186 /* Found the job where one of its processes changed its state.
4187 * Is there at least one live and running process in this job? */
4188 if (jobstate != JOBRUNNING) {
4189 /* No. All live processes in the job are stopped
4190 * (JOBSTOPPED) or there are no live processes (JOBDONE)
4192 thisjob->changed = 1;
4193 if (thisjob->state != jobstate) {
4194 TRACE(("Job %d: changing state from %d to %d\n",
4195 jobno(thisjob), thisjob->state, jobstate));
4196 thisjob->state = jobstate;
4198 if (jobstate == JOBSTOPPED)
4199 set_curjob(thisjob, CUR_STOPPED);
4205 /* The process wasn't found in job list */
4207 if (!WIFSTOPPED(status))
4213 if (thisjob && thisjob == job) {
4217 len = sprint_status48(s, status, 1);
4229 showjob(struct job *jp, int mode)
4231 struct procstat *ps;
4232 struct procstat *psend;
4235 char s[16 + 16 + 48];
4236 FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
4240 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4241 /* just output process (group) id of pipeline */
4242 fprintf(out, "%d\n", ps->ps_pid);
4246 col = fmtstr(s, 16, "[%d] ", jobno(jp));
4251 else if (curjob && jp == curjob->prev_job)
4254 if (mode & SHOW_PIDS)
4255 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
4257 psend = ps + jp->nprocs;
4259 if (jp->state == JOBRUNNING) {
4260 strcpy(s + col, "Running");
4261 col += sizeof("Running") - 1;
4263 int status = psend[-1].ps_status;
4264 if (jp->state == JOBSTOPPED)
4265 status = jp->stopstatus;
4266 col += sprint_status48(s + col, status, 0);
4268 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
4270 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
4271 * or prints several "PID | <cmdN>" lines,
4272 * depending on SHOW_PIDS bit.
4273 * We do not print status of individual processes
4274 * between PID and <cmdN>. bash does it, but not very well:
4275 * first line shows overall job status, not process status,
4276 * making it impossible to know 1st process status.
4280 /* for each process */
4283 if (mode & SHOW_PIDS)
4284 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
4286 fprintf(out, "%s%*c%s%s",
4288 33 - col >= 0 ? 33 - col : 0, ' ',
4289 ps == jp->ps ? "" : "| ",
4292 } while (++ps != psend);
4293 newline_and_flush(out);
4297 if (jp->state == JOBDONE) {
4298 TRACE(("showjob: freeing job %d\n", jobno(jp)));
4304 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4305 * statuses have changed since the last call to showjobs.
4312 TRACE(("showjobs(0x%x) called\n", mode));
4314 /* Handle all finished jobs */
4315 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
4318 for (jp = curjob; jp; jp = jp->prev_job) {
4319 if (!(mode & SHOW_CHANGED) || jp->changed) {
4325 static int FAST_FUNC
4326 jobscmd(int argc UNUSED_PARAM, char **argv)
4331 while ((m = nextopt("lp")) != '\0') {
4335 mode |= SHOW_ONLY_PGID;
4341 showjob(getjob(*argv, 0), mode);
4351 /* Called only on finished or stopped jobs (no members are running) */
4353 getstatus(struct job *job)
4357 struct procstat *ps;
4359 /* Fetch last member's status */
4360 ps = job->ps + job->nprocs - 1;
4361 status = ps->ps_status;
4363 /* "set -o pipefail" mode: use last _nonzero_ status */
4364 while (status == 0 && --ps >= job->ps)
4365 status = ps->ps_status;
4368 retval = WEXITSTATUS(status);
4369 if (!WIFEXITED(status)) {
4371 retval = WSTOPSIG(status);
4372 if (!WIFSTOPPED(status))
4375 /* XXX: limits number of signals */
4376 retval = WTERMSIG(status);
4378 if (retval == SIGINT)
4384 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
4385 jobno(job), job->nprocs, status, retval));
4389 static int FAST_FUNC
4390 waitcmd(int argc UNUSED_PARAM, char **argv)
4401 /* wait for all jobs */
4405 if (!jp) /* no running procs */
4407 if (jp->state == JOBRUNNING)
4413 * "When bash is waiting for an asynchronous command via
4414 * the wait builtin, the reception of a signal for which a trap
4415 * has been set will cause the wait builtin to return immediately
4416 * with an exit status greater than 128, immediately after which
4417 * the trap is executed."
4419 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4420 /* if child sends us a signal *and immediately exits*,
4421 * dowait() returns pid > 0. Check this case,
4422 * not "if (dowait() < 0)"!
4431 if (**argv != '%') {
4432 pid_t pid = number(*argv);
4437 if (job->ps[job->nprocs - 1].ps_pid == pid)
4439 job = job->prev_job;
4442 job = getjob(*argv, 0);
4444 /* loop until process terminated or stopped */
4445 while (job->state == JOBRUNNING) {
4446 dowait(DOWAIT_BLOCK_OR_SIG, NULL);
4451 retval = getstatus(job);
4458 retval = 128 + pending_sig;
4467 struct job *jp, *jq;
4469 len = njobs * sizeof(*jp);
4471 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4473 offset = (char *)jp - (char *)jq;
4475 /* Relocate pointers */
4478 jq = (struct job *)((char *)jq + l);
4482 #define joff(p) ((struct job *)((char *)(p) + l))
4483 #define jmove(p) (p) = (void *)((char *)(p) + offset)
4484 if (joff(jp)->ps == &jq->ps0)
4485 jmove(joff(jp)->ps);
4486 if (joff(jp)->prev_job)
4487 jmove(joff(jp)->prev_job);
4497 jp = (struct job *)((char *)jp + len);
4501 } while (--jq >= jp);
4506 * Return a new job structure.
4507 * Called with interrupts off.
4510 makejob(/*union node *node,*/ int nprocs)
4515 for (i = njobs, jp = jobtab; ; jp++) {
4522 if (jp->state != JOBDONE || !jp->waited)
4531 memset(jp, 0, sizeof(*jp));
4533 /* jp->jobctl is a bitfield.
4534 * "jp->jobctl |= doing_jobctl" likely to give awful code */
4538 jp->prev_job = curjob;
4543 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4545 TRACE(("makejob(%d) returns %%%d\n", nprocs,
4552 * Return a string identifying a command (to be printed by the
4555 static char *cmdnextc;
4558 cmdputs(const char *s)
4560 static const char vstype[VSTYPE + 1][3] = {
4561 "", "}", "-", "+", "?", "=",
4562 "%", "%%", "#", "##"
4563 IF_BASH_SUBSTR(, ":")
4564 IF_BASH_PATTERN_SUBST(, "/", "//")
4567 const char *p, *str;
4571 unsigned char subtype = 0;
4575 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4577 while ((c = *p++) != '\0') {
4585 if ((subtype & VSTYPE) == VSLENGTH)
4591 str = "\"}" + !(quoted & 1);
4598 #if ENABLE_FEATURE_SH_MATH
4613 if ((subtype & VSTYPE) != VSNORMAL)
4615 str = vstype[subtype & VSTYPE];
4616 if (subtype & VSNUL)
4625 /* These can only happen inside quotes */
4638 while ((c = *str++) != '\0') {
4641 } /* while *p++ not NUL */
4644 USTPUTC('"', nextc);
4650 /* cmdtxt() and cmdlist() call each other */
4651 static void cmdtxt(union node *n);
4654 cmdlist(union node *np, int sep)
4656 for (; np; np = np->narg.next) {
4660 if (sep && np->narg.next)
4666 cmdtxt(union node *n)
4669 struct nodelist *lp;
4680 lp = n->npipe.cmdlist;
4698 cmdtxt(n->nbinary.ch1);
4714 cmdtxt(n->nif.test);
4716 if (n->nif.elsepart) {
4717 cmdtxt(n->nif.ifpart);
4719 n = n->nif.elsepart;
4737 cmdtxt(n->nbinary.ch1);
4747 cmdputs(n->nfor.var);
4749 cmdlist(n->nfor.args, 1);
4754 cmdputs(n->narg.text);
4758 cmdlist(n->ncmd.args, 1);
4759 cmdlist(n->ncmd.redirect, 0);
4772 cmdputs(n->ncase.expr->narg.text);
4774 for (np = n->ncase.cases; np; np = np->nclist.next) {
4775 cmdtxt(np->nclist.pattern);
4777 cmdtxt(np->nclist.body);
4791 #if BASH_REDIR_OUTPUT
4806 cmdputs(utoa(n->nfile.fd));
4808 if (n->type == NTOFD || n->type == NFROMFD) {
4809 cmdputs(utoa(n->ndup.dupfd));
4818 commandtext(union node *n)
4822 STARTSTACKSTR(cmdnextc);
4824 name = stackblock();
4825 TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
4826 return ckstrdup(name);
4831 * Fork off a subshell. If we are doing job control, give the subshell its
4832 * own process group. Jp is a job structure that the job is to be added to.
4833 * N is the command that will be evaluated by the child. Both jp and n may
4834 * be NULL. The mode parameter can be one of the following:
4835 * FORK_FG - Fork off a foreground process.
4836 * FORK_BG - Fork off a background process.
4837 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4838 * process group even if job control is on.
4840 * When job control is turned off, background processes have their standard
4841 * input redirected to /dev/null (except for the second and later processes
4844 * Called with interrupts off.
4847 * Clear traps on a fork.
4855 for (tp = trap; tp < &trap[NSIG]; tp++) {
4856 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
4857 if (trap_ptr == trap)
4859 /* else: it "belongs" to trap_ptr vector, don't free */
4861 if ((tp - trap) != 0)
4862 setsignal(tp - trap);
4869 /* Lives far away from here, needed for forkchild */
4870 static void closescript(void);
4872 /* Called after fork(), in child */
4873 /* jp and n are NULL when called by openhere() for heredoc support */
4874 static NOINLINE void
4875 forkchild(struct job *jp, union node *n, int mode)
4879 TRACE(("Child shell %d\n", getpid()));
4883 /* man bash: "Non-builtin commands run by bash have signal handlers
4884 * set to the values inherited by the shell from its parent".
4885 * Do we do it correctly? */
4889 if (mode == FORK_NOJOB /* is it `xxx` ? */
4890 && n && n->type == NCMD /* is it single cmd? */
4891 /* && n->ncmd.args->type == NARG - always true? */
4892 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
4893 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4894 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4896 TRACE(("Trap hack\n"));
4897 /* Awful hack for `trap` or $(trap).
4899 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4900 * contains an example where "trap" is executed in a subshell:
4902 * save_traps=$(trap)
4904 * eval "$save_traps"
4906 * Standard does not say that "trap" in subshell shall print
4907 * parent shell's traps. It only says that its output
4908 * must have suitable form, but then, in the above example
4909 * (which is not supposed to be normative), it implies that.
4911 * bash (and probably other shell) does implement it
4912 * (traps are reset to defaults, but "trap" still shows them),
4913 * but as a result, "trap" logic is hopelessly messed up:
4916 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4917 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4918 * # true | trap <--- trap is in subshell - no output (ditto)
4919 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4920 * trap -- 'echo Ho' SIGWINCH
4921 * # echo `(trap)` <--- in subshell in subshell - output
4922 * trap -- 'echo Ho' SIGWINCH
4923 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4924 * trap -- 'echo Ho' SIGWINCH
4926 * The rules when to forget and when to not forget traps
4927 * get really complex and nonsensical.
4929 * Our solution: ONLY bare $(trap) or `trap` is special.
4931 /* Save trap handler strings for trap builtin to print */
4932 trap_ptr = xmemdup(trap, sizeof(trap));
4933 /* Fall through into clearing traps */
4937 /* do job control only in root shell */
4939 if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
4942 if (jp->nprocs == 0)
4945 pgrp = jp->ps[0].ps_pid;
4946 /* this can fail because we are doing it in the parent also */
4948 if (mode == FORK_FG)
4949 xtcsetpgrp(ttyfd, pgrp);
4954 if (mode == FORK_BG) {
4955 /* man bash: "When job control is not in effect,
4956 * asynchronous commands ignore SIGINT and SIGQUIT" */
4959 if (jp->nprocs == 0) {
4961 if (open(bb_dev_null, O_RDONLY) != 0)
4962 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
4966 if (iflag) { /* why if iflag only? */
4971 * "In all cases, bash ignores SIGQUIT. Non-builtin
4972 * commands run by bash have signal handlers
4973 * set to the values inherited by the shell
4975 * Take care of the second rule: */
4979 if (n && n->type == NCMD
4980 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4982 TRACE(("Job hack\n"));
4983 /* "jobs": we do not want to clear job list for it,
4984 * instead we remove only _its_ own_ job from job list.
4985 * This makes "jobs .... | cat" more useful.
4991 for (jp = curjob; jp; jp = jp->prev_job)
4996 /* Called after fork(), in parent */
4998 #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
5001 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
5003 TRACE(("In parent shell: child = %d\n", pid));
5005 /* jp is NULL when called by openhere() for heredoc support */
5006 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
5012 if (mode != FORK_NOJOB && jp->jobctl) {
5015 if (jp->nprocs == 0)
5018 pgrp = jp->ps[0].ps_pid;
5019 /* This can fail because we are doing it in the child also */
5023 if (mode == FORK_BG) {
5024 backgndpid = pid; /* set $! */
5025 set_curjob(jp, CUR_RUNNING);
5028 struct procstat *ps = &jp->ps[jp->nprocs++];
5031 ps->ps_cmd = nullstr;
5033 if (doing_jobctl && n)
5034 ps->ps_cmd = commandtext(n);
5039 /* jp and n are NULL when called by openhere() for heredoc support */
5041 forkshell(struct job *jp, union node *n, int mode)
5045 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
5048 TRACE(("Fork failed, errno=%d", errno));
5051 ash_msg_and_raise_error("can't fork");
5054 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
5055 forkchild(jp, n, mode);
5057 forkparent(jp, n, mode, pid);
5063 * Wait for job to finish.
5065 * Under job control we have the problem that while a child process
5066 * is running interrupts generated by the user are sent to the child
5067 * but not to the shell. This means that an infinite loop started by
5068 * an interactive user may be hard to kill. With job control turned off,
5069 * an interactive user may place an interactive program inside a loop.
5070 * If the interactive program catches interrupts, the user doesn't want
5071 * these interrupts to also abort the loop. The approach we take here
5072 * is to have the shell ignore interrupt signals while waiting for a
5073 * foreground process to terminate, and then send itself an interrupt
5074 * signal if the child process was terminated by an interrupt signal.
5075 * Unfortunately, some programs want to do a bit of cleanup and then
5076 * exit on interrupt; unless these processes terminate themselves by
5077 * sending a signal to themselves (instead of calling exit) they will
5078 * confuse this approach.
5080 * Called with interrupts off.
5083 waitforjob(struct job *jp)
5087 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
5090 while (jp->state == JOBRUNNING) {
5091 /* In non-interactive shells, we _can_ get
5092 * a keyboard signal here and be EINTRed,
5093 * but we just loop back, waiting for command to complete.
5096 * "If bash is waiting for a command to complete and receives
5097 * a signal for which a trap has been set, the trap
5098 * will not be executed until the command completes."
5100 * Reality is that even if trap is not set, bash
5101 * will not act on the signal until command completes.
5102 * Try this. sleep5intoff.c:
5103 * #include <signal.h>
5104 * #include <unistd.h>
5107 * sigemptyset(&set);
5108 * sigaddset(&set, SIGINT);
5109 * sigaddset(&set, SIGQUIT);
5110 * sigprocmask(SIG_BLOCK, &set, NULL);
5114 * $ bash -c './sleep5intoff; echo hi'
5115 * ^C^C^C^C <--- pressing ^C once a second
5117 * $ bash -c './sleep5intoff; echo hi'
5118 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
5121 dowait(DOWAIT_BLOCK, jp);
5128 xtcsetpgrp(ttyfd, rootpid);
5129 restore_tty_if_stopped_or_signaled(jp);
5132 * This is truly gross.
5133 * If we're doing job control, then we did a TIOCSPGRP which
5134 * caused us (the shell) to no longer be in the controlling
5135 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
5136 * intuit from the subprocess exit status whether a SIGINT
5137 * occurred, and if so interrupt ourselves. Yuck. - mycroft
5139 if (jp->sigint) /* TODO: do the same with all signals */
5140 raise(SIGINT); /* ... by raise(jp->sig) instead? */
5142 if (jp->state == JOBDONE)
5149 * return 1 if there are stopped jobs, otherwise 0
5161 if (jp && jp->state == JOBSTOPPED) {
5162 out2str("You have stopped jobs.\n");
5172 * Code for dealing with input/output redirection.
5177 #define EMPTY -2 /* marks an unused slot in redirtab */
5178 #define CLOSED -3 /* marks a slot of previously-closed fd */
5181 * Handle here documents. Normally we fork off a process to write the
5182 * data to a pipe. If the document is short, we can stuff the data in
5183 * the pipe without forking.
5185 /* openhere needs this forward reference */
5186 static void expandhere(union node *arg, int fd);
5188 openhere(union node *redir)
5194 ash_msg_and_raise_error("pipe call failed");
5195 if (redir->type == NHERE) {
5196 len = strlen(redir->nhere.doc->narg.text);
5197 if (len <= PIPE_BUF) {
5198 full_write(pip[1], redir->nhere.doc->narg.text, len);
5202 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5205 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
5206 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
5207 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
5208 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
5209 signal(SIGPIPE, SIG_DFL);
5210 if (redir->type == NHERE)
5211 full_write(pip[1], redir->nhere.doc->narg.text, len);
5213 expandhere(redir->nhere.doc, pip[1]);
5214 _exit(EXIT_SUCCESS);
5222 openredirect(union node *redir)
5228 switch (redir->nfile.type) {
5229 /* Can't happen, our single caller does this itself */
5235 return openhere(redir);
5238 /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
5239 * allocated space. Do it only when we know it is safe.
5241 fname = redir->nfile.expfname;
5243 switch (redir->nfile.type) {
5249 f = open(fname, O_RDONLY);
5254 f = open(fname, O_RDWR|O_CREAT, 0666);
5259 #if BASH_REDIR_OUTPUT
5262 /* Take care of noclobber mode. */
5264 if (stat(fname, &sb) < 0) {
5265 f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
5268 } else if (!S_ISREG(sb.st_mode)) {
5269 f = open(fname, O_WRONLY, 0666);
5272 if (fstat(f, &sb) < 0 && S_ISREG(sb.st_mode)) {
5285 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
5290 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5298 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
5300 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
5304 * Copy a file descriptor to be >= 10. Throws exception on error.
5312 newfd = fcntl(from, F_DUPFD, 10);
5313 err = newfd < 0 ? errno : 0;
5316 ash_msg_and_raise_error("%d: %m", from);
5318 fcntl(newfd, F_SETFD, FD_CLOEXEC);
5324 dup2_or_raise(int from, int to)
5328 newfd = (from != to) ? dup2(from, to) : to;
5330 /* Happens when source fd is not open: try "echo >&99" */
5331 ash_msg_and_raise_error("%d: %m", from);
5336 /* Struct def and variable are moved down to the first usage site */
5341 struct redirtab *next;
5343 struct two_fd_t two_fd[];
5345 #define redirlist (G_var.redirlist)
5347 COPYFD_RESTORE = (int)~(INT_MAX),
5351 need_to_remember(struct redirtab *rp, int fd)
5355 if (!rp) /* remembering was not requested */
5358 for (i = 0; i < rp->pair_count; i++) {
5359 if (rp->two_fd[i].orig == fd) {
5360 /* already remembered */
5367 /* "hidden" fd is a fd used to read scripts, or a copy of such */
5369 is_hidden_fd(struct redirtab *rp, int fd)
5372 struct parsefile *pf;
5376 /* Check open scripts' fds */
5379 /* We skip pf_fd == 0 case because of the following case:
5380 * $ ash # running ash interactively
5382 * and in script.sh: "exec 9>&0".
5383 * Even though top-level pf_fd _is_ 0,
5384 * it's still ok to use it: "read" builtin uses it,
5385 * why should we cripple "exec" builtin?
5387 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
5395 /* Check saved fds of redirects */
5396 fd |= COPYFD_RESTORE;
5397 for (i = 0; i < rp->pair_count; i++) {
5398 if (rp->two_fd[i].copy == fd) {
5406 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5407 * old file descriptors are stashed away so that the redirection can be
5408 * undone by calling popredir.
5410 /* flags passed to redirect */
5411 #define REDIR_PUSH 01 /* save previous values of file descriptors */
5412 #define REDIR_SAVEFD2 03 /* set preverrout */
5414 redirect(union node *redir, int flags)
5416 struct redirtab *sv;
5421 int copied_fd2 = -1;
5430 if (flags & REDIR_PUSH) {
5431 union node *tmp = redir;
5434 #if BASH_REDIR_OUTPUT
5435 if (tmp->nfile.type == NTO2)
5438 tmp = tmp->nfile.next;
5440 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
5441 sv->next = redirlist;
5442 sv->pair_count = sv_pos;
5444 while (sv_pos > 0) {
5446 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5452 fd = redir->nfile.fd;
5453 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
5454 right_fd = redir->ndup.dupfd;
5455 //bb_error_msg("doing %d > %d", fd, right_fd);
5456 /* redirect from/to same file descriptor? */
5459 /* "echo >&10" and 10 is a fd opened to a sh script? */
5460 if (is_hidden_fd(sv, right_fd)) {
5461 errno = EBADF; /* as if it is closed */
5462 ash_msg_and_raise_error("%d: %m", right_fd);
5466 newfd = openredirect(redir); /* always >= 0 */
5468 /* Descriptor wasn't open before redirect.
5469 * Mark it for close in the future */
5470 if (need_to_remember(sv, fd)) {
5471 goto remember_to_close;
5476 #if BASH_REDIR_OUTPUT
5479 if (need_to_remember(sv, fd)) {
5480 /* Copy old descriptor */
5481 /* Careful to not accidentally "save"
5482 * to the same fd as right side fd in N>&M */
5483 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5484 #if defined(F_DUPFD_CLOEXEC)
5485 i = fcntl(fd, F_DUPFD_CLOEXEC, minfd);
5487 i = fcntl(fd, F_DUPFD, minfd);
5492 /* Strange error (e.g. "too many files" EMFILE?) */
5496 ash_msg_and_raise_error("%d: %m", fd);
5499 /* EBADF: it is not open - good, remember to close it */
5502 } else { /* fd is open, save its copy */
5503 #if !defined(F_DUPFD_CLOEXEC)
5504 fcntl(i, F_SETFD, FD_CLOEXEC);
5506 /* "exec fd>&-" should not close fds
5507 * which point to script file(s).
5508 * Force them to be restored afterwards */
5509 if (is_hidden_fd(sv, fd))
5510 i |= COPYFD_RESTORE;
5514 sv->two_fd[sv_pos].orig = fd;
5515 sv->two_fd[sv_pos].copy = i;
5519 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
5520 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
5521 /* Don't want to trigger debugging */
5525 dup2_or_raise(redir->ndup.dupfd, fd);
5527 } else if (fd != newfd) { /* move newfd to fd */
5528 dup2_or_raise(newfd, fd);
5529 #if BASH_REDIR_OUTPUT
5530 if (!(redir->nfile.type == NTO2 && fd == 2))
5534 #if BASH_REDIR_OUTPUT
5535 if (redir->nfile.type == NTO2 && fd == 1) {
5536 /* We already redirected it to fd 1, now copy it to 2 */
5542 } while ((redir = redir->nfile.next) != NULL);
5545 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5546 preverrout_fd = copied_fd2;
5550 * Undo the effects of the last redirection.
5553 popredir(int drop, int restore)
5555 struct redirtab *rp;
5558 if (redirlist == NULL)
5562 for (i = 0; i < rp->pair_count; i++) {
5563 int fd = rp->two_fd[i].orig;
5564 int copy = rp->two_fd[i].copy;
5565 if (copy == CLOSED) {
5570 if (copy != EMPTY) {
5571 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
5572 copy &= ~COPYFD_RESTORE;
5574 dup2_or_raise(copy, fd);
5576 close(copy & ~COPYFD_RESTORE);
5579 redirlist = rp->next;
5585 * Undo all redirections. Called on error or interrupt.
5589 redirectsafe(union node *redir, int flags)
5592 volatile int saveint;
5593 struct jmploc *volatile savehandler = exception_handler;
5594 struct jmploc jmploc;
5597 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5598 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
5600 exception_handler = &jmploc;
5601 redirect(redir, flags);
5603 exception_handler = savehandler;
5604 if (err && exception_type != EXERROR)
5605 longjmp(exception_handler->loc, 1);
5606 RESTORE_INT(saveint);
5611 /* ============ Routines to expand arguments to commands
5613 * We have to deal with backquotes, shell variables, and file metacharacters.
5616 #if ENABLE_FEATURE_SH_MATH
5618 ash_arith(const char *s)
5620 arith_state_t math_state;
5623 math_state.lookupvar = lookupvar;
5624 math_state.setvar = setvar0;
5625 //math_state.endofname = endofname;
5628 result = arith(&math_state, s);
5629 if (math_state.errmsg)
5630 ash_msg_and_raise_error(math_state.errmsg);
5640 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
5641 #define EXP_TILDE 0x2 /* do normal tilde expansion */
5642 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5643 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5644 /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
5645 * POSIX says for this case:
5646 * Pathname expansion shall not be performed on the word by a
5647 * non-interactive shell; an interactive shell may perform it, but shall
5648 * do so only when the expansion would result in one word.
5649 * Currently, our code complies to the above rule by never globbing
5650 * redirection filenames.
5651 * Bash performs globbing, unless it is non-interactive and in POSIX mode.
5652 * (this means that on a typical Linux distro, bash almost always
5653 * performs globbing, and thus diverges from what we do).
5655 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5656 #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
5657 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5658 #define EXP_WORD 0x80 /* expand word in parameter expansion */
5659 #define EXP_QUOTED 0x100 /* expand word in double quotes */
5663 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5664 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5665 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5666 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5667 #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
5669 /* Add CTLESC when necessary. */
5670 #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT)
5671 /* Do not skip NUL characters. */
5672 #define QUOTES_KEEPNUL EXP_TILDE
5675 * Structure specifying which parts of the string should be searched
5676 * for IFS characters.
5679 struct ifsregion *next; /* next region in list */
5680 int begoff; /* offset of start of region */
5681 int endoff; /* offset of end of region */
5682 int nulonly; /* search for nul bytes only */
5686 struct strlist *list;
5687 struct strlist **lastp;
5690 /* output of current string */
5691 static char *expdest;
5692 /* list of back quote expressions */
5693 static struct nodelist *argbackq;
5694 /* first struct in list of ifs regions */
5695 static struct ifsregion ifsfirst;
5696 /* last struct in list */
5697 static struct ifsregion *ifslastp;
5698 /* holds expanded arg list */
5699 static struct arglist exparg;
5703 * cvtnum() is used even if math support is off (to prepare $? values and such).
5710 /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
5711 len = sizeof(arith_t) * 3;
5712 /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
5713 if (sizeof(arith_t) < 4) len += 2;
5715 expdest = makestrspace(len, expdest);
5716 len = fmtstr(expdest, len, ARITH_FMT, num);
5717 STADJUST(len, expdest);
5722 * Break the argument string into pieces based upon IFS and add the
5723 * strings to the argument list. The regions of the string to be
5724 * searched for IFS characters have been stored by recordregion.
5727 ifsbreakup(char *string, struct arglist *arglist)
5729 struct ifsregion *ifsp;
5734 const char *ifs, *realifs;
5739 if (ifslastp != NULL) {
5742 realifs = ifsset() ? ifsval() : defifs;
5745 p = string + ifsp->begoff;
5746 nulonly = ifsp->nulonly;
5747 ifs = nulonly ? nullstr : realifs;
5749 while (p < string + ifsp->endoff) {
5751 if ((unsigned char)*p == CTLESC)
5753 if (!strchr(ifs, *p)) {
5758 ifsspc = (strchr(defifs, *p) != NULL);
5759 /* Ignore IFS whitespace at start */
5760 if (q == start && ifsspc) {
5766 sp = stzalloc(sizeof(*sp));
5768 *arglist->lastp = sp;
5769 arglist->lastp = &sp->next;
5773 if (p >= string + ifsp->endoff) {
5777 if ((unsigned char)*p == CTLESC)
5779 if (strchr(ifs, *p) == NULL) {
5783 if (strchr(defifs, *p) == NULL) {
5798 } while (ifsp != NULL);
5807 sp = stzalloc(sizeof(*sp));
5809 *arglist->lastp = sp;
5810 arglist->lastp = &sp->next;
5816 struct ifsregion *p = ifsfirst.next;
5823 struct ifsregion *ifsp;
5828 ifsfirst.next = NULL;
5835 esclen(const char *start, const char *p)
5839 while (p > start && (unsigned char)*--p == CTLESC) {
5846 * Remove any CTLESC characters from a string.
5849 rmescapes(char *str, int flag)
5851 static const char qchars[] ALIGN1 = {
5852 IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
5856 unsigned protect_against_glob;
5858 IF_BASH_PATTERN_SUBST(unsigned slash = flag & RMESCAPE_SLASH;)
5860 p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash));
5866 if (flag & RMESCAPE_ALLOC) {
5867 size_t len = p - str;
5868 size_t fulllen = len + strlen(p) + 1;
5870 if (flag & RMESCAPE_GROW) {
5871 int strloc = str - (char *)stackblock();
5872 r = makestrspace(fulllen, expdest);
5873 /* p and str may be invalidated by makestrspace */
5874 str = (char *)stackblock() + strloc;
5876 } else if (flag & RMESCAPE_HEAP) {
5877 r = ckmalloc(fulllen);
5879 r = stalloc(fulllen);
5883 q = (char *)mempcpy(q, str, len);
5888 globbing = flag & RMESCAPE_GLOB;
5889 protect_against_glob = globbing;
5891 if ((unsigned char)*p == CTLQUOTEMARK) {
5892 // Note: both inquotes and protect_against_glob only affect whether
5893 // CTLESC,<ch> gets converted to <ch> or to \<ch>
5894 inquotes = ~inquotes;
5896 protect_against_glob = globbing;
5899 if ((unsigned char)*p == CTLESC) {
5903 ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
5905 if (protect_against_glob) {
5907 * We used to trust glob() and fnmatch() to eat
5908 * superfluous escapes (\z where z has no
5909 * special meaning anyway). But this causes
5910 * bugs such as string of one greek letter rho
5911 * (unicode-encoded as two bytes "cf,81")
5912 * getting encoded as "cf,CTLESC,81"
5913 * and here, converted to "cf,\,81" -
5914 * which does not go well with some flavors
5915 * of fnmatch() in unicode locales
5916 * (for example, glibc <= 2.22).
5918 * Lets add "\" only on the chars which need it.
5919 * Testcases for less obvious chars are shown.
5924 || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
5925 || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
5926 || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
5927 || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
5928 /* Some libc support [^negate], that's why "^" also needs love */
5929 || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
5934 } else if (*p == '\\' && !inquotes) {
5935 /* naked back slash */
5936 protect_against_glob = 0;
5939 #if BASH_PATTERN_SUBST
5940 else if (*p == '/' && slash) {
5941 /* stop handling globbing and mark location of slash */
5942 globbing = slash = 0;
5946 protect_against_glob = globbing;
5951 if (flag & RMESCAPE_GROW) {
5953 STADJUST(q - r + 1, expdest);
5957 #define pmatch(a, b) !fnmatch((a), (b), 0)
5960 * Prepare a pattern for a expmeta (internal glob(3)) call.
5962 * Returns an stalloced string.
5965 preglob(const char *pattern, int flag)
5967 return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
5971 * Put a string on the stack.
5974 memtodest(const char *p, size_t len, int syntax, int quotes)
5981 q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
5984 unsigned char c = *p++;
5986 if (quotes & QUOTES_ESC) {
5987 int n = SIT(c, syntax);
5989 || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
5996 } else if (!(quotes & QUOTES_KEEPNUL))
6005 strtodest(const char *p, int syntax, int quotes)
6007 size_t len = strlen(p);
6008 memtodest(p, len, syntax, quotes);
6013 * Record the fact that we have to scan this region of the
6014 * string for IFS characters.
6017 recordregion(int start, int end, int nulonly)
6019 struct ifsregion *ifsp;
6021 if (ifslastp == NULL) {
6025 ifsp = ckzalloc(sizeof(*ifsp));
6026 /*ifsp->next = NULL; - ckzalloc did it */
6027 ifslastp->next = ifsp;
6031 ifslastp->begoff = start;
6032 ifslastp->endoff = end;
6033 ifslastp->nulonly = nulonly;
6037 removerecordregions(int endoff)
6039 if (ifslastp == NULL)
6042 if (ifsfirst.endoff > endoff) {
6043 while (ifsfirst.next) {
6044 struct ifsregion *ifsp;
6046 ifsp = ifsfirst.next->next;
6047 free(ifsfirst.next);
6048 ifsfirst.next = ifsp;
6051 if (ifsfirst.begoff > endoff) {
6054 ifslastp = &ifsfirst;
6055 ifsfirst.endoff = endoff;
6060 ifslastp = &ifsfirst;
6061 while (ifslastp->next && ifslastp->next->begoff < endoff)
6062 ifslastp = ifslastp->next;
6063 while (ifslastp->next) {
6064 struct ifsregion *ifsp;
6066 ifsp = ifslastp->next->next;
6067 free(ifslastp->next);
6068 ifslastp->next = ifsp;
6071 if (ifslastp->endoff > endoff)
6072 ifslastp->endoff = endoff;
6076 exptilde(char *startp, char *p, int flags)
6082 int quotes = flags & QUOTES_ESC;
6086 while ((c = *++p) != '\0') {
6093 if (flags & EXP_VARTILDE)
6103 if (*name == '\0') {
6104 home = lookupvar("HOME");
6106 pw = getpwnam(name);
6111 if (!home || !*home)
6114 strtodest(home, SQSYNTAX, quotes);
6122 * Execute a command inside back quotes. If it's a builtin command, we
6123 * want to save its output in a block obtained from malloc. Otherwise
6124 * we fork off a subprocess and get the output of the command via a pipe.
6125 * Should be called with interrupts off.
6127 struct backcmd { /* result of evalbackcmd */
6128 int fd; /* file descriptor to read from */
6129 int nleft; /* number of chars in buffer */
6130 char *buf; /* buffer */
6131 struct job *jp; /* job structure for command */
6134 /* These forward decls are needed to use "eval" code for backticks handling: */
6135 /* flags in argument to evaltree */
6136 #define EV_EXIT 01 /* exit after evaluating tree */
6137 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
6138 static int evaltree(union node *, int);
6140 static void FAST_FUNC
6141 evalbackcmd(union node *n, struct backcmd *result)
6155 ash_msg_and_raise_error("pipe call failed");
6156 jp = makejob(/*n,*/ 1);
6157 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6163 dup2_or_raise(pip[1], 1);
6166 /* TODO: eflag clearing makes the following not abort:
6167 * ash -c 'set -e; z=$(false;echo foo); echo $z'
6168 * which is what bash does (unless it is in POSIX mode).
6169 * dash deleted "eflag = 0" line in the commit
6170 * Date: Mon, 28 Jun 2010 17:11:58 +1000
6171 * [EVAL] Don't clear eflag in evalbackcmd
6172 * For now, preserve bash-like behavior, it seems to be somewhat more useful:
6176 evaltree(n, EV_EXIT); /* actually evaltreenr... */
6181 result->fd = pip[0];
6185 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
6186 result->fd, result->buf, result->nleft, result->jp));
6190 * Expand stuff in backwards quotes.
6193 expbackq(union node *cmd, int flag)
6201 int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
6202 struct stackmark smark;
6205 startloc = expdest - (char *)stackblock();
6206 pushstackmark(&smark, startloc);
6207 evalbackcmd(cmd, &in);
6208 popstackmark(&smark);
6215 memtodest(p, i, syntax, flag & QUOTES_ESC);
6219 i = nonblock_immune_read(in.fd, buf, sizeof(buf));
6220 TRACE(("expbackq: read returns %d\n", i));
6229 back_exitstatus = waitforjob(in.jp);
6233 /* Eat all trailing newlines */
6235 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
6239 if (!(flag & EXP_QUOTED))
6240 recordregion(startloc, dest - (char *)stackblock(), 0);
6241 TRACE(("evalbackq: size:%d:'%.*s'\n",
6242 (int)((dest - (char *)stackblock()) - startloc),
6243 (int)((dest - (char *)stackblock()) - startloc),
6244 stackblock() + startloc));
6247 #if ENABLE_FEATURE_SH_MATH
6249 * Expand arithmetic expression. Backup to start of expression,
6250 * evaluate, place result in (backed up) result, adjust string position.
6262 * This routine is slightly over-complicated for
6263 * efficiency. Next we scan backwards looking for the
6264 * start of arithmetic.
6266 start = stackblock();
6273 while ((unsigned char)*p != CTLARI) {
6277 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
6282 esc = esclen(start, p);
6292 removerecordregions(begoff);
6296 if (flag & QUOTES_ESC)
6297 rmescapes(p + 1, 0);
6299 len = cvtnum(ash_arith(p + 1));
6301 if (!(flag & EXP_QUOTED))
6302 recordregion(begoff, begoff + len, 0);
6306 /* argstr needs it */
6307 static char *evalvar(char *p, int flags, struct strlist *var_str_list);
6310 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
6311 * characters to allow for further processing. Otherwise treat
6312 * $@ like $* since no splitting will be performed.
6314 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
6315 * over shell variables. Needed for "A=a B=$A; echo $B" case - we use it
6316 * for correct expansion of "B=$A" word.
6319 argstr(char *p, int flags, struct strlist *var_str_list)
6321 static const char spclchars[] ALIGN1 = {
6329 #if ENABLE_FEATURE_SH_MATH
6334 const char *reject = spclchars;
6335 int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
6340 if (!(flags & EXP_VARTILDE)) {
6342 } else if (flags & EXP_VARTILDE2) {
6347 if (flags & EXP_TILDE) {
6350 flags &= ~EXP_TILDE;
6354 p = exptilde(p, q, flags);
6357 startloc = expdest - (char *)stackblock();
6361 length += strcspn(p + length, reject);
6365 IF_FEATURE_SH_MATH(|| c == CTLENDARI)
6367 /* c == '=' || c == ':' || c == CTLENDARI */
6373 expdest = stack_nputstr(p, length, expdest);
6374 newloc = expdest - (char *)stackblock();
6375 if (breakall && !inquotes && newloc > startloc) {
6376 recordregion(startloc, newloc, 0);
6387 if (flags & EXP_VARTILDE2) {
6391 flags |= EXP_VARTILDE2;
6396 * sort of a hack - expand tildes in variable
6397 * assignments (after the first '=' and after ':'s).
6406 case CTLENDVAR: /* ??? */
6409 inquotes ^= EXP_QUOTED;
6410 /* "$@" syntax adherence hack */
6411 if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
6412 p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
6416 if (flags & QUOTES_ESC) {
6427 * Quoted parameter expansion pattern: remove quote
6428 * unless inside inner quotes or we have a literal
6431 if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
6432 EXP_QPAT && *p != '\\')
6437 TRACE(("argstr: evalvar('%s')\n", p));
6438 p = evalvar(p, flags | inquotes, var_str_list);
6439 TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
6442 expbackq(argbackq->n, flags | inquotes);
6443 argbackq = argbackq->next;
6445 #if ENABLE_FEATURE_SH_MATH
6448 expari(flags | inquotes);
6457 scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
6458 char *pattern, int quotes, int zero)
6467 const char *s = loc2;
6474 match = pmatch(pattern, s);
6479 if (quotes && (unsigned char)*loc == CTLESC)
6488 scanright(char *startp, char *rmesc, char *rmescend,
6489 char *pattern, int quotes, int match_at_start)
6491 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6492 int try2optimize = match_at_start;
6498 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6499 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6500 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6502 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6503 * and on each iteration they go back two/one char until they reach the beginning.
6504 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6506 /* TODO: document in what other circumstances we are called. */
6508 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
6511 const char *s = loc2;
6512 if (match_at_start) {
6516 match = pmatch(pattern, s);
6517 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
6521 #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6523 /* Maybe we can optimize this:
6524 * if pattern ends with unescaped *, we can avoid checking
6525 * shorter strings: if "foo*" doesn't match "raw_value_of_v",
6526 * it won't match truncated "raw_value_of_" strings too.
6528 unsigned plen = strlen(pattern);
6529 /* Does it end with "*"? */
6530 if (plen != 0 && pattern[--plen] == '*') {
6531 /* "xxxx*" is not escaped */
6532 /* "xxx\*" is escaped */
6533 /* "xx\\*" is not escaped */
6534 /* "x\\\*" is escaped */
6536 while (plen != 0 && pattern[--plen] == '\\')
6539 break; /* ends with unescaped "*" */
6547 esc = esclen(startp, loc);
6558 static void varunset(const char *, const char *, const char *, int) NORETURN;
6560 varunset(const char *end, const char *var, const char *umsg, int varflags)
6566 msg = "parameter not set";
6568 if ((unsigned char)*end == CTLENDVAR) {
6569 if (varflags & VSNUL)
6575 ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
6579 subevalvar(char *p, char *varname, int strloc, int subtype,
6580 int startloc, int varflags, int flag, struct strlist *var_str_list)
6582 struct nodelist *saveargbackq = argbackq;
6583 int quotes = flag & QUOTES_ESC;
6586 char *rmesc, *rmescend;
6588 int amount, resetloc;
6589 IF_BASH_PATTERN_SUBST(int workloc;)
6590 IF_BASH_PATTERN_SUBST(char *repl = NULL;)
6592 char *(*scan)(char*, char*, char*, char*, int, int);
6594 //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
6595 // p, varname, strloc, subtype, startloc, varflags, quotes);
6597 argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
6598 (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
6600 STPUTC('\0', expdest);
6601 argbackq = saveargbackq;
6602 startp = (char *)stackblock() + startloc;
6606 setvar0(varname, startp);
6607 amount = startp - expdest;
6608 STADJUST(amount, expdest);
6612 varunset(p, varname, startp, varflags);
6617 int pos, len, orig_len;
6620 loc = str = stackblock() + strloc;
6622 # if !ENABLE_FEATURE_SH_MATH
6623 # define ash_arith number
6625 /* Read POS in ${var:POS:LEN} */
6626 colon = strchr(loc, ':');
6627 if (colon) *colon = '\0';
6628 pos = ash_arith(loc);
6629 if (colon) *colon = ':';
6631 /* Read LEN in ${var:POS:LEN} */
6632 len = str - startp - 1;
6633 /* *loc != '\0', guaranteed by parser */
6637 /* Adjust the length by the number of escapes */
6638 for (ptr = startp; ptr < (str - 1); ptr++) {
6639 if ((unsigned char)*ptr == CTLESC) {
6646 if (*loc++ == ':') {
6648 len = ash_arith(loc);
6650 /* Skip POS in ${var:POS:LEN} */
6652 while (*loc && *loc != ':') {
6655 if (*loc++ == ':') {
6656 len = ash_arith(loc);
6662 /* ${VAR:$((-n)):l} starts n chars from the end */
6663 pos = orig_len + pos;
6665 if ((unsigned)pos >= orig_len) {
6666 /* apart from obvious ${VAR:999999:l},
6667 * covers ${VAR:$((-9999999)):l} - result is ""
6674 /* ${VAR:N:-M} sets LEN to strlen()-M */
6675 len = (orig_len - pos) + len;
6677 if ((unsigned)len > (orig_len - pos))
6678 len = orig_len - pos;
6680 for (str = startp; pos; str++, pos--) {
6681 if (quotes && (unsigned char)*str == CTLESC)
6684 for (loc = startp; len; len--) {
6685 if (quotes && (unsigned char)*str == CTLESC)
6690 amount = loc - expdest;
6691 STADJUST(amount, expdest);
6694 #endif /* BASH_SUBSTR */
6697 resetloc = expdest - (char *)stackblock();
6699 #if BASH_PATTERN_SUBST
6700 /* We'll comeback here if we grow the stack while handling
6701 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6702 * stack will need rebasing, and we'll need to remove our work
6708 amount = expdest - ((char *)stackblock() + resetloc);
6709 STADJUST(-amount, expdest);
6710 startp = (char *)stackblock() + startloc;
6713 rmescend = (char *)stackblock() + strloc;
6715 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
6716 if (rmesc != startp) {
6718 startp = (char *)stackblock() + startloc;
6722 str = (char *)stackblock() + strloc;
6724 * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
6725 * The result is a_\_z_c (not a\_\_z_c)!
6727 * The search pattern and replace string treat backslashes differently!
6728 * RMESCAPE_SLASH causes preglob to work differently on the pattern
6729 * and string. It's only used on the first call.
6731 preglob(str, IF_BASH_PATTERN_SUBST(
6732 (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
6733 RMESCAPE_SLASH : ) 0);
6735 #if BASH_PATTERN_SUBST
6736 workloc = expdest - (char *)stackblock();
6737 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6742 repl = strchr(str, CTLESC);
6748 //bb_error_msg("str:'%s' repl:'%s'", str, repl);
6750 /* If there's no pattern to match, return the expansion unmolested */
6759 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6760 //bb_error_msg("scanright('%s'):'%s'", str, loc);
6762 /* No match, advance */
6763 char *restart_detect = stackblock();
6765 STPUTC(*idx, expdest);
6766 if (quotes && (unsigned char)*idx == CTLESC) {
6769 STPUTC(*idx, expdest);
6771 if (stackblock() != restart_detect)
6776 /* continue; - prone to quadratic behavior, smarter code: */
6779 if (str[0] == '*') {
6780 /* Pattern is "*foo". If "*foo" does not match "long_string",
6781 * it would never match "ong_string" etc, no point in trying.
6788 if (subtype == VSREPLACEALL) {
6790 if (quotes && (unsigned char)*idx == CTLESC)
6799 //bb_error_msg("repl:'%s'", repl);
6800 for (loc = (char*)repl; *loc; loc++) {
6801 char *restart_detect = stackblock();
6802 if (quotes && *loc == '\\') {
6803 STPUTC(CTLESC, expdest);
6806 STPUTC(*loc, expdest);
6807 if (stackblock() != restart_detect)
6812 if (subtype == VSREPLACE) {
6813 //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
6815 char *restart_detect = stackblock();
6816 STPUTC(*idx, expdest);
6817 if (stackblock() != restart_detect)
6826 /* We've put the replaced text into a buffer at workloc, now
6827 * move it to the right place and adjust the stack.
6829 STPUTC('\0', expdest);
6830 startp = (char *)stackblock() + startloc;
6831 memmove(startp, (char *)stackblock() + workloc, len + 1);
6832 //bb_error_msg("startp:'%s'", startp);
6833 amount = expdest - (startp + len);
6834 STADJUST(-amount, expdest);
6837 #endif /* BASH_PATTERN_SUBST */
6839 subtype -= VSTRIMRIGHT;
6841 if (subtype < 0 || subtype > 7)
6844 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
6845 zero = subtype >> 1;
6846 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6847 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6849 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6852 memmove(startp, loc, str - loc);
6853 loc = startp + (str - loc) - 1;
6856 amount = loc - expdest;
6857 STADJUST(amount, expdest);
6863 * Add the value of a specialized variable to the stack string.
6864 * name parameter (examples):
6865 * ash -c 'echo $1' name:'1='
6866 * ash -c 'echo $qwe' name:'qwe='
6867 * ash -c 'echo $$' name:'$='
6868 * ash -c 'echo ${$}' name:'$='
6869 * ash -c 'echo ${$##q}' name:'$=q'
6870 * ash -c 'echo ${#$}' name:'$='
6871 * note: examples with bad shell syntax:
6872 * ash -c 'echo ${#$1}' name:'$=1'
6873 * ash -c 'echo ${#1#}' name:'1=#'
6875 static NOINLINE ssize_t
6876 varvalue(char *name, int varflags, int flags, struct strlist *var_str_list, int *quotedp)
6883 int quoted = *quotedp;
6884 int subtype = varflags & VSTYPE;
6885 int discard = subtype == VSPLUS || subtype == VSLENGTH;
6886 int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
6889 sep = (flags & EXP_FULL) << CHAR_BIT;
6890 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6900 num = shellparam.nparam;
6908 goto check_1char_name;
6910 expdest = makestrspace(NOPTS, expdest);
6911 for (i = NOPTS - 1; i >= 0; i--) {
6913 USTPUTC(optletters(i), expdest);
6919 /* handles cases similar to ${#$1} */
6920 if (name[2] != '\0')
6921 raise_error_syntax("bad substitution");
6934 sep |= ifsset() ? ifsval()[0] : ' ';
6941 while ((p = *ap++) != NULL) {
6942 len += strtodest(p, syntax, quotes);
6946 memtodest(&sepc, 1, syntax, quotes);
6961 num = atoi(name); /* number(name) fails on ${N#str} etc */
6962 if (num < 0 || num > shellparam.nparam)
6964 p = num ? shellparam.p[num - 1] : arg0;
6967 /* NB: name has form "VAR=..." */
6969 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6970 * which should be considered before we check variables. */
6972 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6976 str = var_str_list->text;
6977 eq = strchr(str, '=');
6978 if (!eq) /* stop at first non-assignment */
6981 if (name_len == (unsigned)(eq - str)
6982 && strncmp(str, name, name_len) == 0
6985 /* goto value; - WRONG! */
6986 /* think "A=1 A=2 B=$A" */
6988 var_str_list = var_str_list->next;
6989 } while (var_str_list);
6993 p = lookupvar(name);
6998 len = strtodest(p, syntax, quotes);
6999 #if ENABLE_UNICODE_SUPPORT
7000 if (subtype == VSLENGTH && len > 0) {
7001 reinit_unicode_for_ash();
7002 if (unicode_status == UNICODE_ON) {
7003 STADJUST(-len, expdest);
7005 len = unicode_strlen(p);
7013 STADJUST(-len, expdest);
7018 * Expand a variable, and return a pointer to the next character in the
7022 evalvar(char *p, int flag, struct strlist *var_str_list)
7033 varflags = (unsigned char) *p++;
7034 subtype = varflags & VSTYPE;
7037 raise_error_syntax("bad substitution");
7039 quoted = flag & EXP_QUOTED;
7041 easy = (!quoted || (*var == '@' && shellparam.nparam));
7042 startloc = expdest - (char *)stackblock();
7043 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
7046 varlen = varvalue(var, varflags, flag, var_str_list, "ed);
7047 if (varflags & VSNUL)
7050 if (subtype == VSPLUS) {
7051 varlen = -1 - varlen;
7055 if (subtype == VSMINUS) {
7060 flag | EXP_TILDE | EXP_WORD,
7068 if (subtype == VSASSIGN || subtype == VSQUESTION) {
7072 subevalvar(p, var, 0, subtype, startloc, varflags,
7073 flag & ~QUOTES_ESC, var_str_list);
7076 * Remove any recorded regions beyond
7079 removerecordregions(startloc);
7083 if (varlen < 0 && uflag)
7084 varunset(p, var, 0, 0);
7086 if (subtype == VSLENGTH) {
7087 cvtnum(varlen > 0 ? varlen : 0);
7091 if (subtype == VSNORMAL) {
7095 recordregion(startloc, expdest - (char *)stackblock(), quoted);
7104 case VSTRIMRIGHTMAX:
7108 #if BASH_PATTERN_SUBST
7120 * Terminate the string and start recording the pattern
7123 STPUTC('\0', expdest);
7124 patloc = expdest - (char *)stackblock();
7125 if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
7126 startloc, varflags, flag, var_str_list)) {
7127 int amount = expdest - (
7128 (char *)stackblock() + patloc - 1
7130 STADJUST(-amount, expdest);
7132 /* Remove any recorded regions beyond start of variable */
7133 removerecordregions(startloc);
7138 if (subtype != VSNORMAL) { /* skip to end of alternative */
7141 unsigned char c = *p++;
7144 else if (c == CTLBACKQ) {
7146 argbackq = argbackq->next;
7147 } else if (c == CTLVAR) {
7148 if ((*p++ & VSTYPE) != VSNORMAL)
7150 } else if (c == CTLENDVAR) {
7160 * Add a file name to the list.
7163 addfname(const char *name)
7167 sp = stzalloc(sizeof(*sp));
7168 sp->text = sstrdup(name);
7170 exparg.lastp = &sp->next;
7173 /* Avoid glob() (and thus, stat() et al) for words like "echo" */
7175 hasmeta(const char *p)
7177 static const char chars[] ALIGN1 = {
7178 '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
7182 p = strpbrk(p, chars);
7185 switch ((unsigned char) *p) {
7189 if (*p == CTLQUOTEMARK)
7193 if (*p == '\0') /* huh? */
7204 if (!strchr(p + 1, ']')) {
7205 /* It's not a properly closed [] pattern,
7206 * but other metas may follow. Continue checking.
7207 * my[file* _is_ globbed by bash
7208 * and matches filenames like "my[file1".
7224 /* If we want to use glob() from libc... */
7225 #if !ENABLE_ASH_INTERNAL_GLOB
7227 /* Add the result of glob() to the list */
7229 addglob(const glob_t *pglob)
7231 char **p = pglob->gl_pathv;
7238 expandmeta(struct strlist *str /*, int flag*/)
7240 /* TODO - EXP_REDIR */
7250 if (!hasmeta(str->text))
7254 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7255 // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
7256 // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
7258 // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
7259 // if you pass it "file\?", it returns "file\?", not "file?", if no match.
7260 // Which means you need to unescape the string, right? Not so fast:
7261 // if there _is_ a file named "file\?" (with backslash), it is returned
7262 // as "file\?" too (whichever pattern you used to find it, say, "file*").
7263 // You DON'T KNOW by looking at the result whether you need to unescape it.
7265 // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
7266 // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
7267 // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
7268 // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
7269 // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
7270 // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
7271 i = glob(p, 0, NULL, &pglob);
7272 //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
7277 #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
7278 /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
7279 if (!(pglob.gl_flags & GLOB_MAGCHAR))
7291 *exparg.lastp = str;
7292 rmescapes(str->text, 0);
7293 exparg.lastp = &str->next;
7295 default: /* GLOB_NOSPACE */
7298 ash_msg_and_raise_error(bb_msg_memory_exhausted);
7305 /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7308 * Do metacharacter (i.e. *, ?, [...]) expansion.
7311 expmeta(char *expdir, char *enddir, char *name)
7327 for (p = name; esc = 0, *p; p += esc + 1) {
7328 if (*p == '*' || *p == '?')
7330 else if (*p == '[') {
7337 if (*q == '/' || *q == '\0')
7347 if (p[esc] == '/') {
7350 start = p + esc + 1;
7354 if (metaflag == 0) { /* we've reached the end of the file name */
7355 if (enddir != expdir)
7363 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
7374 } while (p < start);
7376 if (enddir == expdir) {
7378 } else if (enddir == expdir + 1 && *expdir == '/') {
7387 if (enddir != expdir)
7389 if (*endname == 0) {
7402 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7403 if (dp->d_name[0] == '.' && !matchdot)
7405 if (pmatch(start, dp->d_name)) {
7407 strcpy(enddir, dp->d_name);
7410 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
7413 expmeta(expdir, p, endname);
7419 endname[-esc - 1] = esc ? '\\' : '/';
7422 static struct strlist *
7423 msort(struct strlist *list, int len)
7425 struct strlist *p, *q = NULL;
7426 struct strlist **lpp;
7434 for (n = half; --n >= 0;) {
7438 q->next = NULL; /* terminate first half of list */
7439 q = msort(list, half); /* sort first half of list */
7440 p = msort(p, len - half); /* sort second half */
7443 #if ENABLE_LOCALE_SUPPORT
7444 if (strcoll(p->text, q->text) < 0)
7446 if (strcmp(p->text, q->text) < 0)
7470 * Sort the results of file name expansion. It calculates the number of
7471 * strings to sort and then calls msort (short for merge sort) to do the
7474 static struct strlist *
7475 expsort(struct strlist *str)
7481 for (sp = str; sp; sp = sp->next)
7483 return msort(str, len);
7487 expandmeta(struct strlist *str /*, int flag*/)
7489 /* TODO - EXP_REDIR */
7493 struct strlist **savelastp;
7499 if (!hasmeta(str->text))
7501 savelastp = exparg.lastp;
7504 p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7506 int i = strlen(str->text);
7507 //BUGGY estimation of how long expanded name can be
7508 expdir = ckmalloc(i < 2048 ? 2048 : i+1);
7510 expmeta(expdir, expdir, p);
7515 if (exparg.lastp == savelastp) {
7520 *exparg.lastp = str;
7521 rmescapes(str->text, 0);
7522 exparg.lastp = &str->next;
7524 *exparg.lastp = NULL;
7525 *savelastp = sp = expsort(*savelastp);
7526 while (sp->next != NULL)
7528 exparg.lastp = &sp->next;
7533 #endif /* ENABLE_ASH_INTERNAL_GLOB */
7536 * Perform variable substitution and command substitution on an argument,
7537 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7538 * perform splitting and file name expansion. When arglist is NULL, perform
7539 * here document expansion.
7542 expandarg(union node *arg, struct arglist *arglist, int flag)
7547 argbackq = arg->narg.backquote;
7548 STARTSTACKSTR(expdest);
7549 TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
7550 argstr(arg->narg.text, flag,
7551 /* var_str_list: */ arglist ? arglist->list : NULL);
7552 p = _STPUTC('\0', expdest);
7554 if (arglist == NULL) {
7555 /* here document expanded */
7558 p = grabstackstr(p);
7559 TRACE(("expandarg: p:'%s'\n", p));
7560 exparg.lastp = &exparg.list;
7564 if (flag & EXP_FULL) {
7565 ifsbreakup(p, &exparg);
7566 *exparg.lastp = NULL;
7567 exparg.lastp = &exparg.list;
7568 expandmeta(exparg.list /*, flag*/);
7570 sp = stzalloc(sizeof(*sp));
7573 exparg.lastp = &sp->next;
7575 *exparg.lastp = NULL;
7577 *arglist->lastp = exparg.list;
7578 arglist->lastp = exparg.lastp;
7586 * Expand shell variables and backquotes inside a here document.
7589 expandhere(union node *arg, int fd)
7591 expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
7592 full_write(fd, stackblock(), expdest - (char *)stackblock());
7596 * Returns true if the pattern matches the string.
7599 patmatch(char *pattern, const char *string)
7601 char *p = preglob(pattern, 0);
7602 //bb_error_msg("fnmatch(pattern:'%s',str:'%s')", p, string);
7603 return pmatch(p, string);
7607 * See if a pattern matches in a case statement.
7610 casematch(union node *pattern, char *val)
7612 struct stackmark smark;
7615 setstackmark(&smark);
7616 argbackq = pattern->narg.backquote;
7617 STARTSTACKSTR(expdest);
7618 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7619 /* var_str_list: */ NULL);
7620 STACKSTRNUL(expdest);
7622 result = patmatch(stackblock(), val);
7623 popstackmark(&smark);
7628 /* ============ find_command */
7632 int (*builtin)(int, char **) FAST_FUNC;
7633 /* unsigned flags; */
7635 #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
7636 /* "regular" builtins always take precedence over commands,
7637 * regardless of PATH=....%builtin... position */
7638 #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
7639 #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
7642 smallint cmdtype; /* CMDxxx */
7645 /* index >= 0 for commands without path (slashes) */
7646 /* (TODO: what exactly does the value mean? PATH position?) */
7647 /* index == -1 for commands with slashes */
7648 /* index == (-2 - applet_no) for NOFORK applets */
7649 const struct builtincmd *cmd;
7650 struct funcnode *func;
7653 /* values of cmdtype */
7654 #define CMDUNKNOWN -1 /* no entry in table for command */
7655 #define CMDNORMAL 0 /* command is an executable program */
7656 #define CMDFUNCTION 1 /* command is a shell function */
7657 #define CMDBUILTIN 2 /* command is a shell builtin */
7659 /* action to find_command() */
7660 #define DO_ERR 0x01 /* prints errors */
7661 #define DO_ABS 0x02 /* checks absolute paths */
7662 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7663 #define DO_ALTPATH 0x08 /* using alternate path */
7664 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7666 static void find_command(char *, struct cmdentry *, int, const char *);
7669 /* ============ Hashing commands */
7672 * When commands are first encountered, they are entered in a hash table.
7673 * This ensures that a full path search will not have to be done for them
7674 * on each invocation.
7676 * We should investigate converting to a linear search, even though that
7677 * would make the command name "hash" a misnomer.
7681 struct tblentry *next; /* next entry in hash chain */
7682 union param param; /* definition of builtin function */
7683 smallint cmdtype; /* CMDxxx */
7684 char rehash; /* if set, cd done since entry created */
7685 char cmdname[1]; /* name of command */
7688 static struct tblentry **cmdtable;
7689 #define INIT_G_cmdtable() do { \
7690 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7693 static int builtinloc = -1; /* index in path of %builtin, or -1 */
7697 tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
7699 #if ENABLE_FEATURE_SH_STANDALONE
7700 if (applet_no >= 0) {
7701 if (APPLET_IS_NOEXEC(applet_no)) {
7705 popredir(/*drop:*/ 1, /*restore:*/ 0);
7706 run_applet_no_and_exit(applet_no, cmd, argv);
7708 /* re-exec ourselves with the new arguments */
7709 execve(bb_busybox_exec_path, argv, envp);
7710 /* If they called chroot or otherwise made the binary no longer
7711 * executable, fall through */
7718 execve(cmd, argv, envp);
7719 } while (errno == EINTR);
7721 execve(cmd, argv, envp);
7723 if (cmd != (char*) bb_busybox_exec_path && errno == ENOEXEC) {
7724 /* Run "cmd" as a shell script:
7725 * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
7726 * "If the execve() function fails with ENOEXEC, the shell
7727 * shall execute a command equivalent to having a shell invoked
7728 * with the command name as its first operand,
7729 * with any remaining arguments passed to the new shell"
7731 * That is, do not use $SHELL, user's shell, or /bin/sh;
7732 * just call ourselves.
7734 * Note that bash reads ~80 chars of the file, and if it sees
7735 * a zero byte before it sees newline, it doesn't try to
7736 * interpret it, but fails with "cannot execute binary file"
7737 * message and exit code 126. For one, this prevents attempts
7738 * to interpret foreign ELF binaries as shell scripts.
7741 cmd = (char*) bb_busybox_exec_path;
7742 /* NB: this is only possible because all callers of shellexec()
7743 * ensure that the argv[-1] slot exists!
7746 argv[0] = (char*) "ash";
7752 * Exec a program. Never returns. If you change this routine, you may
7753 * have to change the find_command routine as well.
7754 * argv[-1] must exist and be writable! See tryexec() for why.
7756 static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
7757 static void shellexec(char *prog, char **argv, const char *path, int idx)
7763 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
7765 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
7766 if (strchr(prog, '/') != NULL
7767 #if ENABLE_FEATURE_SH_STANDALONE
7768 || (applet_no = find_applet_by_name(prog)) >= 0
7771 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
7772 if (applet_no >= 0) {
7773 /* We tried execing ourself, but it didn't work.
7774 * Maybe /proc/self/exe doesn't exist?
7783 while ((cmdname = path_advance(&path, prog)) != NULL) {
7784 if (--idx < 0 && pathopt == NULL) {
7785 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
7786 if (errno != ENOENT && errno != ENOTDIR)
7793 /* Map to POSIX errors */
7805 exitstatus = exerrno;
7806 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7807 prog, e, suppress_int));
7808 ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
7813 printentry(struct tblentry *cmdp)
7819 idx = cmdp->param.index;
7822 name = path_advance(&path, cmdp->cmdname);
7824 } while (--idx >= 0);
7825 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7829 * Clear out command entries. The argument specifies the first entry in
7830 * PATH which has changed.
7833 clearcmdentry(int firstchange)
7835 struct tblentry **tblp;
7836 struct tblentry **pp;
7837 struct tblentry *cmdp;
7840 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7842 while ((cmdp = *pp) != NULL) {
7843 if ((cmdp->cmdtype == CMDNORMAL &&
7844 cmdp->param.index >= firstchange)
7845 || (cmdp->cmdtype == CMDBUILTIN &&
7846 builtinloc >= firstchange)
7859 * Locate a command in the command hash table. If "add" is nonzero,
7860 * add the command to the table if it is not already present. The
7861 * variable "lastcmdentry" is set to point to the address of the link
7862 * pointing to the entry, so that delete_cmd_entry can delete the
7865 * Interrupts must be off if called with add != 0.
7867 static struct tblentry **lastcmdentry;
7869 static struct tblentry *
7870 cmdlookup(const char *name, int add)
7872 unsigned int hashval;
7874 struct tblentry *cmdp;
7875 struct tblentry **pp;
7878 hashval = (unsigned char)*p << 4;
7880 hashval += (unsigned char)*p++;
7882 pp = &cmdtable[hashval % CMDTABLESIZE];
7883 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7884 if (strcmp(cmdp->cmdname, name) == 0)
7888 if (add && cmdp == NULL) {
7889 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7891 /* + 1 - already done because
7892 * tblentry::cmdname is char[1] */);
7893 /*cmdp->next = NULL; - ckzalloc did it */
7894 cmdp->cmdtype = CMDUNKNOWN;
7895 strcpy(cmdp->cmdname, name);
7902 * Delete the command entry returned on the last lookup.
7905 delete_cmd_entry(void)
7907 struct tblentry *cmdp;
7910 cmdp = *lastcmdentry;
7911 *lastcmdentry = cmdp->next;
7912 if (cmdp->cmdtype == CMDFUNCTION)
7913 freefunc(cmdp->param.func);
7919 * Add a new command entry, replacing any existing command entry for
7920 * the same name - except special builtins.
7923 addcmdentry(char *name, struct cmdentry *entry)
7925 struct tblentry *cmdp;
7927 cmdp = cmdlookup(name, 1);
7928 if (cmdp->cmdtype == CMDFUNCTION) {
7929 freefunc(cmdp->param.func);
7931 cmdp->cmdtype = entry->cmdtype;
7932 cmdp->param = entry->u;
7936 static int FAST_FUNC
7937 hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
7939 struct tblentry **pp;
7940 struct tblentry *cmdp;
7942 struct cmdentry entry;
7945 if (nextopt("r") != '\0') {
7950 if (*argptr == NULL) {
7951 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7952 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7953 if (cmdp->cmdtype == CMDNORMAL)
7961 while ((name = *argptr) != NULL) {
7962 cmdp = cmdlookup(name, 0);
7964 && (cmdp->cmdtype == CMDNORMAL
7965 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7969 find_command(name, &entry, DO_ERR, pathval());
7970 if (entry.cmdtype == CMDUNKNOWN)
7978 * Called when a cd is done. Marks all commands so the next time they
7979 * are executed they will be rehashed.
7984 struct tblentry **pp;
7985 struct tblentry *cmdp;
7987 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7988 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7989 if (cmdp->cmdtype == CMDNORMAL
7990 || (cmdp->cmdtype == CMDBUILTIN
7991 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
8001 * Fix command hash table when PATH changed.
8002 * Called before PATH is changed. The argument is the new value of PATH;
8003 * pathval() still returns the old value at this point.
8004 * Called with interrupts off.
8006 static void FAST_FUNC
8007 changepath(const char *new)
8015 firstchange = 9999; /* assume no change */
8021 if ((*old == '\0' && *new == ':')
8022 || (*old == ':' && *new == '\0')
8026 old = new; /* ignore subsequent differences */
8030 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
8037 if (builtinloc < 0 && idx_bltin >= 0)
8038 builtinloc = idx_bltin; /* zap builtins */
8039 if (builtinloc >= 0 && idx_bltin < 0)
8041 clearcmdentry(firstchange);
8042 builtinloc = idx_bltin;
8078 typedef smallint token_id_t;
8080 /* Nth bit indicates if token marks the end of a list */
8083 /* 0 */ | (1u << TEOF)
8084 /* 1 */ | (0u << TNL)
8085 /* 2 */ | (0u << TREDIR)
8086 /* 3 */ | (0u << TWORD)
8087 /* 4 */ | (0u << TSEMI)
8088 /* 5 */ | (0u << TBACKGND)
8089 /* 6 */ | (0u << TAND)
8090 /* 7 */ | (0u << TOR)
8091 /* 8 */ | (0u << TPIPE)
8092 /* 9 */ | (0u << TLP)
8093 /* 10 */ | (1u << TRP)
8094 /* 11 */ | (1u << TENDCASE)
8095 /* 12 */ | (1u << TENDBQUOTE)
8096 /* 13 */ | (0u << TNOT)
8097 /* 14 */ | (0u << TCASE)
8098 /* 15 */ | (1u << TDO)
8099 /* 16 */ | (1u << TDONE)
8100 /* 17 */ | (1u << TELIF)
8101 /* 18 */ | (1u << TELSE)
8102 /* 19 */ | (1u << TESAC)
8103 /* 20 */ | (1u << TFI)
8104 /* 21 */ | (0u << TFOR)
8106 /* 22 */ | (0u << TFUNCTION)
8108 /* 23 */ | (0u << TIF)
8109 /* 24 */ | (0u << TIN)
8110 /* 25 */ | (1u << TTHEN)
8111 /* 26 */ | (0u << TUNTIL)
8112 /* 27 */ | (0u << TWHILE)
8113 /* 28 */ | (0u << TBEGIN)
8114 /* 29 */ | (1u << TEND)
8115 , /* thus far 29 bits used */
8118 static const char *const tokname_array[] = {
8132 #define KWDOFFSET 13
8133 /* the following are keywords */
8155 /* Wrapper around strcmp for qsort/bsearch/... */
8157 pstrcmp(const void *a, const void *b)
8159 return strcmp((char*)a, *(char**)b);
8162 static const char *const *
8163 findkwd(const char *s)
8165 return bsearch(s, tokname_array + KWDOFFSET,
8166 ARRAY_SIZE(tokname_array) - KWDOFFSET,
8167 sizeof(tokname_array[0]), pstrcmp);
8171 * Locate and print what a word is...
8174 describe_command(char *command, const char *path, int describe_command_verbose)
8176 struct cmdentry entry;
8177 #if ENABLE_ASH_ALIAS
8178 const struct alias *ap;
8181 path = path ? path : pathval();
8183 if (describe_command_verbose) {
8187 /* First look at the keywords */
8188 if (findkwd(command)) {
8189 out1str(describe_command_verbose ? " is a shell keyword" : command);
8193 #if ENABLE_ASH_ALIAS
8194 /* Then look at the aliases */
8195 ap = lookupalias(command, 0);
8197 if (!describe_command_verbose) {
8202 out1fmt(" is an alias for %s", ap->val);
8207 find_command(command, &entry, DO_ABS, path);
8209 switch (entry.cmdtype) {
8211 int j = entry.u.index;
8217 p = path_advance(&path, command);
8221 if (describe_command_verbose) {
8222 out1fmt(" is %s", p);
8230 if (describe_command_verbose) {
8231 out1str(" is a shell function");
8238 if (describe_command_verbose) {
8239 out1fmt(" is a %sshell builtin",
8240 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
8241 "special " : nullstr
8249 if (describe_command_verbose) {
8250 out1str(": not found\n");
8259 static int FAST_FUNC
8260 typecmd(int argc UNUSED_PARAM, char **argv)
8266 /* type -p ... ? (we don't bother checking for 'p') */
8267 if (argv[1] && argv[1][0] == '-') {
8272 err |= describe_command(argv[i++], NULL, verbose);
8277 #if ENABLE_ASH_CMDCMD
8278 /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
8280 parse_command_args(char **argv, const char **path)
8293 if (c == '-' && !*cp) {
8301 *path = bb_default_path;
8304 /* run 'typecmd' for other options */
8313 static int FAST_FUNC
8314 commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8322 const char *path = NULL;
8324 /* "command [-p] PROG ARGS" (that is, without -V or -v)
8325 * never reaches this function.
8328 while ((c = nextopt("pvV")) != '\0')
8330 verify |= VERIFY_VERBOSE;
8332 /*verify |= VERIFY_BRIEF*/;
8338 path = bb_default_path;
8340 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
8342 if (/*verify && */ cmd)
8343 return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
8350 /*static int funcblocksize; // size of structures in function */
8351 /*static int funcstringsize; // size of strings in node */
8352 static void *funcblock; /* block to allocate function from */
8353 static char *funcstring_end; /* end of block to allocate strings from */
8355 static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8356 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
8357 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
8358 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
8359 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
8360 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
8361 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
8362 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
8363 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
8364 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
8365 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
8366 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
8367 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
8368 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
8369 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
8370 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
8371 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
8372 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8373 #if BASH_REDIR_OUTPUT
8374 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
8376 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
8377 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
8378 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
8379 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
8380 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8381 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
8382 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8383 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
8384 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
8387 static int calcsize(int funcblocksize, union node *n);
8390 sizenodelist(int funcblocksize, struct nodelist *lp)
8393 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8394 funcblocksize = calcsize(funcblocksize, lp->n);
8397 return funcblocksize;
8401 calcsize(int funcblocksize, union node *n)
8404 return funcblocksize;
8405 funcblocksize += nodesize[n->type];
8408 funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
8409 funcblocksize = calcsize(funcblocksize, n->ncmd.args);
8410 funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
8413 funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
8418 funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
8419 funcblocksize = calcsize(funcblocksize, n->nredir.n);
8426 funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
8427 funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
8430 funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
8431 funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
8432 funcblocksize = calcsize(funcblocksize, n->nif.test);
8435 funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
8436 funcblocksize = calcsize(funcblocksize, n->nfor.body);
8437 funcblocksize = calcsize(funcblocksize, n->nfor.args);
8440 funcblocksize = calcsize(funcblocksize, n->ncase.cases);
8441 funcblocksize = calcsize(funcblocksize, n->ncase.expr);
8444 funcblocksize = calcsize(funcblocksize, n->nclist.body);
8445 funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
8446 funcblocksize = calcsize(funcblocksize, n->nclist.next);
8450 funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
8451 funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
8452 funcblocksize = calcsize(funcblocksize, n->narg.next);
8455 #if BASH_REDIR_OUTPUT
8462 funcblocksize = calcsize(funcblocksize, n->nfile.fname);
8463 funcblocksize = calcsize(funcblocksize, n->nfile.next);
8467 funcblocksize = calcsize(funcblocksize, n->ndup.vname);
8468 funcblocksize = calcsize(funcblocksize, n->ndup.next);
8472 funcblocksize = calcsize(funcblocksize, n->nhere.doc);
8473 funcblocksize = calcsize(funcblocksize, n->nhere.next);
8476 funcblocksize = calcsize(funcblocksize, n->nnot.com);
8479 return funcblocksize;
8483 nodeckstrdup(char *s)
8485 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
8486 return strcpy(funcstring_end, s);
8489 static union node *copynode(union node *);
8491 static struct nodelist *
8492 copynodelist(struct nodelist *lp)
8494 struct nodelist *start;
8495 struct nodelist **lpp;
8500 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
8501 (*lpp)->n = copynode(lp->n);
8503 lpp = &(*lpp)->next;
8510 copynode(union node *n)
8517 funcblock = (char *) funcblock + nodesize[n->type];
8521 new->ncmd.redirect = copynode(n->ncmd.redirect);
8522 new->ncmd.args = copynode(n->ncmd.args);
8523 new->ncmd.assign = copynode(n->ncmd.assign);
8526 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8527 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
8532 new->nredir.redirect = copynode(n->nredir.redirect);
8533 new->nredir.n = copynode(n->nredir.n);
8540 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8541 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8544 new->nif.elsepart = copynode(n->nif.elsepart);
8545 new->nif.ifpart = copynode(n->nif.ifpart);
8546 new->nif.test = copynode(n->nif.test);
8549 new->nfor.var = nodeckstrdup(n->nfor.var);
8550 new->nfor.body = copynode(n->nfor.body);
8551 new->nfor.args = copynode(n->nfor.args);
8554 new->ncase.cases = copynode(n->ncase.cases);
8555 new->ncase.expr = copynode(n->ncase.expr);
8558 new->nclist.body = copynode(n->nclist.body);
8559 new->nclist.pattern = copynode(n->nclist.pattern);
8560 new->nclist.next = copynode(n->nclist.next);
8564 new->narg.backquote = copynodelist(n->narg.backquote);
8565 new->narg.text = nodeckstrdup(n->narg.text);
8566 new->narg.next = copynode(n->narg.next);
8569 #if BASH_REDIR_OUTPUT
8576 new->nfile.fname = copynode(n->nfile.fname);
8577 new->nfile.fd = n->nfile.fd;
8578 new->nfile.next = copynode(n->nfile.next);
8582 new->ndup.vname = copynode(n->ndup.vname);
8583 new->ndup.dupfd = n->ndup.dupfd;
8584 new->ndup.fd = n->ndup.fd;
8585 new->ndup.next = copynode(n->ndup.next);
8589 new->nhere.doc = copynode(n->nhere.doc);
8590 new->nhere.fd = n->nhere.fd;
8591 new->nhere.next = copynode(n->nhere.next);
8594 new->nnot.com = copynode(n->nnot.com);
8597 new->type = n->type;
8602 * Make a copy of a parse tree.
8604 static struct funcnode *
8605 copyfunc(union node *n)
8610 /*funcstringsize = 0;*/
8611 blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
8612 f = ckzalloc(blocksize /* + funcstringsize */);
8613 funcblock = (char *) f + offsetof(struct funcnode, n);
8614 funcstring_end = (char *) f + blocksize;
8616 /* f->count = 0; - ckzalloc did it */
8621 * Define a shell function.
8624 defun(union node *func)
8626 struct cmdentry entry;
8629 entry.cmdtype = CMDFUNCTION;
8630 entry.u.func = copyfunc(func);
8631 addcmdentry(func->narg.text, &entry);
8635 /* Reasons for skipping commands (see comment on breakcmd routine) */
8636 #define SKIPBREAK (1 << 0)
8637 #define SKIPCONT (1 << 1)
8638 #define SKIPFUNC (1 << 2)
8639 static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
8640 static int skipcount; /* number of levels to skip */
8641 static int funcnest; /* depth of function calls */
8642 static int loopnest; /* current loop nesting level */
8644 /* Forward decl way out to parsing code - dotrap needs it */
8645 static int evalstring(char *s, int flags);
8647 /* Called to execute a trap.
8648 * Single callsite - at the end of evaltree().
8649 * If we return non-zero, evaltree raises EXEXIT exception.
8651 * Perhaps we should avoid entering new trap handlers
8652 * while we are executing a trap handler. [is it a TODO?]
8659 uint8_t last_status;
8664 last_status = exitstatus;
8668 TRACE(("dotrap entered\n"));
8669 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8681 /* non-trapped SIGINT is handled separately by raise_interrupt,
8682 * don't upset it by resetting gotsig[SIGINT-1] */
8683 if (sig == SIGINT && !p)
8686 TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
8692 exitstatus = last_status;
8693 TRACE(("dotrap returns\n"));
8696 /* forward declarations - evaluation is fairly recursive business... */
8697 static int evalloop(union node *, int);
8698 static int evalfor(union node *, int);
8699 static int evalcase(union node *, int);
8700 static int evalsubshell(union node *, int);
8701 static void expredir(union node *);
8702 static int evalpipe(union node *, int);
8703 static int evalcommand(union node *, int);
8704 static int evalbltin(const struct builtincmd *, int, char **, int);
8705 static void prehash(union node *);
8708 * Evaluate a parse tree. The value is left in the global variable
8712 evaltree(union node *n, int flags)
8715 int (*evalfn)(union node *, int);
8719 TRACE(("evaltree(NULL) called\n"));
8722 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
8729 out1fmt("Node type = %d\n", n->type);
8734 status = !evaltree(n->nnot.com, EV_TESTED);
8737 expredir(n->nredir.redirect);
8738 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8740 status = evaltree(n->nredir.n, flags & EV_TESTED);
8742 if (n->nredir.redirect)
8743 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
8746 evalfn = evalcommand;
8748 if (eflag && !(flags & EV_TESTED))
8760 evalfn = evalsubshell;
8773 #error NAND + 1 != NOR
8775 #if NOR + 1 != NSEMI
8776 #error NOR + 1 != NSEMI
8778 unsigned is_or = n->type - NAND;
8781 (flags | ((is_or >> 1) - 1)) & EV_TESTED
8783 if ((!status) == is_or || evalskip)
8789 status = evalfn(n, flags);
8793 status = evaltree(n->nif.test, EV_TESTED);
8800 if (n->nif.elsepart) {
8801 n = n->nif.elsepart;
8808 /* Not necessary. To test it:
8809 * "false; f() { qwerty; }; echo $?" should print 0.
8813 exitstatus = status;
8817 /* Order of checks below is important:
8818 * signal handlers trigger before exit caused by "set -e".
8822 if (checkexit & status)
8823 raise_exception(EXEXIT);
8824 if (flags & EV_EXIT)
8825 raise_exception(EXEXIT);
8827 TRACE(("leaving evaltree (no interrupts)\n"));
8831 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8834 int evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8839 int skip = evalskip;
8846 if (--skipcount <= 0) {
8857 evalloop(union node *n, int flags)
8868 i = evaltree(n->nbinary.ch1, EV_TESTED);
8870 if (skip == SKIPFUNC)
8874 if (n->type != NWHILE)
8878 status = evaltree(n->nbinary.ch2, flags);
8880 } while (!(skip & ~SKIPCONT));
8887 evalfor(union node *n, int flags)
8889 struct arglist arglist;
8892 struct stackmark smark;
8895 setstackmark(&smark);
8896 arglist.list = NULL;
8897 arglist.lastp = &arglist.list;
8898 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
8899 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8901 *arglist.lastp = NULL;
8905 for (sp = arglist.list; sp; sp = sp->next) {
8906 setvar0(n->nfor.var, sp->text);
8907 status = evaltree(n->nfor.body, flags);
8908 if (skiploop() & ~SKIPCONT)
8912 popstackmark(&smark);
8918 evalcase(union node *n, int flags)
8922 struct arglist arglist;
8923 struct stackmark smark;
8926 setstackmark(&smark);
8927 arglist.list = NULL;
8928 arglist.lastp = &arglist.list;
8929 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
8930 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8931 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
8932 if (casematch(patp, arglist.list->text)) {
8933 /* Ensure body is non-empty as otherwise
8934 * EV_EXIT may prevent us from setting the
8937 if (evalskip == 0 && cp->nclist.body) {
8938 status = evaltree(cp->nclist.body, flags);
8945 popstackmark(&smark);
8951 * Kick off a subshell to evaluate a tree.
8954 evalsubshell(union node *n, int flags)
8957 int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
8960 expredir(n->nredir.redirect);
8961 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
8964 if (backgnd == FORK_FG)
8966 jp = makejob(/*n,*/ 1);
8967 if (forkshell(jp, n, backgnd) == 0) {
8972 flags &= ~EV_TESTED;
8974 redirect(n->nredir.redirect, 0);
8975 evaltreenr(n->nredir.n, flags);
8980 if (backgnd == FORK_FG)
8981 status = waitforjob(jp);
8987 * Compute the names of the files in a redirection list.
8989 static void fixredir(union node *, const char *, int);
8991 expredir(union node *n)
8995 for (redir = n; redir; redir = redir->nfile.next) {
8999 fn.lastp = &fn.list;
9000 switch (redir->type) {
9004 #if BASH_REDIR_OUTPUT
9009 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
9010 TRACE(("expredir expanded to '%s'\n", fn.list->text));
9011 #if BASH_REDIR_OUTPUT
9015 // By the design of stack allocator, the loop of this kind:
9016 // while true; do while true; do break; done </dev/null; done
9017 // will look like a memory leak: ash plans to free expfname's
9018 // of "/dev/null" as soon as it finishes running the loop
9019 // (in this case, never).
9020 // This "fix" is wrong:
9021 if (redir->nfile.expfname)
9022 stunalloc(redir->nfile.expfname);
9023 // It results in corrupted state of stacked allocations.
9025 redir->nfile.expfname = fn.list->text;
9028 case NTOFD: /* >& */
9029 if (redir->ndup.vname) {
9030 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
9031 if (fn.list == NULL)
9032 ash_msg_and_raise_error("redir error");
9033 #if BASH_REDIR_OUTPUT
9034 //FIXME: we used expandarg with different args!
9035 if (!isdigit_str9(fn.list->text)) {
9036 /* >&file, not >&fd */
9037 if (redir->nfile.fd != 1) /* 123>&file - BAD */
9038 ash_msg_and_raise_error("redir error");
9040 goto store_expfname;
9043 fixredir(redir, fn.list->text, 1);
9051 * Evaluate a pipeline. All the processes in the pipeline are children
9052 * of the process creating the pipeline. (This differs from some versions
9053 * of the shell, which make the last process in a pipeline the parent
9057 evalpipe(union node *n, int flags)
9060 struct nodelist *lp;
9066 TRACE(("evalpipe(0x%lx) called\n", (long)n));
9068 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
9072 if (n->npipe.pipe_backgnd == 0)
9074 jp = makejob(/*n,*/ pipelen);
9076 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
9080 if (pipe(pip) < 0) {
9082 ash_msg_and_raise_error("pipe call failed");
9085 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
9099 evaltreenr(lp->n, flags);
9106 /* Don't want to trigger debugging */
9110 if (n->npipe.pipe_backgnd == 0) {
9111 status = waitforjob(jp);
9112 TRACE(("evalpipe: job done exit status %d\n", status));
9120 * Controls whether the shell is interactive or not.
9123 setinteractive(int on)
9125 static smallint is_interactive;
9127 if (++on == is_interactive)
9129 is_interactive = on;
9133 #if !ENABLE_FEATURE_SH_EXTRA_QUIET
9134 if (is_interactive > 1) {
9135 /* Looks like they want an interactive shell */
9136 static smallint did_banner;
9139 /* note: ash and hush share this string */
9140 out1fmt("\n\n%s %s\n"
9141 IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
9144 "built-in shell (ash)"
9158 setinteractive(iflag);
9160 #if ENABLE_FEATURE_EDITING_VI
9162 line_input_state->flags |= VI_MODE;
9164 line_input_state->flags &= ~VI_MODE;
9166 viflag = 0; /* forcibly keep the option off */
9170 static struct localvar *localvars;
9173 * Called after a function returns.
9174 * Interrupts must be off.
9179 struct localvar *lvp;
9182 while ((lvp = localvars) != NULL) {
9183 localvars = lvp->next;
9185 TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
9186 if (vp == NULL) { /* $- saved */
9187 memcpy(optlist, lvp->text, sizeof(optlist));
9188 free((char*)lvp->text);
9190 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
9191 unsetvar(vp->var_text);
9194 vp->var_func(var_end(lvp->text));
9195 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
9196 free((char*)vp->var_text);
9197 vp->flags = lvp->flags;
9198 vp->var_text = lvp->text;
9205 evalfun(struct funcnode *func, int argc, char **argv, int flags)
9207 volatile struct shparam saveparam;
9208 struct localvar *volatile savelocalvars;
9209 struct jmploc *volatile savehandler;
9210 struct jmploc jmploc;
9213 saveparam = shellparam;
9214 savelocalvars = localvars;
9215 savehandler = exception_handler;
9216 e = setjmp(jmploc.loc);
9221 exception_handler = &jmploc;
9223 shellparam.malloced = 0;
9227 shellparam.nparam = argc - 1;
9228 shellparam.p = argv + 1;
9229 #if ENABLE_ASH_GETOPTS
9230 shellparam.optind = 1;
9231 shellparam.optoff = -1;
9233 evaltree(func->n.narg.next, flags & EV_TESTED);
9239 localvars = savelocalvars;
9240 freeparam(&shellparam);
9241 shellparam = saveparam;
9242 exception_handler = savehandler;
9244 evalskip &= ~SKIPFUNC;
9249 * Make a variable a local variable. When a variable is made local, it's
9250 * value and flags are saved in a localvar structure. The saved values
9251 * will be restored when the shell function returns. We handle the name
9252 * "-" as a special case: it makes changes to "set +-options" local
9253 * (options will be restored on return from the function).
9258 struct localvar *lvp;
9261 char *eq = strchr(name, '=');
9264 /* Cater for duplicate "local". Examples:
9265 * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
9266 * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
9270 if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
9274 * it's a duplicate "local VAR" declaration, do nothing
9281 lvp = ckzalloc(sizeof(*lvp));
9282 if (LONE_DASH(name)) {
9284 p = ckmalloc(sizeof(optlist));
9285 lvp->text = memcpy(p, optlist, sizeof(optlist));
9288 vpp = hashvar(name);
9289 vp = *findvar(vpp, name);
9291 /* variable did not exist yet */
9293 setvareq(name, VSTRFIXED);
9295 setvar(name, NULL, VSTRFIXED);
9296 vp = *vpp; /* the new variable */
9297 lvp->flags = VUNSET;
9299 lvp->text = vp->var_text;
9300 lvp->flags = vp->flags;
9301 /* make sure neither "struct var" nor string gets freed
9302 * during (un)setting:
9304 vp->flags |= VSTRFIXED|VTEXTFIXED;
9308 /* "local VAR" unsets VAR: */
9309 setvar0(name, NULL);
9313 lvp->next = localvars;
9320 * The "local" command.
9322 static int FAST_FUNC
9323 localcmd(int argc UNUSED_PARAM, char **argv)
9328 ash_msg_and_raise_error("not in a function");
9331 while ((name = *argv++) != NULL) {
9337 static int FAST_FUNC
9338 falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9343 static int FAST_FUNC
9344 truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9349 static int FAST_FUNC
9350 execcmd(int argc UNUSED_PARAM, char **argv)
9353 while (nextopt("a:") != '\0')
9354 /* nextopt() sets optionarg to "-a ARGV0" */;
9360 iflag = 0; /* exit on error */
9363 /* We should set up signals for "exec CMD"
9364 * the same way as for "CMD" without "exec".
9365 * But optschanged->setinteractive->setsignal
9366 * still thought we are a root shell. Therefore, for example,
9367 * SIGQUIT is still set to IGN. Fix it:
9371 /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
9372 /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
9373 /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
9377 argv[0] = optionarg;
9378 shellexec(prog, argv, pathval(), 0);
9385 * The return command.
9387 static int FAST_FUNC
9388 returncmd(int argc UNUSED_PARAM, char **argv)
9391 * If called outside a function, do what ksh does;
9392 * skip the rest of the file.
9394 evalskip = SKIPFUNC;
9395 return argv[1] ? number(argv[1]) : exitstatus;
9398 /* Forward declarations for builtintab[] */
9399 static int breakcmd(int, char **) FAST_FUNC;
9400 static int dotcmd(int, char **) FAST_FUNC;
9401 static int evalcmd(int, char **, int) FAST_FUNC;
9402 static int exitcmd(int, char **) FAST_FUNC;
9403 static int exportcmd(int, char **) FAST_FUNC;
9404 #if ENABLE_ASH_GETOPTS
9405 static int getoptscmd(int, char **) FAST_FUNC;
9408 static int helpcmd(int, char **) FAST_FUNC;
9411 static int historycmd(int, char **) FAST_FUNC;
9413 #if ENABLE_FEATURE_SH_MATH
9414 static int letcmd(int, char **) FAST_FUNC;
9416 static int readcmd(int, char **) FAST_FUNC;
9417 static int setcmd(int, char **) FAST_FUNC;
9418 static int shiftcmd(int, char **) FAST_FUNC;
9419 static int timescmd(int, char **) FAST_FUNC;
9420 static int trapcmd(int, char **) FAST_FUNC;
9421 static int umaskcmd(int, char **) FAST_FUNC;
9422 static int unsetcmd(int, char **) FAST_FUNC;
9423 static int ulimitcmd(int, char **) FAST_FUNC;
9425 #define BUILTIN_NOSPEC "0"
9426 #define BUILTIN_SPECIAL "1"
9427 #define BUILTIN_REGULAR "2"
9428 #define BUILTIN_SPEC_REG "3"
9429 #define BUILTIN_ASSIGN "4"
9430 #define BUILTIN_SPEC_ASSG "5"
9431 #define BUILTIN_REG_ASSG "6"
9432 #define BUILTIN_SPEC_REG_ASSG "7"
9434 /* Stubs for calling non-FAST_FUNC's */
9436 static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
9438 #if ENABLE_ASH_PRINTF
9439 static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
9441 #if ENABLE_ASH_TEST || BASH_TEST2
9442 static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
9445 /* Keep these in proper order since it is searched via bsearch() */
9446 static const struct builtincmd builtintab[] = {
9447 { BUILTIN_SPEC_REG "." , dotcmd },
9448 { BUILTIN_SPEC_REG ":" , truecmd },
9450 { BUILTIN_REGULAR "[" , testcmd },
9453 { BUILTIN_REGULAR "[[" , testcmd },
9455 #if ENABLE_ASH_ALIAS
9456 { BUILTIN_REG_ASSG "alias" , aliascmd },
9459 { BUILTIN_REGULAR "bg" , fg_bgcmd },
9461 { BUILTIN_SPEC_REG "break" , breakcmd },
9462 { BUILTIN_REGULAR "cd" , cdcmd },
9463 { BUILTIN_NOSPEC "chdir" , cdcmd },
9464 #if ENABLE_ASH_CMDCMD
9465 { BUILTIN_REGULAR "command" , commandcmd },
9467 { BUILTIN_SPEC_REG "continue", breakcmd },
9469 { BUILTIN_REGULAR "echo" , echocmd },
9471 { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
9472 { BUILTIN_SPEC_REG "exec" , execcmd },
9473 { BUILTIN_SPEC_REG "exit" , exitcmd },
9474 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
9475 { BUILTIN_REGULAR "false" , falsecmd },
9477 { BUILTIN_REGULAR "fg" , fg_bgcmd },
9479 #if ENABLE_ASH_GETOPTS
9480 { BUILTIN_REGULAR "getopts" , getoptscmd },
9482 { BUILTIN_NOSPEC "hash" , hashcmd },
9484 { BUILTIN_NOSPEC "help" , helpcmd },
9487 { BUILTIN_NOSPEC "history" , historycmd },
9490 { BUILTIN_REGULAR "jobs" , jobscmd },
9491 { BUILTIN_REGULAR "kill" , killcmd },
9493 #if ENABLE_FEATURE_SH_MATH
9494 { BUILTIN_NOSPEC "let" , letcmd },
9496 { BUILTIN_ASSIGN "local" , localcmd },
9497 #if ENABLE_ASH_PRINTF
9498 { BUILTIN_REGULAR "printf" , printfcmd },
9500 { BUILTIN_NOSPEC "pwd" , pwdcmd },
9501 { BUILTIN_REGULAR "read" , readcmd },
9502 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
9503 { BUILTIN_SPEC_REG "return" , returncmd },
9504 { BUILTIN_SPEC_REG "set" , setcmd },
9505 { BUILTIN_SPEC_REG "shift" , shiftcmd },
9507 { BUILTIN_SPEC_REG "source" , dotcmd },
9510 { BUILTIN_REGULAR "test" , testcmd },
9512 { BUILTIN_SPEC_REG "times" , timescmd },
9513 { BUILTIN_SPEC_REG "trap" , trapcmd },
9514 { BUILTIN_REGULAR "true" , truecmd },
9515 { BUILTIN_NOSPEC "type" , typecmd },
9516 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
9517 { BUILTIN_REGULAR "umask" , umaskcmd },
9518 #if ENABLE_ASH_ALIAS
9519 { BUILTIN_REGULAR "unalias" , unaliascmd },
9521 { BUILTIN_SPEC_REG "unset" , unsetcmd },
9522 { BUILTIN_REGULAR "wait" , waitcmd },
9525 /* Should match the above table! */
9526 #define COMMANDCMD (builtintab + \
9528 /* [ */ 1 * ENABLE_ASH_TEST + \
9529 /* [[ */ 1 * BASH_TEST2 + \
9530 /* alias */ 1 * ENABLE_ASH_ALIAS + \
9531 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
9532 /* break cd cddir */ 3)
9533 #define EVALCMD (COMMANDCMD + \
9534 /* command */ 1 * ENABLE_ASH_CMDCMD + \
9535 /* continue */ 1 + \
9536 /* echo */ 1 * ENABLE_ASH_ECHO + \
9538 #define EXECCMD (EVALCMD + \
9542 * Search the table of builtin commands.
9545 pstrcmp1(const void *a, const void *b)
9547 return strcmp((char*)a, *(char**)b + 1);
9549 static struct builtincmd *
9550 find_builtin(const char *name)
9552 struct builtincmd *bp;
9555 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
9562 * Execute a simple command.
9565 isassignment(const char *p)
9567 const char *q = endofname(p);
9572 static int FAST_FUNC
9573 bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
9575 /* Preserve exitstatus of a previous possible redirection
9576 * as POSIX mandates */
9577 return back_exitstatus;
9580 evalcommand(union node *cmd, int flags)
9582 static const struct builtincmd null_bltin = {
9583 "\0\0", bltincmd /* why three NULs? */
9585 struct stackmark smark;
9587 struct arglist arglist;
9588 struct arglist varlist;
9591 const struct strlist *sp;
9592 struct cmdentry cmdentry;
9599 struct builtincmd *bcmd;
9600 smallint cmd_is_exec;
9601 smallint pseudovarflag = 0;
9603 /* First expand the arguments. */
9604 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9605 setstackmark(&smark);
9606 back_exitstatus = 0;
9608 cmdentry.cmdtype = CMDBUILTIN;
9609 cmdentry.u.cmd = &null_bltin;
9610 varlist.lastp = &varlist.list;
9611 *varlist.lastp = NULL;
9612 arglist.lastp = &arglist.list;
9613 *arglist.lastp = NULL;
9616 if (cmd->ncmd.args) {
9617 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9618 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9621 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9622 struct strlist **spp;
9624 spp = arglist.lastp;
9625 if (pseudovarflag && isassignment(argp->narg.text))
9626 expandarg(argp, &arglist, EXP_VARTILDE);
9628 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9630 for (sp = *spp; sp; sp = sp->next)
9634 /* Reserve one extra spot at the front for shellexec. */
9635 nargv = stalloc(sizeof(char *) * (argc + 2));
9637 for (sp = arglist.list; sp; sp = sp->next) {
9638 TRACE(("evalcommand arg: %s\n", sp->text));
9639 *nargv++ = sp->text;
9644 if (iflag && funcnest == 0 && argc > 0)
9645 lastarg = nargv[-1];
9648 expredir(cmd->ncmd.redirect);
9649 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
9651 path = vpath.var_text;
9652 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9653 struct strlist **spp;
9656 spp = varlist.lastp;
9657 expandarg(argp, &varlist, EXP_VARTILDE);
9660 * Modify the command lookup path, if a PATH= assignment
9664 if (varcmp(p, path) == 0)
9668 /* Print the command if xflag is set. */
9670 const char *pfx = "";
9672 fdprintf(preverrout_fd, "%s", expandstr(ps4val()));
9676 char *varval = sp->text;
9677 char *eq = strchrnul(varval, '=');
9680 fdprintf(preverrout_fd, "%s%.*s%s",
9682 (int)(eq - varval), varval,
9683 maybe_single_quote(eq)
9691 fdprintf(preverrout_fd, "%s%s",
9693 /* always quote if matches reserved word: */
9695 ? single_quote(sp->text)
9696 : maybe_single_quote(sp->text)
9701 safe_write(preverrout_fd, "\n", 1);
9707 /* Now locate the command. */
9709 int cmd_flag = DO_ERR;
9710 #if ENABLE_ASH_CMDCMD
9711 const char *oldpath = path + 5;
9715 find_command(argv[0], &cmdentry, cmd_flag, path);
9716 if (cmdentry.cmdtype == CMDUNKNOWN) {
9717 flush_stdout_stderr();
9722 /* implement bltin and command here */
9723 if (cmdentry.cmdtype != CMDBUILTIN)
9726 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9727 if (cmdentry.u.cmd == EXECCMD)
9729 #if ENABLE_ASH_CMDCMD
9730 if (cmdentry.u.cmd == COMMANDCMD) {
9732 nargv = parse_command_args(argv, &path);
9735 /* It's "command [-p] PROG ARGS" (that is, no -Vv).
9736 * nargv => "PROG". path is updated if -p.
9738 argc -= nargv - argv;
9740 cmd_flag |= DO_NOFUNC;
9749 exitstatus = status;
9751 /* We have a redirection error. */
9753 raise_exception(EXERROR);
9758 /* Execute the command. */
9759 switch (cmdentry.cmdtype) {
9762 #if ENABLE_FEATURE_SH_NOFORK
9763 /* (1) BUG: if variables are set, we need to fork, or save/restore them
9764 * around run_nofork_applet() call.
9765 * (2) Should this check also be done in forkshell()?
9766 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9768 /* find_command() encodes applet_no as (-2 - applet_no) */
9769 int applet_no = (- cmdentry.u.index - 2);
9770 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
9771 listsetvar(varlist.list, VEXPORT|VSTACK);
9772 /* run <applet>_main() */
9773 status = run_nofork_applet(applet_no, argv);
9777 /* Can we avoid forking off? For example, very last command
9778 * in a script or a subshell does not need forking,
9779 * we can just exec it.
9781 if (!(flags & EV_EXIT) || may_have_traps) {
9782 /* No, forking off a child is necessary */
9785 jp = makejob(/*cmd,*/ 1);
9786 if (forkshell(jp, cmd, FORK_FG) != 0) {
9788 status = waitforjob(jp);
9790 TRACE(("forked child exited with %d\n", status));
9795 /* fall through to exec'ing external program */
9797 listsetvar(varlist.list, VEXPORT|VSTACK);
9798 shellexec(argv[0], argv, path, cmdentry.u.index);
9802 cmdenviron = varlist.list;
9804 struct strlist *list = cmdenviron;
9806 if (spclbltin > 0 || argc == 0) {
9808 if (cmd_is_exec && argc > 1)
9811 listsetvar(list, i);
9813 /* Tight loop with builtins only:
9814 * "while kill -0 $child; do true; done"
9815 * will never exit even if $child died, unless we do this
9816 * to reap the zombie and make kill detect that it's gone: */
9817 dowait(DOWAIT_NONBLOCK, NULL);
9819 if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
9820 if (exception_type == EXERROR && spclbltin <= 0) {
9825 longjmp(exception_handler->loc, 1);
9830 listsetvar(varlist.list, 0);
9831 /* See above for the rationale */
9832 dowait(DOWAIT_NONBLOCK, NULL);
9833 if (evalfun(cmdentry.u.func, argc, argv, flags))
9836 status = exitstatus;
9841 if (cmd->ncmd.redirect)
9842 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
9844 /* dsl: I think this is intended to be used to support
9845 * '_' in 'vi' command mode during line editing...
9846 * However I implemented that within libedit itself.
9848 setvar0("_", lastarg);
9850 popstackmark(&smark);
9856 evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
9858 char *volatile savecmdname;
9859 struct jmploc *volatile savehandler;
9860 struct jmploc jmploc;
9864 savecmdname = commandname;
9865 savehandler = exception_handler;
9866 i = setjmp(jmploc.loc);
9869 exception_handler = &jmploc;
9870 commandname = argv[0];
9872 optptr = NULL; /* initialize nextopt */
9874 status = evalcmd(argc, argv, flags);
9876 status = (*cmd->builtin)(argc, argv);
9877 flush_stdout_stderr();
9878 status |= ferror(stdout);
9879 exitstatus = status;
9882 commandname = savecmdname;
9883 exception_handler = savehandler;
9889 goodname(const char *p)
9891 return endofname(p)[0] == '\0';
9896 * Search for a command. This is called before we fork so that the
9897 * location of the command will be available in the parent as well as
9898 * the child. The check for "goodname" is an overly conservative
9899 * check that the name will not be subject to expansion.
9902 prehash(union node *n)
9904 struct cmdentry entry;
9906 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9907 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
9911 /* ============ Builtin commands
9913 * Builtin commands whose functions are closely tied to evaluation
9914 * are implemented here.
9918 * Handle break and continue commands. Break, continue, and return are
9919 * all handled by setting the evalskip flag. The evaluation routines
9920 * above all check this flag, and if it is set they start skipping
9921 * commands rather than executing them. The variable skipcount is
9922 * the number of loops to break/continue, or the number of function
9923 * levels to return. (The latter is always 1.) It should probably
9924 * be an error to break out of more loops than exist, but it isn't
9925 * in the standard shell so we don't make it one here.
9927 static int FAST_FUNC
9928 breakcmd(int argc UNUSED_PARAM, char **argv)
9930 int n = argv[1] ? number(argv[1]) : 1;
9933 ash_msg_and_raise_error(msg_illnum, argv[1]);
9937 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
9945 * This implements the input routines used by the parser.
9949 INPUT_PUSH_FILE = 1,
9950 INPUT_NOFILE_OK = 2,
9953 static smallint checkkwd;
9954 /* values of checkkwd variable */
9955 #define CHKALIAS 0x1
9960 * Push a string back onto the input at this current parsefile level.
9961 * We handle aliases this way.
9963 #if !ENABLE_ASH_ALIAS
9964 #define pushstring(s, ap) pushstring(s)
9967 pushstring(char *s, struct alias *ap)
9974 if (g_parsefile->strpush) {
9975 sp = ckzalloc(sizeof(*sp));
9976 sp->prev = g_parsefile->strpush;
9978 sp = &(g_parsefile->basestrpush);
9980 g_parsefile->strpush = sp;
9981 sp->prev_string = g_parsefile->next_to_pgetc;
9982 sp->prev_left_in_line = g_parsefile->left_in_line;
9983 sp->unget = g_parsefile->unget;
9984 memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
9985 #if ENABLE_ASH_ALIAS
9988 ap->flag |= ALIASINUSE;
9992 g_parsefile->next_to_pgetc = s;
9993 g_parsefile->left_in_line = len;
9994 g_parsefile->unget = 0;
10001 struct strpush *sp = g_parsefile->strpush;
10004 #if ENABLE_ASH_ALIAS
10006 if (g_parsefile->next_to_pgetc[-1] == ' '
10007 || g_parsefile->next_to_pgetc[-1] == '\t'
10009 checkkwd |= CHKALIAS;
10011 if (sp->string != sp->ap->val) {
10014 sp->ap->flag &= ~ALIASINUSE;
10015 if (sp->ap->flag & ALIASDEAD) {
10016 unalias(sp->ap->name);
10020 g_parsefile->next_to_pgetc = sp->prev_string;
10021 g_parsefile->left_in_line = sp->prev_left_in_line;
10022 g_parsefile->unget = sp->unget;
10023 memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
10024 g_parsefile->strpush = sp->prev;
10025 if (sp != &(g_parsefile->basestrpush))
10034 char *buf = g_parsefile->buf;
10036 g_parsefile->next_to_pgetc = buf;
10037 #if ENABLE_FEATURE_EDITING
10039 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
10040 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10043 # if ENABLE_ASH_IDLE_TIMEOUT
10045 const char *tmout_var = lookupvar("TMOUT");
10047 timeout = atoi(tmout_var) * 1000;
10053 # if ENABLE_FEATURE_TAB_COMPLETION
10054 line_input_state->path_lookup = pathval();
10056 reinit_unicode_for_ash();
10057 nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
10059 /* ^C pressed, "convert" to SIGINT */
10060 write(STDOUT_FILENO, "^C", 2);
10061 if (trap[SIGINT]) {
10067 exitstatus = 128 + SIGINT;
10073 /* Ctrl+D pressed */
10076 # if ENABLE_ASH_IDLE_TIMEOUT
10077 else if (errno == EAGAIN && timeout > 0) {
10078 puts("\007timed out waiting for input: auto-logout");
10085 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
10088 #if 0 /* disabled: nonblock_immune_read() handles this problem */
10090 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
10091 int flags = fcntl(0, F_GETFL);
10092 if (flags >= 0 && (flags & O_NONBLOCK)) {
10093 flags &= ~O_NONBLOCK;
10094 if (fcntl(0, F_SETFL, flags) >= 0) {
10095 out2str("sh: turning off NDELAY mode\n");
10106 * Refill the input buffer and return the next input character:
10108 * 1) If a string was pushed back on the input, pop it;
10109 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
10110 * or we are reading from a string so we can't refill the buffer,
10112 * 3) If there is more stuff in this buffer, use it else call read to fill it.
10113 * 4) Process input up to the next newline, deleting nul characters.
10115 //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
10116 #define pgetc_debug(...) ((void)0)
10117 static int pgetc(void);
10124 if (g_parsefile->strpush) {
10125 #if ENABLE_ASH_ALIAS
10126 if (g_parsefile->left_in_line == -1
10127 && g_parsefile->strpush->ap
10128 && g_parsefile->next_to_pgetc[-1] != ' '
10129 && g_parsefile->next_to_pgetc[-1] != '\t'
10131 pgetc_debug("preadbuffer PEOA");
10138 /* on both branches above g_parsefile->left_in_line < 0.
10139 * "pgetc" needs refilling.
10142 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
10143 * pungetc() may increment it a few times.
10144 * Assuming it won't increment it to less than -90.
10146 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
10147 pgetc_debug("preadbuffer PEOF1");
10148 /* even in failure keep left_in_line and next_to_pgetc
10149 * in lock step, for correct multi-layer pungetc.
10150 * left_in_line was decremented before preadbuffer(),
10151 * must inc next_to_pgetc: */
10152 g_parsefile->next_to_pgetc++;
10156 more = g_parsefile->left_in_buffer;
10158 flush_stdout_stderr();
10162 /* don't try reading again */
10163 g_parsefile->left_in_line = -99;
10164 pgetc_debug("preadbuffer PEOF2");
10165 g_parsefile->next_to_pgetc++;
10170 /* Find out where's the end of line.
10171 * Set g_parsefile->left_in_line
10172 * and g_parsefile->left_in_buffer acordingly.
10173 * NUL chars are deleted.
10175 q = g_parsefile->next_to_pgetc;
10183 memmove(q, q + 1, more);
10187 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10193 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
10194 if (g_parsefile->left_in_line < 0)
10199 g_parsefile->left_in_buffer = more;
10204 out2str(g_parsefile->next_to_pgetc);
10208 pgetc_debug("preadbuffer at %d:%p'%s'",
10209 g_parsefile->left_in_line,
10210 g_parsefile->next_to_pgetc,
10211 g_parsefile->next_to_pgetc);
10212 return (unsigned char)*g_parsefile->next_to_pgetc++;
10218 g_parsefile->linno++;
10219 setprompt_if(doprompt, 2);
10224 g_parsefile->linno++;
10225 needprompt = doprompt;
10233 pgetc_debug("pgetc at %d:%p'%s'",
10234 g_parsefile->left_in_line,
10235 g_parsefile->next_to_pgetc,
10236 g_parsefile->next_to_pgetc);
10237 if (g_parsefile->unget)
10238 return g_parsefile->lastc[--g_parsefile->unget];
10240 if (--g_parsefile->left_in_line >= 0)
10241 c = (unsigned char)*g_parsefile->next_to_pgetc++;
10245 g_parsefile->lastc[1] = g_parsefile->lastc[0];
10246 g_parsefile->lastc[0] = c;
10251 #if ENABLE_ASH_ALIAS
10253 pgetc_without_PEOA(void)
10257 pgetc_debug("pgetc at %d:%p'%s'",
10258 g_parsefile->left_in_line,
10259 g_parsefile->next_to_pgetc,
10260 g_parsefile->next_to_pgetc);
10262 } while (c == PEOA);
10266 # define pgetc_without_PEOA() pgetc()
10270 * Read a line from the script.
10273 pfgets(char *line, int len)
10279 while (--nleft > 0) {
10280 c = pgetc_without_PEOA();
10295 * Undo a call to pgetc. Only two characters may be pushed back.
10296 * PEOF may be pushed back.
10301 g_parsefile->unget++;
10304 /* This one eats backslash+newline */
10310 while ((c = pgetc()) == '\\') {
10311 if (pgetc() != '\n') {
10323 * To handle the "." command, a stack of input files is used. Pushfile
10324 * adds a new entry to the stack and popfile restores the previous level.
10329 struct parsefile *pf;
10331 pf = ckzalloc(sizeof(*pf));
10332 pf->prev = g_parsefile;
10334 /*pf->strpush = NULL; - ckzalloc did it */
10335 /*pf->basestrpush.prev = NULL;*/
10343 struct parsefile *pf = g_parsefile;
10349 if (pf->pf_fd >= 0)
10352 while (pf->strpush)
10354 g_parsefile = pf->prev;
10360 * Return to top level.
10365 while (g_parsefile != &basepf)
10370 * Close the file(s) that the shell is reading commands from. Called
10371 * after a fork is done.
10377 if (g_parsefile->pf_fd > 0) {
10378 close(g_parsefile->pf_fd);
10379 g_parsefile->pf_fd = 0;
10384 * Like setinputfile, but takes an open file descriptor. Call this with
10388 setinputfd(int fd, int push)
10392 g_parsefile->buf = NULL;
10394 g_parsefile->pf_fd = fd;
10395 if (g_parsefile->buf == NULL)
10396 g_parsefile->buf = ckmalloc(IBUFSIZ);
10397 g_parsefile->left_in_buffer = 0;
10398 g_parsefile->left_in_line = 0;
10399 g_parsefile->linno = 1;
10403 * Set the input to take input from a file. If push is set, push the
10404 * old input onto the stack first.
10407 setinputfile(const char *fname, int flags)
10412 fd = open(fname, O_RDONLY);
10414 if (flags & INPUT_NOFILE_OK)
10417 ash_msg_and_raise_error("can't open '%s'", fname);
10422 close_on_exec_on(fd);
10423 setinputfd(fd, flags & INPUT_PUSH_FILE);
10430 * Like setinputfile, but takes input from a string.
10433 setinputstring(char *string)
10437 g_parsefile->next_to_pgetc = string;
10438 g_parsefile->left_in_line = strlen(string);
10439 g_parsefile->buf = NULL;
10440 g_parsefile->linno = 1;
10446 * Routines to check for mail.
10449 #if ENABLE_ASH_MAIL
10451 /* Hash of mtimes of mailboxes */
10452 static unsigned mailtime_hash;
10453 /* Set if MAIL or MAILPATH is changed. */
10454 static smallint mail_var_path_changed;
10457 * Print appropriate message(s) if mail has arrived.
10458 * If mail_var_path_changed is set,
10459 * then the value of MAIL has mail_var_path_changed,
10460 * so we just update the values.
10469 struct stackmark smark;
10472 setstackmark(&smark);
10473 mpath = mpathset() ? mpathval() : mailval();
10476 p = path_advance(&mpath, nullstr);
10481 for (q = p; *q; q++)
10487 q[-1] = '\0'; /* delete trailing '/' */
10488 if (stat(p, &statb) < 0) {
10491 /* Very simplistic "hash": just a sum of all mtimes */
10492 new_hash += (unsigned)statb.st_mtime;
10494 if (!mail_var_path_changed && mailtime_hash != new_hash) {
10495 if (mailtime_hash != 0)
10496 out2str("you have mail\n");
10497 mailtime_hash = new_hash;
10499 mail_var_path_changed = 0;
10500 popstackmark(&smark);
10503 static void FAST_FUNC
10504 changemail(const char *val UNUSED_PARAM)
10506 mail_var_path_changed = 1;
10509 #endif /* ASH_MAIL */
10512 /* ============ ??? */
10515 * Set the shell parameters.
10518 setparam(char **argv)
10524 for (nparam = 0; argv[nparam]; nparam++)
10526 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
10528 *ap++ = ckstrdup(*argv++);
10531 freeparam(&shellparam);
10532 shellparam.malloced = 1;
10533 shellparam.nparam = nparam;
10534 shellparam.p = newparam;
10535 #if ENABLE_ASH_GETOPTS
10536 shellparam.optind = 1;
10537 shellparam.optoff = -1;
10542 * Process shell options. The global variable argptr contains a pointer
10543 * to the argument list; we advance it past the options.
10545 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
10546 * For a non-interactive shell, an error condition encountered
10547 * by a special built-in ... shall cause the shell to write a diagnostic message
10548 * to standard error and exit as shown in the following table:
10549 * Error Special Built-In
10551 * Utility syntax error (option or operand error) Shall exit
10553 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
10554 * we see that bash does not do that (set "finishes" with error code 1 instead,
10555 * and shell continues), and people rely on this behavior!
10557 * set -o barfoo 2>/dev/null
10560 * Oh well. Let's mimic that.
10563 plus_minus_o(char *name, int val)
10568 for (i = 0; i < NOPTS; i++) {
10569 if (strcmp(name, optnames(i)) == 0) {
10574 ash_msg("illegal option %co %s", val ? '-' : '+', name);
10577 for (i = 0; i < NOPTS; i++) {
10579 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
10581 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
10587 setoption(int flag, int val)
10591 for (i = 0; i < NOPTS; i++) {
10592 if (optletters(i) == flag) {
10597 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
10601 options(int cmdline)
10609 while ((p = *argptr) != NULL) {
10611 if (c != '-' && c != '+')
10614 val = 0; /* val = 0 if c == '+' */
10617 if (p[0] == '\0' || LONE_DASH(p)) {
10619 /* "-" means turn off -x and -v */
10622 /* "--" means reset params */
10623 else if (*argptr == NULL)
10626 break; /* "-" or "--" terminates options */
10629 /* first char was + or - */
10630 while ((c = *p++) != '\0') {
10631 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
10632 if (c == 'c' && cmdline) {
10633 minusc = p; /* command is after shell args */
10634 } else if (c == 'o') {
10635 if (plus_minus_o(*argptr, val)) {
10636 /* it already printed err message */
10637 return 1; /* error */
10641 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10643 /* bash does not accept +-login, we also won't */
10644 } else if (cmdline && val && (c == '-')) { /* long options */
10645 if (strcmp(p, "login") == 0)
10657 * The shift builtin command.
10659 static int FAST_FUNC
10660 shiftcmd(int argc UNUSED_PARAM, char **argv)
10667 n = number(argv[1]);
10668 if (n > shellparam.nparam)
10669 n = 0; /* bash compat, was = shellparam.nparam; */
10671 shellparam.nparam -= n;
10672 for (ap1 = shellparam.p; --n >= 0; ap1++) {
10673 if (shellparam.malloced)
10676 ap2 = shellparam.p;
10677 while ((*ap2++ = *ap1++) != NULL)
10679 #if ENABLE_ASH_GETOPTS
10680 shellparam.optind = 1;
10681 shellparam.optoff = -1;
10688 * POSIX requires that 'set' (but not export or readonly) output the
10689 * variables in lexicographic order - by the locale's collating order (sigh).
10690 * Maybe we could keep them in an ordered balanced binary tree
10691 * instead of hashed lists.
10692 * For now just roll 'em through qsort for printing...
10695 showvars(const char *sep_prefix, int on, int off)
10698 char **ep, **epend;
10700 ep = listvars(on, off, &epend);
10701 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10703 sep = *sep_prefix ? " " : sep_prefix;
10705 for (; ep < epend; ep++) {
10709 p = strchrnul(*ep, '=');
10712 q = single_quote(++p);
10713 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10719 * The set command builtin.
10721 static int FAST_FUNC
10722 setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10727 return showvars(nullstr, 0, VUNSET);
10730 retval = options(/*cmdline:*/ 0);
10731 if (retval == 0) { /* if no parse error... */
10733 if (*argptr != NULL) {
10741 #if ENABLE_ASH_RANDOM_SUPPORT
10742 static void FAST_FUNC
10743 change_random(const char *value)
10747 if (value == NULL) {
10748 /* "get", generate */
10749 t = next_random(&random_gen);
10750 /* set without recursion */
10751 setvar(vrandom.var_text, utoa(t), VNOFUNC);
10752 vrandom.flags &= ~VNOFUNC;
10755 t = strtoul(value, NULL, 10);
10756 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
10761 #if ENABLE_ASH_GETOPTS
10763 getopts(char *optstr, char *optvar, char **optfirst)
10770 int ind = shellparam.optind;
10771 int off = shellparam.optoff;
10775 shellparam.optind = -1;
10776 optnext = optfirst + ind - 1;
10778 if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
10781 p = optnext[-1] + off;
10782 if (p == NULL || *p == '\0') {
10783 /* Current word is done, advance */
10785 if (p == NULL || *p != '-' || *++p == '\0') {
10792 if (LONE_DASH(p)) /* check for "--" */
10797 for (q = optstr; *q != c;) {
10799 if (optstr[0] == ':') {
10801 /*sbuf[1] = '\0'; - already is */
10802 setvar0("OPTARG", sbuf);
10804 fprintf(stderr, "Illegal option -%c\n", c);
10805 unsetvar("OPTARG");
10815 if (*p == '\0' && (p = *optnext) == NULL) {
10816 if (optstr[0] == ':') {
10818 /*sbuf[1] = '\0'; - already is */
10819 setvar0("OPTARG", sbuf);
10822 fprintf(stderr, "No arg for -%c option\n", c);
10823 unsetvar("OPTARG");
10831 setvar0("OPTARG", p);
10834 setvar0("OPTARG", nullstr);
10836 ind = optnext - optfirst + 1;
10837 setvar("OPTIND", itoa(ind), VNOFUNC);
10839 /*sbuf[1] = '\0'; - already is */
10840 setvar0(optvar, sbuf);
10842 shellparam.optoff = p ? p - *(optnext - 1) : -1;
10843 shellparam.optind = ind;
10849 * The getopts builtin. Shellparam.optnext points to the next argument
10850 * to be processed. Shellparam.optptr points to the next character to
10851 * be processed in the current argument. If shellparam.optnext is NULL,
10852 * then it's the first time getopts has been called.
10854 static int FAST_FUNC
10855 getoptscmd(int argc, char **argv)
10860 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
10862 optbase = shellparam.p;
10863 if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
10864 shellparam.optind = 1;
10865 shellparam.optoff = -1;
10868 optbase = &argv[3];
10869 if ((unsigned)shellparam.optind > argc - 2) {
10870 shellparam.optind = 1;
10871 shellparam.optoff = -1;
10875 return getopts(argv[1], argv[2], optbase);
10877 #endif /* ASH_GETOPTS */
10880 /* ============ Shell parser */
10883 struct heredoc *next; /* next here document in list */
10884 union node *here; /* redirection node */
10885 char *eofmark; /* string indicating end of input */
10886 smallint striptabs; /* if set, strip leading tabs */
10889 static smallint tokpushback; /* last token pushed back */
10890 static smallint quoteflag; /* set if (part of) last token was quoted */
10891 static token_id_t lasttoken; /* last token read (integer id Txxx) */
10892 static struct heredoc *heredoclist; /* list of here documents to read */
10893 static char *wordtext; /* text of last word returned by readtoken */
10894 static struct nodelist *backquotelist;
10895 static union node *redirnode;
10896 static struct heredoc *heredoc;
10898 static const char *
10899 tokname(char *buf, int tok)
10902 return tokname_array[tok];
10903 sprintf(buf, "\"%s\"", tokname_array[tok]);
10907 /* raise_error_unexpected_syntax:
10908 * Called when an unexpected token is read during the parse. The argument
10909 * is the token that is expected, or -1 if more than one type of token can
10910 * occur at this point.
10912 static void raise_error_unexpected_syntax(int) NORETURN;
10914 raise_error_unexpected_syntax(int token)
10920 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
10922 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
10923 raise_error_syntax(msg);
10927 #define EOFMARKLEN 79
10929 /* parsing is heavily cross-recursive, need these forward decls */
10930 static union node *andor(void);
10931 static union node *pipeline(void);
10932 static union node *parse_command(void);
10933 static void parseheredoc(void);
10934 static int peektoken(void);
10935 static int readtoken(void);
10937 static union node *
10940 union node *n1, *n2, *n3;
10945 switch (peektoken()) {
10953 if (!n1 && (nlflag & 1))
10959 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10960 if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
10966 if (tok == TBACKGND) {
10967 if (n2->type == NPIPE) {
10968 n2->npipe.pipe_backgnd = 1;
10970 if (n2->type != NREDIR) {
10971 n3 = stzalloc(sizeof(struct nredir));
10973 /*n3->nredir.redirect = NULL; - stzalloc did it */
10976 n2->type = NBACKGND;
10982 n3 = stzalloc(sizeof(struct nbinary));
10984 n3->nbinary.ch1 = n1;
10985 n3->nbinary.ch2 = n2;
10998 raise_error_unexpected_syntax(-1);
11005 static union node *
11008 union node *n1, *n2, *n3;
11016 } else if (t == TOR) {
11022 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11024 n3 = stzalloc(sizeof(struct nbinary));
11026 n3->nbinary.ch1 = n1;
11027 n3->nbinary.ch2 = n2;
11032 static union node *
11035 union node *n1, *n2, *pipenode;
11036 struct nodelist *lp, *prev;
11040 TRACE(("pipeline: entered\n"));
11041 if (readtoken() == TNOT) {
11043 checkkwd = CHKKWD | CHKALIAS;
11046 n1 = parse_command();
11047 if (readtoken() == TPIPE) {
11048 pipenode = stzalloc(sizeof(struct npipe));
11049 pipenode->type = NPIPE;
11050 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
11051 lp = stzalloc(sizeof(struct nodelist));
11052 pipenode->npipe.cmdlist = lp;
11056 lp = stzalloc(sizeof(struct nodelist));
11057 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11058 lp->n = parse_command();
11060 } while (readtoken() == TPIPE);
11066 n2 = stzalloc(sizeof(struct nnot));
11074 static union node *
11079 n = stzalloc(sizeof(struct narg));
11081 /*n->narg.next = NULL; - stzalloc did it */
11082 n->narg.text = wordtext;
11083 n->narg.backquote = backquotelist;
11088 fixredir(union node *n, const char *text, int err)
11092 TRACE(("Fix redir %s %d\n", text, err));
11094 n->ndup.vname = NULL;
11096 fd = bb_strtou(text, NULL, 10);
11097 if (!errno && fd >= 0)
11098 n->ndup.dupfd = fd;
11099 else if (LONE_DASH(text))
11100 n->ndup.dupfd = -1;
11103 raise_error_syntax("bad fd number");
11104 n->ndup.vname = makename();
11109 * Returns true if the text contains nothing to expand (no dollar signs
11113 noexpand(const char *text)
11117 while ((c = *text++) != '\0') {
11118 if (c == CTLQUOTEMARK)
11122 else if (SIT(c, BASESYNTAX) == CCTL)
11131 union node *n = redirnode;
11133 if (readtoken() != TWORD)
11134 raise_error_unexpected_syntax(-1);
11135 if (n->type == NHERE) {
11136 struct heredoc *here = heredoc;
11140 if (quoteflag == 0)
11142 TRACE(("Here document %d\n", n->type));
11143 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
11144 raise_error_syntax("illegal eof marker for << redirection");
11145 rmescapes(wordtext, 0);
11146 here->eofmark = wordtext;
11148 if (heredoclist == NULL)
11149 heredoclist = here;
11151 for (p = heredoclist; p->next; p = p->next)
11155 } else if (n->type == NTOFD || n->type == NFROMFD) {
11156 fixredir(n, wordtext, 0);
11158 n->nfile.fname = makename();
11162 static union node *
11165 union node *args, **app;
11166 union node *n = NULL;
11167 union node *vars, **vpp;
11168 union node **rpp, *redir;
11171 smallint double_brackets_flag = 0;
11173 IF_BASH_FUNCTION(smallint function_flag = 0;)
11182 savecheckkwd = CHKALIAS;
11185 checkkwd = savecheckkwd;
11190 if (peektoken() != TWORD)
11191 raise_error_unexpected_syntax(TWORD);
11196 case TAND: /* "&&" */
11197 case TOR: /* "||" */
11198 if (!double_brackets_flag) {
11202 wordtext = (char *) (t == TAND ? "-a" : "-o");
11205 n = stzalloc(sizeof(struct narg));
11207 /*n->narg.next = NULL; - stzalloc did it */
11208 n->narg.text = wordtext;
11210 if (strcmp("[[", wordtext) == 0)
11211 double_brackets_flag = 1;
11212 else if (strcmp("]]", wordtext) == 0)
11213 double_brackets_flag = 0;
11215 n->narg.backquote = backquotelist;
11216 if (savecheckkwd && isassignment(wordtext)) {
11218 vpp = &n->narg.next;
11221 app = &n->narg.next;
11225 if (function_flag) {
11226 checkkwd = CHKNL | CHKKWD;
11227 switch (peektoken()) {
11239 if (strcmp("[[", wordtext) == 0)
11243 raise_error_unexpected_syntax(-1);
11249 *rpp = n = redirnode;
11250 rpp = &n->nfile.next;
11251 parsefname(); /* read name of redirection file */
11254 IF_BASH_FUNCTION(do_func:)
11255 if (args && app == &args->narg.next
11258 struct builtincmd *bcmd;
11261 /* We have a function */
11262 if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
11263 raise_error_unexpected_syntax(TRP);
11264 name = n->narg.text;
11265 if (!goodname(name)
11266 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
11268 raise_error_syntax("bad function name");
11271 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11272 n->narg.next = parse_command();
11275 IF_BASH_FUNCTION(function_flag = 0;)
11286 n = stzalloc(sizeof(struct ncmd));
11288 n->ncmd.args = args;
11289 n->ncmd.assign = vars;
11290 n->ncmd.redirect = redir;
11294 static union node *
11295 parse_command(void)
11297 union node *n1, *n2;
11298 union node *ap, **app;
11299 union node *cp, **cpp;
11300 union node *redir, **rpp;
11307 switch (readtoken()) {
11309 raise_error_unexpected_syntax(-1);
11312 n1 = stzalloc(sizeof(struct nif));
11314 n1->nif.test = list(0);
11315 if (readtoken() != TTHEN)
11316 raise_error_unexpected_syntax(TTHEN);
11317 n1->nif.ifpart = list(0);
11319 while (readtoken() == TELIF) {
11320 n2->nif.elsepart = stzalloc(sizeof(struct nif));
11321 n2 = n2->nif.elsepart;
11323 n2->nif.test = list(0);
11324 if (readtoken() != TTHEN)
11325 raise_error_unexpected_syntax(TTHEN);
11326 n2->nif.ifpart = list(0);
11328 if (lasttoken == TELSE)
11329 n2->nif.elsepart = list(0);
11331 n2->nif.elsepart = NULL;
11339 n1 = stzalloc(sizeof(struct nbinary));
11340 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
11341 n1->nbinary.ch1 = list(0);
11344 TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
11345 got == TWORD ? wordtext : ""));
11346 raise_error_unexpected_syntax(TDO);
11348 n1->nbinary.ch2 = list(0);
11353 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
11354 raise_error_syntax("bad for loop variable");
11355 n1 = stzalloc(sizeof(struct nfor));
11357 n1->nfor.var = wordtext;
11358 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11359 if (readtoken() == TIN) {
11361 while (readtoken() == TWORD) {
11362 n2 = stzalloc(sizeof(struct narg));
11364 /*n2->narg.next = NULL; - stzalloc did it */
11365 n2->narg.text = wordtext;
11366 n2->narg.backquote = backquotelist;
11368 app = &n2->narg.next;
11371 n1->nfor.args = ap;
11372 if (lasttoken != TNL && lasttoken != TSEMI)
11373 raise_error_unexpected_syntax(-1);
11375 n2 = stzalloc(sizeof(struct narg));
11377 /*n2->narg.next = NULL; - stzalloc did it */
11378 n2->narg.text = (char *)dolatstr;
11379 /*n2->narg.backquote = NULL;*/
11380 n1->nfor.args = n2;
11382 * Newline or semicolon here is optional (but note
11383 * that the original Bourne shell only allowed NL).
11385 if (lasttoken != TSEMI)
11388 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11389 if (readtoken() != TDO)
11390 raise_error_unexpected_syntax(TDO);
11391 n1->nfor.body = list(0);
11395 n1 = stzalloc(sizeof(struct ncase));
11397 if (readtoken() != TWORD)
11398 raise_error_unexpected_syntax(TWORD);
11399 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
11401 /*n2->narg.next = NULL; - stzalloc did it */
11402 n2->narg.text = wordtext;
11403 n2->narg.backquote = backquotelist;
11404 checkkwd = CHKNL | CHKKWD | CHKALIAS;
11405 if (readtoken() != TIN)
11406 raise_error_unexpected_syntax(TIN);
11407 cpp = &n1->ncase.cases;
11409 checkkwd = CHKNL | CHKKWD;
11411 while (t != TESAC) {
11412 if (lasttoken == TLP)
11414 *cpp = cp = stzalloc(sizeof(struct nclist));
11416 app = &cp->nclist.pattern;
11418 *app = ap = stzalloc(sizeof(struct narg));
11420 /*ap->narg.next = NULL; - stzalloc did it */
11421 ap->narg.text = wordtext;
11422 ap->narg.backquote = backquotelist;
11423 if (readtoken() != TPIPE)
11425 app = &ap->narg.next;
11428 //ap->narg.next = NULL;
11429 if (lasttoken != TRP)
11430 raise_error_unexpected_syntax(TRP);
11431 cp->nclist.body = list(2);
11433 cpp = &cp->nclist.next;
11435 checkkwd = CHKNL | CHKKWD;
11439 raise_error_unexpected_syntax(TENDCASE);
11446 n1 = stzalloc(sizeof(struct nredir));
11447 n1->type = NSUBSHELL;
11448 n1->nredir.n = list(0);
11449 /*n1->nredir.redirect = NULL; - stzalloc did it */
11456 IF_BASH_FUNCTION(case TFUNCTION:)
11460 return simplecmd();
11463 if (readtoken() != t)
11464 raise_error_unexpected_syntax(t);
11467 /* Now check for redirection which may follow command */
11468 checkkwd = CHKKWD | CHKALIAS;
11470 while (readtoken() == TREDIR) {
11471 *rpp = n2 = redirnode;
11472 rpp = &n2->nfile.next;
11478 if (n1->type != NSUBSHELL) {
11479 n2 = stzalloc(sizeof(struct nredir));
11484 n1->nredir.redirect = redir;
11489 #if BASH_DOLLAR_SQUOTE
11491 decode_dollar_squote(void)
11493 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
11499 p = strchr(C_escapes, c);
11504 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
11508 } while ((unsigned char)(c - '0') <= 7 && --cnt);
11510 } else if (c == 'x') { /* \xHH */
11514 } while (isxdigit(c) && --cnt);
11516 if (cnt == 3) { /* \x but next char is "bad" */
11520 } else { /* simple seq like \\ or \t */
11525 c = bb_process_escape_sequence((void*)&p);
11526 } else { /* unrecognized "\z": print both chars unless ' or " */
11527 if (c != '\'' && c != '"') {
11529 c |= 0x100; /* "please encode \, then me" */
11537 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
11538 * is not NULL, read a here document. In the latter case, eofmark is the
11539 * word which marks the end of the document and striptabs is true if
11540 * leading tabs should be stripped from the document. The argument c
11541 * is the first character of the input token or document.
11543 * Because C does not have internal subroutines, I have simulated them
11544 * using goto's to implement the subroutine linkage. The following macros
11545 * will run code that appears at the end of readtoken1.
11547 #define CHECKEND() {goto checkend; checkend_return:;}
11548 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
11549 #define PARSESUB() {goto parsesub; parsesub_return:;}
11550 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
11551 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
11552 #define PARSEARITH() {goto parsearith; parsearith_return:;}
11554 readtoken1(int c, int syntax, char *eofmark, int striptabs)
11556 /* NB: syntax parameter fits into smallint */
11557 /* c parameter is an unsigned char or PEOF or PEOA */
11560 char line[EOFMARKLEN + 1];
11561 struct nodelist *bqlist;
11565 IF_FEATURE_SH_MATH(smallint prevsyntax;) /* syntax before arithmetic */
11566 smallint pssyntax; /* we are expanding a prompt string */
11567 int varnest; /* levels of variables expansion */
11568 IF_FEATURE_SH_MATH(int arinest;) /* levels of arithmetic expansion */
11569 IF_FEATURE_SH_MATH(int parenlevel;) /* levels of parens in arithmetic */
11570 int dqvarnest; /* levels of variables expansion within double quotes */
11572 IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
11574 startlinno = g_parsefile->linno;
11577 IF_FEATURE_SH_MATH(prevsyntax = 0;)
11578 pssyntax = (syntax == PSSYNTAX);
11581 dblquote = (syntax == DQSYNTAX);
11583 IF_FEATURE_SH_MATH(arinest = 0;)
11584 IF_FEATURE_SH_MATH(parenlevel = 0;)
11587 STARTSTACKSTR(out);
11589 /* For each line, until end of word */
11590 CHECKEND(); /* set c to PEOF if at end of here document */
11591 for (;;) { /* until end of line or end of word */
11592 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
11593 switch (SIT(c, syntax)) {
11594 case CNL: /* '\n' */
11595 if (syntax == BASESYNTAX)
11596 goto endword; /* exit outer loop */
11600 goto loop; /* continue outer loop */
11605 #if BASH_DOLLAR_SQUOTE
11606 if (c == '\\' && bash_dollar_squote) {
11607 c = decode_dollar_squote();
11609 /* skip $'\000', $'\x00' (like bash) */
11613 /* Unknown escape. Encode as '\z' */
11614 c = (unsigned char)c;
11615 if (eofmark == NULL || dblquote)
11616 USTPUTC(CTLESC, out);
11617 USTPUTC('\\', out);
11621 if (eofmark == NULL || dblquote)
11622 USTPUTC(CTLESC, out);
11625 case CBACK: /* backslash */
11626 c = pgetc_without_PEOA();
11628 USTPUTC(CTLESC, out);
11629 USTPUTC('\\', out);
11631 } else if (c == '\n') {
11634 if (c == '$' && pssyntax) {
11635 USTPUTC(CTLESC, out);
11636 USTPUTC('\\', out);
11638 /* Backslash is retained if we are in "str" and next char isn't special */
11643 && (c != '"' || eofmark != NULL)
11645 USTPUTC('\\', out);
11647 USTPUTC(CTLESC, out);
11655 if (eofmark == NULL) {
11656 USTPUTC(CTLQUOTEMARK, out);
11664 IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
11665 if (eofmark != NULL && varnest == 0) {
11668 if (dqvarnest == 0) {
11669 syntax = BASESYNTAX;
11676 case CVAR: /* '$' */
11677 PARSESUB(); /* parse substitution */
11679 case CENDVAR: /* '}' */
11682 if (dqvarnest > 0) {
11689 #if ENABLE_FEATURE_SH_MATH
11690 case CLP: /* '(' in arithmetic */
11694 case CRP: /* ')' in arithmetic */
11695 if (parenlevel > 0) {
11698 if (pgetc_eatbnl() == ')') {
11700 if (--arinest == 0) {
11701 syntax = prevsyntax;
11705 * unbalanced parens
11706 * (don't 2nd guess - no error)
11714 case CBQUOTE: /* '`' */
11718 goto endword; /* exit outer loop */
11722 if (varnest == 0) {
11723 #if BASH_REDIR_OUTPUT
11725 //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
11726 if (pgetc() == '>')
11727 c = 0x100 + '>'; /* flag &> */
11731 goto endword; /* exit outer loop */
11733 IF_ASH_ALIAS(if (c != PEOA))
11740 #if ENABLE_FEATURE_SH_MATH
11741 if (syntax == ARISYNTAX)
11742 raise_error_syntax("missing '))'");
11744 if (syntax != BASESYNTAX && eofmark == NULL)
11745 raise_error_syntax("unterminated quoted string");
11746 if (varnest != 0) {
11747 startlinno = g_parsefile->linno;
11749 raise_error_syntax("missing '}'");
11751 USTPUTC('\0', out);
11752 len = out - (char *)stackblock();
11753 out = stackblock();
11754 if (eofmark == NULL) {
11755 if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
11758 if (isdigit_str9(out)) {
11759 PARSEREDIR(); /* passed as params: out, c */
11760 lasttoken = TREDIR;
11763 /* else: non-number X seen, interpret it
11764 * as "NNNX>file" = "NNNX >file" */
11768 quoteflag = quotef;
11769 backquotelist = bqlist;
11770 grabstackblock(len);
11774 /* end of readtoken routine */
11777 * Check to see whether we are at the end of the here document. When this
11778 * is called, c is set to the first character of the next input line. If
11779 * we are at the end of the here document, this routine sets the c to PEOF.
11783 #if ENABLE_ASH_ALIAS
11785 c = pgetc_without_PEOA();
11788 while (c == '\t') {
11789 c = pgetc_without_PEOA();
11792 if (c == *eofmark) {
11793 if (pfgets(line, sizeof(line)) != NULL) {
11798 for (q = eofmark + 1;; p++, q++) {
11802 if (!*q || cc != *q)
11809 pushstring(line, NULL);
11814 goto checkend_return;
11818 * Parse a redirection operator. The variable "out" points to a string
11819 * specifying the fd to be redirected. The variable "c" contains the
11820 * first character of the redirection operator.
11823 /* out is already checked to be a valid number or "" */
11824 int fd = (*out == '\0' ? -1 : atoi(out));
11827 np = stzalloc(sizeof(struct nfile));
11832 np->type = NAPPEND;
11834 np->type = NCLOBBER;
11837 /* it also can be NTO2 (>&file), but we can't figure it out yet */
11843 #if BASH_REDIR_OUTPUT
11844 else if (c == 0x100 + '>') { /* this flags &> redirection */
11846 pgetc(); /* this is '>', no need to check */
11850 else { /* c == '<' */
11851 /*np->nfile.fd = 0; - stzalloc did it */
11855 if (sizeof(struct nfile) != sizeof(struct nhere)) {
11856 np = stzalloc(sizeof(struct nhere));
11857 /*np->nfile.fd = 0; - stzalloc did it */
11860 heredoc = stzalloc(sizeof(struct heredoc));
11861 heredoc->here = np;
11864 heredoc->striptabs = 1;
11866 /*heredoc->striptabs = 0; - stzalloc did it */
11872 np->type = NFROMFD;
11876 np->type = NFROMTO;
11888 goto parseredir_return;
11892 * Parse a substitution. At this point, we have read the dollar sign
11893 * and nothing else.
11896 /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11897 * (assuming ascii char codes, as the original implementation did) */
11898 #define is_special(c) \
11899 (((unsigned)(c) - 33 < 32) \
11900 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
11902 unsigned char subtype;
11905 c = pgetc_eatbnl();
11906 if (c > 255 /* PEOA or PEOF */
11907 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
11909 #if BASH_DOLLAR_SQUOTE
11910 if (syntax != DQSYNTAX && c == '\'')
11911 bash_dollar_squote = 1;
11916 } else if (c == '(') {
11917 /* $(command) or $((arith)) */
11918 if (pgetc_eatbnl() == '(') {
11919 #if ENABLE_FEATURE_SH_MATH
11922 raise_error_syntax("support for $((arith)) is disabled");
11929 /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
11930 USTPUTC(CTLVAR, out);
11931 typeloc = out - (char *)stackblock();
11933 subtype = VSNORMAL;
11935 c = pgetc_eatbnl();
11940 /* $[{[#]]NAME[}] */
11943 c = pgetc_eatbnl();
11944 } while (is_in_name(c));
11945 } else if (isdigit(c)) {
11946 /* $[{[#]]NUM[}] */
11949 c = pgetc_eatbnl();
11950 } while (isdigit(c));
11951 } else if (is_special(c)) {
11952 /* $[{[#]]<specialchar>[}] */
11955 c = pgetc_eatbnl();
11956 if (!subtype && cc == '#') {
11957 subtype = VSLENGTH;
11958 if (c == '_' || isalnum(c))
11961 c = pgetc_eatbnl();
11962 if (cc == '}' || c != '}') {
11973 if (c != '}' && subtype == VSLENGTH) {
11974 /* ${#VAR didn't end with } */
11978 if (subtype == 0) {
11979 static const char types[] ALIGN1 = "}-+?=";
11980 /* ${VAR...} but not $VAR or ${#VAR} */
11981 /* c == first char after VAR */
11984 c = pgetc_eatbnl();
11986 /* This check is only needed to not misinterpret
11987 * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
11990 if (!strchr(types, c)) {
11991 subtype = VSSUBSTR;
11993 break; /* "goto badsub" is bigger (!) */
11999 const char *p = strchr(types, c);
12002 subtype |= p - types + VSNORMAL;
12008 subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
12009 c = pgetc_eatbnl();
12015 #if BASH_PATTERN_SUBST
12017 /* ${v/[/]pattern/repl} */
12018 //TODO: encode pattern and repl separately.
12019 // Currently ${v/$var_with_slash/repl} is horribly broken
12020 subtype = VSREPLACE;
12021 c = pgetc_eatbnl();
12024 subtype++; /* VSREPLACEALL */
12032 ((unsigned char *)stackblock())[typeloc] = subtype;
12033 if (subtype != VSNORMAL) {
12040 goto parsesub_return;
12044 * Called to parse command substitutions. Newstyle is set if the command
12045 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
12046 * list of commands (passed by reference), and savelen is the number of
12047 * characters on the top of the stack which must be preserved.
12050 struct nodelist **nlpp;
12054 smallint saveprompt = 0;
12057 savelen = out - (char *)stackblock();
12060 * FIXME: this can allocate very large block on stack and SEGV.
12062 * echo "..<100kbytes>..`true` $(true) `true` ..."
12063 * allocates 100kb for every command subst. With about
12064 * a hundred command substitutions stack overflows.
12065 * With larger prepended string, SEGV happens sooner.
12067 str = alloca(savelen);
12068 memcpy(str, stackblock(), savelen);
12072 /* We must read until the closing backquote, giving special
12073 * treatment to some slashes, and then push the string and
12074 * reread it as input, interpreting it normally.
12080 STARTSTACKSTR(pout);
12084 setprompt_if(needprompt, 2);
12095 * If eating a newline, avoid putting
12096 * the newline into the new character
12097 * stream (via the STPUTC after the
12102 if (pc != '\\' && pc != '`' && pc != '$'
12103 && (!dblquote || pc != '"')
12105 STPUTC('\\', pout);
12107 if (pc <= 255 /* not PEOA or PEOF */) {
12113 IF_ASH_ALIAS(case PEOA:)
12114 startlinno = g_parsefile->linno;
12115 raise_error_syntax("EOF in backquote substitution");
12127 STPUTC('\0', pout);
12128 psavelen = pout - (char *)stackblock();
12129 if (psavelen > 0) {
12130 pstr = grabstackstr(pout);
12131 setinputstring(pstr);
12136 nlpp = &(*nlpp)->next;
12137 *nlpp = stzalloc(sizeof(**nlpp));
12138 /* (*nlpp)->next = NULL; - stzalloc did it */
12141 saveprompt = doprompt;
12148 doprompt = saveprompt;
12149 else if (readtoken() != TRP)
12150 raise_error_unexpected_syntax(TRP);
12155 * Start reading from old file again, ignoring any pushed back
12156 * tokens left from the backquote parsing
12161 while (stackblocksize() <= savelen)
12163 STARTSTACKSTR(out);
12165 memcpy(out, str, savelen);
12166 STADJUST(savelen, out);
12168 USTPUTC(CTLBACKQ, out);
12170 goto parsebackq_oldreturn;
12171 goto parsebackq_newreturn;
12174 #if ENABLE_FEATURE_SH_MATH
12176 * Parse an arithmetic expansion (indicate start of one and set state)
12179 if (++arinest == 1) {
12180 prevsyntax = syntax;
12181 syntax = ARISYNTAX;
12183 USTPUTC(CTLARI, out);
12184 goto parsearith_return;
12187 } /* end of readtoken */
12190 * Read the next input token.
12191 * If the token is a word, we set backquotelist to the list of cmds in
12192 * backquotes. We set quoteflag to true if any part of the word was
12194 * If the token is TREDIR, then we set redirnode to a structure containing
12196 * In all cases, the variable startlinno is set to the number of the line
12197 * on which the token starts.
12199 * [Change comment: here documents and internal procedures]
12200 * [Readtoken shouldn't have any arguments. Perhaps we should make the
12201 * word parsing code into a separate routine. In this case, readtoken
12202 * doesn't need to have any internal procedures, but parseword does.
12203 * We could also make parseoperator in essence the main routine, and
12204 * have parseword (readtoken1?) handle both words and redirection.]
12206 #define NEW_xxreadtoken
12207 #ifdef NEW_xxreadtoken
12208 /* singles must be first! */
12209 static const char xxreadtoken_chars[7] ALIGN1 = {
12210 '\n', '(', ')', /* singles */
12211 '&', '|', ';', /* doubles */
12215 #define xxreadtoken_singles 3
12216 #define xxreadtoken_doubles 3
12218 static const char xxreadtoken_tokens[] ALIGN1 = {
12219 TNL, TLP, TRP, /* only single occurrence allowed */
12220 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
12221 TEOF, /* corresponds to trailing nul */
12222 TAND, TOR, TENDCASE /* if double occurrence */
12234 setprompt_if(needprompt, 2);
12235 startlinno = g_parsefile->linno;
12236 for (;;) { /* until token or start of word found */
12238 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
12242 while ((c = pgetc()) != '\n' && c != PEOF)
12245 } else if (c == '\\') {
12246 if (pgetc() != '\n') {
12248 break; /* return readtoken1(...) */
12254 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
12260 p = strchr(xxreadtoken_chars, c);
12262 break; /* return readtoken1(...) */
12264 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
12266 if (cc == c) { /* double occurrence? */
12267 p += xxreadtoken_doubles + 1;
12270 #if BASH_REDIR_OUTPUT
12271 if (c == '&' && cc == '>') /* &> */
12272 break; /* return readtoken1(...) */
12277 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
12282 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
12284 #else /* old xxreadtoken */
12285 #define RETURN(token) return lasttoken = token
12295 setprompt_if(needprompt, 2);
12296 startlinno = g_parsefile->linno;
12297 for (;;) { /* until token or start of word found */
12300 case ' ': case '\t':
12301 IF_ASH_ALIAS(case PEOA:)
12304 while ((c = pgetc()) != '\n' && c != PEOF)
12309 if (pgetc() == '\n') {
12321 if (pgetc() == '&')
12326 if (pgetc() == '|')
12331 if (pgetc() == ';')
12344 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
12347 #endif /* old xxreadtoken */
12353 int kwd = checkkwd;
12355 smallint alreadyseen = tokpushback;
12358 #if ENABLE_ASH_ALIAS
12374 if (t != TWORD || quoteflag) {
12379 * check for keywords
12381 if (kwd & CHKKWD) {
12382 const char *const *pp;
12384 pp = findkwd(wordtext);
12386 lasttoken = t = pp - tokname_array;
12387 TRACE(("keyword '%s' recognized\n", tokname_array[t]));
12392 if (checkkwd & CHKALIAS) {
12393 #if ENABLE_ASH_ALIAS
12395 ap = lookupalias(wordtext, 1);
12398 pushstring(ap->val, ap);
12408 TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12410 TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
12426 * Read and parse a command. Returns NODE_EOF on end of file.
12427 * (NULL is a valid parse tree indicating a blank line.)
12429 static union node *
12430 parsecmd(int interact)
12435 doprompt = interact;
12436 setprompt_if(doprompt, doprompt);
12442 * Input any here documents.
12447 struct heredoc *here;
12450 here = heredoclist;
12451 heredoclist = NULL;
12454 setprompt_if(needprompt, 2);
12455 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
12456 here->eofmark, here->striptabs);
12457 n = stzalloc(sizeof(struct narg));
12458 n->narg.type = NARG;
12459 /*n->narg.next = NULL; - stzalloc did it */
12460 n->narg.text = wordtext;
12461 n->narg.backquote = backquotelist;
12462 here->here->nhere.doc = n;
12469 * called by editline -- any expansions to the prompt should be added here.
12471 static const char *
12472 expandstr(const char *ps)
12477 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
12478 * and token processing _can_ alter it (delete NULs etc). */
12479 setinputstring((char *)ps);
12481 saveprompt = doprompt;
12483 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
12484 doprompt = saveprompt;
12488 n.narg.type = NARG;
12489 n.narg.next = NULL;
12490 n.narg.text = wordtext;
12491 n.narg.backquote = backquotelist;
12493 expandarg(&n, NULL, EXP_QUOTED);
12494 return stackblock();
12500 return tokpushback && lasttoken == TEOF;
12504 * Execute a command or commands contained in a string.
12507 evalstring(char *s, int flags)
12509 struct jmploc *volatile savehandler;
12510 struct jmploc jmploc;
12514 struct stackmark smark;
12519 setstackmark(&smark);
12522 /* On exception inside execution loop, we must popfile().
12523 * Try interactively:
12525 * command eval "a=b" # throws "is read only" error
12526 * "command BLTIN" is not supposed to abort (even in non-interactive use).
12527 * But if we skip popfile(), we hit EOF in eval's string, and exit.
12529 savehandler = exception_handler;
12530 ex = setjmp(jmploc.loc);
12533 exception_handler = &jmploc;
12535 while ((n = parsecmd(0)) != NODE_EOF) {
12538 i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
12541 popstackmark(&smark);
12546 popstackmark(&smark);
12550 exception_handler = savehandler;
12552 longjmp(exception_handler->loc, ex);
12558 * The eval command.
12560 static int FAST_FUNC
12561 evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
12570 STARTSTACKSTR(concat);
12572 concat = stack_putstr(p, concat);
12576 STPUTC(' ', concat);
12578 STPUTC('\0', concat);
12579 p = grabstackstr(concat);
12581 return evalstring(p, flags & EV_TESTED);
12587 * Read and execute commands.
12588 * "Top" is nonzero for the top level command loop;
12589 * it turns on prompting if the shell is interactive.
12595 struct stackmark smark;
12600 TRACE(("cmdloop(%d) called\n", top));
12604 setstackmark(&smark);
12607 showjobs(SHOW_CHANGED|SHOW_STDERR);
12610 if (iflag && top) {
12614 n = parsecmd(inter);
12616 if (DEBUG > 2 && debug && (n != NODE_EOF))
12619 if (n == NODE_EOF) {
12620 if (!top || numeof >= 50)
12622 if (!stoppedjobs()) {
12625 out2str("\nUse \"exit\" to leave shell.\n");
12628 } else if (nflag == 0) {
12631 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
12634 i = evaltree(n, 0);
12638 popstackmark(&smark);
12642 evalskip &= ~SKIPFUNC;
12650 * Take commands from a file. To be compatible we should do a path
12651 * search for the file, which is necessary to find sub-commands.
12654 find_dot_file(char *name)
12657 const char *path = pathval();
12660 /* don't try this for absolute or relative paths */
12661 if (strchr(name, '/'))
12664 while ((fullname = path_advance(&path, name)) != NULL) {
12665 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12667 * Don't bother freeing here, since it will
12668 * be freed by the caller.
12672 if (fullname != name)
12673 stunalloc(fullname);
12676 /* not found in the PATH */
12677 ash_msg_and_raise_error("%s: not found", name);
12681 static int FAST_FUNC
12682 dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
12684 /* "false; . empty_file; echo $?" should print 0, not 1: */
12688 char *args_need_save;
12689 struct strlist *sp;
12690 volatile struct shparam saveparam;
12692 for (sp = cmdenviron; sp; sp = sp->next)
12693 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
12695 nextopt(nullstr); /* handle possible "--" */
12699 /* bash says: "bash: .: filename argument required" */
12700 return 2; /* bash compat */
12703 /* This aborts if file isn't found, which is POSIXly correct.
12704 * bash returns exitcode 1 instead.
12706 fullname = find_dot_file(argv[0]);
12708 args_need_save = argv[0];
12709 if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
12711 saveparam = shellparam;
12712 shellparam.malloced = 0;
12716 shellparam.nparam = argc;
12717 shellparam.p = argv;
12720 /* This aborts if file can't be opened, which is POSIXly correct.
12721 * bash returns exitcode 1 instead.
12723 setinputfile(fullname, INPUT_PUSH_FILE);
12724 commandname = fullname;
12725 status = cmdloop(0);
12728 if (args_need_save) {
12729 freeparam(&shellparam);
12730 shellparam = saveparam;
12736 static int FAST_FUNC
12737 exitcmd(int argc UNUSED_PARAM, char **argv)
12742 exitstatus = number(argv[1]);
12743 raise_exception(EXEXIT);
12748 * Read a file containing shell functions.
12751 readcmdfile(char *name)
12753 setinputfile(name, INPUT_PUSH_FILE);
12759 /* ============ find_command inplementation */
12762 * Resolve a command name. If you change this routine, you may have to
12763 * change the shellexec routine as well.
12766 find_command(char *name, struct cmdentry *entry, int act, const char *path)
12768 struct tblentry *cmdp;
12775 struct builtincmd *bcmd;
12777 /* If name contains a slash, don't use PATH or hash table */
12778 if (strchr(name, '/') != NULL) {
12779 entry->u.index = -1;
12780 if (act & DO_ABS) {
12781 while (stat(name, &statb) < 0) {
12783 if (errno == EINTR)
12786 entry->cmdtype = CMDUNKNOWN;
12790 entry->cmdtype = CMDNORMAL;
12794 /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
12796 updatetbl = (path == pathval());
12799 if (strstr(path, "%builtin") != NULL)
12800 act |= DO_ALTBLTIN;
12803 /* If name is in the table, check answer will be ok */
12804 cmdp = cmdlookup(name, 0);
12805 if (cmdp != NULL) {
12808 switch (cmdp->cmdtype) {
12826 } else if (cmdp->rehash == 0)
12827 /* if not invalidated by cd, we're done */
12831 /* If %builtin not in path, check for builtin next */
12832 bcmd = find_builtin(name);
12834 if (IS_BUILTIN_REGULAR(bcmd))
12835 goto builtin_success;
12836 if (act & DO_ALTPATH) {
12837 if (!(act & DO_ALTBLTIN))
12838 goto builtin_success;
12839 } else if (builtinloc <= 0) {
12840 goto builtin_success;
12844 #if ENABLE_FEATURE_SH_STANDALONE
12846 int applet_no = find_applet_by_name(name);
12847 if (applet_no >= 0) {
12848 entry->cmdtype = CMDNORMAL;
12849 entry->u.index = -2 - applet_no;
12855 /* We have to search path. */
12856 prev = -1; /* where to start */
12857 if (cmdp && cmdp->rehash) { /* doing a rehash */
12858 if (cmdp->cmdtype == CMDBUILTIN)
12861 prev = cmdp->param.index;
12867 while ((fullname = path_advance(&path, name)) != NULL) {
12868 stunalloc(fullname);
12869 /* NB: code below will still use fullname
12870 * despite it being "unallocated" */
12873 if (prefix(pathopt, "builtin")) {
12875 goto builtin_success;
12878 if ((act & DO_NOFUNC)
12879 || !prefix(pathopt, "func")
12880 ) { /* ignore unimplemented options */
12884 /* if rehash, don't redo absolute path names */
12885 if (fullname[0] == '/' && idx <= prev) {
12888 TRACE(("searchexec \"%s\": no change\n", name));
12891 while (stat(fullname, &statb) < 0) {
12893 if (errno == EINTR)
12896 if (errno != ENOENT && errno != ENOTDIR)
12900 e = EACCES; /* if we fail, this will be the error */
12901 if (!S_ISREG(statb.st_mode))
12903 if (pathopt) { /* this is a %func directory */
12904 stalloc(strlen(fullname) + 1);
12905 /* NB: stalloc will return space pointed by fullname
12906 * (because we don't have any intervening allocations
12907 * between stunalloc above and this stalloc) */
12908 readcmdfile(fullname);
12909 cmdp = cmdlookup(name, 0);
12910 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12911 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12912 stunalloc(fullname);
12915 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12917 entry->cmdtype = CMDNORMAL;
12918 entry->u.index = idx;
12922 cmdp = cmdlookup(name, 1);
12923 cmdp->cmdtype = CMDNORMAL;
12924 cmdp->param.index = idx;
12929 /* We failed. If there was an entry for this command, delete it */
12930 if (cmdp && updatetbl)
12931 delete_cmd_entry();
12933 ash_msg("%s: %s", name, errmsg(e, "not found"));
12934 entry->cmdtype = CMDUNKNOWN;
12939 entry->cmdtype = CMDBUILTIN;
12940 entry->u.cmd = bcmd;
12944 cmdp = cmdlookup(name, 1);
12945 cmdp->cmdtype = CMDBUILTIN;
12946 cmdp->param.cmd = bcmd;
12950 entry->cmdtype = cmdp->cmdtype;
12951 entry->u = cmdp->param;
12956 * The trap builtin.
12958 static int FAST_FUNC
12959 trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
12963 int signo, exitcode;
12968 for (signo = 0; signo < NSIG; signo++) {
12969 char *tr = trap_ptr[signo];
12971 /* note: bash adds "SIG", but only if invoked
12972 * as "bash". If called as "sh", or if set -o posix,
12973 * then it prints short signal names.
12974 * We are printing short names: */
12975 out1fmt("trap -- %s %s\n",
12977 get_signame(signo));
12978 /* trap_ptr != trap only if we are in special-cased `trap` code.
12979 * In this case, we will exit very soon, no need to free(). */
12980 /* if (trap_ptr != trap && tp[0]) */
12985 if (trap_ptr != trap) {
12993 /* Why the second check?
12994 * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
12995 * In this case, NUM is signal no, not an action.
12998 if (ap[1] && !is_number(ap[0]))
13003 signo = get_signum(*ap);
13005 /* Mimic bash message exactly */
13006 ash_msg("%s: invalid signal specification", *ap);
13012 if (LONE_DASH(action))
13015 if (action[0]) /* not NULL and not "" and not "-" */
13016 may_have_traps = 1;
13017 action = ckstrdup(action);
13021 trap[signo] = action;
13032 /* ============ Builtins */
13034 #if ENABLE_ASH_HELP
13035 static int FAST_FUNC
13036 helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13042 "Built-in commands:\n"
13043 "------------------\n");
13044 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
13045 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
13046 builtintab[i].name + 1);
13052 # if ENABLE_FEATURE_SH_STANDALONE
13054 const char *a = applet_names;
13056 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
13061 while (*a++ != '\0')
13066 newline_and_flush(stdout);
13067 return EXIT_SUCCESS;
13072 static int FAST_FUNC
13073 historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13075 show_history(line_input_state);
13076 return EXIT_SUCCESS;
13081 * The export and readonly commands.
13083 static int FAST_FUNC
13084 exportcmd(int argc UNUSED_PARAM, char **argv)
13094 /* "readonly" in bash accepts, but ignores -n.
13095 * We do the same: it saves a conditional in nextopt's param.
13098 while ((opt = nextopt("np")) != '\0') {
13100 flag_off = VEXPORT;
13103 if (argv[0][0] == 'r') {
13105 flag_off = 0; /* readonly ignores -n */
13107 flag_off = ~flag_off;
13109 /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
13115 p = strchr(name, '=');
13119 vp = *findvar(hashvar(name), name);
13121 vp->flags = ((vp->flags | flag) & flag_off);
13125 setvar(name, p, (flag & flag_off));
13126 } while ((name = *++aptr) != NULL);
13131 /* No arguments. Show the list of exported or readonly vars.
13134 showvars(argv[0], flag, 0);
13139 * Delete a function if it exists.
13142 unsetfunc(const char *name)
13144 struct tblentry *cmdp;
13146 cmdp = cmdlookup(name, 0);
13147 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
13148 delete_cmd_entry();
13152 * The unset builtin command. We unset the function before we unset the
13153 * variable to allow a function to be unset when there is a readonly variable
13154 * with the same name.
13156 static int FAST_FUNC
13157 unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13163 while ((i = nextopt("vf")) != 0) {
13167 for (ap = argptr; *ap; ap++) {
13178 static const unsigned char timescmd_str[] ALIGN1 = {
13179 ' ', offsetof(struct tms, tms_utime),
13180 '\n', offsetof(struct tms, tms_stime),
13181 ' ', offsetof(struct tms, tms_cutime),
13182 '\n', offsetof(struct tms, tms_cstime),
13185 static int FAST_FUNC
13186 timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13188 unsigned long clk_tck, s, t;
13189 const unsigned char *p;
13192 clk_tck = bb_clk_tck();
13197 t = *(clock_t *)(((char *) &buf) + p[1]);
13200 out1fmt("%lum%lu.%03lus%c",
13202 (t * 1000) / clk_tck,
13210 #if ENABLE_FEATURE_SH_MATH
13212 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
13213 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
13215 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
13217 static int FAST_FUNC
13218 letcmd(int argc UNUSED_PARAM, char **argv)
13224 ash_msg_and_raise_error("expression expected");
13226 i = ash_arith(*argv);
13234 * The read builtin. Options:
13235 * -r Do not interpret '\' specially
13236 * -s Turn off echo (tty only)
13237 * -n NCHARS Read NCHARS max
13238 * -p PROMPT Display PROMPT on stderr (if input is from tty)
13239 * -t SECONDS Timeout after SECONDS (tty or pipe only)
13240 * -u FD Read from given FD instead of fd 0
13241 * This uses unbuffered input, which may be avoidable in some cases.
13242 * TODO: bash also has:
13243 * -a ARRAY Read into array[0],[1],etc
13244 * -d DELIM End on DELIM char, not newline
13245 * -e Use line editing (tty only)
13247 static int FAST_FUNC
13248 readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13250 char *opt_n = NULL;
13251 char *opt_p = NULL;
13252 char *opt_t = NULL;
13253 char *opt_u = NULL;
13254 int read_flags = 0;
13258 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
13267 read_flags |= BUILTIN_READ_SILENT;
13273 read_flags |= BUILTIN_READ_RAW;
13283 /* "read -s" needs to save/restore termios, can't allow ^C
13284 * to jump out of it.
13288 r = shell_builtin_read(setvar0,
13290 bltinlookup("IFS"), /* can be NULL */
13299 if ((uintptr_t)r == 1 && errno == EINTR) {
13300 /* to get SIGCHLD: sleep 1 & read x; echo $x */
13301 if (pending_sig == 0)
13305 if ((uintptr_t)r > 1)
13306 ash_msg_and_raise_error(r);
13308 return (uintptr_t)r;
13311 static int FAST_FUNC
13312 umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
13314 static const char permuser[3] ALIGN1 = "ogu";
13317 int symbolic_mode = 0;
13319 while (nextopt("S") != '\0') {
13328 if (*argptr == NULL) {
13329 if (symbolic_mode) {
13330 char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
13337 *p++ = permuser[i];
13339 /* mask is 0..0uuugggooo. i=2 selects uuu bits */
13340 if (!(mask & 0400)) *p++ = 'r';
13341 if (!(mask & 0200)) *p++ = 'w';
13342 if (!(mask & 0100)) *p++ = 'x';
13350 out1fmt("%04o\n", mask);
13353 char *modestr = *argptr;
13354 /* numeric umasks are taken as-is */
13355 /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
13356 if (!isdigit(modestr[0]))
13358 mask = bb_parse_mode(modestr, mask);
13359 if ((unsigned)mask > 0777) {
13360 ash_msg_and_raise_error("illegal mode: %s", modestr);
13362 if (!isdigit(modestr[0]))
13369 static int FAST_FUNC
13370 ulimitcmd(int argc UNUSED_PARAM, char **argv)
13372 return shell_builtin_ulimit(argv);
13375 /* ============ main() and helpers */
13378 * Called to exit the shell.
13387 #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
13388 save_history(line_input_state);
13390 status = exitstatus;
13391 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13392 if (setjmp(loc.loc)) {
13393 if (exception_type == EXEXIT)
13394 status = exitstatus;
13397 exception_handler = &loc;
13403 /*free(p); - we'll exit soon */
13406 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
13407 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
13410 flush_stdout_stderr();
13418 /* we will never free this */
13419 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
13421 sigmode[SIGCHLD - 1] = S_DFL;
13422 setsignal(SIGCHLD);
13424 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13425 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13427 signal(SIGHUP, SIG_DFL);
13432 struct stat st1, st2;
13435 for (envp = environ; envp && *envp; envp++) {
13436 p = endofname(*envp);
13437 if (p != *envp && *p == '=') {
13438 setvareq(*envp, VEXPORT|VTEXTFIXED);
13442 setvareq((char*)defoptindvar, VTEXTFIXED);
13444 setvar0("PPID", utoa(getppid()));
13446 p = lookupvar("SHLVL");
13447 setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
13449 #if BASH_HOSTNAME_VAR
13450 if (!lookupvar("HOSTNAME")) {
13451 struct utsname uts;
13453 setvar0("HOSTNAME", uts.nodename);
13456 p = lookupvar("PWD");
13458 if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
13459 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
13469 //usage:#define ash_trivial_usage
13470 //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
13471 //usage:#define ash_full_usage "\n\n"
13472 //usage: "Unix shell interpreter"
13475 * Process the shell command line arguments.
13478 procargs(char **argv)
13481 const char *xminusc;
13486 /* if (xargv[0]) - mmm, this is always true! */
13488 for (i = 0; i < NOPTS; i++)
13491 if (options(/*cmdline:*/ 1)) {
13492 /* it already printed err message */
13493 raise_exception(EXERROR);
13497 if (*xargv == NULL) {
13499 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13502 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13506 for (i = 0; i < NOPTS; i++)
13507 if (optlist[i] == 2)
13512 /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
13517 } else if (!sflag) {
13518 setinputfile(*xargv, 0);
13521 commandname = arg0;
13524 shellparam.p = xargv;
13525 #if ENABLE_ASH_GETOPTS
13526 shellparam.optind = 1;
13527 shellparam.optoff = -1;
13529 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
13531 shellparam.nparam++;
13538 * Read /etc/profile, ~/.profile, $ENV.
13541 read_profile(const char *name)
13543 name = expandstr(name);
13544 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13551 * This routine is called when an error or an interrupt occurs in an
13552 * interactive shell and control is returned to the main command loop.
13553 * (In dash, this function is auto-generated by build machinery).
13562 /* from expand.c: */
13565 /* from input.c: */
13566 g_parsefile->left_in_buffer = 0;
13567 g_parsefile->left_in_line = 0; /* clear input buffer */
13570 /* from redir.c: */
13572 popredir(/*drop:*/ 0, /*restore:*/ 0);
13576 static short profile_buf[16384];
13577 extern int etext();
13581 * Main routine. We initialize things, parse the arguments, execute
13582 * profiles if we're a login shell, and then call cmdloop to execute
13583 * commands. The setjmp call sets up the location to jump to when an
13584 * exception occurs. When an exception occurs the variable "state"
13585 * is used to figure out how far we had gotten.
13587 int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
13588 int ash_main(int argc UNUSED_PARAM, char **argv)
13590 volatile smallint state;
13591 struct jmploc jmploc;
13592 struct stackmark smark;
13594 /* Initialize global data */
13598 #if ENABLE_ASH_ALIAS
13604 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13607 #if ENABLE_FEATURE_EDITING
13608 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13611 if (setjmp(jmploc.loc)) {
13617 e = exception_type;
13619 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
13623 newline_and_flush(stderr);
13626 popstackmark(&smark);
13627 FORCE_INT_ON; /* enable interrupts */
13636 exception_handler = &jmploc;
13637 rootpid = getpid();
13640 setstackmark(&smark);
13643 TRACE(("Shell args: "));
13644 trace_puts_args(argv);
13647 if (argv[0] && argv[0][0] == '-')
13653 read_profile("/etc/profile");
13656 hp = lookupvar("HOME");
13658 read_profile("$HOME/.profile");
13664 getuid() == geteuid() && getgid() == getegid() &&
13668 const char *shinit = lookupvar("ENV");
13669 if (shinit != NULL && *shinit != '\0')
13670 read_profile(shinit);
13672 popstackmark(&smark);
13676 /* evalstring pushes parsefile stack.
13677 * Ensure we don't falsely claim that 0 (stdin)
13678 * is one of stacked source fds.
13679 * Testcase: ash -c 'exec 1>&0' must not complain. */
13680 // if (!sflag) g_parsefile->pf_fd = -1;
13681 // ^^ not necessary since now we special-case fd 0
13682 // in is_hidden_fd() to not be considered "hidden fd"
13683 evalstring(minusc, sflag ? 0 : EV_EXIT);
13686 if (sflag || minusc == NULL) {
13687 #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
13689 const char *hp = lookupvar("HISTFILE");
13691 hp = lookupvar("HOME");
13694 hp = concat_path_file(hp, ".ash_history");
13695 setvar0("HISTFILE", hp);
13698 hp = lookupvar("HISTFILE");
13702 line_input_state->hist_file = hp;
13703 # if ENABLE_FEATURE_SH_HISTFILESIZE
13704 hp = lookupvar("HISTFILESIZE");
13705 line_input_state->max_history = size_from_HISTFILESIZE(hp);
13709 state4: /* XXX ??? - why isn't this before the "if" statement */
13717 extern void _mcleanup(void);
13721 TRACE(("End of main reached\n"));
13728 * Copyright (c) 1989, 1991, 1993, 1994
13729 * The Regents of the University of California. All rights reserved.
13731 * This code is derived from software contributed to Berkeley by
13732 * Kenneth Almquist.
13734 * Redistribution and use in source and binary forms, with or without
13735 * modification, are permitted provided that the following conditions
13737 * 1. Redistributions of source code must retain the above copyright
13738 * notice, this list of conditions and the following disclaimer.
13739 * 2. Redistributions in binary form must reproduce the above copyright
13740 * notice, this list of conditions and the following disclaimer in the
13741 * documentation and/or other materials provided with the distribution.
13742 * 3. Neither the name of the University nor the names of its contributors
13743 * may be used to endorse or promote products derived from this software
13744 * without specific prior written permission.
13746 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13747 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13748 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13749 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13750 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13751 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13752 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13753 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13754 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13755 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF